xref: /linux/kernel/bpf/verifier.c (revision eb71ab2bf72260054677e348498ba995a057c463)
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_obj(*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_obj(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 	u64 tnum_next, tmax;
2383 	bool umin_in_tnum;
2384 
2385 	/* min signed is max(sign bit) | min(other bits) */
2386 	reg->smin_value = max_t(s64, reg->smin_value,
2387 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2388 	/* max signed is min(sign bit) | max(other bits) */
2389 	reg->smax_value = min_t(s64, reg->smax_value,
2390 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2391 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2392 	reg->umax_value = min(reg->umax_value,
2393 			      reg->var_off.value | reg->var_off.mask);
2394 
2395 	/* Check if u64 and tnum overlap in a single value */
2396 	tnum_next = tnum_step(reg->var_off, reg->umin_value);
2397 	umin_in_tnum = (reg->umin_value & ~reg->var_off.mask) == reg->var_off.value;
2398 	tmax = reg->var_off.value | reg->var_off.mask;
2399 	if (umin_in_tnum && tnum_next > reg->umax_value) {
2400 		/* The u64 range and the tnum only overlap in umin.
2401 		 * u64:  ---[xxxxxx]-----
2402 		 * tnum: --xx----------x-
2403 		 */
2404 		___mark_reg_known(reg, reg->umin_value);
2405 	} else if (!umin_in_tnum && tnum_next == tmax) {
2406 		/* The u64 range and the tnum only overlap in the maximum value
2407 		 * represented by the tnum, called tmax.
2408 		 * u64:  ---[xxxxxx]-----
2409 		 * tnum: xx-----x--------
2410 		 */
2411 		___mark_reg_known(reg, tmax);
2412 	} else if (!umin_in_tnum && tnum_next <= reg->umax_value &&
2413 		   tnum_step(reg->var_off, tnum_next) > reg->umax_value) {
2414 		/* The u64 range and the tnum only overlap in between umin
2415 		 * (excluded) and umax.
2416 		 * u64:  ---[xxxxxx]-----
2417 		 * tnum: xx----x-------x-
2418 		 */
2419 		___mark_reg_known(reg, tnum_next);
2420 	}
2421 }
2422 
2423 static void __update_reg_bounds(struct bpf_reg_state *reg)
2424 {
2425 	__update_reg32_bounds(reg);
2426 	__update_reg64_bounds(reg);
2427 }
2428 
2429 /* Uses signed min/max values to inform unsigned, and vice-versa */
2430 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2431 {
2432 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
2433 	 * bits to improve our u32/s32 boundaries.
2434 	 *
2435 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
2436 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
2437 	 * [10, 20] range. But this property holds for any 64-bit range as
2438 	 * long as upper 32 bits in that entire range of values stay the same.
2439 	 *
2440 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
2441 	 * in decimal) has the same upper 32 bits throughout all the values in
2442 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
2443 	 * range.
2444 	 *
2445 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
2446 	 * following the rules outlined below about u64/s64 correspondence
2447 	 * (which equally applies to u32 vs s32 correspondence). In general it
2448 	 * depends on actual hexadecimal values of 32-bit range. They can form
2449 	 * only valid u32, or only valid s32 ranges in some cases.
2450 	 *
2451 	 * So we use all these insights to derive bounds for subregisters here.
2452 	 */
2453 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
2454 		/* u64 to u32 casting preserves validity of low 32 bits as
2455 		 * a range, if upper 32 bits are the same
2456 		 */
2457 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2458 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2459 
2460 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2461 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2462 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2463 		}
2464 	}
2465 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2466 		/* low 32 bits should form a proper u32 range */
2467 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2468 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2469 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2470 		}
2471 		/* low 32 bits should form a proper s32 range */
2472 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2473 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2474 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2475 		}
2476 	}
2477 	/* Special case where upper bits form a small sequence of two
2478 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2479 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2480 	 * going from negative numbers to positive numbers. E.g., let's say we
2481 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2482 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2483 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2484 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2485 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2486 	 * upper 32 bits. As a random example, s64 range
2487 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2488 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2489 	 */
2490 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2491 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2492 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2493 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2494 	}
2495 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2496 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2497 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2498 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2499 	}
2500 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2501 	 * try to learn from that
2502 	 */
2503 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2504 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2505 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2506 	}
2507 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2508 	 * are the same, so combine.  This works even in the negative case, e.g.
2509 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2510 	 */
2511 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2512 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2513 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2514 	}
2515 }
2516 
2517 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2518 {
2519 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2520 	 * try to learn from that. Let's do a bit of ASCII art to see when
2521 	 * this is happening. Let's take u64 range first:
2522 	 *
2523 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2524 	 * |-------------------------------|--------------------------------|
2525 	 *
2526 	 * Valid u64 range is formed when umin and umax are anywhere in the
2527 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2528 	 * straightforward. Let's see how s64 range maps onto the same range
2529 	 * of values, annotated below the line for comparison:
2530 	 *
2531 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2532 	 * |-------------------------------|--------------------------------|
2533 	 * 0                        S64_MAX S64_MIN                        -1
2534 	 *
2535 	 * So s64 values basically start in the middle and they are logically
2536 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2537 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2538 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2539 	 * more visually as mapped to sign-agnostic range of hex values.
2540 	 *
2541 	 *  u64 start                                               u64 end
2542 	 *  _______________________________________________________________
2543 	 * /                                                               \
2544 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2545 	 * |-------------------------------|--------------------------------|
2546 	 * 0                        S64_MAX S64_MIN                        -1
2547 	 *                                / \
2548 	 * >------------------------------   ------------------------------->
2549 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2550 	 *
2551 	 * What this means is that, in general, we can't always derive
2552 	 * something new about u64 from any random s64 range, and vice versa.
2553 	 *
2554 	 * But we can do that in two particular cases. One is when entire
2555 	 * u64/s64 range is *entirely* contained within left half of the above
2556 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2557 	 *
2558 	 * |-------------------------------|--------------------------------|
2559 	 *     ^                   ^            ^                 ^
2560 	 *     A                   B            C                 D
2561 	 *
2562 	 * [A, B] and [C, D] are contained entirely in their respective halves
2563 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2564 	 * will be non-negative both as u64 and s64 (and in fact it will be
2565 	 * identical ranges no matter the signedness). [C, D] treated as s64
2566 	 * will be a range of negative values, while in u64 it will be
2567 	 * non-negative range of values larger than 0x8000000000000000.
2568 	 *
2569 	 * Now, any other range here can't be represented in both u64 and s64
2570 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2571 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2572 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2573 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2574 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2575 	 * ranges as u64. Currently reg_state can't represent two segments per
2576 	 * numeric domain, so in such situations we can only derive maximal
2577 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2578 	 *
2579 	 * So we use these facts to derive umin/umax from smin/smax and vice
2580 	 * versa only if they stay within the same "half". This is equivalent
2581 	 * to checking sign bit: lower half will have sign bit as zero, upper
2582 	 * half have sign bit 1. Below in code we simplify this by just
2583 	 * casting umin/umax as smin/smax and checking if they form valid
2584 	 * range, and vice versa. Those are equivalent checks.
2585 	 */
2586 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2587 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2588 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2589 	}
2590 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2591 	 * are the same, so combine.  This works even in the negative case, e.g.
2592 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2593 	 */
2594 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2595 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2596 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2597 	} else {
2598 		/* If the s64 range crosses the sign boundary, then it's split
2599 		 * between the beginning and end of the U64 domain. In that
2600 		 * case, we can derive new bounds if the u64 range overlaps
2601 		 * with only one end of the s64 range.
2602 		 *
2603 		 * In the following example, the u64 range overlaps only with
2604 		 * positive portion of the s64 range.
2605 		 *
2606 		 * 0                                                   U64_MAX
2607 		 * |  [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]              |
2608 		 * |----------------------------|----------------------------|
2609 		 * |xxxxx s64 range xxxxxxxxx]                       [xxxxxxx|
2610 		 * 0                     S64_MAX S64_MIN                    -1
2611 		 *
2612 		 * We can thus derive the following new s64 and u64 ranges.
2613 		 *
2614 		 * 0                                                   U64_MAX
2615 		 * |  [xxxxxx u64 range xxxxx]                               |
2616 		 * |----------------------------|----------------------------|
2617 		 * |  [xxxxxx s64 range xxxxx]                               |
2618 		 * 0                     S64_MAX S64_MIN                    -1
2619 		 *
2620 		 * If they overlap in two places, we can't derive anything
2621 		 * because reg_state can't represent two ranges per numeric
2622 		 * domain.
2623 		 *
2624 		 * 0                                                   U64_MAX
2625 		 * |  [xxxxxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxxxxx]        |
2626 		 * |----------------------------|----------------------------|
2627 		 * |xxxxx s64 range xxxxxxxxx]                    [xxxxxxxxxx|
2628 		 * 0                     S64_MAX S64_MIN                    -1
2629 		 *
2630 		 * The first condition below corresponds to the first diagram
2631 		 * above.
2632 		 */
2633 		if (reg->umax_value < (u64)reg->smin_value) {
2634 			reg->smin_value = (s64)reg->umin_value;
2635 			reg->umax_value = min_t(u64, reg->umax_value, reg->smax_value);
2636 		} else if ((u64)reg->smax_value < reg->umin_value) {
2637 			/* This second condition considers the case where the u64 range
2638 			 * overlaps with the negative portion of the s64 range:
2639 			 *
2640 			 * 0                                                   U64_MAX
2641 			 * |              [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]  |
2642 			 * |----------------------------|----------------------------|
2643 			 * |xxxxxxxxx]                       [xxxxxxxxxxxx s64 range |
2644 			 * 0                     S64_MAX S64_MIN                    -1
2645 			 */
2646 			reg->smax_value = (s64)reg->umax_value;
2647 			reg->umin_value = max_t(u64, reg->umin_value, reg->smin_value);
2648 		}
2649 	}
2650 }
2651 
2652 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2653 {
2654 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2655 	 * values on both sides of 64-bit range in hope to have tighter range.
2656 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2657 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2658 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2659 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2660 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2661 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2662 	 * We just need to make sure that derived bounds we are intersecting
2663 	 * with are well-formed ranges in respective s64 or u64 domain, just
2664 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2665 	 */
2666 	__u64 new_umin, new_umax;
2667 	__s64 new_smin, new_smax;
2668 
2669 	/* u32 -> u64 tightening, it's always well-formed */
2670 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2671 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2672 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2673 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2674 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2675 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2676 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2677 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2678 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2679 
2680 	/* Here we would like to handle a special case after sign extending load,
2681 	 * when upper bits for a 64-bit range are all 1s or all 0s.
2682 	 *
2683 	 * Upper bits are all 1s when register is in a range:
2684 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2685 	 * Upper bits are all 0s when register is in a range:
2686 	 *   [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2687 	 * Together this forms are continuous range:
2688 	 *   [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2689 	 *
2690 	 * Now, suppose that register range is in fact tighter:
2691 	 *   [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2692 	 * Also suppose that it's 32-bit range is positive,
2693 	 * meaning that lower 32-bits of the full 64-bit register
2694 	 * are in the range:
2695 	 *   [0x0000_0000, 0x7fff_ffff] (W)
2696 	 *
2697 	 * If this happens, then any value in a range:
2698 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2699 	 * is smaller than a lowest bound of the range (R):
2700 	 *   0xffff_ffff_8000_0000
2701 	 * which means that upper bits of the full 64-bit register
2702 	 * can't be all 1s, when lower bits are in range (W).
2703 	 *
2704 	 * Note that:
2705 	 *  - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2706 	 *  - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2707 	 * These relations are used in the conditions below.
2708 	 */
2709 	if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2710 		reg->smin_value = reg->s32_min_value;
2711 		reg->smax_value = reg->s32_max_value;
2712 		reg->umin_value = reg->s32_min_value;
2713 		reg->umax_value = reg->s32_max_value;
2714 		reg->var_off = tnum_intersect(reg->var_off,
2715 					      tnum_range(reg->smin_value, reg->smax_value));
2716 	}
2717 }
2718 
2719 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2720 {
2721 	__reg32_deduce_bounds(reg);
2722 	__reg64_deduce_bounds(reg);
2723 	__reg_deduce_mixed_bounds(reg);
2724 }
2725 
2726 /* Attempts to improve var_off based on unsigned min/max information */
2727 static void __reg_bound_offset(struct bpf_reg_state *reg)
2728 {
2729 	struct tnum var64_off = tnum_intersect(reg->var_off,
2730 					       tnum_range(reg->umin_value,
2731 							  reg->umax_value));
2732 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2733 					       tnum_range(reg->u32_min_value,
2734 							  reg->u32_max_value));
2735 
2736 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2737 }
2738 
2739 static void reg_bounds_sync(struct bpf_reg_state *reg)
2740 {
2741 	/* We might have learned new bounds from the var_off. */
2742 	__update_reg_bounds(reg);
2743 	/* We might have learned something about the sign bit. */
2744 	__reg_deduce_bounds(reg);
2745 	__reg_deduce_bounds(reg);
2746 	__reg_deduce_bounds(reg);
2747 	/* We might have learned some bits from the bounds. */
2748 	__reg_bound_offset(reg);
2749 	/* Intersecting with the old var_off might have improved our bounds
2750 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2751 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2752 	 */
2753 	__update_reg_bounds(reg);
2754 }
2755 
2756 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2757 				   struct bpf_reg_state *reg, const char *ctx)
2758 {
2759 	const char *msg;
2760 
2761 	if (reg->umin_value > reg->umax_value ||
2762 	    reg->smin_value > reg->smax_value ||
2763 	    reg->u32_min_value > reg->u32_max_value ||
2764 	    reg->s32_min_value > reg->s32_max_value) {
2765 		    msg = "range bounds violation";
2766 		    goto out;
2767 	}
2768 
2769 	if (tnum_is_const(reg->var_off)) {
2770 		u64 uval = reg->var_off.value;
2771 		s64 sval = (s64)uval;
2772 
2773 		if (reg->umin_value != uval || reg->umax_value != uval ||
2774 		    reg->smin_value != sval || reg->smax_value != sval) {
2775 			msg = "const tnum out of sync with range bounds";
2776 			goto out;
2777 		}
2778 	}
2779 
2780 	if (tnum_subreg_is_const(reg->var_off)) {
2781 		u32 uval32 = tnum_subreg(reg->var_off).value;
2782 		s32 sval32 = (s32)uval32;
2783 
2784 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2785 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2786 			msg = "const subreg tnum out of sync with range bounds";
2787 			goto out;
2788 		}
2789 	}
2790 
2791 	return 0;
2792 out:
2793 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2794 		     "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)",
2795 		     ctx, msg, reg->umin_value, reg->umax_value,
2796 		     reg->smin_value, reg->smax_value,
2797 		     reg->u32_min_value, reg->u32_max_value,
2798 		     reg->s32_min_value, reg->s32_max_value,
2799 		     reg->var_off.value, reg->var_off.mask);
2800 	if (env->test_reg_invariants)
2801 		return -EFAULT;
2802 	__mark_reg_unbounded(reg);
2803 	return 0;
2804 }
2805 
2806 static bool __reg32_bound_s64(s32 a)
2807 {
2808 	return a >= 0 && a <= S32_MAX;
2809 }
2810 
2811 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2812 {
2813 	reg->umin_value = reg->u32_min_value;
2814 	reg->umax_value = reg->u32_max_value;
2815 
2816 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2817 	 * be positive otherwise set to worse case bounds and refine later
2818 	 * from tnum.
2819 	 */
2820 	if (__reg32_bound_s64(reg->s32_min_value) &&
2821 	    __reg32_bound_s64(reg->s32_max_value)) {
2822 		reg->smin_value = reg->s32_min_value;
2823 		reg->smax_value = reg->s32_max_value;
2824 	} else {
2825 		reg->smin_value = 0;
2826 		reg->smax_value = U32_MAX;
2827 	}
2828 }
2829 
2830 /* Mark a register as having a completely unknown (scalar) value. */
2831 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2832 {
2833 	/*
2834 	 * Clear type, off, and union(map_ptr, range) and
2835 	 * padding between 'type' and union
2836 	 */
2837 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2838 	reg->type = SCALAR_VALUE;
2839 	reg->id = 0;
2840 	reg->ref_obj_id = 0;
2841 	reg->var_off = tnum_unknown;
2842 	reg->frameno = 0;
2843 	reg->precise = false;
2844 	__mark_reg_unbounded(reg);
2845 }
2846 
2847 /* Mark a register as having a completely unknown (scalar) value,
2848  * initialize .precise as true when not bpf capable.
2849  */
2850 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2851 			       struct bpf_reg_state *reg)
2852 {
2853 	__mark_reg_unknown_imprecise(reg);
2854 	reg->precise = !env->bpf_capable;
2855 }
2856 
2857 static void mark_reg_unknown(struct bpf_verifier_env *env,
2858 			     struct bpf_reg_state *regs, u32 regno)
2859 {
2860 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2861 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2862 		/* Something bad happened, let's kill all regs except FP */
2863 		for (regno = 0; regno < BPF_REG_FP; regno++)
2864 			__mark_reg_not_init(env, regs + regno);
2865 		return;
2866 	}
2867 	__mark_reg_unknown(env, regs + regno);
2868 }
2869 
2870 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2871 				struct bpf_reg_state *regs,
2872 				u32 regno,
2873 				s32 s32_min,
2874 				s32 s32_max)
2875 {
2876 	struct bpf_reg_state *reg = regs + regno;
2877 
2878 	reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2879 	reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2880 
2881 	reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2882 	reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2883 
2884 	reg_bounds_sync(reg);
2885 
2886 	return reg_bounds_sanity_check(env, reg, "s32_range");
2887 }
2888 
2889 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2890 				struct bpf_reg_state *reg)
2891 {
2892 	__mark_reg_unknown(env, reg);
2893 	reg->type = NOT_INIT;
2894 }
2895 
2896 static void mark_reg_not_init(struct bpf_verifier_env *env,
2897 			      struct bpf_reg_state *regs, u32 regno)
2898 {
2899 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2900 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2901 		/* Something bad happened, let's kill all regs except FP */
2902 		for (regno = 0; regno < BPF_REG_FP; regno++)
2903 			__mark_reg_not_init(env, regs + regno);
2904 		return;
2905 	}
2906 	__mark_reg_not_init(env, regs + regno);
2907 }
2908 
2909 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2910 			   struct bpf_reg_state *regs, u32 regno,
2911 			   enum bpf_reg_type reg_type,
2912 			   struct btf *btf, u32 btf_id,
2913 			   enum bpf_type_flag flag)
2914 {
2915 	switch (reg_type) {
2916 	case SCALAR_VALUE:
2917 		mark_reg_unknown(env, regs, regno);
2918 		return 0;
2919 	case PTR_TO_BTF_ID:
2920 		mark_reg_known_zero(env, regs, regno);
2921 		regs[regno].type = PTR_TO_BTF_ID | flag;
2922 		regs[regno].btf = btf;
2923 		regs[regno].btf_id = btf_id;
2924 		if (type_may_be_null(flag))
2925 			regs[regno].id = ++env->id_gen;
2926 		return 0;
2927 	case PTR_TO_MEM:
2928 		mark_reg_known_zero(env, regs, regno);
2929 		regs[regno].type = PTR_TO_MEM | flag;
2930 		regs[regno].mem_size = 0;
2931 		return 0;
2932 	default:
2933 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2934 		return -EFAULT;
2935 	}
2936 }
2937 
2938 #define DEF_NOT_SUBREG	(0)
2939 static void init_reg_state(struct bpf_verifier_env *env,
2940 			   struct bpf_func_state *state)
2941 {
2942 	struct bpf_reg_state *regs = state->regs;
2943 	int i;
2944 
2945 	for (i = 0; i < MAX_BPF_REG; i++) {
2946 		mark_reg_not_init(env, regs, i);
2947 		regs[i].subreg_def = DEF_NOT_SUBREG;
2948 	}
2949 
2950 	/* frame pointer */
2951 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2952 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2953 	regs[BPF_REG_FP].frameno = state->frameno;
2954 }
2955 
2956 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2957 {
2958 	return (struct bpf_retval_range){ minval, maxval };
2959 }
2960 
2961 #define BPF_MAIN_FUNC (-1)
2962 static void init_func_state(struct bpf_verifier_env *env,
2963 			    struct bpf_func_state *state,
2964 			    int callsite, int frameno, int subprogno)
2965 {
2966 	state->callsite = callsite;
2967 	state->frameno = frameno;
2968 	state->subprogno = subprogno;
2969 	state->callback_ret_range = retval_range(0, 0);
2970 	init_reg_state(env, state);
2971 	mark_verifier_state_scratched(env);
2972 }
2973 
2974 /* Similar to push_stack(), but for async callbacks */
2975 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2976 						int insn_idx, int prev_insn_idx,
2977 						int subprog, bool is_sleepable)
2978 {
2979 	struct bpf_verifier_stack_elem *elem;
2980 	struct bpf_func_state *frame;
2981 
2982 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
2983 	if (!elem)
2984 		return ERR_PTR(-ENOMEM);
2985 
2986 	elem->insn_idx = insn_idx;
2987 	elem->prev_insn_idx = prev_insn_idx;
2988 	elem->next = env->head;
2989 	elem->log_pos = env->log.end_pos;
2990 	env->head = elem;
2991 	env->stack_size++;
2992 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2993 		verbose(env,
2994 			"The sequence of %d jumps is too complex for async cb.\n",
2995 			env->stack_size);
2996 		return ERR_PTR(-E2BIG);
2997 	}
2998 	/* Unlike push_stack() do not copy_verifier_state().
2999 	 * The caller state doesn't matter.
3000 	 * This is async callback. It starts in a fresh stack.
3001 	 * Initialize it similar to do_check_common().
3002 	 */
3003 	elem->st.branches = 1;
3004 	elem->st.in_sleepable = is_sleepable;
3005 	frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT);
3006 	if (!frame)
3007 		return ERR_PTR(-ENOMEM);
3008 	init_func_state(env, frame,
3009 			BPF_MAIN_FUNC /* callsite */,
3010 			0 /* frameno within this callchain */,
3011 			subprog /* subprog number within this prog */);
3012 	elem->st.frame[0] = frame;
3013 	return &elem->st;
3014 }
3015 
3016 
3017 enum reg_arg_type {
3018 	SRC_OP,		/* register is used as source operand */
3019 	DST_OP,		/* register is used as destination operand */
3020 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
3021 };
3022 
3023 static int cmp_subprogs(const void *a, const void *b)
3024 {
3025 	return ((struct bpf_subprog_info *)a)->start -
3026 	       ((struct bpf_subprog_info *)b)->start;
3027 }
3028 
3029 /* Find subprogram that contains instruction at 'off' */
3030 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)
3031 {
3032 	struct bpf_subprog_info *vals = env->subprog_info;
3033 	int l, r, m;
3034 
3035 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
3036 		return NULL;
3037 
3038 	l = 0;
3039 	r = env->subprog_cnt - 1;
3040 	while (l < r) {
3041 		m = l + (r - l + 1) / 2;
3042 		if (vals[m].start <= off)
3043 			l = m;
3044 		else
3045 			r = m - 1;
3046 	}
3047 	return &vals[l];
3048 }
3049 
3050 /* Find subprogram that starts exactly at 'off' */
3051 static int find_subprog(struct bpf_verifier_env *env, int off)
3052 {
3053 	struct bpf_subprog_info *p;
3054 
3055 	p = bpf_find_containing_subprog(env, off);
3056 	if (!p || p->start != off)
3057 		return -ENOENT;
3058 	return p - env->subprog_info;
3059 }
3060 
3061 static int add_subprog(struct bpf_verifier_env *env, int off)
3062 {
3063 	int insn_cnt = env->prog->len;
3064 	int ret;
3065 
3066 	if (off >= insn_cnt || off < 0) {
3067 		verbose(env, "call to invalid destination\n");
3068 		return -EINVAL;
3069 	}
3070 	ret = find_subprog(env, off);
3071 	if (ret >= 0)
3072 		return ret;
3073 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
3074 		verbose(env, "too many subprograms\n");
3075 		return -E2BIG;
3076 	}
3077 	/* determine subprog starts. The end is one before the next starts */
3078 	env->subprog_info[env->subprog_cnt++].start = off;
3079 	sort(env->subprog_info, env->subprog_cnt,
3080 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
3081 	return env->subprog_cnt - 1;
3082 }
3083 
3084 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
3085 {
3086 	struct bpf_prog_aux *aux = env->prog->aux;
3087 	struct btf *btf = aux->btf;
3088 	const struct btf_type *t;
3089 	u32 main_btf_id, id;
3090 	const char *name;
3091 	int ret, i;
3092 
3093 	/* Non-zero func_info_cnt implies valid btf */
3094 	if (!aux->func_info_cnt)
3095 		return 0;
3096 	main_btf_id = aux->func_info[0].type_id;
3097 
3098 	t = btf_type_by_id(btf, main_btf_id);
3099 	if (!t) {
3100 		verbose(env, "invalid btf id for main subprog in func_info\n");
3101 		return -EINVAL;
3102 	}
3103 
3104 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
3105 	if (IS_ERR(name)) {
3106 		ret = PTR_ERR(name);
3107 		/* If there is no tag present, there is no exception callback */
3108 		if (ret == -ENOENT)
3109 			ret = 0;
3110 		else if (ret == -EEXIST)
3111 			verbose(env, "multiple exception callback tags for main subprog\n");
3112 		return ret;
3113 	}
3114 
3115 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
3116 	if (ret < 0) {
3117 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
3118 		return ret;
3119 	}
3120 	id = ret;
3121 	t = btf_type_by_id(btf, id);
3122 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3123 		verbose(env, "exception callback '%s' must have global linkage\n", name);
3124 		return -EINVAL;
3125 	}
3126 	ret = 0;
3127 	for (i = 0; i < aux->func_info_cnt; i++) {
3128 		if (aux->func_info[i].type_id != id)
3129 			continue;
3130 		ret = aux->func_info[i].insn_off;
3131 		/* Further func_info and subprog checks will also happen
3132 		 * later, so assume this is the right insn_off for now.
3133 		 */
3134 		if (!ret) {
3135 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
3136 			ret = -EINVAL;
3137 		}
3138 	}
3139 	if (!ret) {
3140 		verbose(env, "exception callback type id not found in func_info\n");
3141 		ret = -EINVAL;
3142 	}
3143 	return ret;
3144 }
3145 
3146 #define MAX_KFUNC_DESCS 256
3147 #define MAX_KFUNC_BTFS	256
3148 
3149 struct bpf_kfunc_desc {
3150 	struct btf_func_model func_model;
3151 	u32 func_id;
3152 	s32 imm;
3153 	u16 offset;
3154 	unsigned long addr;
3155 };
3156 
3157 struct bpf_kfunc_btf {
3158 	struct btf *btf;
3159 	struct module *module;
3160 	u16 offset;
3161 };
3162 
3163 struct bpf_kfunc_desc_tab {
3164 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
3165 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
3166 	 * available, therefore at the end of verification do_misc_fixups()
3167 	 * sorts this by imm and offset.
3168 	 */
3169 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
3170 	u32 nr_descs;
3171 };
3172 
3173 struct bpf_kfunc_btf_tab {
3174 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
3175 	u32 nr_descs;
3176 };
3177 
3178 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc,
3179 			    int insn_idx);
3180 
3181 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
3182 {
3183 	const struct bpf_kfunc_desc *d0 = a;
3184 	const struct bpf_kfunc_desc *d1 = b;
3185 
3186 	/* func_id is not greater than BTF_MAX_TYPE */
3187 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
3188 }
3189 
3190 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
3191 {
3192 	const struct bpf_kfunc_btf *d0 = a;
3193 	const struct bpf_kfunc_btf *d1 = b;
3194 
3195 	return d0->offset - d1->offset;
3196 }
3197 
3198 static struct bpf_kfunc_desc *
3199 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
3200 {
3201 	struct bpf_kfunc_desc desc = {
3202 		.func_id = func_id,
3203 		.offset = offset,
3204 	};
3205 	struct bpf_kfunc_desc_tab *tab;
3206 
3207 	tab = prog->aux->kfunc_tab;
3208 	return bsearch(&desc, tab->descs, tab->nr_descs,
3209 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
3210 }
3211 
3212 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3213 		       u16 btf_fd_idx, u8 **func_addr)
3214 {
3215 	const struct bpf_kfunc_desc *desc;
3216 
3217 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
3218 	if (!desc)
3219 		return -EFAULT;
3220 
3221 	*func_addr = (u8 *)desc->addr;
3222 	return 0;
3223 }
3224 
3225 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
3226 					 s16 offset)
3227 {
3228 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
3229 	struct bpf_kfunc_btf_tab *tab;
3230 	struct bpf_kfunc_btf *b;
3231 	struct module *mod;
3232 	struct btf *btf;
3233 	int btf_fd;
3234 
3235 	tab = env->prog->aux->kfunc_btf_tab;
3236 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
3237 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
3238 	if (!b) {
3239 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
3240 			verbose(env, "too many different module BTFs\n");
3241 			return ERR_PTR(-E2BIG);
3242 		}
3243 
3244 		if (bpfptr_is_null(env->fd_array)) {
3245 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
3246 			return ERR_PTR(-EPROTO);
3247 		}
3248 
3249 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
3250 					    offset * sizeof(btf_fd),
3251 					    sizeof(btf_fd)))
3252 			return ERR_PTR(-EFAULT);
3253 
3254 		btf = btf_get_by_fd(btf_fd);
3255 		if (IS_ERR(btf)) {
3256 			verbose(env, "invalid module BTF fd specified\n");
3257 			return btf;
3258 		}
3259 
3260 		if (!btf_is_module(btf)) {
3261 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
3262 			btf_put(btf);
3263 			return ERR_PTR(-EINVAL);
3264 		}
3265 
3266 		mod = btf_try_get_module(btf);
3267 		if (!mod) {
3268 			btf_put(btf);
3269 			return ERR_PTR(-ENXIO);
3270 		}
3271 
3272 		b = &tab->descs[tab->nr_descs++];
3273 		b->btf = btf;
3274 		b->module = mod;
3275 		b->offset = offset;
3276 
3277 		/* sort() reorders entries by value, so b may no longer point
3278 		 * to the right entry after this
3279 		 */
3280 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3281 		     kfunc_btf_cmp_by_off, NULL);
3282 	} else {
3283 		btf = b->btf;
3284 	}
3285 
3286 	return btf;
3287 }
3288 
3289 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
3290 {
3291 	if (!tab)
3292 		return;
3293 
3294 	while (tab->nr_descs--) {
3295 		module_put(tab->descs[tab->nr_descs].module);
3296 		btf_put(tab->descs[tab->nr_descs].btf);
3297 	}
3298 	kfree(tab);
3299 }
3300 
3301 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
3302 {
3303 	if (offset) {
3304 		if (offset < 0) {
3305 			/* In the future, this can be allowed to increase limit
3306 			 * of fd index into fd_array, interpreted as u16.
3307 			 */
3308 			verbose(env, "negative offset disallowed for kernel module function call\n");
3309 			return ERR_PTR(-EINVAL);
3310 		}
3311 
3312 		return __find_kfunc_desc_btf(env, offset);
3313 	}
3314 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
3315 }
3316 
3317 #define KF_IMPL_SUFFIX "_impl"
3318 
3319 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_env *env,
3320 						    struct btf *btf,
3321 						    const char *func_name)
3322 {
3323 	char *buf = env->tmp_str_buf;
3324 	const struct btf_type *func;
3325 	s32 impl_id;
3326 	int len;
3327 
3328 	len = snprintf(buf, TMP_STR_BUF_LEN, "%s%s", func_name, KF_IMPL_SUFFIX);
3329 	if (len < 0 || len >= TMP_STR_BUF_LEN) {
3330 		verbose(env, "function name %s%s is too long\n", func_name, KF_IMPL_SUFFIX);
3331 		return NULL;
3332 	}
3333 
3334 	impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC);
3335 	if (impl_id <= 0) {
3336 		verbose(env, "cannot find function %s in BTF\n", buf);
3337 		return NULL;
3338 	}
3339 
3340 	func = btf_type_by_id(btf, impl_id);
3341 
3342 	return btf_type_by_id(btf, func->type);
3343 }
3344 
3345 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
3346 			    s32 func_id,
3347 			    s16 offset,
3348 			    struct bpf_kfunc_meta *kfunc)
3349 {
3350 	const struct btf_type *func, *func_proto;
3351 	const char *func_name;
3352 	u32 *kfunc_flags;
3353 	struct btf *btf;
3354 
3355 	if (func_id <= 0) {
3356 		verbose(env, "invalid kernel function btf_id %d\n", func_id);
3357 		return -EINVAL;
3358 	}
3359 
3360 	btf = find_kfunc_desc_btf(env, offset);
3361 	if (IS_ERR(btf)) {
3362 		verbose(env, "failed to find BTF for kernel function\n");
3363 		return PTR_ERR(btf);
3364 	}
3365 
3366 	/*
3367 	 * Note that kfunc_flags may be NULL at this point, which
3368 	 * means that we couldn't find func_id in any relevant
3369 	 * kfunc_id_set. This most likely indicates an invalid kfunc
3370 	 * call.  However we don't fail with an error here,
3371 	 * and let the caller decide what to do with NULL kfunc->flags.
3372 	 */
3373 	kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog);
3374 
3375 	func = btf_type_by_id(btf, func_id);
3376 	if (!func || !btf_type_is_func(func)) {
3377 		verbose(env, "kernel btf_id %d is not a function\n", func_id);
3378 		return -EINVAL;
3379 	}
3380 
3381 	func_name = btf_name_by_offset(btf, func->name_off);
3382 
3383 	/*
3384 	 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag
3385 	 * can be found through the counterpart _impl kfunc.
3386 	 */
3387 	if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS))
3388 		func_proto = find_kfunc_impl_proto(env, btf, func_name);
3389 	else
3390 		func_proto = btf_type_by_id(btf, func->type);
3391 
3392 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3393 		verbose(env, "kernel function btf_id %d does not have a valid func_proto\n",
3394 			func_id);
3395 		return -EINVAL;
3396 	}
3397 
3398 	memset(kfunc, 0, sizeof(*kfunc));
3399 	kfunc->btf = btf;
3400 	kfunc->id = func_id;
3401 	kfunc->name = func_name;
3402 	kfunc->proto = func_proto;
3403 	kfunc->flags = kfunc_flags;
3404 
3405 	return 0;
3406 }
3407 
3408 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
3409 {
3410 	struct bpf_kfunc_btf_tab *btf_tab;
3411 	struct btf_func_model func_model;
3412 	struct bpf_kfunc_desc_tab *tab;
3413 	struct bpf_prog_aux *prog_aux;
3414 	struct bpf_kfunc_meta kfunc;
3415 	struct bpf_kfunc_desc *desc;
3416 	unsigned long addr;
3417 	int err;
3418 
3419 	prog_aux = env->prog->aux;
3420 	tab = prog_aux->kfunc_tab;
3421 	btf_tab = prog_aux->kfunc_btf_tab;
3422 	if (!tab) {
3423 		if (!btf_vmlinux) {
3424 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3425 			return -ENOTSUPP;
3426 		}
3427 
3428 		if (!env->prog->jit_requested) {
3429 			verbose(env, "JIT is required for calling kernel function\n");
3430 			return -ENOTSUPP;
3431 		}
3432 
3433 		if (!bpf_jit_supports_kfunc_call()) {
3434 			verbose(env, "JIT does not support calling kernel function\n");
3435 			return -ENOTSUPP;
3436 		}
3437 
3438 		if (!env->prog->gpl_compatible) {
3439 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3440 			return -EINVAL;
3441 		}
3442 
3443 		tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT);
3444 		if (!tab)
3445 			return -ENOMEM;
3446 		prog_aux->kfunc_tab = tab;
3447 	}
3448 
3449 	/* func_id == 0 is always invalid, but instead of returning an error, be
3450 	 * conservative and wait until the code elimination pass before returning
3451 	 * error, so that invalid calls that get pruned out can be in BPF programs
3452 	 * loaded from userspace.  It is also required that offset be untouched
3453 	 * for such calls.
3454 	 */
3455 	if (!func_id && !offset)
3456 		return 0;
3457 
3458 	if (!btf_tab && offset) {
3459 		btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT);
3460 		if (!btf_tab)
3461 			return -ENOMEM;
3462 		prog_aux->kfunc_btf_tab = btf_tab;
3463 	}
3464 
3465 	if (find_kfunc_desc(env->prog, func_id, offset))
3466 		return 0;
3467 
3468 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
3469 		verbose(env, "too many different kernel function calls\n");
3470 		return -E2BIG;
3471 	}
3472 
3473 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
3474 	if (err)
3475 		return err;
3476 
3477 	addr = kallsyms_lookup_name(kfunc.name);
3478 	if (!addr) {
3479 		verbose(env, "cannot find address for kernel function %s\n", kfunc.name);
3480 		return -EINVAL;
3481 	}
3482 
3483 	if (bpf_dev_bound_kfunc_id(func_id)) {
3484 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3485 		if (err)
3486 			return err;
3487 	}
3488 
3489 	err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model);
3490 	if (err)
3491 		return err;
3492 
3493 	desc = &tab->descs[tab->nr_descs++];
3494 	desc->func_id = func_id;
3495 	desc->offset = offset;
3496 	desc->addr = addr;
3497 	desc->func_model = func_model;
3498 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3499 	     kfunc_desc_cmp_by_id_off, NULL);
3500 	return 0;
3501 }
3502 
3503 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3504 {
3505 	const struct bpf_kfunc_desc *d0 = a;
3506 	const struct bpf_kfunc_desc *d1 = b;
3507 
3508 	if (d0->imm != d1->imm)
3509 		return d0->imm < d1->imm ? -1 : 1;
3510 	if (d0->offset != d1->offset)
3511 		return d0->offset < d1->offset ? -1 : 1;
3512 	return 0;
3513 }
3514 
3515 static int set_kfunc_desc_imm(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc)
3516 {
3517 	unsigned long call_imm;
3518 
3519 	if (bpf_jit_supports_far_kfunc_call()) {
3520 		call_imm = desc->func_id;
3521 	} else {
3522 		call_imm = BPF_CALL_IMM(desc->addr);
3523 		/* Check whether the relative offset overflows desc->imm */
3524 		if ((unsigned long)(s32)call_imm != call_imm) {
3525 			verbose(env, "address of kernel func_id %u is out of range\n",
3526 				desc->func_id);
3527 			return -EINVAL;
3528 		}
3529 	}
3530 	desc->imm = call_imm;
3531 	return 0;
3532 }
3533 
3534 static int sort_kfunc_descs_by_imm_off(struct bpf_verifier_env *env)
3535 {
3536 	struct bpf_kfunc_desc_tab *tab;
3537 	int i, err;
3538 
3539 	tab = env->prog->aux->kfunc_tab;
3540 	if (!tab)
3541 		return 0;
3542 
3543 	for (i = 0; i < tab->nr_descs; i++) {
3544 		err = set_kfunc_desc_imm(env, &tab->descs[i]);
3545 		if (err)
3546 			return err;
3547 	}
3548 
3549 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3550 	     kfunc_desc_cmp_by_imm_off, NULL);
3551 	return 0;
3552 }
3553 
3554 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3555 {
3556 	return !!prog->aux->kfunc_tab;
3557 }
3558 
3559 const struct btf_func_model *
3560 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3561 			 const struct bpf_insn *insn)
3562 {
3563 	const struct bpf_kfunc_desc desc = {
3564 		.imm = insn->imm,
3565 		.offset = insn->off,
3566 	};
3567 	const struct bpf_kfunc_desc *res;
3568 	struct bpf_kfunc_desc_tab *tab;
3569 
3570 	tab = prog->aux->kfunc_tab;
3571 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3572 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3573 
3574 	return res ? &res->func_model : NULL;
3575 }
3576 
3577 static int add_kfunc_in_insns(struct bpf_verifier_env *env,
3578 			      struct bpf_insn *insn, int cnt)
3579 {
3580 	int i, ret;
3581 
3582 	for (i = 0; i < cnt; i++, insn++) {
3583 		if (bpf_pseudo_kfunc_call(insn)) {
3584 			ret = add_kfunc_call(env, insn->imm, insn->off);
3585 			if (ret < 0)
3586 				return ret;
3587 		}
3588 	}
3589 	return 0;
3590 }
3591 
3592 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3593 {
3594 	struct bpf_subprog_info *subprog = env->subprog_info;
3595 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3596 	struct bpf_insn *insn = env->prog->insnsi;
3597 
3598 	/* Add entry function. */
3599 	ret = add_subprog(env, 0);
3600 	if (ret)
3601 		return ret;
3602 
3603 	for (i = 0; i < insn_cnt; i++, insn++) {
3604 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3605 		    !bpf_pseudo_kfunc_call(insn))
3606 			continue;
3607 
3608 		if (!env->bpf_capable) {
3609 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3610 			return -EPERM;
3611 		}
3612 
3613 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3614 			ret = add_subprog(env, i + insn->imm + 1);
3615 		else
3616 			ret = add_kfunc_call(env, insn->imm, insn->off);
3617 
3618 		if (ret < 0)
3619 			return ret;
3620 	}
3621 
3622 	ret = bpf_find_exception_callback_insn_off(env);
3623 	if (ret < 0)
3624 		return ret;
3625 	ex_cb_insn = ret;
3626 
3627 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3628 	 * marked using BTF decl tag to serve as the exception callback.
3629 	 */
3630 	if (ex_cb_insn) {
3631 		ret = add_subprog(env, ex_cb_insn);
3632 		if (ret < 0)
3633 			return ret;
3634 		for (i = 1; i < env->subprog_cnt; i++) {
3635 			if (env->subprog_info[i].start != ex_cb_insn)
3636 				continue;
3637 			env->exception_callback_subprog = i;
3638 			mark_subprog_exc_cb(env, i);
3639 			break;
3640 		}
3641 	}
3642 
3643 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3644 	 * logic. 'subprog_cnt' should not be increased.
3645 	 */
3646 	subprog[env->subprog_cnt].start = insn_cnt;
3647 
3648 	if (env->log.level & BPF_LOG_LEVEL2)
3649 		for (i = 0; i < env->subprog_cnt; i++)
3650 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3651 
3652 	return 0;
3653 }
3654 
3655 static int check_subprogs(struct bpf_verifier_env *env)
3656 {
3657 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3658 	struct bpf_subprog_info *subprog = env->subprog_info;
3659 	struct bpf_insn *insn = env->prog->insnsi;
3660 	int insn_cnt = env->prog->len;
3661 
3662 	/* now check that all jumps are within the same subprog */
3663 	subprog_start = subprog[cur_subprog].start;
3664 	subprog_end = subprog[cur_subprog + 1].start;
3665 	for (i = 0; i < insn_cnt; i++) {
3666 		u8 code = insn[i].code;
3667 
3668 		if (code == (BPF_JMP | BPF_CALL) &&
3669 		    insn[i].src_reg == 0 &&
3670 		    insn[i].imm == BPF_FUNC_tail_call) {
3671 			subprog[cur_subprog].has_tail_call = true;
3672 			subprog[cur_subprog].tail_call_reachable = true;
3673 		}
3674 		if (BPF_CLASS(code) == BPF_LD &&
3675 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3676 			subprog[cur_subprog].has_ld_abs = true;
3677 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3678 			goto next;
3679 		if (BPF_OP(code) == BPF_CALL)
3680 			goto next;
3681 		if (BPF_OP(code) == BPF_EXIT) {
3682 			subprog[cur_subprog].exit_idx = i;
3683 			goto next;
3684 		}
3685 		off = i + bpf_jmp_offset(&insn[i]) + 1;
3686 		if (off < subprog_start || off >= subprog_end) {
3687 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3688 			return -EINVAL;
3689 		}
3690 next:
3691 		if (i == subprog_end - 1) {
3692 			/* to avoid fall-through from one subprog into another
3693 			 * the last insn of the subprog should be either exit
3694 			 * or unconditional jump back or bpf_throw call
3695 			 */
3696 			if (code != (BPF_JMP | BPF_EXIT) &&
3697 			    code != (BPF_JMP32 | BPF_JA) &&
3698 			    code != (BPF_JMP | BPF_JA)) {
3699 				verbose(env, "last insn is not an exit or jmp\n");
3700 				return -EINVAL;
3701 			}
3702 			subprog_start = subprog_end;
3703 			cur_subprog++;
3704 			if (cur_subprog < env->subprog_cnt)
3705 				subprog_end = subprog[cur_subprog + 1].start;
3706 		}
3707 	}
3708 	return 0;
3709 }
3710 
3711 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3712 				    int spi, int nr_slots)
3713 {
3714 	int err, i;
3715 
3716 	for (i = 0; i < nr_slots; i++) {
3717 		err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi - i));
3718 		if (err)
3719 			return err;
3720 		mark_stack_slot_scratched(env, spi - i);
3721 	}
3722 	return 0;
3723 }
3724 
3725 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3726 {
3727 	int spi;
3728 
3729 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3730 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3731 	 * check_kfunc_call.
3732 	 */
3733 	if (reg->type == CONST_PTR_TO_DYNPTR)
3734 		return 0;
3735 	spi = dynptr_get_spi(env, reg);
3736 	if (spi < 0)
3737 		return spi;
3738 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3739 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3740 	 * read.
3741 	 */
3742 	return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS);
3743 }
3744 
3745 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3746 			  int spi, int nr_slots)
3747 {
3748 	return mark_stack_slot_obj_read(env, reg, spi, nr_slots);
3749 }
3750 
3751 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3752 {
3753 	int spi;
3754 
3755 	spi = irq_flag_get_spi(env, reg);
3756 	if (spi < 0)
3757 		return spi;
3758 	return mark_stack_slot_obj_read(env, reg, spi, 1);
3759 }
3760 
3761 /* This function is supposed to be used by the following 32-bit optimization
3762  * code only. It returns TRUE if the source or destination register operates
3763  * on 64-bit, otherwise return FALSE.
3764  */
3765 static bool is_reg64(struct bpf_insn *insn,
3766 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3767 {
3768 	u8 code, class, op;
3769 
3770 	code = insn->code;
3771 	class = BPF_CLASS(code);
3772 	op = BPF_OP(code);
3773 	if (class == BPF_JMP) {
3774 		/* BPF_EXIT for "main" will reach here. Return TRUE
3775 		 * conservatively.
3776 		 */
3777 		if (op == BPF_EXIT)
3778 			return true;
3779 		if (op == BPF_CALL) {
3780 			/* BPF to BPF call will reach here because of marking
3781 			 * caller saved clobber with DST_OP_NO_MARK for which we
3782 			 * don't care the register def because they are anyway
3783 			 * marked as NOT_INIT already.
3784 			 */
3785 			if (insn->src_reg == BPF_PSEUDO_CALL)
3786 				return false;
3787 			/* Helper call will reach here because of arg type
3788 			 * check, conservatively return TRUE.
3789 			 */
3790 			if (t == SRC_OP)
3791 				return true;
3792 
3793 			return false;
3794 		}
3795 	}
3796 
3797 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3798 		return false;
3799 
3800 	if (class == BPF_ALU64 || class == BPF_JMP ||
3801 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3802 		return true;
3803 
3804 	if (class == BPF_ALU || class == BPF_JMP32)
3805 		return false;
3806 
3807 	if (class == BPF_LDX) {
3808 		if (t != SRC_OP)
3809 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3810 		/* LDX source must be ptr. */
3811 		return true;
3812 	}
3813 
3814 	if (class == BPF_STX) {
3815 		/* BPF_STX (including atomic variants) has one or more source
3816 		 * operands, one of which is a ptr. Check whether the caller is
3817 		 * asking about it.
3818 		 */
3819 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3820 			return true;
3821 		return BPF_SIZE(code) == BPF_DW;
3822 	}
3823 
3824 	if (class == BPF_LD) {
3825 		u8 mode = BPF_MODE(code);
3826 
3827 		/* LD_IMM64 */
3828 		if (mode == BPF_IMM)
3829 			return true;
3830 
3831 		/* Both LD_IND and LD_ABS return 32-bit data. */
3832 		if (t != SRC_OP)
3833 			return  false;
3834 
3835 		/* Implicit ctx ptr. */
3836 		if (regno == BPF_REG_6)
3837 			return true;
3838 
3839 		/* Explicit source could be any width. */
3840 		return true;
3841 	}
3842 
3843 	if (class == BPF_ST)
3844 		/* The only source register for BPF_ST is a ptr. */
3845 		return true;
3846 
3847 	/* Conservatively return true at default. */
3848 	return true;
3849 }
3850 
3851 /* Return the regno defined by the insn, or -1. */
3852 static int insn_def_regno(const struct bpf_insn *insn)
3853 {
3854 	switch (BPF_CLASS(insn->code)) {
3855 	case BPF_JMP:
3856 	case BPF_JMP32:
3857 	case BPF_ST:
3858 		return -1;
3859 	case BPF_STX:
3860 		if (BPF_MODE(insn->code) == BPF_ATOMIC ||
3861 		    BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) {
3862 			if (insn->imm == BPF_CMPXCHG)
3863 				return BPF_REG_0;
3864 			else if (insn->imm == BPF_LOAD_ACQ)
3865 				return insn->dst_reg;
3866 			else if (insn->imm & BPF_FETCH)
3867 				return insn->src_reg;
3868 		}
3869 		return -1;
3870 	default:
3871 		return insn->dst_reg;
3872 	}
3873 }
3874 
3875 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3876 static bool insn_has_def32(struct bpf_insn *insn)
3877 {
3878 	int dst_reg = insn_def_regno(insn);
3879 
3880 	if (dst_reg == -1)
3881 		return false;
3882 
3883 	return !is_reg64(insn, dst_reg, NULL, DST_OP);
3884 }
3885 
3886 static void mark_insn_zext(struct bpf_verifier_env *env,
3887 			   struct bpf_reg_state *reg)
3888 {
3889 	s32 def_idx = reg->subreg_def;
3890 
3891 	if (def_idx == DEF_NOT_SUBREG)
3892 		return;
3893 
3894 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3895 	/* The dst will be zero extended, so won't be sub-register anymore. */
3896 	reg->subreg_def = DEF_NOT_SUBREG;
3897 }
3898 
3899 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3900 			   enum reg_arg_type t)
3901 {
3902 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3903 	struct bpf_reg_state *reg;
3904 	bool rw64;
3905 
3906 	if (regno >= MAX_BPF_REG) {
3907 		verbose(env, "R%d is invalid\n", regno);
3908 		return -EINVAL;
3909 	}
3910 
3911 	mark_reg_scratched(env, regno);
3912 
3913 	reg = &regs[regno];
3914 	rw64 = is_reg64(insn, regno, reg, t);
3915 	if (t == SRC_OP) {
3916 		/* check whether register used as source operand can be read */
3917 		if (reg->type == NOT_INIT) {
3918 			verbose(env, "R%d !read_ok\n", regno);
3919 			return -EACCES;
3920 		}
3921 		/* We don't need to worry about FP liveness because it's read-only */
3922 		if (regno == BPF_REG_FP)
3923 			return 0;
3924 
3925 		if (rw64)
3926 			mark_insn_zext(env, reg);
3927 
3928 		return 0;
3929 	} else {
3930 		/* check whether register used as dest operand can be written to */
3931 		if (regno == BPF_REG_FP) {
3932 			verbose(env, "frame pointer is read only\n");
3933 			return -EACCES;
3934 		}
3935 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3936 		if (t == DST_OP)
3937 			mark_reg_unknown(env, regs, regno);
3938 	}
3939 	return 0;
3940 }
3941 
3942 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3943 			 enum reg_arg_type t)
3944 {
3945 	struct bpf_verifier_state *vstate = env->cur_state;
3946 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3947 
3948 	return __check_reg_arg(env, state->regs, regno, t);
3949 }
3950 
3951 static int insn_stack_access_flags(int frameno, int spi)
3952 {
3953 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3954 }
3955 
3956 static int insn_stack_access_spi(int insn_flags)
3957 {
3958 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3959 }
3960 
3961 static int insn_stack_access_frameno(int insn_flags)
3962 {
3963 	return insn_flags & INSN_F_FRAMENO_MASK;
3964 }
3965 
3966 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3967 {
3968 	env->insn_aux_data[idx].jmp_point = true;
3969 }
3970 
3971 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3972 {
3973 	return env->insn_aux_data[insn_idx].jmp_point;
3974 }
3975 
3976 #define LR_FRAMENO_BITS	3
3977 #define LR_SPI_BITS	6
3978 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3979 #define LR_SIZE_BITS	4
3980 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3981 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3982 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3983 #define LR_SPI_OFF	LR_FRAMENO_BITS
3984 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3985 #define LINKED_REGS_MAX	6
3986 
3987 struct linked_reg {
3988 	u8 frameno;
3989 	union {
3990 		u8 spi;
3991 		u8 regno;
3992 	};
3993 	bool is_reg;
3994 };
3995 
3996 struct linked_regs {
3997 	int cnt;
3998 	struct linked_reg entries[LINKED_REGS_MAX];
3999 };
4000 
4001 static struct linked_reg *linked_regs_push(struct linked_regs *s)
4002 {
4003 	if (s->cnt < LINKED_REGS_MAX)
4004 		return &s->entries[s->cnt++];
4005 
4006 	return NULL;
4007 }
4008 
4009 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
4010  * number of elements currently in stack.
4011  * Pack one history entry for linked registers as 10 bits in the following format:
4012  * - 3-bits frameno
4013  * - 6-bits spi_or_reg
4014  * - 1-bit  is_reg
4015  */
4016 static u64 linked_regs_pack(struct linked_regs *s)
4017 {
4018 	u64 val = 0;
4019 	int i;
4020 
4021 	for (i = 0; i < s->cnt; ++i) {
4022 		struct linked_reg *e = &s->entries[i];
4023 		u64 tmp = 0;
4024 
4025 		tmp |= e->frameno;
4026 		tmp |= e->spi << LR_SPI_OFF;
4027 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
4028 
4029 		val <<= LR_ENTRY_BITS;
4030 		val |= tmp;
4031 	}
4032 	val <<= LR_SIZE_BITS;
4033 	val |= s->cnt;
4034 	return val;
4035 }
4036 
4037 static void linked_regs_unpack(u64 val, struct linked_regs *s)
4038 {
4039 	int i;
4040 
4041 	s->cnt = val & LR_SIZE_MASK;
4042 	val >>= LR_SIZE_BITS;
4043 
4044 	for (i = 0; i < s->cnt; ++i) {
4045 		struct linked_reg *e = &s->entries[i];
4046 
4047 		e->frameno =  val & LR_FRAMENO_MASK;
4048 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
4049 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
4050 		val >>= LR_ENTRY_BITS;
4051 	}
4052 }
4053 
4054 /* for any branch, call, exit record the history of jmps in the given state */
4055 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
4056 			    int insn_flags, u64 linked_regs)
4057 {
4058 	u32 cnt = cur->jmp_history_cnt;
4059 	struct bpf_jmp_history_entry *p;
4060 	size_t alloc_size;
4061 
4062 	/* combine instruction flags if we already recorded this instruction */
4063 	if (env->cur_hist_ent) {
4064 		/* atomic instructions push insn_flags twice, for READ and
4065 		 * WRITE sides, but they should agree on stack slot
4066 		 */
4067 		verifier_bug_if((env->cur_hist_ent->flags & insn_flags) &&
4068 				(env->cur_hist_ent->flags & insn_flags) != insn_flags,
4069 				env, "insn history: insn_idx %d cur flags %x new flags %x",
4070 				env->insn_idx, env->cur_hist_ent->flags, insn_flags);
4071 		env->cur_hist_ent->flags |= insn_flags;
4072 		verifier_bug_if(env->cur_hist_ent->linked_regs != 0, env,
4073 				"insn history: insn_idx %d linked_regs: %#llx",
4074 				env->insn_idx, env->cur_hist_ent->linked_regs);
4075 		env->cur_hist_ent->linked_regs = linked_regs;
4076 		return 0;
4077 	}
4078 
4079 	cnt++;
4080 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
4081 	p = krealloc(cur->jmp_history, alloc_size, GFP_KERNEL_ACCOUNT);
4082 	if (!p)
4083 		return -ENOMEM;
4084 	cur->jmp_history = p;
4085 
4086 	p = &cur->jmp_history[cnt - 1];
4087 	p->idx = env->insn_idx;
4088 	p->prev_idx = env->prev_insn_idx;
4089 	p->flags = insn_flags;
4090 	p->linked_regs = linked_regs;
4091 	cur->jmp_history_cnt = cnt;
4092 	env->cur_hist_ent = p;
4093 
4094 	return 0;
4095 }
4096 
4097 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
4098 						        u32 hist_end, int insn_idx)
4099 {
4100 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
4101 		return &st->jmp_history[hist_end - 1];
4102 	return NULL;
4103 }
4104 
4105 /* Backtrack one insn at a time. If idx is not at the top of recorded
4106  * history then previous instruction came from straight line execution.
4107  * Return -ENOENT if we exhausted all instructions within given state.
4108  *
4109  * It's legal to have a bit of a looping with the same starting and ending
4110  * insn index within the same state, e.g.: 3->4->5->3, so just because current
4111  * instruction index is the same as state's first_idx doesn't mean we are
4112  * done. If there is still some jump history left, we should keep going. We
4113  * need to take into account that we might have a jump history between given
4114  * state's parent and itself, due to checkpointing. In this case, we'll have
4115  * history entry recording a jump from last instruction of parent state and
4116  * first instruction of given state.
4117  */
4118 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
4119 			     u32 *history)
4120 {
4121 	u32 cnt = *history;
4122 
4123 	if (i == st->first_insn_idx) {
4124 		if (cnt == 0)
4125 			return -ENOENT;
4126 		if (cnt == 1 && st->jmp_history[0].idx == i)
4127 			return -ENOENT;
4128 	}
4129 
4130 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
4131 		i = st->jmp_history[cnt - 1].prev_idx;
4132 		(*history)--;
4133 	} else {
4134 		i--;
4135 	}
4136 	return i;
4137 }
4138 
4139 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
4140 {
4141 	const struct btf_type *func;
4142 	struct btf *desc_btf;
4143 
4144 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
4145 		return NULL;
4146 
4147 	desc_btf = find_kfunc_desc_btf(data, insn->off);
4148 	if (IS_ERR(desc_btf))
4149 		return "<error>";
4150 
4151 	func = btf_type_by_id(desc_btf, insn->imm);
4152 	return btf_name_by_offset(desc_btf, func->name_off);
4153 }
4154 
4155 static void verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
4156 {
4157 	const struct bpf_insn_cbs cbs = {
4158 		.cb_call	= disasm_kfunc_name,
4159 		.cb_print	= verbose,
4160 		.private_data	= env,
4161 	};
4162 
4163 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
4164 }
4165 
4166 static inline void bt_init(struct backtrack_state *bt, u32 frame)
4167 {
4168 	bt->frame = frame;
4169 }
4170 
4171 static inline void bt_reset(struct backtrack_state *bt)
4172 {
4173 	struct bpf_verifier_env *env = bt->env;
4174 
4175 	memset(bt, 0, sizeof(*bt));
4176 	bt->env = env;
4177 }
4178 
4179 static inline u32 bt_empty(struct backtrack_state *bt)
4180 {
4181 	u64 mask = 0;
4182 	int i;
4183 
4184 	for (i = 0; i <= bt->frame; i++)
4185 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
4186 
4187 	return mask == 0;
4188 }
4189 
4190 static inline int bt_subprog_enter(struct backtrack_state *bt)
4191 {
4192 	if (bt->frame == MAX_CALL_FRAMES - 1) {
4193 		verifier_bug(bt->env, "subprog enter from frame %d", bt->frame);
4194 		return -EFAULT;
4195 	}
4196 	bt->frame++;
4197 	return 0;
4198 }
4199 
4200 static inline int bt_subprog_exit(struct backtrack_state *bt)
4201 {
4202 	if (bt->frame == 0) {
4203 		verifier_bug(bt->env, "subprog exit from frame 0");
4204 		return -EFAULT;
4205 	}
4206 	bt->frame--;
4207 	return 0;
4208 }
4209 
4210 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4211 {
4212 	bt->reg_masks[frame] |= 1 << reg;
4213 }
4214 
4215 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4216 {
4217 	bt->reg_masks[frame] &= ~(1 << reg);
4218 }
4219 
4220 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
4221 {
4222 	bt_set_frame_reg(bt, bt->frame, reg);
4223 }
4224 
4225 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
4226 {
4227 	bt_clear_frame_reg(bt, bt->frame, reg);
4228 }
4229 
4230 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4231 {
4232 	bt->stack_masks[frame] |= 1ull << slot;
4233 }
4234 
4235 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4236 {
4237 	bt->stack_masks[frame] &= ~(1ull << slot);
4238 }
4239 
4240 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
4241 {
4242 	return bt->reg_masks[frame];
4243 }
4244 
4245 static inline u32 bt_reg_mask(struct backtrack_state *bt)
4246 {
4247 	return bt->reg_masks[bt->frame];
4248 }
4249 
4250 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
4251 {
4252 	return bt->stack_masks[frame];
4253 }
4254 
4255 static inline u64 bt_stack_mask(struct backtrack_state *bt)
4256 {
4257 	return bt->stack_masks[bt->frame];
4258 }
4259 
4260 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
4261 {
4262 	return bt->reg_masks[bt->frame] & (1 << reg);
4263 }
4264 
4265 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
4266 {
4267 	return bt->reg_masks[frame] & (1 << reg);
4268 }
4269 
4270 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
4271 {
4272 	return bt->stack_masks[frame] & (1ull << slot);
4273 }
4274 
4275 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
4276 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
4277 {
4278 	DECLARE_BITMAP(mask, 64);
4279 	bool first = true;
4280 	int i, n;
4281 
4282 	buf[0] = '\0';
4283 
4284 	bitmap_from_u64(mask, reg_mask);
4285 	for_each_set_bit(i, mask, 32) {
4286 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
4287 		first = false;
4288 		buf += n;
4289 		buf_sz -= n;
4290 		if (buf_sz < 0)
4291 			break;
4292 	}
4293 }
4294 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
4295 void bpf_fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
4296 {
4297 	DECLARE_BITMAP(mask, 64);
4298 	bool first = true;
4299 	int i, n;
4300 
4301 	buf[0] = '\0';
4302 
4303 	bitmap_from_u64(mask, stack_mask);
4304 	for_each_set_bit(i, mask, 64) {
4305 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
4306 		first = false;
4307 		buf += n;
4308 		buf_sz -= n;
4309 		if (buf_sz < 0)
4310 			break;
4311 	}
4312 }
4313 
4314 /* If any register R in hist->linked_regs is marked as precise in bt,
4315  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
4316  */
4317 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
4318 {
4319 	struct linked_regs linked_regs;
4320 	bool some_precise = false;
4321 	int i;
4322 
4323 	if (!hist || hist->linked_regs == 0)
4324 		return;
4325 
4326 	linked_regs_unpack(hist->linked_regs, &linked_regs);
4327 	for (i = 0; i < linked_regs.cnt; ++i) {
4328 		struct linked_reg *e = &linked_regs.entries[i];
4329 
4330 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
4331 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
4332 			some_precise = true;
4333 			break;
4334 		}
4335 	}
4336 
4337 	if (!some_precise)
4338 		return;
4339 
4340 	for (i = 0; i < linked_regs.cnt; ++i) {
4341 		struct linked_reg *e = &linked_regs.entries[i];
4342 
4343 		if (e->is_reg)
4344 			bt_set_frame_reg(bt, e->frameno, e->regno);
4345 		else
4346 			bt_set_frame_slot(bt, e->frameno, e->spi);
4347 	}
4348 }
4349 
4350 /* For given verifier state backtrack_insn() is called from the last insn to
4351  * the first insn. Its purpose is to compute a bitmask of registers and
4352  * stack slots that needs precision in the parent verifier state.
4353  *
4354  * @idx is an index of the instruction we are currently processing;
4355  * @subseq_idx is an index of the subsequent instruction that:
4356  *   - *would be* executed next, if jump history is viewed in forward order;
4357  *   - *was* processed previously during backtracking.
4358  */
4359 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
4360 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
4361 {
4362 	struct bpf_insn *insn = env->prog->insnsi + idx;
4363 	u8 class = BPF_CLASS(insn->code);
4364 	u8 opcode = BPF_OP(insn->code);
4365 	u8 mode = BPF_MODE(insn->code);
4366 	u32 dreg = insn->dst_reg;
4367 	u32 sreg = insn->src_reg;
4368 	u32 spi, i, fr;
4369 
4370 	if (insn->code == 0)
4371 		return 0;
4372 	if (env->log.level & BPF_LOG_LEVEL2) {
4373 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
4374 		verbose(env, "mark_precise: frame%d: regs=%s ",
4375 			bt->frame, env->tmp_str_buf);
4376 		bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
4377 		verbose(env, "stack=%s before ", env->tmp_str_buf);
4378 		verbose(env, "%d: ", idx);
4379 		verbose_insn(env, insn);
4380 	}
4381 
4382 	/* If there is a history record that some registers gained range at this insn,
4383 	 * propagate precision marks to those registers, so that bt_is_reg_set()
4384 	 * accounts for these registers.
4385 	 */
4386 	bt_sync_linked_regs(bt, hist);
4387 
4388 	if (class == BPF_ALU || class == BPF_ALU64) {
4389 		if (!bt_is_reg_set(bt, dreg))
4390 			return 0;
4391 		if (opcode == BPF_END || opcode == BPF_NEG) {
4392 			/* sreg is reserved and unused
4393 			 * dreg still need precision before this insn
4394 			 */
4395 			return 0;
4396 		} else if (opcode == BPF_MOV) {
4397 			if (BPF_SRC(insn->code) == BPF_X) {
4398 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
4399 				 * dreg needs precision after this insn
4400 				 * sreg needs precision before this insn
4401 				 */
4402 				bt_clear_reg(bt, dreg);
4403 				if (sreg != BPF_REG_FP)
4404 					bt_set_reg(bt, sreg);
4405 			} else {
4406 				/* dreg = K
4407 				 * dreg needs precision after this insn.
4408 				 * Corresponding register is already marked
4409 				 * as precise=true in this verifier state.
4410 				 * No further markings in parent are necessary
4411 				 */
4412 				bt_clear_reg(bt, dreg);
4413 			}
4414 		} else {
4415 			if (BPF_SRC(insn->code) == BPF_X) {
4416 				/* dreg += sreg
4417 				 * both dreg and sreg need precision
4418 				 * before this insn
4419 				 */
4420 				if (sreg != BPF_REG_FP)
4421 					bt_set_reg(bt, sreg);
4422 			} /* else dreg += K
4423 			   * dreg still needs precision before this insn
4424 			   */
4425 		}
4426 	} else if (class == BPF_LDX || is_atomic_load_insn(insn)) {
4427 		if (!bt_is_reg_set(bt, dreg))
4428 			return 0;
4429 		bt_clear_reg(bt, dreg);
4430 
4431 		/* scalars can only be spilled into stack w/o losing precision.
4432 		 * Load from any other memory can be zero extended.
4433 		 * The desire to keep that precision is already indicated
4434 		 * by 'precise' mark in corresponding register of this state.
4435 		 * No further tracking necessary.
4436 		 */
4437 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4438 			return 0;
4439 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
4440 		 * that [fp - off] slot contains scalar that needs to be
4441 		 * tracked with precision
4442 		 */
4443 		spi = insn_stack_access_spi(hist->flags);
4444 		fr = insn_stack_access_frameno(hist->flags);
4445 		bt_set_frame_slot(bt, fr, spi);
4446 	} else if (class == BPF_STX || class == BPF_ST) {
4447 		if (bt_is_reg_set(bt, dreg))
4448 			/* stx & st shouldn't be using _scalar_ dst_reg
4449 			 * to access memory. It means backtracking
4450 			 * encountered a case of pointer subtraction.
4451 			 */
4452 			return -ENOTSUPP;
4453 		/* scalars can only be spilled into stack */
4454 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4455 			return 0;
4456 		spi = insn_stack_access_spi(hist->flags);
4457 		fr = insn_stack_access_frameno(hist->flags);
4458 		if (!bt_is_frame_slot_set(bt, fr, spi))
4459 			return 0;
4460 		bt_clear_frame_slot(bt, fr, spi);
4461 		if (class == BPF_STX)
4462 			bt_set_reg(bt, sreg);
4463 	} else if (class == BPF_JMP || class == BPF_JMP32) {
4464 		if (bpf_pseudo_call(insn)) {
4465 			int subprog_insn_idx, subprog;
4466 
4467 			subprog_insn_idx = idx + insn->imm + 1;
4468 			subprog = find_subprog(env, subprog_insn_idx);
4469 			if (subprog < 0)
4470 				return -EFAULT;
4471 
4472 			if (subprog_is_global(env, subprog)) {
4473 				/* check that jump history doesn't have any
4474 				 * extra instructions from subprog; the next
4475 				 * instruction after call to global subprog
4476 				 * should be literally next instruction in
4477 				 * caller program
4478 				 */
4479 				verifier_bug_if(idx + 1 != subseq_idx, env,
4480 						"extra insn from subprog");
4481 				/* r1-r5 are invalidated after subprog call,
4482 				 * so for global func call it shouldn't be set
4483 				 * anymore
4484 				 */
4485 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4486 					verifier_bug(env, "global subprog unexpected regs %x",
4487 						     bt_reg_mask(bt));
4488 					return -EFAULT;
4489 				}
4490 				/* global subprog always sets R0 */
4491 				bt_clear_reg(bt, BPF_REG_0);
4492 				return 0;
4493 			} else {
4494 				/* static subprog call instruction, which
4495 				 * means that we are exiting current subprog,
4496 				 * so only r1-r5 could be still requested as
4497 				 * precise, r0 and r6-r10 or any stack slot in
4498 				 * the current frame should be zero by now
4499 				 */
4500 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4501 					verifier_bug(env, "static subprog unexpected regs %x",
4502 						     bt_reg_mask(bt));
4503 					return -EFAULT;
4504 				}
4505 				/* we are now tracking register spills correctly,
4506 				 * so any instance of leftover slots is a bug
4507 				 */
4508 				if (bt_stack_mask(bt) != 0) {
4509 					verifier_bug(env,
4510 						     "static subprog leftover stack slots %llx",
4511 						     bt_stack_mask(bt));
4512 					return -EFAULT;
4513 				}
4514 				/* propagate r1-r5 to the caller */
4515 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
4516 					if (bt_is_reg_set(bt, i)) {
4517 						bt_clear_reg(bt, i);
4518 						bt_set_frame_reg(bt, bt->frame - 1, i);
4519 					}
4520 				}
4521 				if (bt_subprog_exit(bt))
4522 					return -EFAULT;
4523 				return 0;
4524 			}
4525 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
4526 			/* exit from callback subprog to callback-calling helper or
4527 			 * kfunc call. Use idx/subseq_idx check to discern it from
4528 			 * straight line code backtracking.
4529 			 * Unlike the subprog call handling above, we shouldn't
4530 			 * propagate precision of r1-r5 (if any requested), as they are
4531 			 * not actually arguments passed directly to callback subprogs
4532 			 */
4533 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4534 				verifier_bug(env, "callback unexpected regs %x",
4535 					     bt_reg_mask(bt));
4536 				return -EFAULT;
4537 			}
4538 			if (bt_stack_mask(bt) != 0) {
4539 				verifier_bug(env, "callback leftover stack slots %llx",
4540 					     bt_stack_mask(bt));
4541 				return -EFAULT;
4542 			}
4543 			/* clear r1-r5 in callback subprog's mask */
4544 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4545 				bt_clear_reg(bt, i);
4546 			if (bt_subprog_exit(bt))
4547 				return -EFAULT;
4548 			return 0;
4549 		} else if (opcode == BPF_CALL) {
4550 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
4551 			 * catch this error later. Make backtracking conservative
4552 			 * with ENOTSUPP.
4553 			 */
4554 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
4555 				return -ENOTSUPP;
4556 			/* regular helper call sets R0 */
4557 			bt_clear_reg(bt, BPF_REG_0);
4558 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4559 				/* if backtracking was looking for registers R1-R5
4560 				 * they should have been found already.
4561 				 */
4562 				verifier_bug(env, "backtracking call unexpected regs %x",
4563 					     bt_reg_mask(bt));
4564 				return -EFAULT;
4565 			}
4566 			if (insn->src_reg == BPF_REG_0 && insn->imm == BPF_FUNC_tail_call
4567 			    && subseq_idx - idx != 1) {
4568 				if (bt_subprog_enter(bt))
4569 					return -EFAULT;
4570 			}
4571 		} else if (opcode == BPF_EXIT) {
4572 			bool r0_precise;
4573 
4574 			/* Backtracking to a nested function call, 'idx' is a part of
4575 			 * the inner frame 'subseq_idx' is a part of the outer frame.
4576 			 * In case of a regular function call, instructions giving
4577 			 * precision to registers R1-R5 should have been found already.
4578 			 * In case of a callback, it is ok to have R1-R5 marked for
4579 			 * backtracking, as these registers are set by the function
4580 			 * invoking callback.
4581 			 */
4582 			if (subseq_idx >= 0 && bpf_calls_callback(env, subseq_idx))
4583 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4584 					bt_clear_reg(bt, i);
4585 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4586 				verifier_bug(env, "backtracking exit unexpected regs %x",
4587 					     bt_reg_mask(bt));
4588 				return -EFAULT;
4589 			}
4590 
4591 			/* BPF_EXIT in subprog or callback always returns
4592 			 * right after the call instruction, so by checking
4593 			 * whether the instruction at subseq_idx-1 is subprog
4594 			 * call or not we can distinguish actual exit from
4595 			 * *subprog* from exit from *callback*. In the former
4596 			 * case, we need to propagate r0 precision, if
4597 			 * necessary. In the former we never do that.
4598 			 */
4599 			r0_precise = subseq_idx - 1 >= 0 &&
4600 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4601 				     bt_is_reg_set(bt, BPF_REG_0);
4602 
4603 			bt_clear_reg(bt, BPF_REG_0);
4604 			if (bt_subprog_enter(bt))
4605 				return -EFAULT;
4606 
4607 			if (r0_precise)
4608 				bt_set_reg(bt, BPF_REG_0);
4609 			/* r6-r9 and stack slots will stay set in caller frame
4610 			 * bitmasks until we return back from callee(s)
4611 			 */
4612 			return 0;
4613 		} else if (BPF_SRC(insn->code) == BPF_X) {
4614 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4615 				return 0;
4616 			/* dreg <cond> sreg
4617 			 * Both dreg and sreg need precision before
4618 			 * this insn. If only sreg was marked precise
4619 			 * before it would be equally necessary to
4620 			 * propagate it to dreg.
4621 			 */
4622 			if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK))
4623 				bt_set_reg(bt, sreg);
4624 			if (!hist || !(hist->flags & INSN_F_DST_REG_STACK))
4625 				bt_set_reg(bt, dreg);
4626 		} else if (BPF_SRC(insn->code) == BPF_K) {
4627 			 /* dreg <cond> K
4628 			  * Only dreg still needs precision before
4629 			  * this insn, so for the K-based conditional
4630 			  * there is nothing new to be marked.
4631 			  */
4632 		}
4633 	} else if (class == BPF_LD) {
4634 		if (!bt_is_reg_set(bt, dreg))
4635 			return 0;
4636 		bt_clear_reg(bt, dreg);
4637 		/* It's ld_imm64 or ld_abs or ld_ind.
4638 		 * For ld_imm64 no further tracking of precision
4639 		 * into parent is necessary
4640 		 */
4641 		if (mode == BPF_IND || mode == BPF_ABS)
4642 			/* to be analyzed */
4643 			return -ENOTSUPP;
4644 	}
4645 	/* Propagate precision marks to linked registers, to account for
4646 	 * registers marked as precise in this function.
4647 	 */
4648 	bt_sync_linked_regs(bt, hist);
4649 	return 0;
4650 }
4651 
4652 /* the scalar precision tracking algorithm:
4653  * . at the start all registers have precise=false.
4654  * . scalar ranges are tracked as normal through alu and jmp insns.
4655  * . once precise value of the scalar register is used in:
4656  *   .  ptr + scalar alu
4657  *   . if (scalar cond K|scalar)
4658  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
4659  *   backtrack through the verifier states and mark all registers and
4660  *   stack slots with spilled constants that these scalar registers
4661  *   should be precise.
4662  * . during state pruning two registers (or spilled stack slots)
4663  *   are equivalent if both are not precise.
4664  *
4665  * Note the verifier cannot simply walk register parentage chain,
4666  * since many different registers and stack slots could have been
4667  * used to compute single precise scalar.
4668  *
4669  * The approach of starting with precise=true for all registers and then
4670  * backtrack to mark a register as not precise when the verifier detects
4671  * that program doesn't care about specific value (e.g., when helper
4672  * takes register as ARG_ANYTHING parameter) is not safe.
4673  *
4674  * It's ok to walk single parentage chain of the verifier states.
4675  * It's possible that this backtracking will go all the way till 1st insn.
4676  * All other branches will be explored for needing precision later.
4677  *
4678  * The backtracking needs to deal with cases like:
4679  *   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)
4680  * r9 -= r8
4681  * r5 = r9
4682  * if r5 > 0x79f goto pc+7
4683  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4684  * r5 += 1
4685  * ...
4686  * call bpf_perf_event_output#25
4687  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4688  *
4689  * and this case:
4690  * r6 = 1
4691  * call foo // uses callee's r6 inside to compute r0
4692  * r0 += r6
4693  * if r0 == 0 goto
4694  *
4695  * to track above reg_mask/stack_mask needs to be independent for each frame.
4696  *
4697  * Also if parent's curframe > frame where backtracking started,
4698  * the verifier need to mark registers in both frames, otherwise callees
4699  * may incorrectly prune callers. This is similar to
4700  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4701  *
4702  * For now backtracking falls back into conservative marking.
4703  */
4704 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4705 				     struct bpf_verifier_state *st)
4706 {
4707 	struct bpf_func_state *func;
4708 	struct bpf_reg_state *reg;
4709 	int i, j;
4710 
4711 	if (env->log.level & BPF_LOG_LEVEL2) {
4712 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4713 			st->curframe);
4714 	}
4715 
4716 	/* big hammer: mark all scalars precise in this path.
4717 	 * pop_stack may still get !precise scalars.
4718 	 * We also skip current state and go straight to first parent state,
4719 	 * because precision markings in current non-checkpointed state are
4720 	 * not needed. See why in the comment in __mark_chain_precision below.
4721 	 */
4722 	for (st = st->parent; st; st = st->parent) {
4723 		for (i = 0; i <= st->curframe; i++) {
4724 			func = st->frame[i];
4725 			for (j = 0; j < BPF_REG_FP; j++) {
4726 				reg = &func->regs[j];
4727 				if (reg->type != SCALAR_VALUE || reg->precise)
4728 					continue;
4729 				reg->precise = true;
4730 				if (env->log.level & BPF_LOG_LEVEL2) {
4731 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4732 						i, j);
4733 				}
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 || reg->precise)
4740 					continue;
4741 				reg->precise = true;
4742 				if (env->log.level & BPF_LOG_LEVEL2) {
4743 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4744 						i, -(j + 1) * 8);
4745 				}
4746 			}
4747 		}
4748 	}
4749 }
4750 
4751 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4752 {
4753 	struct bpf_func_state *func;
4754 	struct bpf_reg_state *reg;
4755 	int i, j;
4756 
4757 	for (i = 0; i <= st->curframe; i++) {
4758 		func = st->frame[i];
4759 		for (j = 0; j < BPF_REG_FP; j++) {
4760 			reg = &func->regs[j];
4761 			if (reg->type != SCALAR_VALUE)
4762 				continue;
4763 			reg->precise = false;
4764 		}
4765 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4766 			if (!is_spilled_reg(&func->stack[j]))
4767 				continue;
4768 			reg = &func->stack[j].spilled_ptr;
4769 			if (reg->type != SCALAR_VALUE)
4770 				continue;
4771 			reg->precise = false;
4772 		}
4773 	}
4774 }
4775 
4776 /*
4777  * __mark_chain_precision() backtracks BPF program instruction sequence and
4778  * chain of verifier states making sure that register *regno* (if regno >= 0)
4779  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4780  * SCALARS, as well as any other registers and slots that contribute to
4781  * a tracked state of given registers/stack slots, depending on specific BPF
4782  * assembly instructions (see backtrack_insns() for exact instruction handling
4783  * logic). This backtracking relies on recorded jmp_history and is able to
4784  * traverse entire chain of parent states. This process ends only when all the
4785  * necessary registers/slots and their transitive dependencies are marked as
4786  * precise.
4787  *
4788  * One important and subtle aspect is that precise marks *do not matter* in
4789  * the currently verified state (current state). It is important to understand
4790  * why this is the case.
4791  *
4792  * First, note that current state is the state that is not yet "checkpointed",
4793  * i.e., it is not yet put into env->explored_states, and it has no children
4794  * states as well. It's ephemeral, and can end up either a) being discarded if
4795  * compatible explored state is found at some point or BPF_EXIT instruction is
4796  * reached or b) checkpointed and put into env->explored_states, branching out
4797  * into one or more children states.
4798  *
4799  * In the former case, precise markings in current state are completely
4800  * ignored by state comparison code (see regsafe() for details). Only
4801  * checkpointed ("old") state precise markings are important, and if old
4802  * state's register/slot is precise, regsafe() assumes current state's
4803  * register/slot as precise and checks value ranges exactly and precisely. If
4804  * states turn out to be compatible, current state's necessary precise
4805  * markings and any required parent states' precise markings are enforced
4806  * after the fact with propagate_precision() logic, after the fact. But it's
4807  * important to realize that in this case, even after marking current state
4808  * registers/slots as precise, we immediately discard current state. So what
4809  * actually matters is any of the precise markings propagated into current
4810  * state's parent states, which are always checkpointed (due to b) case above).
4811  * As such, for scenario a) it doesn't matter if current state has precise
4812  * markings set or not.
4813  *
4814  * Now, for the scenario b), checkpointing and forking into child(ren)
4815  * state(s). Note that before current state gets to checkpointing step, any
4816  * processed instruction always assumes precise SCALAR register/slot
4817  * knowledge: if precise value or range is useful to prune jump branch, BPF
4818  * verifier takes this opportunity enthusiastically. Similarly, when
4819  * register's value is used to calculate offset or memory address, exact
4820  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4821  * what we mentioned above about state comparison ignoring precise markings
4822  * during state comparison, BPF verifier ignores and also assumes precise
4823  * markings *at will* during instruction verification process. But as verifier
4824  * assumes precision, it also propagates any precision dependencies across
4825  * parent states, which are not yet finalized, so can be further restricted
4826  * based on new knowledge gained from restrictions enforced by their children
4827  * states. This is so that once those parent states are finalized, i.e., when
4828  * they have no more active children state, state comparison logic in
4829  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4830  * required for correctness.
4831  *
4832  * To build a bit more intuition, note also that once a state is checkpointed,
4833  * the path we took to get to that state is not important. This is crucial
4834  * property for state pruning. When state is checkpointed and finalized at
4835  * some instruction index, it can be correctly and safely used to "short
4836  * circuit" any *compatible* state that reaches exactly the same instruction
4837  * index. I.e., if we jumped to that instruction from a completely different
4838  * code path than original finalized state was derived from, it doesn't
4839  * matter, current state can be discarded because from that instruction
4840  * forward having a compatible state will ensure we will safely reach the
4841  * exit. States describe preconditions for further exploration, but completely
4842  * forget the history of how we got here.
4843  *
4844  * This also means that even if we needed precise SCALAR range to get to
4845  * finalized state, but from that point forward *that same* SCALAR register is
4846  * never used in a precise context (i.e., it's precise value is not needed for
4847  * correctness), it's correct and safe to mark such register as "imprecise"
4848  * (i.e., precise marking set to false). This is what we rely on when we do
4849  * not set precise marking in current state. If no child state requires
4850  * precision for any given SCALAR register, it's safe to dictate that it can
4851  * be imprecise. If any child state does require this register to be precise,
4852  * we'll mark it precise later retroactively during precise markings
4853  * propagation from child state to parent states.
4854  *
4855  * Skipping precise marking setting in current state is a mild version of
4856  * relying on the above observation. But we can utilize this property even
4857  * more aggressively by proactively forgetting any precise marking in the
4858  * current state (which we inherited from the parent state), right before we
4859  * checkpoint it and branch off into new child state. This is done by
4860  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4861  * finalized states which help in short circuiting more future states.
4862  */
4863 static int __mark_chain_precision(struct bpf_verifier_env *env,
4864 				  struct bpf_verifier_state *starting_state,
4865 				  int regno,
4866 				  bool *changed)
4867 {
4868 	struct bpf_verifier_state *st = starting_state;
4869 	struct backtrack_state *bt = &env->bt;
4870 	int first_idx = st->first_insn_idx;
4871 	int last_idx = starting_state->insn_idx;
4872 	int subseq_idx = -1;
4873 	struct bpf_func_state *func;
4874 	bool tmp, skip_first = true;
4875 	struct bpf_reg_state *reg;
4876 	int i, fr, err;
4877 
4878 	if (!env->bpf_capable)
4879 		return 0;
4880 
4881 	changed = changed ?: &tmp;
4882 	/* set frame number from which we are starting to backtrack */
4883 	bt_init(bt, starting_state->curframe);
4884 
4885 	/* Do sanity checks against current state of register and/or stack
4886 	 * slot, but don't set precise flag in current state, as precision
4887 	 * tracking in the current state is unnecessary.
4888 	 */
4889 	func = st->frame[bt->frame];
4890 	if (regno >= 0) {
4891 		reg = &func->regs[regno];
4892 		if (reg->type != SCALAR_VALUE) {
4893 			verifier_bug(env, "backtracking misuse");
4894 			return -EFAULT;
4895 		}
4896 		bt_set_reg(bt, regno);
4897 	}
4898 
4899 	if (bt_empty(bt))
4900 		return 0;
4901 
4902 	for (;;) {
4903 		DECLARE_BITMAP(mask, 64);
4904 		u32 history = st->jmp_history_cnt;
4905 		struct bpf_jmp_history_entry *hist;
4906 
4907 		if (env->log.level & BPF_LOG_LEVEL2) {
4908 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4909 				bt->frame, last_idx, first_idx, subseq_idx);
4910 		}
4911 
4912 		if (last_idx < 0) {
4913 			/* we are at the entry into subprog, which
4914 			 * is expected for global funcs, but only if
4915 			 * requested precise registers are R1-R5
4916 			 * (which are global func's input arguments)
4917 			 */
4918 			if (st->curframe == 0 &&
4919 			    st->frame[0]->subprogno > 0 &&
4920 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4921 			    bt_stack_mask(bt) == 0 &&
4922 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4923 				bitmap_from_u64(mask, bt_reg_mask(bt));
4924 				for_each_set_bit(i, mask, 32) {
4925 					reg = &st->frame[0]->regs[i];
4926 					bt_clear_reg(bt, i);
4927 					if (reg->type == SCALAR_VALUE) {
4928 						reg->precise = true;
4929 						*changed = true;
4930 					}
4931 				}
4932 				return 0;
4933 			}
4934 
4935 			verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %llx",
4936 				     st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4937 			return -EFAULT;
4938 		}
4939 
4940 		for (i = last_idx;;) {
4941 			if (skip_first) {
4942 				err = 0;
4943 				skip_first = false;
4944 			} else {
4945 				hist = get_jmp_hist_entry(st, history, i);
4946 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4947 			}
4948 			if (err == -ENOTSUPP) {
4949 				mark_all_scalars_precise(env, starting_state);
4950 				bt_reset(bt);
4951 				return 0;
4952 			} else if (err) {
4953 				return err;
4954 			}
4955 			if (bt_empty(bt))
4956 				/* Found assignment(s) into tracked register in this state.
4957 				 * Since this state is already marked, just return.
4958 				 * Nothing to be tracked further in the parent state.
4959 				 */
4960 				return 0;
4961 			subseq_idx = i;
4962 			i = get_prev_insn_idx(st, i, &history);
4963 			if (i == -ENOENT)
4964 				break;
4965 			if (i >= env->prog->len) {
4966 				/* This can happen if backtracking reached insn 0
4967 				 * and there are still reg_mask or stack_mask
4968 				 * to backtrack.
4969 				 * It means the backtracking missed the spot where
4970 				 * particular register was initialized with a constant.
4971 				 */
4972 				verifier_bug(env, "backtracking idx %d", i);
4973 				return -EFAULT;
4974 			}
4975 		}
4976 		st = st->parent;
4977 		if (!st)
4978 			break;
4979 
4980 		for (fr = bt->frame; fr >= 0; fr--) {
4981 			func = st->frame[fr];
4982 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4983 			for_each_set_bit(i, mask, 32) {
4984 				reg = &func->regs[i];
4985 				if (reg->type != SCALAR_VALUE) {
4986 					bt_clear_frame_reg(bt, fr, i);
4987 					continue;
4988 				}
4989 				if (reg->precise) {
4990 					bt_clear_frame_reg(bt, fr, i);
4991 				} else {
4992 					reg->precise = true;
4993 					*changed = true;
4994 				}
4995 			}
4996 
4997 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4998 			for_each_set_bit(i, mask, 64) {
4999 				if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE,
5000 						    env, "stack slot %d, total slots %d",
5001 						    i, func->allocated_stack / BPF_REG_SIZE))
5002 					return -EFAULT;
5003 
5004 				if (!is_spilled_scalar_reg(&func->stack[i])) {
5005 					bt_clear_frame_slot(bt, fr, i);
5006 					continue;
5007 				}
5008 				reg = &func->stack[i].spilled_ptr;
5009 				if (reg->precise) {
5010 					bt_clear_frame_slot(bt, fr, i);
5011 				} else {
5012 					reg->precise = true;
5013 					*changed = true;
5014 				}
5015 			}
5016 			if (env->log.level & BPF_LOG_LEVEL2) {
5017 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
5018 					     bt_frame_reg_mask(bt, fr));
5019 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
5020 					fr, env->tmp_str_buf);
5021 				bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
5022 					       bt_frame_stack_mask(bt, fr));
5023 				verbose(env, "stack=%s: ", env->tmp_str_buf);
5024 				print_verifier_state(env, st, fr, true);
5025 			}
5026 		}
5027 
5028 		if (bt_empty(bt))
5029 			return 0;
5030 
5031 		subseq_idx = first_idx;
5032 		last_idx = st->last_insn_idx;
5033 		first_idx = st->first_insn_idx;
5034 	}
5035 
5036 	/* if we still have requested precise regs or slots, we missed
5037 	 * something (e.g., stack access through non-r10 register), so
5038 	 * fallback to marking all precise
5039 	 */
5040 	if (!bt_empty(bt)) {
5041 		mark_all_scalars_precise(env, starting_state);
5042 		bt_reset(bt);
5043 	}
5044 
5045 	return 0;
5046 }
5047 
5048 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
5049 {
5050 	return __mark_chain_precision(env, env->cur_state, regno, NULL);
5051 }
5052 
5053 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
5054  * desired reg and stack masks across all relevant frames
5055  */
5056 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
5057 				      struct bpf_verifier_state *starting_state)
5058 {
5059 	return __mark_chain_precision(env, starting_state, -1, NULL);
5060 }
5061 
5062 static bool is_spillable_regtype(enum bpf_reg_type type)
5063 {
5064 	switch (base_type(type)) {
5065 	case PTR_TO_MAP_VALUE:
5066 	case PTR_TO_STACK:
5067 	case PTR_TO_CTX:
5068 	case PTR_TO_PACKET:
5069 	case PTR_TO_PACKET_META:
5070 	case PTR_TO_PACKET_END:
5071 	case PTR_TO_FLOW_KEYS:
5072 	case CONST_PTR_TO_MAP:
5073 	case PTR_TO_SOCKET:
5074 	case PTR_TO_SOCK_COMMON:
5075 	case PTR_TO_TCP_SOCK:
5076 	case PTR_TO_XDP_SOCK:
5077 	case PTR_TO_BTF_ID:
5078 	case PTR_TO_BUF:
5079 	case PTR_TO_MEM:
5080 	case PTR_TO_FUNC:
5081 	case PTR_TO_MAP_KEY:
5082 	case PTR_TO_ARENA:
5083 		return true;
5084 	default:
5085 		return false;
5086 	}
5087 }
5088 
5089 /* Does this register contain a constant zero? */
5090 static bool register_is_null(struct bpf_reg_state *reg)
5091 {
5092 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
5093 }
5094 
5095 /* check if register is a constant scalar value */
5096 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
5097 {
5098 	return reg->type == SCALAR_VALUE &&
5099 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
5100 }
5101 
5102 /* assuming is_reg_const() is true, return constant value of a register */
5103 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
5104 {
5105 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
5106 }
5107 
5108 static bool __is_pointer_value(bool allow_ptr_leaks,
5109 			       const struct bpf_reg_state *reg)
5110 {
5111 	if (allow_ptr_leaks)
5112 		return false;
5113 
5114 	return reg->type != SCALAR_VALUE;
5115 }
5116 
5117 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
5118 					struct bpf_reg_state *src_reg)
5119 {
5120 	if (src_reg->type != SCALAR_VALUE)
5121 		return;
5122 
5123 	if (src_reg->id & BPF_ADD_CONST) {
5124 		/*
5125 		 * The verifier is processing rX = rY insn and
5126 		 * rY->id has special linked register already.
5127 		 * Cleared it, since multiple rX += const are not supported.
5128 		 */
5129 		src_reg->id = 0;
5130 		src_reg->off = 0;
5131 	}
5132 
5133 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
5134 		/* Ensure that src_reg has a valid ID that will be copied to
5135 		 * dst_reg and then will be used by sync_linked_regs() to
5136 		 * propagate min/max range.
5137 		 */
5138 		src_reg->id = ++env->id_gen;
5139 }
5140 
5141 /* Copy src state preserving dst->parent and dst->live fields */
5142 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
5143 {
5144 	*dst = *src;
5145 }
5146 
5147 static void save_register_state(struct bpf_verifier_env *env,
5148 				struct bpf_func_state *state,
5149 				int spi, struct bpf_reg_state *reg,
5150 				int size)
5151 {
5152 	int i;
5153 
5154 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
5155 
5156 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
5157 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
5158 
5159 	/* size < 8 bytes spill */
5160 	for (; i; i--)
5161 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
5162 }
5163 
5164 static bool is_bpf_st_mem(struct bpf_insn *insn)
5165 {
5166 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
5167 }
5168 
5169 static int get_reg_width(struct bpf_reg_state *reg)
5170 {
5171 	return fls64(reg->umax_value);
5172 }
5173 
5174 /* See comment for mark_fastcall_pattern_for_call() */
5175 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
5176 					  struct bpf_func_state *state, int insn_idx, int off)
5177 {
5178 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
5179 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
5180 	int i;
5181 
5182 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
5183 		return;
5184 	/* access to the region [max_stack_depth .. fastcall_stack_off)
5185 	 * from something that is not a part of the fastcall pattern,
5186 	 * disable fastcall rewrites for current subprogram by setting
5187 	 * fastcall_stack_off to a value smaller than any possible offset.
5188 	 */
5189 	subprog->fastcall_stack_off = S16_MIN;
5190 	/* reset fastcall aux flags within subprogram,
5191 	 * happens at most once per subprogram
5192 	 */
5193 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
5194 		aux[i].fastcall_spills_num = 0;
5195 		aux[i].fastcall_pattern = 0;
5196 	}
5197 }
5198 
5199 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
5200  * stack boundary and alignment are checked in check_mem_access()
5201  */
5202 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
5203 				       /* stack frame we're writing to */
5204 				       struct bpf_func_state *state,
5205 				       int off, int size, int value_regno,
5206 				       int insn_idx)
5207 {
5208 	struct bpf_func_state *cur; /* state of the current function */
5209 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
5210 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5211 	struct bpf_reg_state *reg = NULL;
5212 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
5213 
5214 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
5215 	 * so it's aligned access and [off, off + size) are within stack limits
5216 	 */
5217 	if (!env->allow_ptr_leaks &&
5218 	    is_spilled_reg(&state->stack[spi]) &&
5219 	    !is_spilled_scalar_reg(&state->stack[spi]) &&
5220 	    size != BPF_REG_SIZE) {
5221 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
5222 		return -EACCES;
5223 	}
5224 
5225 	cur = env->cur_state->frame[env->cur_state->curframe];
5226 	if (value_regno >= 0)
5227 		reg = &cur->regs[value_regno];
5228 	if (!env->bypass_spec_v4) {
5229 		bool sanitize = reg && is_spillable_regtype(reg->type);
5230 
5231 		for (i = 0; i < size; i++) {
5232 			u8 type = state->stack[spi].slot_type[i];
5233 
5234 			if (type != STACK_MISC && type != STACK_ZERO) {
5235 				sanitize = true;
5236 				break;
5237 			}
5238 		}
5239 
5240 		if (sanitize)
5241 			env->insn_aux_data[insn_idx].nospec_result = true;
5242 	}
5243 
5244 	err = destroy_if_dynptr_stack_slot(env, state, spi);
5245 	if (err)
5246 		return err;
5247 
5248 	if (!(off % BPF_REG_SIZE) && size == BPF_REG_SIZE) {
5249 		/* only mark the slot as written if all 8 bytes were written
5250 		 * otherwise read propagation may incorrectly stop too soon
5251 		 * when stack slots are partially written.
5252 		 * This heuristic means that read propagation will be
5253 		 * conservative, since it will add reg_live_read marks
5254 		 * to stack slots all the way to first state when programs
5255 		 * writes+reads less than 8 bytes
5256 		 */
5257 		bpf_mark_stack_write(env, state->frameno, BIT(spi));
5258 	}
5259 
5260 	check_fastcall_stack_contract(env, state, insn_idx, off);
5261 	mark_stack_slot_scratched(env, spi);
5262 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
5263 		bool reg_value_fits;
5264 
5265 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
5266 		/* Make sure that reg had an ID to build a relation on spill. */
5267 		if (reg_value_fits)
5268 			assign_scalar_id_before_mov(env, reg);
5269 		save_register_state(env, state, spi, reg, size);
5270 		/* Break the relation on a narrowing spill. */
5271 		if (!reg_value_fits)
5272 			state->stack[spi].spilled_ptr.id = 0;
5273 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
5274 		   env->bpf_capable) {
5275 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
5276 
5277 		memset(tmp_reg, 0, sizeof(*tmp_reg));
5278 		__mark_reg_known(tmp_reg, insn->imm);
5279 		tmp_reg->type = SCALAR_VALUE;
5280 		save_register_state(env, state, spi, tmp_reg, size);
5281 	} else if (reg && is_spillable_regtype(reg->type)) {
5282 		/* register containing pointer is being spilled into stack */
5283 		if (size != BPF_REG_SIZE) {
5284 			verbose_linfo(env, insn_idx, "; ");
5285 			verbose(env, "invalid size of register spill\n");
5286 			return -EACCES;
5287 		}
5288 		if (state != cur && reg->type == PTR_TO_STACK) {
5289 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
5290 			return -EINVAL;
5291 		}
5292 		save_register_state(env, state, spi, reg, size);
5293 	} else {
5294 		u8 type = STACK_MISC;
5295 
5296 		/* regular write of data into stack destroys any spilled ptr */
5297 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5298 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
5299 		if (is_stack_slot_special(&state->stack[spi]))
5300 			for (i = 0; i < BPF_REG_SIZE; i++)
5301 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
5302 
5303 		/* when we zero initialize stack slots mark them as such */
5304 		if ((reg && register_is_null(reg)) ||
5305 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
5306 			/* STACK_ZERO case happened because register spill
5307 			 * wasn't properly aligned at the stack slot boundary,
5308 			 * so it's not a register spill anymore; force
5309 			 * originating register to be precise to make
5310 			 * STACK_ZERO correct for subsequent states
5311 			 */
5312 			err = mark_chain_precision(env, value_regno);
5313 			if (err)
5314 				return err;
5315 			type = STACK_ZERO;
5316 		}
5317 
5318 		/* Mark slots affected by this stack write. */
5319 		for (i = 0; i < size; i++)
5320 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
5321 		insn_flags = 0; /* not a register spill */
5322 	}
5323 
5324 	if (insn_flags)
5325 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5326 	return 0;
5327 }
5328 
5329 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
5330  * known to contain a variable offset.
5331  * This function checks whether the write is permitted and conservatively
5332  * tracks the effects of the write, considering that each stack slot in the
5333  * dynamic range is potentially written to.
5334  *
5335  * 'off' includes 'regno->off'.
5336  * 'value_regno' can be -1, meaning that an unknown value is being written to
5337  * the stack.
5338  *
5339  * Spilled pointers in range are not marked as written because we don't know
5340  * what's going to be actually written. This means that read propagation for
5341  * future reads cannot be terminated by this write.
5342  *
5343  * For privileged programs, uninitialized stack slots are considered
5344  * initialized by this write (even though we don't know exactly what offsets
5345  * are going to be written to). The idea is that we don't want the verifier to
5346  * reject future reads that access slots written to through variable offsets.
5347  */
5348 static int check_stack_write_var_off(struct bpf_verifier_env *env,
5349 				     /* func where register points to */
5350 				     struct bpf_func_state *state,
5351 				     int ptr_regno, int off, int size,
5352 				     int value_regno, int insn_idx)
5353 {
5354 	struct bpf_func_state *cur; /* state of the current function */
5355 	int min_off, max_off;
5356 	int i, err;
5357 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
5358 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5359 	bool writing_zero = false;
5360 	/* set if the fact that we're writing a zero is used to let any
5361 	 * stack slots remain STACK_ZERO
5362 	 */
5363 	bool zero_used = false;
5364 
5365 	cur = env->cur_state->frame[env->cur_state->curframe];
5366 	ptr_reg = &cur->regs[ptr_regno];
5367 	min_off = ptr_reg->smin_value + off;
5368 	max_off = ptr_reg->smax_value + off + size;
5369 	if (value_regno >= 0)
5370 		value_reg = &cur->regs[value_regno];
5371 	if ((value_reg && register_is_null(value_reg)) ||
5372 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
5373 		writing_zero = true;
5374 
5375 	for (i = min_off; i < max_off; i++) {
5376 		int spi;
5377 
5378 		spi = __get_spi(i);
5379 		err = destroy_if_dynptr_stack_slot(env, state, spi);
5380 		if (err)
5381 			return err;
5382 	}
5383 
5384 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
5385 	/* Variable offset writes destroy any spilled pointers in range. */
5386 	for (i = min_off; i < max_off; i++) {
5387 		u8 new_type, *stype;
5388 		int slot, spi;
5389 
5390 		slot = -i - 1;
5391 		spi = slot / BPF_REG_SIZE;
5392 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5393 		mark_stack_slot_scratched(env, spi);
5394 
5395 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
5396 			/* Reject the write if range we may write to has not
5397 			 * been initialized beforehand. If we didn't reject
5398 			 * here, the ptr status would be erased below (even
5399 			 * though not all slots are actually overwritten),
5400 			 * possibly opening the door to leaks.
5401 			 *
5402 			 * We do however catch STACK_INVALID case below, and
5403 			 * only allow reading possibly uninitialized memory
5404 			 * later for CAP_PERFMON, as the write may not happen to
5405 			 * that slot.
5406 			 */
5407 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
5408 				insn_idx, i);
5409 			return -EINVAL;
5410 		}
5411 
5412 		/* If writing_zero and the spi slot contains a spill of value 0,
5413 		 * maintain the spill type.
5414 		 */
5415 		if (writing_zero && *stype == STACK_SPILL &&
5416 		    is_spilled_scalar_reg(&state->stack[spi])) {
5417 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
5418 
5419 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
5420 				zero_used = true;
5421 				continue;
5422 			}
5423 		}
5424 
5425 		/* Erase all other spilled pointers. */
5426 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5427 
5428 		/* Update the slot type. */
5429 		new_type = STACK_MISC;
5430 		if (writing_zero && *stype == STACK_ZERO) {
5431 			new_type = STACK_ZERO;
5432 			zero_used = true;
5433 		}
5434 		/* If the slot is STACK_INVALID, we check whether it's OK to
5435 		 * pretend that it will be initialized by this write. The slot
5436 		 * might not actually be written to, and so if we mark it as
5437 		 * initialized future reads might leak uninitialized memory.
5438 		 * For privileged programs, we will accept such reads to slots
5439 		 * that may or may not be written because, if we're reject
5440 		 * them, the error would be too confusing.
5441 		 */
5442 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
5443 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
5444 					insn_idx, i);
5445 			return -EINVAL;
5446 		}
5447 		*stype = new_type;
5448 	}
5449 	if (zero_used) {
5450 		/* backtracking doesn't work for STACK_ZERO yet. */
5451 		err = mark_chain_precision(env, value_regno);
5452 		if (err)
5453 			return err;
5454 	}
5455 	return 0;
5456 }
5457 
5458 /* When register 'dst_regno' is assigned some values from stack[min_off,
5459  * max_off), we set the register's type according to the types of the
5460  * respective stack slots. If all the stack values are known to be zeros, then
5461  * so is the destination reg. Otherwise, the register is considered to be
5462  * SCALAR. This function does not deal with register filling; the caller must
5463  * ensure that all spilled registers in the stack range have been marked as
5464  * read.
5465  */
5466 static void mark_reg_stack_read(struct bpf_verifier_env *env,
5467 				/* func where src register points to */
5468 				struct bpf_func_state *ptr_state,
5469 				int min_off, int max_off, int dst_regno)
5470 {
5471 	struct bpf_verifier_state *vstate = env->cur_state;
5472 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5473 	int i, slot, spi;
5474 	u8 *stype;
5475 	int zeros = 0;
5476 
5477 	for (i = min_off; i < max_off; i++) {
5478 		slot = -i - 1;
5479 		spi = slot / BPF_REG_SIZE;
5480 		mark_stack_slot_scratched(env, spi);
5481 		stype = ptr_state->stack[spi].slot_type;
5482 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
5483 			break;
5484 		zeros++;
5485 	}
5486 	if (zeros == max_off - min_off) {
5487 		/* Any access_size read into register is zero extended,
5488 		 * so the whole register == const_zero.
5489 		 */
5490 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
5491 	} else {
5492 		/* have read misc data from the stack */
5493 		mark_reg_unknown(env, state->regs, dst_regno);
5494 	}
5495 }
5496 
5497 /* Read the stack at 'off' and put the results into the register indicated by
5498  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
5499  * spilled reg.
5500  *
5501  * 'dst_regno' can be -1, meaning that the read value is not going to a
5502  * register.
5503  *
5504  * The access is assumed to be within the current stack bounds.
5505  */
5506 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
5507 				      /* func where src register points to */
5508 				      struct bpf_func_state *reg_state,
5509 				      int off, int size, int dst_regno)
5510 {
5511 	struct bpf_verifier_state *vstate = env->cur_state;
5512 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5513 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
5514 	struct bpf_reg_state *reg;
5515 	u8 *stype, type;
5516 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
5517 	int err;
5518 
5519 	stype = reg_state->stack[spi].slot_type;
5520 	reg = &reg_state->stack[spi].spilled_ptr;
5521 
5522 	mark_stack_slot_scratched(env, spi);
5523 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
5524 	err = bpf_mark_stack_read(env, reg_state->frameno, env->insn_idx, BIT(spi));
5525 	if (err)
5526 		return err;
5527 
5528 	if (is_spilled_reg(&reg_state->stack[spi])) {
5529 		u8 spill_size = 1;
5530 
5531 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
5532 			spill_size++;
5533 
5534 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
5535 			if (reg->type != SCALAR_VALUE) {
5536 				verbose_linfo(env, env->insn_idx, "; ");
5537 				verbose(env, "invalid size of register fill\n");
5538 				return -EACCES;
5539 			}
5540 
5541 			if (dst_regno < 0)
5542 				return 0;
5543 
5544 			if (size <= spill_size &&
5545 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
5546 				/* The earlier check_reg_arg() has decided the
5547 				 * subreg_def for this insn.  Save it first.
5548 				 */
5549 				s32 subreg_def = state->regs[dst_regno].subreg_def;
5550 
5551 				if (env->bpf_capable && size == 4 && spill_size == 4 &&
5552 				    get_reg_width(reg) <= 32)
5553 					/* Ensure stack slot has an ID to build a relation
5554 					 * with the destination register on fill.
5555 					 */
5556 					assign_scalar_id_before_mov(env, reg);
5557 				copy_register_state(&state->regs[dst_regno], reg);
5558 				state->regs[dst_regno].subreg_def = subreg_def;
5559 
5560 				/* Break the relation on a narrowing fill.
5561 				 * coerce_reg_to_size will adjust the boundaries.
5562 				 */
5563 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
5564 					state->regs[dst_regno].id = 0;
5565 			} else {
5566 				int spill_cnt = 0, zero_cnt = 0;
5567 
5568 				for (i = 0; i < size; i++) {
5569 					type = stype[(slot - i) % BPF_REG_SIZE];
5570 					if (type == STACK_SPILL) {
5571 						spill_cnt++;
5572 						continue;
5573 					}
5574 					if (type == STACK_MISC)
5575 						continue;
5576 					if (type == STACK_ZERO) {
5577 						zero_cnt++;
5578 						continue;
5579 					}
5580 					if (type == STACK_INVALID && env->allow_uninit_stack)
5581 						continue;
5582 					verbose(env, "invalid read from stack off %d+%d size %d\n",
5583 						off, i, size);
5584 					return -EACCES;
5585 				}
5586 
5587 				if (spill_cnt == size &&
5588 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
5589 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5590 					/* this IS register fill, so keep insn_flags */
5591 				} else if (zero_cnt == size) {
5592 					/* similarly to mark_reg_stack_read(), preserve zeroes */
5593 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5594 					insn_flags = 0; /* not restoring original register state */
5595 				} else {
5596 					mark_reg_unknown(env, state->regs, dst_regno);
5597 					insn_flags = 0; /* not restoring original register state */
5598 				}
5599 			}
5600 		} else if (dst_regno >= 0) {
5601 			/* restore register state from stack */
5602 			if (env->bpf_capable)
5603 				/* Ensure stack slot has an ID to build a relation
5604 				 * with the destination register on fill.
5605 				 */
5606 				assign_scalar_id_before_mov(env, reg);
5607 			copy_register_state(&state->regs[dst_regno], reg);
5608 			/* mark reg as written since spilled pointer state likely
5609 			 * has its liveness marks cleared by is_state_visited()
5610 			 * which resets stack/reg liveness for state transitions
5611 			 */
5612 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5613 			/* If dst_regno==-1, the caller is asking us whether
5614 			 * it is acceptable to use this value as a SCALAR_VALUE
5615 			 * (e.g. for XADD).
5616 			 * We must not allow unprivileged callers to do that
5617 			 * with spilled pointers.
5618 			 */
5619 			verbose(env, "leaking pointer from stack off %d\n",
5620 				off);
5621 			return -EACCES;
5622 		}
5623 	} else {
5624 		for (i = 0; i < size; i++) {
5625 			type = stype[(slot - i) % BPF_REG_SIZE];
5626 			if (type == STACK_MISC)
5627 				continue;
5628 			if (type == STACK_ZERO)
5629 				continue;
5630 			if (type == STACK_INVALID && env->allow_uninit_stack)
5631 				continue;
5632 			verbose(env, "invalid read from stack off %d+%d size %d\n",
5633 				off, i, size);
5634 			return -EACCES;
5635 		}
5636 		if (dst_regno >= 0)
5637 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5638 		insn_flags = 0; /* we are not restoring spilled register */
5639 	}
5640 	if (insn_flags)
5641 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5642 	return 0;
5643 }
5644 
5645 enum bpf_access_src {
5646 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5647 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
5648 };
5649 
5650 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5651 					 int regno, int off, int access_size,
5652 					 bool zero_size_allowed,
5653 					 enum bpf_access_type type,
5654 					 struct bpf_call_arg_meta *meta);
5655 
5656 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5657 {
5658 	return cur_regs(env) + regno;
5659 }
5660 
5661 /* Read the stack at 'ptr_regno + off' and put the result into the register
5662  * 'dst_regno'.
5663  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5664  * but not its variable offset.
5665  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5666  *
5667  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5668  * filling registers (i.e. reads of spilled register cannot be detected when
5669  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5670  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5671  * offset; for a fixed offset check_stack_read_fixed_off should be used
5672  * instead.
5673  */
5674 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5675 				    int ptr_regno, int off, int size, int dst_regno)
5676 {
5677 	/* The state of the source register. */
5678 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5679 	struct bpf_func_state *ptr_state = func(env, reg);
5680 	int err;
5681 	int min_off, max_off;
5682 
5683 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5684 	 */
5685 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5686 					    false, BPF_READ, NULL);
5687 	if (err)
5688 		return err;
5689 
5690 	min_off = reg->smin_value + off;
5691 	max_off = reg->smax_value + off;
5692 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5693 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5694 	return 0;
5695 }
5696 
5697 /* check_stack_read dispatches to check_stack_read_fixed_off or
5698  * check_stack_read_var_off.
5699  *
5700  * The caller must ensure that the offset falls within the allocated stack
5701  * bounds.
5702  *
5703  * 'dst_regno' is a register which will receive the value from the stack. It
5704  * can be -1, meaning that the read value is not going to a register.
5705  */
5706 static int check_stack_read(struct bpf_verifier_env *env,
5707 			    int ptr_regno, int off, int size,
5708 			    int dst_regno)
5709 {
5710 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5711 	struct bpf_func_state *state = func(env, reg);
5712 	int err;
5713 	/* Some accesses are only permitted with a static offset. */
5714 	bool var_off = !tnum_is_const(reg->var_off);
5715 
5716 	/* The offset is required to be static when reads don't go to a
5717 	 * register, in order to not leak pointers (see
5718 	 * check_stack_read_fixed_off).
5719 	 */
5720 	if (dst_regno < 0 && var_off) {
5721 		char tn_buf[48];
5722 
5723 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5724 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5725 			tn_buf, off, size);
5726 		return -EACCES;
5727 	}
5728 	/* Variable offset is prohibited for unprivileged mode for simplicity
5729 	 * since it requires corresponding support in Spectre masking for stack
5730 	 * ALU. See also retrieve_ptr_limit(). The check in
5731 	 * check_stack_access_for_ptr_arithmetic() called by
5732 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5733 	 * with variable offsets, therefore no check is required here. Further,
5734 	 * just checking it here would be insufficient as speculative stack
5735 	 * writes could still lead to unsafe speculative behaviour.
5736 	 */
5737 	if (!var_off) {
5738 		off += reg->var_off.value;
5739 		err = check_stack_read_fixed_off(env, state, off, size,
5740 						 dst_regno);
5741 	} else {
5742 		/* Variable offset stack reads need more conservative handling
5743 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5744 		 * branch.
5745 		 */
5746 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5747 					       dst_regno);
5748 	}
5749 	return err;
5750 }
5751 
5752 
5753 /* check_stack_write dispatches to check_stack_write_fixed_off or
5754  * check_stack_write_var_off.
5755  *
5756  * 'ptr_regno' is the register used as a pointer into the stack.
5757  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5758  * 'value_regno' is the register whose value we're writing to the stack. It can
5759  * be -1, meaning that we're not writing from a register.
5760  *
5761  * The caller must ensure that the offset falls within the maximum stack size.
5762  */
5763 static int check_stack_write(struct bpf_verifier_env *env,
5764 			     int ptr_regno, int off, int size,
5765 			     int value_regno, int insn_idx)
5766 {
5767 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5768 	struct bpf_func_state *state = func(env, reg);
5769 	int err;
5770 
5771 	if (tnum_is_const(reg->var_off)) {
5772 		off += reg->var_off.value;
5773 		err = check_stack_write_fixed_off(env, state, off, size,
5774 						  value_regno, insn_idx);
5775 	} else {
5776 		/* Variable offset stack reads need more conservative handling
5777 		 * than fixed offset ones.
5778 		 */
5779 		err = check_stack_write_var_off(env, state,
5780 						ptr_regno, off, size,
5781 						value_regno, insn_idx);
5782 	}
5783 	return err;
5784 }
5785 
5786 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5787 				 int off, int size, enum bpf_access_type type)
5788 {
5789 	struct bpf_reg_state *reg = reg_state(env, regno);
5790 	struct bpf_map *map = reg->map_ptr;
5791 	u32 cap = bpf_map_flags_to_cap(map);
5792 
5793 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5794 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5795 			map->value_size, off, size);
5796 		return -EACCES;
5797 	}
5798 
5799 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5800 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5801 			map->value_size, off, size);
5802 		return -EACCES;
5803 	}
5804 
5805 	return 0;
5806 }
5807 
5808 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5809 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5810 			      int off, int size, u32 mem_size,
5811 			      bool zero_size_allowed)
5812 {
5813 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5814 	struct bpf_reg_state *reg;
5815 
5816 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5817 		return 0;
5818 
5819 	reg = &cur_regs(env)[regno];
5820 	switch (reg->type) {
5821 	case PTR_TO_MAP_KEY:
5822 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5823 			mem_size, off, size);
5824 		break;
5825 	case PTR_TO_MAP_VALUE:
5826 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5827 			mem_size, off, size);
5828 		break;
5829 	case PTR_TO_PACKET:
5830 	case PTR_TO_PACKET_META:
5831 	case PTR_TO_PACKET_END:
5832 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5833 			off, size, regno, reg->id, off, mem_size);
5834 		break;
5835 	case PTR_TO_MEM:
5836 	default:
5837 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5838 			mem_size, off, size);
5839 	}
5840 
5841 	return -EACCES;
5842 }
5843 
5844 /* check read/write into a memory region with possible variable offset */
5845 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5846 				   int off, int size, u32 mem_size,
5847 				   bool zero_size_allowed)
5848 {
5849 	struct bpf_verifier_state *vstate = env->cur_state;
5850 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5851 	struct bpf_reg_state *reg = &state->regs[regno];
5852 	int err;
5853 
5854 	/* We may have adjusted the register pointing to memory region, so we
5855 	 * need to try adding each of min_value and max_value to off
5856 	 * to make sure our theoretical access will be safe.
5857 	 *
5858 	 * The minimum value is only important with signed
5859 	 * comparisons where we can't assume the floor of a
5860 	 * value is 0.  If we are using signed variables for our
5861 	 * index'es we need to make sure that whatever we use
5862 	 * will have a set floor within our range.
5863 	 */
5864 	if (reg->smin_value < 0 &&
5865 	    (reg->smin_value == S64_MIN ||
5866 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5867 	      reg->smin_value + off < 0)) {
5868 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5869 			regno);
5870 		return -EACCES;
5871 	}
5872 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5873 				 mem_size, zero_size_allowed);
5874 	if (err) {
5875 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5876 			regno);
5877 		return err;
5878 	}
5879 
5880 	/* If we haven't set a max value then we need to bail since we can't be
5881 	 * sure we won't do bad things.
5882 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5883 	 */
5884 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5885 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5886 			regno);
5887 		return -EACCES;
5888 	}
5889 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5890 				 mem_size, zero_size_allowed);
5891 	if (err) {
5892 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5893 			regno);
5894 		return err;
5895 	}
5896 
5897 	return 0;
5898 }
5899 
5900 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5901 			       const struct bpf_reg_state *reg, int regno,
5902 			       bool fixed_off_ok)
5903 {
5904 	/* Access to this pointer-typed register or passing it to a helper
5905 	 * is only allowed in its original, unmodified form.
5906 	 */
5907 
5908 	if (reg->off < 0) {
5909 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5910 			reg_type_str(env, reg->type), regno, reg->off);
5911 		return -EACCES;
5912 	}
5913 
5914 	if (!fixed_off_ok && reg->off) {
5915 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5916 			reg_type_str(env, reg->type), regno, reg->off);
5917 		return -EACCES;
5918 	}
5919 
5920 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5921 		char tn_buf[48];
5922 
5923 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5924 		verbose(env, "variable %s access var_off=%s disallowed\n",
5925 			reg_type_str(env, reg->type), tn_buf);
5926 		return -EACCES;
5927 	}
5928 
5929 	return 0;
5930 }
5931 
5932 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5933 		             const struct bpf_reg_state *reg, int regno)
5934 {
5935 	return __check_ptr_off_reg(env, reg, regno, false);
5936 }
5937 
5938 static int map_kptr_match_type(struct bpf_verifier_env *env,
5939 			       struct btf_field *kptr_field,
5940 			       struct bpf_reg_state *reg, u32 regno)
5941 {
5942 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5943 	int perm_flags;
5944 	const char *reg_name = "";
5945 
5946 	if (btf_is_kernel(reg->btf)) {
5947 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5948 
5949 		/* Only unreferenced case accepts untrusted pointers */
5950 		if (kptr_field->type == BPF_KPTR_UNREF)
5951 			perm_flags |= PTR_UNTRUSTED;
5952 	} else {
5953 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5954 		if (kptr_field->type == BPF_KPTR_PERCPU)
5955 			perm_flags |= MEM_PERCPU;
5956 	}
5957 
5958 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5959 		goto bad_type;
5960 
5961 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5962 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5963 
5964 	/* For ref_ptr case, release function check should ensure we get one
5965 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5966 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5967 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5968 	 * reg->off and reg->ref_obj_id are not needed here.
5969 	 */
5970 	if (__check_ptr_off_reg(env, reg, regno, true))
5971 		return -EACCES;
5972 
5973 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5974 	 * we also need to take into account the reg->off.
5975 	 *
5976 	 * We want to support cases like:
5977 	 *
5978 	 * struct foo {
5979 	 *         struct bar br;
5980 	 *         struct baz bz;
5981 	 * };
5982 	 *
5983 	 * struct foo *v;
5984 	 * v = func();	      // PTR_TO_BTF_ID
5985 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5986 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5987 	 *                    // first member type of struct after comparison fails
5988 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5989 	 *                    // to match type
5990 	 *
5991 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5992 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5993 	 * the struct to match type against first member of struct, i.e. reject
5994 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5995 	 * strict mode to true for type match.
5996 	 */
5997 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5998 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5999 				  kptr_field->type != BPF_KPTR_UNREF))
6000 		goto bad_type;
6001 	return 0;
6002 bad_type:
6003 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
6004 		reg_type_str(env, reg->type), reg_name);
6005 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
6006 	if (kptr_field->type == BPF_KPTR_UNREF)
6007 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
6008 			targ_name);
6009 	else
6010 		verbose(env, "\n");
6011 	return -EINVAL;
6012 }
6013 
6014 static bool in_sleepable(struct bpf_verifier_env *env)
6015 {
6016 	return env->cur_state->in_sleepable;
6017 }
6018 
6019 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
6020  * can dereference RCU protected pointers and result is PTR_TRUSTED.
6021  */
6022 static bool in_rcu_cs(struct bpf_verifier_env *env)
6023 {
6024 	return env->cur_state->active_rcu_locks ||
6025 	       env->cur_state->active_locks ||
6026 	       !in_sleepable(env);
6027 }
6028 
6029 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
6030 BTF_SET_START(rcu_protected_types)
6031 #ifdef CONFIG_NET
6032 BTF_ID(struct, prog_test_ref_kfunc)
6033 #endif
6034 #ifdef CONFIG_CGROUPS
6035 BTF_ID(struct, cgroup)
6036 #endif
6037 #ifdef CONFIG_BPF_JIT
6038 BTF_ID(struct, bpf_cpumask)
6039 #endif
6040 BTF_ID(struct, task_struct)
6041 #ifdef CONFIG_CRYPTO
6042 BTF_ID(struct, bpf_crypto_ctx)
6043 #endif
6044 BTF_SET_END(rcu_protected_types)
6045 
6046 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
6047 {
6048 	if (!btf_is_kernel(btf))
6049 		return true;
6050 	return btf_id_set_contains(&rcu_protected_types, btf_id);
6051 }
6052 
6053 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
6054 {
6055 	struct btf_struct_meta *meta;
6056 
6057 	if (btf_is_kernel(kptr_field->kptr.btf))
6058 		return NULL;
6059 
6060 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
6061 				    kptr_field->kptr.btf_id);
6062 
6063 	return meta ? meta->record : NULL;
6064 }
6065 
6066 static bool rcu_safe_kptr(const struct btf_field *field)
6067 {
6068 	const struct btf_field_kptr *kptr = &field->kptr;
6069 
6070 	return field->type == BPF_KPTR_PERCPU ||
6071 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
6072 }
6073 
6074 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
6075 {
6076 	struct btf_record *rec;
6077 	u32 ret;
6078 
6079 	ret = PTR_MAYBE_NULL;
6080 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
6081 		ret |= MEM_RCU;
6082 		if (kptr_field->type == BPF_KPTR_PERCPU)
6083 			ret |= MEM_PERCPU;
6084 		else if (!btf_is_kernel(kptr_field->kptr.btf))
6085 			ret |= MEM_ALLOC;
6086 
6087 		rec = kptr_pointee_btf_record(kptr_field);
6088 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
6089 			ret |= NON_OWN_REF;
6090 	} else {
6091 		ret |= PTR_UNTRUSTED;
6092 	}
6093 
6094 	return ret;
6095 }
6096 
6097 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
6098 			    struct btf_field *field)
6099 {
6100 	struct bpf_reg_state *reg;
6101 	const struct btf_type *t;
6102 
6103 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
6104 	mark_reg_known_zero(env, cur_regs(env), regno);
6105 	reg = reg_state(env, regno);
6106 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
6107 	reg->mem_size = t->size;
6108 	reg->id = ++env->id_gen;
6109 
6110 	return 0;
6111 }
6112 
6113 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
6114 				 int value_regno, int insn_idx,
6115 				 struct btf_field *kptr_field)
6116 {
6117 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
6118 	int class = BPF_CLASS(insn->code);
6119 	struct bpf_reg_state *val_reg;
6120 	int ret;
6121 
6122 	/* Things we already checked for in check_map_access and caller:
6123 	 *  - Reject cases where variable offset may touch kptr
6124 	 *  - size of access (must be BPF_DW)
6125 	 *  - tnum_is_const(reg->var_off)
6126 	 *  - kptr_field->offset == off + reg->var_off.value
6127 	 */
6128 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
6129 	if (BPF_MODE(insn->code) != BPF_MEM) {
6130 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
6131 		return -EACCES;
6132 	}
6133 
6134 	/* We only allow loading referenced kptr, since it will be marked as
6135 	 * untrusted, similar to unreferenced kptr.
6136 	 */
6137 	if (class != BPF_LDX &&
6138 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
6139 		verbose(env, "store to referenced kptr disallowed\n");
6140 		return -EACCES;
6141 	}
6142 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
6143 		verbose(env, "store to uptr disallowed\n");
6144 		return -EACCES;
6145 	}
6146 
6147 	if (class == BPF_LDX) {
6148 		if (kptr_field->type == BPF_UPTR)
6149 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
6150 
6151 		/* We can simply mark the value_regno receiving the pointer
6152 		 * value from map as PTR_TO_BTF_ID, with the correct type.
6153 		 */
6154 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
6155 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
6156 				      btf_ld_kptr_type(env, kptr_field));
6157 		if (ret < 0)
6158 			return ret;
6159 	} else if (class == BPF_STX) {
6160 		val_reg = reg_state(env, value_regno);
6161 		if (!register_is_null(val_reg) &&
6162 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
6163 			return -EACCES;
6164 	} else if (class == BPF_ST) {
6165 		if (insn->imm) {
6166 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
6167 				kptr_field->offset);
6168 			return -EACCES;
6169 		}
6170 	} else {
6171 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
6172 		return -EACCES;
6173 	}
6174 	return 0;
6175 }
6176 
6177 /*
6178  * Return the size of the memory region accessible from a pointer to map value.
6179  * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible.
6180  */
6181 static u32 map_mem_size(const struct bpf_map *map)
6182 {
6183 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY)
6184 		return map->max_entries * sizeof(long);
6185 
6186 	return map->value_size;
6187 }
6188 
6189 /* check read/write into a map element with possible variable offset */
6190 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
6191 			    int off, int size, bool zero_size_allowed,
6192 			    enum bpf_access_src src)
6193 {
6194 	struct bpf_verifier_state *vstate = env->cur_state;
6195 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6196 	struct bpf_reg_state *reg = &state->regs[regno];
6197 	struct bpf_map *map = reg->map_ptr;
6198 	u32 mem_size = map_mem_size(map);
6199 	struct btf_record *rec;
6200 	int err, i;
6201 
6202 	err = check_mem_region_access(env, regno, off, size, mem_size, zero_size_allowed);
6203 	if (err)
6204 		return err;
6205 
6206 	if (IS_ERR_OR_NULL(map->record))
6207 		return 0;
6208 	rec = map->record;
6209 	for (i = 0; i < rec->cnt; i++) {
6210 		struct btf_field *field = &rec->fields[i];
6211 		u32 p = field->offset;
6212 
6213 		/* If any part of a field  can be touched by load/store, reject
6214 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
6215 		 * it is sufficient to check x1 < y2 && y1 < x2.
6216 		 */
6217 		if (reg->smin_value + off < p + field->size &&
6218 		    p < reg->umax_value + off + size) {
6219 			switch (field->type) {
6220 			case BPF_KPTR_UNREF:
6221 			case BPF_KPTR_REF:
6222 			case BPF_KPTR_PERCPU:
6223 			case BPF_UPTR:
6224 				if (src != ACCESS_DIRECT) {
6225 					verbose(env, "%s cannot be accessed indirectly by helper\n",
6226 						btf_field_type_name(field->type));
6227 					return -EACCES;
6228 				}
6229 				if (!tnum_is_const(reg->var_off)) {
6230 					verbose(env, "%s access cannot have variable offset\n",
6231 						btf_field_type_name(field->type));
6232 					return -EACCES;
6233 				}
6234 				if (p != off + reg->var_off.value) {
6235 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
6236 						btf_field_type_name(field->type),
6237 						p, off + reg->var_off.value);
6238 					return -EACCES;
6239 				}
6240 				if (size != bpf_size_to_bytes(BPF_DW)) {
6241 					verbose(env, "%s access size must be BPF_DW\n",
6242 						btf_field_type_name(field->type));
6243 					return -EACCES;
6244 				}
6245 				break;
6246 			default:
6247 				verbose(env, "%s cannot be accessed directly by load/store\n",
6248 					btf_field_type_name(field->type));
6249 				return -EACCES;
6250 			}
6251 		}
6252 	}
6253 	return 0;
6254 }
6255 
6256 #define MAX_PACKET_OFF 0xffff
6257 
6258 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
6259 				       const struct bpf_call_arg_meta *meta,
6260 				       enum bpf_access_type t)
6261 {
6262 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6263 
6264 	switch (prog_type) {
6265 	/* Program types only with direct read access go here! */
6266 	case BPF_PROG_TYPE_LWT_IN:
6267 	case BPF_PROG_TYPE_LWT_OUT:
6268 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
6269 	case BPF_PROG_TYPE_SK_REUSEPORT:
6270 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6271 	case BPF_PROG_TYPE_CGROUP_SKB:
6272 		if (t == BPF_WRITE)
6273 			return false;
6274 		fallthrough;
6275 
6276 	/* Program types with direct read + write access go here! */
6277 	case BPF_PROG_TYPE_SCHED_CLS:
6278 	case BPF_PROG_TYPE_SCHED_ACT:
6279 	case BPF_PROG_TYPE_XDP:
6280 	case BPF_PROG_TYPE_LWT_XMIT:
6281 	case BPF_PROG_TYPE_SK_SKB:
6282 	case BPF_PROG_TYPE_SK_MSG:
6283 		if (meta)
6284 			return meta->pkt_access;
6285 
6286 		env->seen_direct_write = true;
6287 		return true;
6288 
6289 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
6290 		if (t == BPF_WRITE)
6291 			env->seen_direct_write = true;
6292 
6293 		return true;
6294 
6295 	default:
6296 		return false;
6297 	}
6298 }
6299 
6300 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
6301 			       int size, bool zero_size_allowed)
6302 {
6303 	struct bpf_reg_state *reg = reg_state(env, regno);
6304 	int err;
6305 
6306 	/* We may have added a variable offset to the packet pointer; but any
6307 	 * reg->range we have comes after that.  We are only checking the fixed
6308 	 * offset.
6309 	 */
6310 
6311 	/* We don't allow negative numbers, because we aren't tracking enough
6312 	 * detail to prove they're safe.
6313 	 */
6314 	if (reg->smin_value < 0) {
6315 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6316 			regno);
6317 		return -EACCES;
6318 	}
6319 
6320 	err = reg->range < 0 ? -EINVAL :
6321 	      __check_mem_access(env, regno, off, size, reg->range,
6322 				 zero_size_allowed);
6323 	if (err) {
6324 		verbose(env, "R%d offset is outside of the packet\n", regno);
6325 		return err;
6326 	}
6327 
6328 	/* __check_mem_access has made sure "off + size - 1" is within u16.
6329 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
6330 	 * otherwise find_good_pkt_pointers would have refused to set range info
6331 	 * that __check_mem_access would have rejected this pkt access.
6332 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
6333 	 */
6334 	env->prog->aux->max_pkt_offset =
6335 		max_t(u32, env->prog->aux->max_pkt_offset,
6336 		      off + reg->umax_value + size - 1);
6337 
6338 	return err;
6339 }
6340 
6341 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
6342 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
6343 			    enum bpf_access_type t, struct bpf_insn_access_aux *info)
6344 {
6345 	if (env->ops->is_valid_access &&
6346 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
6347 		/* A non zero info.ctx_field_size indicates that this field is a
6348 		 * candidate for later verifier transformation to load the whole
6349 		 * field and then apply a mask when accessed with a narrower
6350 		 * access than actual ctx access size. A zero info.ctx_field_size
6351 		 * will only allow for whole field access and rejects any other
6352 		 * type of narrower access.
6353 		 */
6354 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
6355 			if (info->ref_obj_id &&
6356 			    !find_reference_state(env->cur_state, info->ref_obj_id)) {
6357 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
6358 					off);
6359 				return -EACCES;
6360 			}
6361 		} else {
6362 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
6363 		}
6364 		/* remember the offset of last byte accessed in ctx */
6365 		if (env->prog->aux->max_ctx_offset < off + size)
6366 			env->prog->aux->max_ctx_offset = off + size;
6367 		return 0;
6368 	}
6369 
6370 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
6371 	return -EACCES;
6372 }
6373 
6374 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
6375 				  int size)
6376 {
6377 	if (size < 0 || off < 0 ||
6378 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
6379 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
6380 			off, size);
6381 		return -EACCES;
6382 	}
6383 	return 0;
6384 }
6385 
6386 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
6387 			     u32 regno, int off, int size,
6388 			     enum bpf_access_type t)
6389 {
6390 	struct bpf_reg_state *reg = reg_state(env, regno);
6391 	struct bpf_insn_access_aux info = {};
6392 	bool valid;
6393 
6394 	if (reg->smin_value < 0) {
6395 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6396 			regno);
6397 		return -EACCES;
6398 	}
6399 
6400 	switch (reg->type) {
6401 	case PTR_TO_SOCK_COMMON:
6402 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
6403 		break;
6404 	case PTR_TO_SOCKET:
6405 		valid = bpf_sock_is_valid_access(off, size, t, &info);
6406 		break;
6407 	case PTR_TO_TCP_SOCK:
6408 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
6409 		break;
6410 	case PTR_TO_XDP_SOCK:
6411 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
6412 		break;
6413 	default:
6414 		valid = false;
6415 	}
6416 
6417 
6418 	if (valid) {
6419 		env->insn_aux_data[insn_idx].ctx_field_size =
6420 			info.ctx_field_size;
6421 		return 0;
6422 	}
6423 
6424 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
6425 		regno, reg_type_str(env, reg->type), off, size);
6426 
6427 	return -EACCES;
6428 }
6429 
6430 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
6431 {
6432 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
6433 }
6434 
6435 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
6436 {
6437 	const struct bpf_reg_state *reg = reg_state(env, regno);
6438 
6439 	return reg->type == PTR_TO_CTX;
6440 }
6441 
6442 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
6443 {
6444 	const struct bpf_reg_state *reg = reg_state(env, regno);
6445 
6446 	return type_is_sk_pointer(reg->type);
6447 }
6448 
6449 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
6450 {
6451 	const struct bpf_reg_state *reg = reg_state(env, regno);
6452 
6453 	return type_is_pkt_pointer(reg->type);
6454 }
6455 
6456 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
6457 {
6458 	const struct bpf_reg_state *reg = reg_state(env, regno);
6459 
6460 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
6461 	return reg->type == PTR_TO_FLOW_KEYS;
6462 }
6463 
6464 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
6465 {
6466 	const struct bpf_reg_state *reg = reg_state(env, regno);
6467 
6468 	return reg->type == PTR_TO_ARENA;
6469 }
6470 
6471 /* Return false if @regno contains a pointer whose type isn't supported for
6472  * atomic instruction @insn.
6473  */
6474 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
6475 			       struct bpf_insn *insn)
6476 {
6477 	if (is_ctx_reg(env, regno))
6478 		return false;
6479 	if (is_pkt_reg(env, regno))
6480 		return false;
6481 	if (is_flow_key_reg(env, regno))
6482 		return false;
6483 	if (is_sk_reg(env, regno))
6484 		return false;
6485 	if (is_arena_reg(env, regno))
6486 		return bpf_jit_supports_insn(insn, true);
6487 
6488 	return true;
6489 }
6490 
6491 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
6492 #ifdef CONFIG_NET
6493 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
6494 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6495 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
6496 #endif
6497 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
6498 };
6499 
6500 static bool is_trusted_reg(const struct bpf_reg_state *reg)
6501 {
6502 	/* A referenced register is always trusted. */
6503 	if (reg->ref_obj_id)
6504 		return true;
6505 
6506 	/* Types listed in the reg2btf_ids are always trusted */
6507 	if (reg2btf_ids[base_type(reg->type)] &&
6508 	    !bpf_type_has_unsafe_modifiers(reg->type))
6509 		return true;
6510 
6511 	/* If a register is not referenced, it is trusted if it has the
6512 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
6513 	 * other type modifiers may be safe, but we elect to take an opt-in
6514 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
6515 	 * not.
6516 	 *
6517 	 * Eventually, we should make PTR_TRUSTED the single source of truth
6518 	 * for whether a register is trusted.
6519 	 */
6520 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
6521 	       !bpf_type_has_unsafe_modifiers(reg->type);
6522 }
6523 
6524 static bool is_rcu_reg(const struct bpf_reg_state *reg)
6525 {
6526 	return reg->type & MEM_RCU;
6527 }
6528 
6529 static void clear_trusted_flags(enum bpf_type_flag *flag)
6530 {
6531 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
6532 }
6533 
6534 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
6535 				   const struct bpf_reg_state *reg,
6536 				   int off, int size, bool strict)
6537 {
6538 	struct tnum reg_off;
6539 	int ip_align;
6540 
6541 	/* Byte size accesses are always allowed. */
6542 	if (!strict || size == 1)
6543 		return 0;
6544 
6545 	/* For platforms that do not have a Kconfig enabling
6546 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
6547 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
6548 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
6549 	 * to this code only in strict mode where we want to emulate
6550 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
6551 	 * unconditional IP align value of '2'.
6552 	 */
6553 	ip_align = 2;
6554 
6555 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
6556 	if (!tnum_is_aligned(reg_off, size)) {
6557 		char tn_buf[48];
6558 
6559 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6560 		verbose(env,
6561 			"misaligned packet access off %d+%s+%d+%d size %d\n",
6562 			ip_align, tn_buf, reg->off, off, size);
6563 		return -EACCES;
6564 	}
6565 
6566 	return 0;
6567 }
6568 
6569 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
6570 				       const struct bpf_reg_state *reg,
6571 				       const char *pointer_desc,
6572 				       int off, int size, bool strict)
6573 {
6574 	struct tnum reg_off;
6575 
6576 	/* Byte size accesses are always allowed. */
6577 	if (!strict || size == 1)
6578 		return 0;
6579 
6580 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
6581 	if (!tnum_is_aligned(reg_off, size)) {
6582 		char tn_buf[48];
6583 
6584 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6585 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
6586 			pointer_desc, tn_buf, reg->off, off, size);
6587 		return -EACCES;
6588 	}
6589 
6590 	return 0;
6591 }
6592 
6593 static int check_ptr_alignment(struct bpf_verifier_env *env,
6594 			       const struct bpf_reg_state *reg, int off,
6595 			       int size, bool strict_alignment_once)
6596 {
6597 	bool strict = env->strict_alignment || strict_alignment_once;
6598 	const char *pointer_desc = "";
6599 
6600 	switch (reg->type) {
6601 	case PTR_TO_PACKET:
6602 	case PTR_TO_PACKET_META:
6603 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
6604 		 * right in front, treat it the very same way.
6605 		 */
6606 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
6607 	case PTR_TO_FLOW_KEYS:
6608 		pointer_desc = "flow keys ";
6609 		break;
6610 	case PTR_TO_MAP_KEY:
6611 		pointer_desc = "key ";
6612 		break;
6613 	case PTR_TO_MAP_VALUE:
6614 		pointer_desc = "value ";
6615 		if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY)
6616 			strict = true;
6617 		break;
6618 	case PTR_TO_CTX:
6619 		pointer_desc = "context ";
6620 		break;
6621 	case PTR_TO_STACK:
6622 		pointer_desc = "stack ";
6623 		/* The stack spill tracking logic in check_stack_write_fixed_off()
6624 		 * and check_stack_read_fixed_off() relies on stack accesses being
6625 		 * aligned.
6626 		 */
6627 		strict = true;
6628 		break;
6629 	case PTR_TO_SOCKET:
6630 		pointer_desc = "sock ";
6631 		break;
6632 	case PTR_TO_SOCK_COMMON:
6633 		pointer_desc = "sock_common ";
6634 		break;
6635 	case PTR_TO_TCP_SOCK:
6636 		pointer_desc = "tcp_sock ";
6637 		break;
6638 	case PTR_TO_XDP_SOCK:
6639 		pointer_desc = "xdp_sock ";
6640 		break;
6641 	case PTR_TO_ARENA:
6642 		return 0;
6643 	default:
6644 		break;
6645 	}
6646 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
6647 					   strict);
6648 }
6649 
6650 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
6651 {
6652 	if (!bpf_jit_supports_private_stack())
6653 		return NO_PRIV_STACK;
6654 
6655 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
6656 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
6657 	 * explicitly.
6658 	 */
6659 	switch (prog->type) {
6660 	case BPF_PROG_TYPE_KPROBE:
6661 	case BPF_PROG_TYPE_TRACEPOINT:
6662 	case BPF_PROG_TYPE_PERF_EVENT:
6663 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6664 		return PRIV_STACK_ADAPTIVE;
6665 	case BPF_PROG_TYPE_TRACING:
6666 	case BPF_PROG_TYPE_LSM:
6667 	case BPF_PROG_TYPE_STRUCT_OPS:
6668 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
6669 			return PRIV_STACK_ADAPTIVE;
6670 		fallthrough;
6671 	default:
6672 		break;
6673 	}
6674 
6675 	return NO_PRIV_STACK;
6676 }
6677 
6678 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
6679 {
6680 	if (env->prog->jit_requested)
6681 		return round_up(stack_depth, 16);
6682 
6683 	/* round up to 32-bytes, since this is granularity
6684 	 * of interpreter stack size
6685 	 */
6686 	return round_up(max_t(u32, stack_depth, 1), 32);
6687 }
6688 
6689 /* starting from main bpf function walk all instructions of the function
6690  * and recursively walk all callees that given function can call.
6691  * Ignore jump and exit insns.
6692  * Since recursion is prevented by check_cfg() this algorithm
6693  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6694  */
6695 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
6696 					 bool priv_stack_supported)
6697 {
6698 	struct bpf_subprog_info *subprog = env->subprog_info;
6699 	struct bpf_insn *insn = env->prog->insnsi;
6700 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
6701 	bool tail_call_reachable = false;
6702 	int ret_insn[MAX_CALL_FRAMES];
6703 	int ret_prog[MAX_CALL_FRAMES];
6704 	int j;
6705 
6706 	i = subprog[idx].start;
6707 	if (!priv_stack_supported)
6708 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6709 process_func:
6710 	/* protect against potential stack overflow that might happen when
6711 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6712 	 * depth for such case down to 256 so that the worst case scenario
6713 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
6714 	 * 8k).
6715 	 *
6716 	 * To get the idea what might happen, see an example:
6717 	 * func1 -> sub rsp, 128
6718 	 *  subfunc1 -> sub rsp, 256
6719 	 *  tailcall1 -> add rsp, 256
6720 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6721 	 *   subfunc2 -> sub rsp, 64
6722 	 *   subfunc22 -> sub rsp, 128
6723 	 *   tailcall2 -> add rsp, 128
6724 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6725 	 *
6726 	 * tailcall will unwind the current stack frame but it will not get rid
6727 	 * of caller's stack as shown on the example above.
6728 	 */
6729 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
6730 		verbose(env,
6731 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6732 			depth);
6733 		return -EACCES;
6734 	}
6735 
6736 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
6737 	if (priv_stack_supported) {
6738 		/* Request private stack support only if the subprog stack
6739 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
6740 		 * avoid jit penalty if the stack usage is small.
6741 		 */
6742 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
6743 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
6744 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
6745 	}
6746 
6747 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6748 		if (subprog_depth > MAX_BPF_STACK) {
6749 			verbose(env, "stack size of subprog %d is %d. Too large\n",
6750 				idx, subprog_depth);
6751 			return -EACCES;
6752 		}
6753 	} else {
6754 		depth += subprog_depth;
6755 		if (depth > MAX_BPF_STACK) {
6756 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
6757 				frame + 1, depth);
6758 			return -EACCES;
6759 		}
6760 	}
6761 continue_func:
6762 	subprog_end = subprog[idx + 1].start;
6763 	for (; i < subprog_end; i++) {
6764 		int next_insn, sidx;
6765 
6766 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6767 			bool err = false;
6768 
6769 			if (!is_bpf_throw_kfunc(insn + i))
6770 				continue;
6771 			if (subprog[idx].is_cb)
6772 				err = true;
6773 			for (int c = 0; c < frame && !err; c++) {
6774 				if (subprog[ret_prog[c]].is_cb) {
6775 					err = true;
6776 					break;
6777 				}
6778 			}
6779 			if (!err)
6780 				continue;
6781 			verbose(env,
6782 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6783 				i, idx);
6784 			return -EINVAL;
6785 		}
6786 
6787 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6788 			continue;
6789 		/* remember insn and function to return to */
6790 		ret_insn[frame] = i + 1;
6791 		ret_prog[frame] = idx;
6792 
6793 		/* find the callee */
6794 		next_insn = i + insn[i].imm + 1;
6795 		sidx = find_subprog(env, next_insn);
6796 		if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
6797 			return -EFAULT;
6798 		if (subprog[sidx].is_async_cb) {
6799 			if (subprog[sidx].has_tail_call) {
6800 				verifier_bug(env, "subprog has tail_call and async cb");
6801 				return -EFAULT;
6802 			}
6803 			/* async callbacks don't increase bpf prog stack size unless called directly */
6804 			if (!bpf_pseudo_call(insn + i))
6805 				continue;
6806 			if (subprog[sidx].is_exception_cb) {
6807 				verbose(env, "insn %d cannot call exception cb directly", i);
6808 				return -EINVAL;
6809 			}
6810 		}
6811 		i = next_insn;
6812 		idx = sidx;
6813 		if (!priv_stack_supported)
6814 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6815 
6816 		if (subprog[idx].has_tail_call)
6817 			tail_call_reachable = true;
6818 
6819 		frame++;
6820 		if (frame >= MAX_CALL_FRAMES) {
6821 			verbose(env, "the call stack of %d frames is too deep !\n",
6822 				frame);
6823 			return -E2BIG;
6824 		}
6825 		goto process_func;
6826 	}
6827 	/* if tail call got detected across bpf2bpf calls then mark each of the
6828 	 * currently present subprog frames as tail call reachable subprogs;
6829 	 * this info will be utilized by JIT so that we will be preserving the
6830 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6831 	 */
6832 	if (tail_call_reachable)
6833 		for (j = 0; j < frame; j++) {
6834 			if (subprog[ret_prog[j]].is_exception_cb) {
6835 				verbose(env, "cannot tail call within exception cb\n");
6836 				return -EINVAL;
6837 			}
6838 			subprog[ret_prog[j]].tail_call_reachable = true;
6839 		}
6840 	if (subprog[0].tail_call_reachable)
6841 		env->prog->aux->tail_call_reachable = true;
6842 
6843 	/* end of for() loop means the last insn of the 'subprog'
6844 	 * was reached. Doesn't matter whether it was JA or EXIT
6845 	 */
6846 	if (frame == 0)
6847 		return 0;
6848 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6849 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6850 	frame--;
6851 	i = ret_insn[frame];
6852 	idx = ret_prog[frame];
6853 	goto continue_func;
6854 }
6855 
6856 static int check_max_stack_depth(struct bpf_verifier_env *env)
6857 {
6858 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6859 	struct bpf_subprog_info *si = env->subprog_info;
6860 	bool priv_stack_supported;
6861 	int ret;
6862 
6863 	for (int i = 0; i < env->subprog_cnt; i++) {
6864 		if (si[i].has_tail_call) {
6865 			priv_stack_mode = NO_PRIV_STACK;
6866 			break;
6867 		}
6868 	}
6869 
6870 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6871 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6872 
6873 	/* All async_cb subprogs use normal kernel stack. If a particular
6874 	 * subprog appears in both main prog and async_cb subtree, that
6875 	 * subprog will use normal kernel stack to avoid potential nesting.
6876 	 * The reverse subprog traversal ensures when main prog subtree is
6877 	 * checked, the subprogs appearing in async_cb subtrees are already
6878 	 * marked as using normal kernel stack, so stack size checking can
6879 	 * be done properly.
6880 	 */
6881 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6882 		if (!i || si[i].is_async_cb) {
6883 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6884 			ret = check_max_stack_depth_subprog(env, i, priv_stack_supported);
6885 			if (ret < 0)
6886 				return ret;
6887 		}
6888 	}
6889 
6890 	for (int i = 0; i < env->subprog_cnt; i++) {
6891 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6892 			env->prog->aux->jits_use_priv_stack = true;
6893 			break;
6894 		}
6895 	}
6896 
6897 	return 0;
6898 }
6899 
6900 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6901 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6902 				  const struct bpf_insn *insn, int idx)
6903 {
6904 	int start = idx + insn->imm + 1, subprog;
6905 
6906 	subprog = find_subprog(env, start);
6907 	if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start))
6908 		return -EFAULT;
6909 	return env->subprog_info[subprog].stack_depth;
6910 }
6911 #endif
6912 
6913 static int __check_buffer_access(struct bpf_verifier_env *env,
6914 				 const char *buf_info,
6915 				 const struct bpf_reg_state *reg,
6916 				 int regno, int off, int size)
6917 {
6918 	if (off < 0) {
6919 		verbose(env,
6920 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6921 			regno, buf_info, off, size);
6922 		return -EACCES;
6923 	}
6924 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6925 		char tn_buf[48];
6926 
6927 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6928 		verbose(env,
6929 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6930 			regno, off, tn_buf);
6931 		return -EACCES;
6932 	}
6933 
6934 	return 0;
6935 }
6936 
6937 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6938 				  const struct bpf_reg_state *reg,
6939 				  int regno, int off, int size)
6940 {
6941 	int err;
6942 
6943 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6944 	if (err)
6945 		return err;
6946 
6947 	if (off + size > env->prog->aux->max_tp_access)
6948 		env->prog->aux->max_tp_access = off + size;
6949 
6950 	return 0;
6951 }
6952 
6953 static int check_buffer_access(struct bpf_verifier_env *env,
6954 			       const struct bpf_reg_state *reg,
6955 			       int regno, int off, int size,
6956 			       bool zero_size_allowed,
6957 			       u32 *max_access)
6958 {
6959 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6960 	int err;
6961 
6962 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6963 	if (err)
6964 		return err;
6965 
6966 	if (off + size > *max_access)
6967 		*max_access = off + size;
6968 
6969 	return 0;
6970 }
6971 
6972 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6973 static void zext_32_to_64(struct bpf_reg_state *reg)
6974 {
6975 	reg->var_off = tnum_subreg(reg->var_off);
6976 	__reg_assign_32_into_64(reg);
6977 }
6978 
6979 /* truncate register to smaller size (in bytes)
6980  * must be called with size < BPF_REG_SIZE
6981  */
6982 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6983 {
6984 	u64 mask;
6985 
6986 	/* clear high bits in bit representation */
6987 	reg->var_off = tnum_cast(reg->var_off, size);
6988 
6989 	/* fix arithmetic bounds */
6990 	mask = ((u64)1 << (size * 8)) - 1;
6991 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6992 		reg->umin_value &= mask;
6993 		reg->umax_value &= mask;
6994 	} else {
6995 		reg->umin_value = 0;
6996 		reg->umax_value = mask;
6997 	}
6998 	reg->smin_value = reg->umin_value;
6999 	reg->smax_value = reg->umax_value;
7000 
7001 	/* If size is smaller than 32bit register the 32bit register
7002 	 * values are also truncated so we push 64-bit bounds into
7003 	 * 32-bit bounds. Above were truncated < 32-bits already.
7004 	 */
7005 	if (size < 4)
7006 		__mark_reg32_unbounded(reg);
7007 
7008 	reg_bounds_sync(reg);
7009 }
7010 
7011 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
7012 {
7013 	if (size == 1) {
7014 		reg->smin_value = reg->s32_min_value = S8_MIN;
7015 		reg->smax_value = reg->s32_max_value = S8_MAX;
7016 	} else if (size == 2) {
7017 		reg->smin_value = reg->s32_min_value = S16_MIN;
7018 		reg->smax_value = reg->s32_max_value = S16_MAX;
7019 	} else {
7020 		/* size == 4 */
7021 		reg->smin_value = reg->s32_min_value = S32_MIN;
7022 		reg->smax_value = reg->s32_max_value = S32_MAX;
7023 	}
7024 	reg->umin_value = reg->u32_min_value = 0;
7025 	reg->umax_value = U64_MAX;
7026 	reg->u32_max_value = U32_MAX;
7027 	reg->var_off = tnum_unknown;
7028 }
7029 
7030 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
7031 {
7032 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
7033 	u64 top_smax_value, top_smin_value;
7034 	u64 num_bits = size * 8;
7035 
7036 	if (tnum_is_const(reg->var_off)) {
7037 		u64_cval = reg->var_off.value;
7038 		if (size == 1)
7039 			reg->var_off = tnum_const((s8)u64_cval);
7040 		else if (size == 2)
7041 			reg->var_off = tnum_const((s16)u64_cval);
7042 		else
7043 			/* size == 4 */
7044 			reg->var_off = tnum_const((s32)u64_cval);
7045 
7046 		u64_cval = reg->var_off.value;
7047 		reg->smax_value = reg->smin_value = u64_cval;
7048 		reg->umax_value = reg->umin_value = u64_cval;
7049 		reg->s32_max_value = reg->s32_min_value = u64_cval;
7050 		reg->u32_max_value = reg->u32_min_value = u64_cval;
7051 		return;
7052 	}
7053 
7054 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
7055 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
7056 
7057 	if (top_smax_value != top_smin_value)
7058 		goto out;
7059 
7060 	/* find the s64_min and s64_min after sign extension */
7061 	if (size == 1) {
7062 		init_s64_max = (s8)reg->smax_value;
7063 		init_s64_min = (s8)reg->smin_value;
7064 	} else if (size == 2) {
7065 		init_s64_max = (s16)reg->smax_value;
7066 		init_s64_min = (s16)reg->smin_value;
7067 	} else {
7068 		init_s64_max = (s32)reg->smax_value;
7069 		init_s64_min = (s32)reg->smin_value;
7070 	}
7071 
7072 	s64_max = max(init_s64_max, init_s64_min);
7073 	s64_min = min(init_s64_max, init_s64_min);
7074 
7075 	/* both of s64_max/s64_min positive or negative */
7076 	if ((s64_max >= 0) == (s64_min >= 0)) {
7077 		reg->s32_min_value = reg->smin_value = s64_min;
7078 		reg->s32_max_value = reg->smax_value = s64_max;
7079 		reg->u32_min_value = reg->umin_value = s64_min;
7080 		reg->u32_max_value = reg->umax_value = s64_max;
7081 		reg->var_off = tnum_range(s64_min, s64_max);
7082 		return;
7083 	}
7084 
7085 out:
7086 	set_sext64_default_val(reg, size);
7087 }
7088 
7089 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
7090 {
7091 	if (size == 1) {
7092 		reg->s32_min_value = S8_MIN;
7093 		reg->s32_max_value = S8_MAX;
7094 	} else {
7095 		/* size == 2 */
7096 		reg->s32_min_value = S16_MIN;
7097 		reg->s32_max_value = S16_MAX;
7098 	}
7099 	reg->u32_min_value = 0;
7100 	reg->u32_max_value = U32_MAX;
7101 	reg->var_off = tnum_subreg(tnum_unknown);
7102 }
7103 
7104 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
7105 {
7106 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
7107 	u32 top_smax_value, top_smin_value;
7108 	u32 num_bits = size * 8;
7109 
7110 	if (tnum_is_const(reg->var_off)) {
7111 		u32_val = reg->var_off.value;
7112 		if (size == 1)
7113 			reg->var_off = tnum_const((s8)u32_val);
7114 		else
7115 			reg->var_off = tnum_const((s16)u32_val);
7116 
7117 		u32_val = reg->var_off.value;
7118 		reg->s32_min_value = reg->s32_max_value = u32_val;
7119 		reg->u32_min_value = reg->u32_max_value = u32_val;
7120 		return;
7121 	}
7122 
7123 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
7124 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
7125 
7126 	if (top_smax_value != top_smin_value)
7127 		goto out;
7128 
7129 	/* find the s32_min and s32_min after sign extension */
7130 	if (size == 1) {
7131 		init_s32_max = (s8)reg->s32_max_value;
7132 		init_s32_min = (s8)reg->s32_min_value;
7133 	} else {
7134 		/* size == 2 */
7135 		init_s32_max = (s16)reg->s32_max_value;
7136 		init_s32_min = (s16)reg->s32_min_value;
7137 	}
7138 	s32_max = max(init_s32_max, init_s32_min);
7139 	s32_min = min(init_s32_max, init_s32_min);
7140 
7141 	if ((s32_min >= 0) == (s32_max >= 0)) {
7142 		reg->s32_min_value = s32_min;
7143 		reg->s32_max_value = s32_max;
7144 		reg->u32_min_value = (u32)s32_min;
7145 		reg->u32_max_value = (u32)s32_max;
7146 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
7147 		return;
7148 	}
7149 
7150 out:
7151 	set_sext32_default_val(reg, size);
7152 }
7153 
7154 static bool bpf_map_is_rdonly(const struct bpf_map *map)
7155 {
7156 	/* A map is considered read-only if the following condition are true:
7157 	 *
7158 	 * 1) BPF program side cannot change any of the map content. The
7159 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
7160 	 *    and was set at map creation time.
7161 	 * 2) The map value(s) have been initialized from user space by a
7162 	 *    loader and then "frozen", such that no new map update/delete
7163 	 *    operations from syscall side are possible for the rest of
7164 	 *    the map's lifetime from that point onwards.
7165 	 * 3) Any parallel/pending map update/delete operations from syscall
7166 	 *    side have been completed. Only after that point, it's safe to
7167 	 *    assume that map value(s) are immutable.
7168 	 */
7169 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
7170 	       READ_ONCE(map->frozen) &&
7171 	       !bpf_map_write_active(map);
7172 }
7173 
7174 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
7175 			       bool is_ldsx)
7176 {
7177 	void *ptr;
7178 	u64 addr;
7179 	int err;
7180 
7181 	err = map->ops->map_direct_value_addr(map, &addr, off);
7182 	if (err)
7183 		return err;
7184 	ptr = (void *)(long)addr + off;
7185 
7186 	switch (size) {
7187 	case sizeof(u8):
7188 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
7189 		break;
7190 	case sizeof(u16):
7191 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
7192 		break;
7193 	case sizeof(u32):
7194 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
7195 		break;
7196 	case sizeof(u64):
7197 		*val = *(u64 *)ptr;
7198 		break;
7199 	default:
7200 		return -EINVAL;
7201 	}
7202 	return 0;
7203 }
7204 
7205 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
7206 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
7207 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
7208 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
7209 
7210 /*
7211  * Allow list few fields as RCU trusted or full trusted.
7212  * This logic doesn't allow mix tagging and will be removed once GCC supports
7213  * btf_type_tag.
7214  */
7215 
7216 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
7217 BTF_TYPE_SAFE_RCU(struct task_struct) {
7218 	const cpumask_t *cpus_ptr;
7219 	struct css_set __rcu *cgroups;
7220 	struct task_struct __rcu *real_parent;
7221 	struct task_struct *group_leader;
7222 };
7223 
7224 BTF_TYPE_SAFE_RCU(struct cgroup) {
7225 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
7226 	struct kernfs_node *kn;
7227 };
7228 
7229 BTF_TYPE_SAFE_RCU(struct css_set) {
7230 	struct cgroup *dfl_cgrp;
7231 };
7232 
7233 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
7234 	struct cgroup *cgroup;
7235 };
7236 
7237 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
7238 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
7239 	struct file __rcu *exe_file;
7240 #ifdef CONFIG_MEMCG
7241 	struct task_struct __rcu *owner;
7242 #endif
7243 };
7244 
7245 /* skb->sk, req->sk are not RCU protected, but we mark them as such
7246  * because bpf prog accessible sockets are SOCK_RCU_FREE.
7247  */
7248 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
7249 	struct sock *sk;
7250 };
7251 
7252 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
7253 	struct sock *sk;
7254 };
7255 
7256 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
7257 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
7258 	struct seq_file *seq;
7259 };
7260 
7261 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
7262 	struct bpf_iter_meta *meta;
7263 	struct task_struct *task;
7264 };
7265 
7266 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
7267 	struct file *file;
7268 };
7269 
7270 BTF_TYPE_SAFE_TRUSTED(struct file) {
7271 	struct inode *f_inode;
7272 };
7273 
7274 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
7275 	struct inode *d_inode;
7276 };
7277 
7278 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
7279 	struct sock *sk;
7280 };
7281 
7282 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) {
7283 	struct mm_struct *vm_mm;
7284 	struct file *vm_file;
7285 };
7286 
7287 static bool type_is_rcu(struct bpf_verifier_env *env,
7288 			struct bpf_reg_state *reg,
7289 			const char *field_name, u32 btf_id)
7290 {
7291 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
7292 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
7293 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
7294 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
7295 
7296 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
7297 }
7298 
7299 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
7300 				struct bpf_reg_state *reg,
7301 				const char *field_name, u32 btf_id)
7302 {
7303 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
7304 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
7305 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
7306 
7307 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
7308 }
7309 
7310 static bool type_is_trusted(struct bpf_verifier_env *env,
7311 			    struct bpf_reg_state *reg,
7312 			    const char *field_name, u32 btf_id)
7313 {
7314 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
7315 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
7316 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
7317 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
7318 
7319 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
7320 }
7321 
7322 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
7323 				    struct bpf_reg_state *reg,
7324 				    const char *field_name, u32 btf_id)
7325 {
7326 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
7327 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
7328 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
7329 
7330 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
7331 					  "__safe_trusted_or_null");
7332 }
7333 
7334 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
7335 				   struct bpf_reg_state *regs,
7336 				   int regno, int off, int size,
7337 				   enum bpf_access_type atype,
7338 				   int value_regno)
7339 {
7340 	struct bpf_reg_state *reg = regs + regno;
7341 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
7342 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
7343 	const char *field_name = NULL;
7344 	enum bpf_type_flag flag = 0;
7345 	u32 btf_id = 0;
7346 	int ret;
7347 
7348 	if (!env->allow_ptr_leaks) {
7349 		verbose(env,
7350 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7351 			tname);
7352 		return -EPERM;
7353 	}
7354 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
7355 		verbose(env,
7356 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
7357 			tname);
7358 		return -EINVAL;
7359 	}
7360 	if (off < 0) {
7361 		verbose(env,
7362 			"R%d is ptr_%s invalid negative access: off=%d\n",
7363 			regno, tname, off);
7364 		return -EACCES;
7365 	}
7366 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
7367 		char tn_buf[48];
7368 
7369 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7370 		verbose(env,
7371 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
7372 			regno, tname, off, tn_buf);
7373 		return -EACCES;
7374 	}
7375 
7376 	if (reg->type & MEM_USER) {
7377 		verbose(env,
7378 			"R%d is ptr_%s access user memory: off=%d\n",
7379 			regno, tname, off);
7380 		return -EACCES;
7381 	}
7382 
7383 	if (reg->type & MEM_PERCPU) {
7384 		verbose(env,
7385 			"R%d is ptr_%s access percpu memory: off=%d\n",
7386 			regno, tname, off);
7387 		return -EACCES;
7388 	}
7389 
7390 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
7391 		if (!btf_is_kernel(reg->btf)) {
7392 			verifier_bug(env, "reg->btf must be kernel btf");
7393 			return -EFAULT;
7394 		}
7395 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
7396 	} else {
7397 		/* Writes are permitted with default btf_struct_access for
7398 		 * program allocated objects (which always have ref_obj_id > 0),
7399 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
7400 		 */
7401 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
7402 			verbose(env, "only read is supported\n");
7403 			return -EACCES;
7404 		}
7405 
7406 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
7407 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
7408 			verifier_bug(env, "ref_obj_id for allocated object must be non-zero");
7409 			return -EFAULT;
7410 		}
7411 
7412 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
7413 	}
7414 
7415 	if (ret < 0)
7416 		return ret;
7417 
7418 	if (ret != PTR_TO_BTF_ID) {
7419 		/* just mark; */
7420 
7421 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
7422 		/* If this is an untrusted pointer, all pointers formed by walking it
7423 		 * also inherit the untrusted flag.
7424 		 */
7425 		flag = PTR_UNTRUSTED;
7426 
7427 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
7428 		/* By default any pointer obtained from walking a trusted pointer is no
7429 		 * longer trusted, unless the field being accessed has explicitly been
7430 		 * marked as inheriting its parent's state of trust (either full or RCU).
7431 		 * For example:
7432 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
7433 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
7434 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
7435 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
7436 		 *
7437 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
7438 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
7439 		 */
7440 		if (type_is_trusted(env, reg, field_name, btf_id)) {
7441 			flag |= PTR_TRUSTED;
7442 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
7443 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
7444 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
7445 			if (type_is_rcu(env, reg, field_name, btf_id)) {
7446 				/* ignore __rcu tag and mark it MEM_RCU */
7447 				flag |= MEM_RCU;
7448 			} else if (flag & MEM_RCU ||
7449 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
7450 				/* __rcu tagged pointers can be NULL */
7451 				flag |= MEM_RCU | PTR_MAYBE_NULL;
7452 
7453 				/* We always trust them */
7454 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
7455 				    flag & PTR_UNTRUSTED)
7456 					flag &= ~PTR_UNTRUSTED;
7457 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
7458 				/* keep as-is */
7459 			} else {
7460 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
7461 				clear_trusted_flags(&flag);
7462 			}
7463 		} else {
7464 			/*
7465 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
7466 			 * aggressively mark as untrusted otherwise such
7467 			 * pointers will be plain PTR_TO_BTF_ID without flags
7468 			 * and will be allowed to be passed into helpers for
7469 			 * compat reasons.
7470 			 */
7471 			flag = PTR_UNTRUSTED;
7472 		}
7473 	} else {
7474 		/* Old compat. Deprecated */
7475 		clear_trusted_flags(&flag);
7476 	}
7477 
7478 	if (atype == BPF_READ && value_regno >= 0) {
7479 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
7480 		if (ret < 0)
7481 			return ret;
7482 	}
7483 
7484 	return 0;
7485 }
7486 
7487 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
7488 				   struct bpf_reg_state *regs,
7489 				   int regno, int off, int size,
7490 				   enum bpf_access_type atype,
7491 				   int value_regno)
7492 {
7493 	struct bpf_reg_state *reg = regs + regno;
7494 	struct bpf_map *map = reg->map_ptr;
7495 	struct bpf_reg_state map_reg;
7496 	enum bpf_type_flag flag = 0;
7497 	const struct btf_type *t;
7498 	const char *tname;
7499 	u32 btf_id;
7500 	int ret;
7501 
7502 	if (!btf_vmlinux) {
7503 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
7504 		return -ENOTSUPP;
7505 	}
7506 
7507 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
7508 		verbose(env, "map_ptr access not supported for map type %d\n",
7509 			map->map_type);
7510 		return -ENOTSUPP;
7511 	}
7512 
7513 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
7514 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
7515 
7516 	if (!env->allow_ptr_leaks) {
7517 		verbose(env,
7518 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7519 			tname);
7520 		return -EPERM;
7521 	}
7522 
7523 	if (off < 0) {
7524 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
7525 			regno, tname, off);
7526 		return -EACCES;
7527 	}
7528 
7529 	if (atype != BPF_READ) {
7530 		verbose(env, "only read from %s is supported\n", tname);
7531 		return -EACCES;
7532 	}
7533 
7534 	/* Simulate access to a PTR_TO_BTF_ID */
7535 	memset(&map_reg, 0, sizeof(map_reg));
7536 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
7537 			      btf_vmlinux, *map->ops->map_btf_id, 0);
7538 	if (ret < 0)
7539 		return ret;
7540 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
7541 	if (ret < 0)
7542 		return ret;
7543 
7544 	if (value_regno >= 0) {
7545 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
7546 		if (ret < 0)
7547 			return ret;
7548 	}
7549 
7550 	return 0;
7551 }
7552 
7553 /* Check that the stack access at the given offset is within bounds. The
7554  * maximum valid offset is -1.
7555  *
7556  * The minimum valid offset is -MAX_BPF_STACK for writes, and
7557  * -state->allocated_stack for reads.
7558  */
7559 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
7560                                           s64 off,
7561                                           struct bpf_func_state *state,
7562                                           enum bpf_access_type t)
7563 {
7564 	int min_valid_off;
7565 
7566 	if (t == BPF_WRITE || env->allow_uninit_stack)
7567 		min_valid_off = -MAX_BPF_STACK;
7568 	else
7569 		min_valid_off = -state->allocated_stack;
7570 
7571 	if (off < min_valid_off || off > -1)
7572 		return -EACCES;
7573 	return 0;
7574 }
7575 
7576 /* Check that the stack access at 'regno + off' falls within the maximum stack
7577  * bounds.
7578  *
7579  * 'off' includes `regno->offset`, but not its dynamic part (if any).
7580  */
7581 static int check_stack_access_within_bounds(
7582 		struct bpf_verifier_env *env,
7583 		int regno, int off, int access_size,
7584 		enum bpf_access_type type)
7585 {
7586 	struct bpf_reg_state *reg = reg_state(env, regno);
7587 	struct bpf_func_state *state = func(env, reg);
7588 	s64 min_off, max_off;
7589 	int err;
7590 	char *err_extra;
7591 
7592 	if (type == BPF_READ)
7593 		err_extra = " read from";
7594 	else
7595 		err_extra = " write to";
7596 
7597 	if (tnum_is_const(reg->var_off)) {
7598 		min_off = (s64)reg->var_off.value + off;
7599 		max_off = min_off + access_size;
7600 	} else {
7601 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
7602 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
7603 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
7604 				err_extra, regno);
7605 			return -EACCES;
7606 		}
7607 		min_off = reg->smin_value + off;
7608 		max_off = reg->smax_value + off + access_size;
7609 	}
7610 
7611 	err = check_stack_slot_within_bounds(env, min_off, state, type);
7612 	if (!err && max_off > 0)
7613 		err = -EINVAL; /* out of stack access into non-negative offsets */
7614 	if (!err && access_size < 0)
7615 		/* access_size should not be negative (or overflow an int); others checks
7616 		 * along the way should have prevented such an access.
7617 		 */
7618 		err = -EFAULT; /* invalid negative access size; integer overflow? */
7619 
7620 	if (err) {
7621 		if (tnum_is_const(reg->var_off)) {
7622 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
7623 				err_extra, regno, off, access_size);
7624 		} else {
7625 			char tn_buf[48];
7626 
7627 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7628 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
7629 				err_extra, regno, tn_buf, off, access_size);
7630 		}
7631 		return err;
7632 	}
7633 
7634 	/* Note that there is no stack access with offset zero, so the needed stack
7635 	 * size is -min_off, not -min_off+1.
7636 	 */
7637 	return grow_stack_state(env, state, -min_off /* size */);
7638 }
7639 
7640 static bool get_func_retval_range(struct bpf_prog *prog,
7641 				  struct bpf_retval_range *range)
7642 {
7643 	if (prog->type == BPF_PROG_TYPE_LSM &&
7644 		prog->expected_attach_type == BPF_LSM_MAC &&
7645 		!bpf_lsm_get_retval_range(prog, range)) {
7646 		return true;
7647 	}
7648 	return false;
7649 }
7650 
7651 /* check whether memory at (regno + off) is accessible for t = (read | write)
7652  * if t==write, value_regno is a register which value is stored into memory
7653  * if t==read, value_regno is a register which will receive the value from memory
7654  * if t==write && value_regno==-1, some unknown value is stored into memory
7655  * if t==read && value_regno==-1, don't care what we read from memory
7656  */
7657 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
7658 			    int off, int bpf_size, enum bpf_access_type t,
7659 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7660 {
7661 	struct bpf_reg_state *regs = cur_regs(env);
7662 	struct bpf_reg_state *reg = regs + regno;
7663 	int size, err = 0;
7664 
7665 	size = bpf_size_to_bytes(bpf_size);
7666 	if (size < 0)
7667 		return size;
7668 
7669 	/* alignment checks will add in reg->off themselves */
7670 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7671 	if (err)
7672 		return err;
7673 
7674 	/* for access checks, reg->off is just part of off */
7675 	off += reg->off;
7676 
7677 	if (reg->type == PTR_TO_MAP_KEY) {
7678 		if (t == BPF_WRITE) {
7679 			verbose(env, "write to change key R%d not allowed\n", regno);
7680 			return -EACCES;
7681 		}
7682 
7683 		err = check_mem_region_access(env, regno, off, size,
7684 					      reg->map_ptr->key_size, false);
7685 		if (err)
7686 			return err;
7687 		if (value_regno >= 0)
7688 			mark_reg_unknown(env, regs, value_regno);
7689 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7690 		struct btf_field *kptr_field = NULL;
7691 
7692 		if (t == BPF_WRITE && value_regno >= 0 &&
7693 		    is_pointer_value(env, value_regno)) {
7694 			verbose(env, "R%d leaks addr into map\n", value_regno);
7695 			return -EACCES;
7696 		}
7697 		err = check_map_access_type(env, regno, off, size, t);
7698 		if (err)
7699 			return err;
7700 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
7701 		if (err)
7702 			return err;
7703 		if (tnum_is_const(reg->var_off))
7704 			kptr_field = btf_record_find(reg->map_ptr->record,
7705 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7706 		if (kptr_field) {
7707 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
7708 		} else if (t == BPF_READ && value_regno >= 0) {
7709 			struct bpf_map *map = reg->map_ptr;
7710 
7711 			/*
7712 			 * If map is read-only, track its contents as scalars,
7713 			 * unless it is an insn array (see the special case below)
7714 			 */
7715 			if (tnum_is_const(reg->var_off) &&
7716 			    bpf_map_is_rdonly(map) &&
7717 			    map->ops->map_direct_value_addr &&
7718 			    map->map_type != BPF_MAP_TYPE_INSN_ARRAY) {
7719 				int map_off = off + reg->var_off.value;
7720 				u64 val = 0;
7721 
7722 				err = bpf_map_direct_read(map, map_off, size,
7723 							  &val, is_ldsx);
7724 				if (err)
7725 					return err;
7726 
7727 				regs[value_regno].type = SCALAR_VALUE;
7728 				__mark_reg_known(&regs[value_regno], val);
7729 			} else if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
7730 				if (bpf_size != BPF_DW) {
7731 					verbose(env, "Invalid read of %d bytes from insn_array\n",
7732 						     size);
7733 					return -EACCES;
7734 				}
7735 				copy_register_state(&regs[value_regno], reg);
7736 				regs[value_regno].type = PTR_TO_INSN;
7737 			} else {
7738 				mark_reg_unknown(env, regs, value_regno);
7739 			}
7740 		}
7741 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7742 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7743 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
7744 
7745 		if (type_may_be_null(reg->type)) {
7746 			verbose(env, "R%d invalid mem access '%s'\n", regno,
7747 				reg_type_str(env, reg->type));
7748 			return -EACCES;
7749 		}
7750 
7751 		if (t == BPF_WRITE && rdonly_mem) {
7752 			verbose(env, "R%d cannot write into %s\n",
7753 				regno, reg_type_str(env, reg->type));
7754 			return -EACCES;
7755 		}
7756 
7757 		if (t == BPF_WRITE && value_regno >= 0 &&
7758 		    is_pointer_value(env, value_regno)) {
7759 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7760 			return -EACCES;
7761 		}
7762 
7763 		/*
7764 		 * Accesses to untrusted PTR_TO_MEM are done through probe
7765 		 * instructions, hence no need to check bounds in that case.
7766 		 */
7767 		if (!rdonly_untrusted)
7768 			err = check_mem_region_access(env, regno, off, size,
7769 						      reg->mem_size, false);
7770 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7771 			mark_reg_unknown(env, regs, value_regno);
7772 	} else if (reg->type == PTR_TO_CTX) {
7773 		struct bpf_retval_range range;
7774 		struct bpf_insn_access_aux info = {
7775 			.reg_type = SCALAR_VALUE,
7776 			.is_ldsx = is_ldsx,
7777 			.log = &env->log,
7778 		};
7779 
7780 		if (t == BPF_WRITE && value_regno >= 0 &&
7781 		    is_pointer_value(env, value_regno)) {
7782 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7783 			return -EACCES;
7784 		}
7785 
7786 		err = check_ptr_off_reg(env, reg, regno);
7787 		if (err < 0)
7788 			return err;
7789 
7790 		err = check_ctx_access(env, insn_idx, off, size, t, &info);
7791 		if (err)
7792 			verbose_linfo(env, insn_idx, "; ");
7793 		if (!err && t == BPF_READ && value_regno >= 0) {
7794 			/* ctx access returns either a scalar, or a
7795 			 * PTR_TO_PACKET[_META,_END]. In the latter
7796 			 * case, we know the offset is zero.
7797 			 */
7798 			if (info.reg_type == SCALAR_VALUE) {
7799 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
7800 					err = __mark_reg_s32_range(env, regs, value_regno,
7801 								   range.minval, range.maxval);
7802 					if (err)
7803 						return err;
7804 				} else {
7805 					mark_reg_unknown(env, regs, value_regno);
7806 				}
7807 			} else {
7808 				mark_reg_known_zero(env, regs,
7809 						    value_regno);
7810 				if (type_may_be_null(info.reg_type))
7811 					regs[value_regno].id = ++env->id_gen;
7812 				/* A load of ctx field could have different
7813 				 * actual load size with the one encoded in the
7814 				 * insn. When the dst is PTR, it is for sure not
7815 				 * a sub-register.
7816 				 */
7817 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7818 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
7819 					regs[value_regno].btf = info.btf;
7820 					regs[value_regno].btf_id = info.btf_id;
7821 					regs[value_regno].ref_obj_id = info.ref_obj_id;
7822 				}
7823 			}
7824 			regs[value_regno].type = info.reg_type;
7825 		}
7826 
7827 	} else if (reg->type == PTR_TO_STACK) {
7828 		/* Basic bounds checks. */
7829 		err = check_stack_access_within_bounds(env, regno, off, size, t);
7830 		if (err)
7831 			return err;
7832 
7833 		if (t == BPF_READ)
7834 			err = check_stack_read(env, regno, off, size,
7835 					       value_regno);
7836 		else
7837 			err = check_stack_write(env, regno, off, size,
7838 						value_regno, insn_idx);
7839 	} else if (reg_is_pkt_pointer(reg)) {
7840 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7841 			verbose(env, "cannot write into packet\n");
7842 			return -EACCES;
7843 		}
7844 		if (t == BPF_WRITE && value_regno >= 0 &&
7845 		    is_pointer_value(env, value_regno)) {
7846 			verbose(env, "R%d leaks addr into packet\n",
7847 				value_regno);
7848 			return -EACCES;
7849 		}
7850 		err = check_packet_access(env, regno, off, size, false);
7851 		if (!err && t == BPF_READ && value_regno >= 0)
7852 			mark_reg_unknown(env, regs, value_regno);
7853 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7854 		if (t == BPF_WRITE && value_regno >= 0 &&
7855 		    is_pointer_value(env, value_regno)) {
7856 			verbose(env, "R%d leaks addr into flow keys\n",
7857 				value_regno);
7858 			return -EACCES;
7859 		}
7860 
7861 		err = check_flow_keys_access(env, off, size);
7862 		if (!err && t == BPF_READ && value_regno >= 0)
7863 			mark_reg_unknown(env, regs, value_regno);
7864 	} else if (type_is_sk_pointer(reg->type)) {
7865 		if (t == BPF_WRITE) {
7866 			verbose(env, "R%d cannot write into %s\n",
7867 				regno, reg_type_str(env, reg->type));
7868 			return -EACCES;
7869 		}
7870 		err = check_sock_access(env, insn_idx, regno, off, size, t);
7871 		if (!err && value_regno >= 0)
7872 			mark_reg_unknown(env, regs, value_regno);
7873 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7874 		err = check_tp_buffer_access(env, reg, regno, off, size);
7875 		if (!err && t == BPF_READ && value_regno >= 0)
7876 			mark_reg_unknown(env, regs, value_regno);
7877 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7878 		   !type_may_be_null(reg->type)) {
7879 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7880 					      value_regno);
7881 	} else if (reg->type == CONST_PTR_TO_MAP) {
7882 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7883 					      value_regno);
7884 	} else if (base_type(reg->type) == PTR_TO_BUF) {
7885 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7886 		u32 *max_access;
7887 
7888 		if (rdonly_mem) {
7889 			if (t == BPF_WRITE) {
7890 				verbose(env, "R%d cannot write into %s\n",
7891 					regno, reg_type_str(env, reg->type));
7892 				return -EACCES;
7893 			}
7894 			max_access = &env->prog->aux->max_rdonly_access;
7895 		} else {
7896 			max_access = &env->prog->aux->max_rdwr_access;
7897 		}
7898 
7899 		err = check_buffer_access(env, reg, regno, off, size, false,
7900 					  max_access);
7901 
7902 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7903 			mark_reg_unknown(env, regs, value_regno);
7904 	} else if (reg->type == PTR_TO_ARENA) {
7905 		if (t == BPF_READ && value_regno >= 0)
7906 			mark_reg_unknown(env, regs, value_regno);
7907 	} else {
7908 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7909 			reg_type_str(env, reg->type));
7910 		return -EACCES;
7911 	}
7912 
7913 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7914 	    regs[value_regno].type == SCALAR_VALUE) {
7915 		if (!is_ldsx)
7916 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7917 			coerce_reg_to_size(&regs[value_regno], size);
7918 		else
7919 			coerce_reg_to_size_sx(&regs[value_regno], size);
7920 	}
7921 	return err;
7922 }
7923 
7924 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7925 			     bool allow_trust_mismatch);
7926 
7927 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
7928 			  bool strict_alignment_once, bool is_ldsx,
7929 			  bool allow_trust_mismatch, const char *ctx)
7930 {
7931 	struct bpf_reg_state *regs = cur_regs(env);
7932 	enum bpf_reg_type src_reg_type;
7933 	int err;
7934 
7935 	/* check src operand */
7936 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7937 	if (err)
7938 		return err;
7939 
7940 	/* check dst operand */
7941 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7942 	if (err)
7943 		return err;
7944 
7945 	src_reg_type = regs[insn->src_reg].type;
7946 
7947 	/* Check if (src_reg + off) is readable. The state of dst_reg will be
7948 	 * updated by this call.
7949 	 */
7950 	err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off,
7951 			       BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
7952 			       strict_alignment_once, is_ldsx);
7953 	err = err ?: save_aux_ptr_type(env, src_reg_type,
7954 				       allow_trust_mismatch);
7955 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
7956 
7957 	return err;
7958 }
7959 
7960 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
7961 			   bool strict_alignment_once)
7962 {
7963 	struct bpf_reg_state *regs = cur_regs(env);
7964 	enum bpf_reg_type dst_reg_type;
7965 	int err;
7966 
7967 	/* check src1 operand */
7968 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7969 	if (err)
7970 		return err;
7971 
7972 	/* check src2 operand */
7973 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7974 	if (err)
7975 		return err;
7976 
7977 	dst_reg_type = regs[insn->dst_reg].type;
7978 
7979 	/* Check if (dst_reg + off) is writeable. */
7980 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7981 			       BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
7982 			       strict_alignment_once, false);
7983 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
7984 
7985 	return err;
7986 }
7987 
7988 static int check_atomic_rmw(struct bpf_verifier_env *env,
7989 			    struct bpf_insn *insn)
7990 {
7991 	int load_reg;
7992 	int err;
7993 
7994 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7995 		verbose(env, "invalid atomic operand size\n");
7996 		return -EINVAL;
7997 	}
7998 
7999 	/* check src1 operand */
8000 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
8001 	if (err)
8002 		return err;
8003 
8004 	/* check src2 operand */
8005 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8006 	if (err)
8007 		return err;
8008 
8009 	if (insn->imm == BPF_CMPXCHG) {
8010 		/* Check comparison of R0 with memory location */
8011 		const u32 aux_reg = BPF_REG_0;
8012 
8013 		err = check_reg_arg(env, aux_reg, SRC_OP);
8014 		if (err)
8015 			return err;
8016 
8017 		if (is_pointer_value(env, aux_reg)) {
8018 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
8019 			return -EACCES;
8020 		}
8021 	}
8022 
8023 	if (is_pointer_value(env, insn->src_reg)) {
8024 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
8025 		return -EACCES;
8026 	}
8027 
8028 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
8029 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
8030 			insn->dst_reg,
8031 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
8032 		return -EACCES;
8033 	}
8034 
8035 	if (insn->imm & BPF_FETCH) {
8036 		if (insn->imm == BPF_CMPXCHG)
8037 			load_reg = BPF_REG_0;
8038 		else
8039 			load_reg = insn->src_reg;
8040 
8041 		/* check and record load of old value */
8042 		err = check_reg_arg(env, load_reg, DST_OP);
8043 		if (err)
8044 			return err;
8045 	} else {
8046 		/* This instruction accesses a memory location but doesn't
8047 		 * actually load it into a register.
8048 		 */
8049 		load_reg = -1;
8050 	}
8051 
8052 	/* Check whether we can read the memory, with second call for fetch
8053 	 * case to simulate the register fill.
8054 	 */
8055 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
8056 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
8057 	if (!err && load_reg >= 0)
8058 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
8059 				       insn->off, BPF_SIZE(insn->code),
8060 				       BPF_READ, load_reg, true, false);
8061 	if (err)
8062 		return err;
8063 
8064 	if (is_arena_reg(env, insn->dst_reg)) {
8065 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
8066 		if (err)
8067 			return err;
8068 	}
8069 	/* Check whether we can write into the same memory. */
8070 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
8071 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
8072 	if (err)
8073 		return err;
8074 	return 0;
8075 }
8076 
8077 static int check_atomic_load(struct bpf_verifier_env *env,
8078 			     struct bpf_insn *insn)
8079 {
8080 	int err;
8081 
8082 	err = check_load_mem(env, insn, true, false, false, "atomic_load");
8083 	if (err)
8084 		return err;
8085 
8086 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
8087 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
8088 			insn->src_reg,
8089 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
8090 		return -EACCES;
8091 	}
8092 
8093 	return 0;
8094 }
8095 
8096 static int check_atomic_store(struct bpf_verifier_env *env,
8097 			      struct bpf_insn *insn)
8098 {
8099 	int err;
8100 
8101 	err = check_store_reg(env, insn, true);
8102 	if (err)
8103 		return err;
8104 
8105 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
8106 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
8107 			insn->dst_reg,
8108 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
8109 		return -EACCES;
8110 	}
8111 
8112 	return 0;
8113 }
8114 
8115 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
8116 {
8117 	switch (insn->imm) {
8118 	case BPF_ADD:
8119 	case BPF_ADD | BPF_FETCH:
8120 	case BPF_AND:
8121 	case BPF_AND | BPF_FETCH:
8122 	case BPF_OR:
8123 	case BPF_OR | BPF_FETCH:
8124 	case BPF_XOR:
8125 	case BPF_XOR | BPF_FETCH:
8126 	case BPF_XCHG:
8127 	case BPF_CMPXCHG:
8128 		return check_atomic_rmw(env, insn);
8129 	case BPF_LOAD_ACQ:
8130 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
8131 			verbose(env,
8132 				"64-bit load-acquires are only supported on 64-bit arches\n");
8133 			return -EOPNOTSUPP;
8134 		}
8135 		return check_atomic_load(env, insn);
8136 	case BPF_STORE_REL:
8137 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
8138 			verbose(env,
8139 				"64-bit store-releases are only supported on 64-bit arches\n");
8140 			return -EOPNOTSUPP;
8141 		}
8142 		return check_atomic_store(env, insn);
8143 	default:
8144 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
8145 			insn->imm);
8146 		return -EINVAL;
8147 	}
8148 }
8149 
8150 /* When register 'regno' is used to read the stack (either directly or through
8151  * a helper function) make sure that it's within stack boundary and, depending
8152  * on the access type and privileges, that all elements of the stack are
8153  * initialized.
8154  *
8155  * 'off' includes 'regno->off', but not its dynamic part (if any).
8156  *
8157  * All registers that have been spilled on the stack in the slots within the
8158  * read offsets are marked as read.
8159  */
8160 static int check_stack_range_initialized(
8161 		struct bpf_verifier_env *env, int regno, int off,
8162 		int access_size, bool zero_size_allowed,
8163 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
8164 {
8165 	struct bpf_reg_state *reg = reg_state(env, regno);
8166 	struct bpf_func_state *state = func(env, reg);
8167 	int err, min_off, max_off, i, j, slot, spi;
8168 	/* Some accesses can write anything into the stack, others are
8169 	 * read-only.
8170 	 */
8171 	bool clobber = false;
8172 
8173 	if (access_size == 0 && !zero_size_allowed) {
8174 		verbose(env, "invalid zero-sized read\n");
8175 		return -EACCES;
8176 	}
8177 
8178 	if (type == BPF_WRITE)
8179 		clobber = true;
8180 
8181 	err = check_stack_access_within_bounds(env, regno, off, access_size, type);
8182 	if (err)
8183 		return err;
8184 
8185 
8186 	if (tnum_is_const(reg->var_off)) {
8187 		min_off = max_off = reg->var_off.value + off;
8188 	} else {
8189 		/* Variable offset is prohibited for unprivileged mode for
8190 		 * simplicity since it requires corresponding support in
8191 		 * Spectre masking for stack ALU.
8192 		 * See also retrieve_ptr_limit().
8193 		 */
8194 		if (!env->bypass_spec_v1) {
8195 			char tn_buf[48];
8196 
8197 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8198 			verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
8199 				regno, tn_buf);
8200 			return -EACCES;
8201 		}
8202 		/* Only initialized buffer on stack is allowed to be accessed
8203 		 * with variable offset. With uninitialized buffer it's hard to
8204 		 * guarantee that whole memory is marked as initialized on
8205 		 * helper return since specific bounds are unknown what may
8206 		 * cause uninitialized stack leaking.
8207 		 */
8208 		if (meta && meta->raw_mode)
8209 			meta = NULL;
8210 
8211 		min_off = reg->smin_value + off;
8212 		max_off = reg->smax_value + off;
8213 	}
8214 
8215 	if (meta && meta->raw_mode) {
8216 		/* Ensure we won't be overwriting dynptrs when simulating byte
8217 		 * by byte access in check_helper_call using meta.access_size.
8218 		 * This would be a problem if we have a helper in the future
8219 		 * which takes:
8220 		 *
8221 		 *	helper(uninit_mem, len, dynptr)
8222 		 *
8223 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
8224 		 * may end up writing to dynptr itself when touching memory from
8225 		 * arg 1. This can be relaxed on a case by case basis for known
8226 		 * safe cases, but reject due to the possibilitiy of aliasing by
8227 		 * default.
8228 		 */
8229 		for (i = min_off; i < max_off + access_size; i++) {
8230 			int stack_off = -i - 1;
8231 
8232 			spi = __get_spi(i);
8233 			/* raw_mode may write past allocated_stack */
8234 			if (state->allocated_stack <= stack_off)
8235 				continue;
8236 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
8237 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
8238 				return -EACCES;
8239 			}
8240 		}
8241 		meta->access_size = access_size;
8242 		meta->regno = regno;
8243 		return 0;
8244 	}
8245 
8246 	for (i = min_off; i < max_off + access_size; i++) {
8247 		u8 *stype;
8248 
8249 		slot = -i - 1;
8250 		spi = slot / BPF_REG_SIZE;
8251 		if (state->allocated_stack <= slot) {
8252 			verbose(env, "allocated_stack too small\n");
8253 			return -EFAULT;
8254 		}
8255 
8256 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
8257 		if (*stype == STACK_MISC)
8258 			goto mark;
8259 		if ((*stype == STACK_ZERO) ||
8260 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
8261 			if (clobber) {
8262 				/* helper can write anything into the stack */
8263 				*stype = STACK_MISC;
8264 			}
8265 			goto mark;
8266 		}
8267 
8268 		if (is_spilled_reg(&state->stack[spi]) &&
8269 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
8270 		     env->allow_ptr_leaks)) {
8271 			if (clobber) {
8272 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
8273 				for (j = 0; j < BPF_REG_SIZE; j++)
8274 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
8275 			}
8276 			goto mark;
8277 		}
8278 
8279 		if (tnum_is_const(reg->var_off)) {
8280 			verbose(env, "invalid read from stack R%d off %d+%d size %d\n",
8281 				regno, min_off, i - min_off, access_size);
8282 		} else {
8283 			char tn_buf[48];
8284 
8285 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8286 			verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n",
8287 				regno, tn_buf, i - min_off, access_size);
8288 		}
8289 		return -EACCES;
8290 mark:
8291 		/* reading any byte out of 8-byte 'spill_slot' will cause
8292 		 * the whole slot to be marked as 'read'
8293 		 */
8294 		err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi));
8295 		if (err)
8296 			return err;
8297 		/* We do not call bpf_mark_stack_write(), as we can not
8298 		 * be sure that whether stack slot is written to or not. Hence,
8299 		 * we must still conservatively propagate reads upwards even if
8300 		 * helper may write to the entire memory range.
8301 		 */
8302 	}
8303 	return 0;
8304 }
8305 
8306 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
8307 				   int access_size, enum bpf_access_type access_type,
8308 				   bool zero_size_allowed,
8309 				   struct bpf_call_arg_meta *meta)
8310 {
8311 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8312 	u32 *max_access;
8313 
8314 	switch (base_type(reg->type)) {
8315 	case PTR_TO_PACKET:
8316 	case PTR_TO_PACKET_META:
8317 		return check_packet_access(env, regno, reg->off, access_size,
8318 					   zero_size_allowed);
8319 	case PTR_TO_MAP_KEY:
8320 		if (access_type == BPF_WRITE) {
8321 			verbose(env, "R%d cannot write into %s\n", regno,
8322 				reg_type_str(env, reg->type));
8323 			return -EACCES;
8324 		}
8325 		return check_mem_region_access(env, regno, reg->off, access_size,
8326 					       reg->map_ptr->key_size, false);
8327 	case PTR_TO_MAP_VALUE:
8328 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
8329 			return -EACCES;
8330 		return check_map_access(env, regno, reg->off, access_size,
8331 					zero_size_allowed, ACCESS_HELPER);
8332 	case PTR_TO_MEM:
8333 		if (type_is_rdonly_mem(reg->type)) {
8334 			if (access_type == BPF_WRITE) {
8335 				verbose(env, "R%d cannot write into %s\n", regno,
8336 					reg_type_str(env, reg->type));
8337 				return -EACCES;
8338 			}
8339 		}
8340 		return check_mem_region_access(env, regno, reg->off,
8341 					       access_size, reg->mem_size,
8342 					       zero_size_allowed);
8343 	case PTR_TO_BUF:
8344 		if (type_is_rdonly_mem(reg->type)) {
8345 			if (access_type == BPF_WRITE) {
8346 				verbose(env, "R%d cannot write into %s\n", regno,
8347 					reg_type_str(env, reg->type));
8348 				return -EACCES;
8349 			}
8350 
8351 			max_access = &env->prog->aux->max_rdonly_access;
8352 		} else {
8353 			max_access = &env->prog->aux->max_rdwr_access;
8354 		}
8355 		return check_buffer_access(env, reg, regno, reg->off,
8356 					   access_size, zero_size_allowed,
8357 					   max_access);
8358 	case PTR_TO_STACK:
8359 		return check_stack_range_initialized(
8360 				env,
8361 				regno, reg->off, access_size,
8362 				zero_size_allowed, access_type, meta);
8363 	case PTR_TO_BTF_ID:
8364 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
8365 					       access_size, BPF_READ, -1);
8366 	case PTR_TO_CTX:
8367 		/* in case the function doesn't know how to access the context,
8368 		 * (because we are in a program of type SYSCALL for example), we
8369 		 * can not statically check its size.
8370 		 * Dynamically check it now.
8371 		 */
8372 		if (!env->ops->convert_ctx_access) {
8373 			int offset = access_size - 1;
8374 
8375 			/* Allow zero-byte read from PTR_TO_CTX */
8376 			if (access_size == 0)
8377 				return zero_size_allowed ? 0 : -EACCES;
8378 
8379 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
8380 						access_type, -1, false, false);
8381 		}
8382 
8383 		fallthrough;
8384 	default: /* scalar_value or invalid ptr */
8385 		/* Allow zero-byte read from NULL, regardless of pointer type */
8386 		if (zero_size_allowed && access_size == 0 &&
8387 		    register_is_null(reg))
8388 			return 0;
8389 
8390 		verbose(env, "R%d type=%s ", regno,
8391 			reg_type_str(env, reg->type));
8392 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
8393 		return -EACCES;
8394 	}
8395 }
8396 
8397 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
8398  * size.
8399  *
8400  * @regno is the register containing the access size. regno-1 is the register
8401  * containing the pointer.
8402  */
8403 static int check_mem_size_reg(struct bpf_verifier_env *env,
8404 			      struct bpf_reg_state *reg, u32 regno,
8405 			      enum bpf_access_type access_type,
8406 			      bool zero_size_allowed,
8407 			      struct bpf_call_arg_meta *meta)
8408 {
8409 	int err;
8410 
8411 	/* This is used to refine r0 return value bounds for helpers
8412 	 * that enforce this value as an upper bound on return values.
8413 	 * See do_refine_retval_range() for helpers that can refine
8414 	 * the return value. C type of helper is u32 so we pull register
8415 	 * bound from umax_value however, if negative verifier errors
8416 	 * out. Only upper bounds can be learned because retval is an
8417 	 * int type and negative retvals are allowed.
8418 	 */
8419 	meta->msize_max_value = reg->umax_value;
8420 
8421 	/* The register is SCALAR_VALUE; the access check happens using
8422 	 * its boundaries. For unprivileged variable accesses, disable
8423 	 * raw mode so that the program is required to initialize all
8424 	 * the memory that the helper could just partially fill up.
8425 	 */
8426 	if (!tnum_is_const(reg->var_off))
8427 		meta = NULL;
8428 
8429 	if (reg->smin_value < 0) {
8430 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
8431 			regno);
8432 		return -EACCES;
8433 	}
8434 
8435 	if (reg->umin_value == 0 && !zero_size_allowed) {
8436 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
8437 			regno, reg->umin_value, reg->umax_value);
8438 		return -EACCES;
8439 	}
8440 
8441 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
8442 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
8443 			regno);
8444 		return -EACCES;
8445 	}
8446 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
8447 				      access_type, zero_size_allowed, meta);
8448 	if (!err)
8449 		err = mark_chain_precision(env, regno);
8450 	return err;
8451 }
8452 
8453 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8454 			 u32 regno, u32 mem_size)
8455 {
8456 	bool may_be_null = type_may_be_null(reg->type);
8457 	struct bpf_reg_state saved_reg;
8458 	int err;
8459 
8460 	if (register_is_null(reg))
8461 		return 0;
8462 
8463 	/* Assuming that the register contains a value check if the memory
8464 	 * access is safe. Temporarily save and restore the register's state as
8465 	 * the conversion shouldn't be visible to a caller.
8466 	 */
8467 	if (may_be_null) {
8468 		saved_reg = *reg;
8469 		mark_ptr_not_null_reg(reg);
8470 	}
8471 
8472 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
8473 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
8474 
8475 	if (may_be_null)
8476 		*reg = saved_reg;
8477 
8478 	return err;
8479 }
8480 
8481 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8482 				    u32 regno)
8483 {
8484 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
8485 	bool may_be_null = type_may_be_null(mem_reg->type);
8486 	struct bpf_reg_state saved_reg;
8487 	struct bpf_call_arg_meta meta;
8488 	int err;
8489 
8490 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
8491 
8492 	memset(&meta, 0, sizeof(meta));
8493 
8494 	if (may_be_null) {
8495 		saved_reg = *mem_reg;
8496 		mark_ptr_not_null_reg(mem_reg);
8497 	}
8498 
8499 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
8500 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
8501 
8502 	if (may_be_null)
8503 		*mem_reg = saved_reg;
8504 
8505 	return err;
8506 }
8507 
8508 enum {
8509 	PROCESS_SPIN_LOCK = (1 << 0),
8510 	PROCESS_RES_LOCK  = (1 << 1),
8511 	PROCESS_LOCK_IRQ  = (1 << 2),
8512 };
8513 
8514 /* Implementation details:
8515  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
8516  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
8517  * Two bpf_map_lookups (even with the same key) will have different reg->id.
8518  * Two separate bpf_obj_new will also have different reg->id.
8519  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
8520  * clears reg->id after value_or_null->value transition, since the verifier only
8521  * cares about the range of access to valid map value pointer and doesn't care
8522  * about actual address of the map element.
8523  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
8524  * reg->id > 0 after value_or_null->value transition. By doing so
8525  * two bpf_map_lookups will be considered two different pointers that
8526  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
8527  * returned from bpf_obj_new.
8528  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8529  * dead-locks.
8530  * Since only one bpf_spin_lock is allowed the checks are simpler than
8531  * reg_is_refcounted() logic. The verifier needs to remember only
8532  * one spin_lock instead of array of acquired_refs.
8533  * env->cur_state->active_locks remembers which map value element or allocated
8534  * object got locked and clears it after bpf_spin_unlock.
8535  */
8536 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags)
8537 {
8538 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
8539 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
8540 	struct bpf_reg_state *reg = reg_state(env, regno);
8541 	struct bpf_verifier_state *cur = env->cur_state;
8542 	bool is_const = tnum_is_const(reg->var_off);
8543 	bool is_irq = flags & PROCESS_LOCK_IRQ;
8544 	u64 val = reg->var_off.value;
8545 	struct bpf_map *map = NULL;
8546 	struct btf *btf = NULL;
8547 	struct btf_record *rec;
8548 	u32 spin_lock_off;
8549 	int err;
8550 
8551 	if (!is_const) {
8552 		verbose(env,
8553 			"R%d doesn't have constant offset. %s_lock has to be at the constant offset\n",
8554 			regno, lock_str);
8555 		return -EINVAL;
8556 	}
8557 	if (reg->type == PTR_TO_MAP_VALUE) {
8558 		map = reg->map_ptr;
8559 		if (!map->btf) {
8560 			verbose(env,
8561 				"map '%s' has to have BTF in order to use %s_lock\n",
8562 				map->name, lock_str);
8563 			return -EINVAL;
8564 		}
8565 	} else {
8566 		btf = reg->btf;
8567 	}
8568 
8569 	rec = reg_btf_record(reg);
8570 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
8571 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
8572 			map ? map->name : "kptr", lock_str);
8573 		return -EINVAL;
8574 	}
8575 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
8576 	if (spin_lock_off != val + reg->off) {
8577 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
8578 			val + reg->off, lock_str, spin_lock_off);
8579 		return -EINVAL;
8580 	}
8581 	if (is_lock) {
8582 		void *ptr;
8583 		int type;
8584 
8585 		if (map)
8586 			ptr = map;
8587 		else
8588 			ptr = btf;
8589 
8590 		if (!is_res_lock && cur->active_locks) {
8591 			if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) {
8592 				verbose(env,
8593 					"Locking two bpf_spin_locks are not allowed\n");
8594 				return -EINVAL;
8595 			}
8596 		} else if (is_res_lock && cur->active_locks) {
8597 			if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) {
8598 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
8599 				return -EINVAL;
8600 			}
8601 		}
8602 
8603 		if (is_res_lock && is_irq)
8604 			type = REF_TYPE_RES_LOCK_IRQ;
8605 		else if (is_res_lock)
8606 			type = REF_TYPE_RES_LOCK;
8607 		else
8608 			type = REF_TYPE_LOCK;
8609 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
8610 		if (err < 0) {
8611 			verbose(env, "Failed to acquire lock state\n");
8612 			return err;
8613 		}
8614 	} else {
8615 		void *ptr;
8616 		int type;
8617 
8618 		if (map)
8619 			ptr = map;
8620 		else
8621 			ptr = btf;
8622 
8623 		if (!cur->active_locks) {
8624 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
8625 			return -EINVAL;
8626 		}
8627 
8628 		if (is_res_lock && is_irq)
8629 			type = REF_TYPE_RES_LOCK_IRQ;
8630 		else if (is_res_lock)
8631 			type = REF_TYPE_RES_LOCK;
8632 		else
8633 			type = REF_TYPE_LOCK;
8634 		if (!find_lock_state(cur, type, reg->id, ptr)) {
8635 			verbose(env, "%s_unlock of different lock\n", lock_str);
8636 			return -EINVAL;
8637 		}
8638 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
8639 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
8640 			return -EINVAL;
8641 		}
8642 		if (release_lock_state(cur, type, reg->id, ptr)) {
8643 			verbose(env, "%s_unlock of different lock\n", lock_str);
8644 			return -EINVAL;
8645 		}
8646 
8647 		invalidate_non_owning_refs(env);
8648 	}
8649 	return 0;
8650 }
8651 
8652 /* Check if @regno is a pointer to a specific field in a map value */
8653 static int check_map_field_pointer(struct bpf_verifier_env *env, u32 regno,
8654 				   enum btf_field_type field_type,
8655 				   struct bpf_map_desc *map_desc)
8656 {
8657 	struct bpf_reg_state *reg = reg_state(env, regno);
8658 	bool is_const = tnum_is_const(reg->var_off);
8659 	struct bpf_map *map = reg->map_ptr;
8660 	u64 val = reg->var_off.value;
8661 	const char *struct_name = btf_field_type_name(field_type);
8662 	int field_off = -1;
8663 
8664 	if (!is_const) {
8665 		verbose(env,
8666 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
8667 			regno, struct_name);
8668 		return -EINVAL;
8669 	}
8670 	if (!map->btf) {
8671 		verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name,
8672 			struct_name);
8673 		return -EINVAL;
8674 	}
8675 	if (!btf_record_has_field(map->record, field_type)) {
8676 		verbose(env, "map '%s' has no valid %s\n", map->name, struct_name);
8677 		return -EINVAL;
8678 	}
8679 	switch (field_type) {
8680 	case BPF_TIMER:
8681 		field_off = map->record->timer_off;
8682 		break;
8683 	case BPF_TASK_WORK:
8684 		field_off = map->record->task_work_off;
8685 		break;
8686 	case BPF_WORKQUEUE:
8687 		field_off = map->record->wq_off;
8688 		break;
8689 	default:
8690 		verifier_bug(env, "unsupported BTF field type: %s\n", struct_name);
8691 		return -EINVAL;
8692 	}
8693 	if (field_off != val + reg->off) {
8694 		verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n",
8695 			val + reg->off, struct_name, field_off);
8696 		return -EINVAL;
8697 	}
8698 	if (map_desc->ptr) {
8699 		verifier_bug(env, "Two map pointers in a %s helper", struct_name);
8700 		return -EFAULT;
8701 	}
8702 	map_desc->uid = reg->map_uid;
8703 	map_desc->ptr = map;
8704 	return 0;
8705 }
8706 
8707 static int process_timer_func(struct bpf_verifier_env *env, int regno,
8708 			      struct bpf_map_desc *map)
8709 {
8710 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8711 		verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
8712 		return -EOPNOTSUPP;
8713 	}
8714 	return check_map_field_pointer(env, regno, BPF_TIMER, map);
8715 }
8716 
8717 static int process_timer_helper(struct bpf_verifier_env *env, int regno,
8718 				struct bpf_call_arg_meta *meta)
8719 {
8720 	return process_timer_func(env, regno, &meta->map);
8721 }
8722 
8723 static int process_timer_kfunc(struct bpf_verifier_env *env, int regno,
8724 			       struct bpf_kfunc_call_arg_meta *meta)
8725 {
8726 	return process_timer_func(env, regno, &meta->map);
8727 }
8728 
8729 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8730 			     struct bpf_call_arg_meta *meta)
8731 {
8732 	struct bpf_reg_state *reg = reg_state(env, regno);
8733 	struct btf_field *kptr_field;
8734 	struct bpf_map *map_ptr;
8735 	struct btf_record *rec;
8736 	u32 kptr_off;
8737 
8738 	if (type_is_ptr_alloc_obj(reg->type)) {
8739 		rec = reg_btf_record(reg);
8740 	} else { /* PTR_TO_MAP_VALUE */
8741 		map_ptr = reg->map_ptr;
8742 		if (!map_ptr->btf) {
8743 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8744 				map_ptr->name);
8745 			return -EINVAL;
8746 		}
8747 		rec = map_ptr->record;
8748 		meta->map.ptr = map_ptr;
8749 	}
8750 
8751 	if (!tnum_is_const(reg->var_off)) {
8752 		verbose(env,
8753 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8754 			regno);
8755 		return -EINVAL;
8756 	}
8757 
8758 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8759 		verbose(env, "R%d has no valid kptr\n", regno);
8760 		return -EINVAL;
8761 	}
8762 
8763 	kptr_off = reg->off + reg->var_off.value;
8764 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8765 	if (!kptr_field) {
8766 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8767 		return -EACCES;
8768 	}
8769 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8770 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8771 		return -EACCES;
8772 	}
8773 	meta->kptr_field = kptr_field;
8774 	return 0;
8775 }
8776 
8777 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8778  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8779  *
8780  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8781  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8782  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8783  *
8784  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
8785  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
8786  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
8787  * mutate the view of the dynptr and also possibly destroy it. In the latter
8788  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
8789  * memory that dynptr points to.
8790  *
8791  * The verifier will keep track both levels of mutation (bpf_dynptr's in
8792  * reg->type and the memory's in reg->dynptr.type), but there is no support for
8793  * readonly dynptr view yet, hence only the first case is tracked and checked.
8794  *
8795  * This is consistent with how C applies the const modifier to a struct object,
8796  * where the pointer itself inside bpf_dynptr becomes const but not what it
8797  * points to.
8798  *
8799  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
8800  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
8801  */
8802 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
8803 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
8804 {
8805 	struct bpf_reg_state *reg = reg_state(env, regno);
8806 	int err;
8807 
8808 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
8809 		verbose(env,
8810 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
8811 			regno - 1);
8812 		return -EINVAL;
8813 	}
8814 
8815 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
8816 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
8817 	 */
8818 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
8819 		verifier_bug(env, "misconfigured dynptr helper type flags");
8820 		return -EFAULT;
8821 	}
8822 
8823 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8824 	 *		 constructing a mutable bpf_dynptr object.
8825 	 *
8826 	 *		 Currently, this is only possible with PTR_TO_STACK
8827 	 *		 pointing to a region of at least 16 bytes which doesn't
8828 	 *		 contain an existing bpf_dynptr.
8829 	 *
8830 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
8831 	 *		 mutated or destroyed. However, the memory it points to
8832 	 *		 may be mutated.
8833 	 *
8834 	 *  None       - Points to a initialized dynptr that can be mutated and
8835 	 *		 destroyed, including mutation of the memory it points
8836 	 *		 to.
8837 	 */
8838 	if (arg_type & MEM_UNINIT) {
8839 		int i;
8840 
8841 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8842 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8843 			return -EINVAL;
8844 		}
8845 
8846 		/* we write BPF_DW bits (8 bytes) at a time */
8847 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8848 			err = check_mem_access(env, insn_idx, regno,
8849 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8850 			if (err)
8851 				return err;
8852 		}
8853 
8854 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
8855 	} else /* MEM_RDONLY and None case from above */ {
8856 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8857 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
8858 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
8859 			return -EINVAL;
8860 		}
8861 
8862 		if (!is_dynptr_reg_valid_init(env, reg)) {
8863 			verbose(env,
8864 				"Expected an initialized dynptr as arg #%d\n",
8865 				regno - 1);
8866 			return -EINVAL;
8867 		}
8868 
8869 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
8870 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
8871 			verbose(env,
8872 				"Expected a dynptr of type %s as arg #%d\n",
8873 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
8874 			return -EINVAL;
8875 		}
8876 
8877 		err = mark_dynptr_read(env, reg);
8878 	}
8879 	return err;
8880 }
8881 
8882 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
8883 {
8884 	struct bpf_func_state *state = func(env, reg);
8885 
8886 	return state->stack[spi].spilled_ptr.ref_obj_id;
8887 }
8888 
8889 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8890 {
8891 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8892 }
8893 
8894 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8895 {
8896 	return meta->kfunc_flags & KF_ITER_NEW;
8897 }
8898 
8899 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8900 {
8901 	return meta->kfunc_flags & KF_ITER_NEXT;
8902 }
8903 
8904 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8905 {
8906 	return meta->kfunc_flags & KF_ITER_DESTROY;
8907 }
8908 
8909 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
8910 			      const struct btf_param *arg)
8911 {
8912 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8913 	 * kfunc is iter state pointer
8914 	 */
8915 	if (is_iter_kfunc(meta))
8916 		return arg_idx == 0;
8917 
8918 	/* iter passed as an argument to a generic kfunc */
8919 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8920 }
8921 
8922 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
8923 			    struct bpf_kfunc_call_arg_meta *meta)
8924 {
8925 	struct bpf_reg_state *reg = reg_state(env, regno);
8926 	const struct btf_type *t;
8927 	int spi, err, i, nr_slots, btf_id;
8928 
8929 	if (reg->type != PTR_TO_STACK) {
8930 		verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
8931 		return -EINVAL;
8932 	}
8933 
8934 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8935 	 * ensures struct convention, so we wouldn't need to do any BTF
8936 	 * validation here. But given iter state can be passed as a parameter
8937 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8938 	 * conservative here.
8939 	 */
8940 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8941 	if (btf_id < 0) {
8942 		verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
8943 		return -EINVAL;
8944 	}
8945 	t = btf_type_by_id(meta->btf, btf_id);
8946 	nr_slots = t->size / BPF_REG_SIZE;
8947 
8948 	if (is_iter_new_kfunc(meta)) {
8949 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8950 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8951 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8952 				iter_type_str(meta->btf, btf_id), regno - 1);
8953 			return -EINVAL;
8954 		}
8955 
8956 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8957 			err = check_mem_access(env, insn_idx, regno,
8958 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8959 			if (err)
8960 				return err;
8961 		}
8962 
8963 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8964 		if (err)
8965 			return err;
8966 	} else {
8967 		/* iter_next() or iter_destroy(), as well as any kfunc
8968 		 * accepting iter argument, expect initialized iter state
8969 		 */
8970 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8971 		switch (err) {
8972 		case 0:
8973 			break;
8974 		case -EINVAL:
8975 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
8976 				iter_type_str(meta->btf, btf_id), regno - 1);
8977 			return err;
8978 		case -EPROTO:
8979 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8980 			return err;
8981 		default:
8982 			return err;
8983 		}
8984 
8985 		spi = iter_get_spi(env, reg, nr_slots);
8986 		if (spi < 0)
8987 			return spi;
8988 
8989 		err = mark_iter_read(env, reg, spi, nr_slots);
8990 		if (err)
8991 			return err;
8992 
8993 		/* remember meta->iter info for process_iter_next_call() */
8994 		meta->iter.spi = spi;
8995 		meta->iter.frameno = reg->frameno;
8996 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8997 
8998 		if (is_iter_destroy_kfunc(meta)) {
8999 			err = unmark_stack_slots_iter(env, reg, nr_slots);
9000 			if (err)
9001 				return err;
9002 		}
9003 	}
9004 
9005 	return 0;
9006 }
9007 
9008 /* Look for a previous loop entry at insn_idx: nearest parent state
9009  * stopped at insn_idx with callsites matching those in cur->frame.
9010  */
9011 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
9012 						  struct bpf_verifier_state *cur,
9013 						  int insn_idx)
9014 {
9015 	struct bpf_verifier_state_list *sl;
9016 	struct bpf_verifier_state *st;
9017 	struct list_head *pos, *head;
9018 
9019 	/* Explored states are pushed in stack order, most recent states come first */
9020 	head = explored_state(env, insn_idx);
9021 	list_for_each(pos, head) {
9022 		sl = container_of(pos, struct bpf_verifier_state_list, node);
9023 		/* If st->branches != 0 state is a part of current DFS verification path,
9024 		 * hence cur & st for a loop.
9025 		 */
9026 		st = &sl->state;
9027 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
9028 		    st->dfs_depth < cur->dfs_depth)
9029 			return st;
9030 	}
9031 
9032 	return NULL;
9033 }
9034 
9035 static void reset_idmap_scratch(struct bpf_verifier_env *env);
9036 static bool regs_exact(const struct bpf_reg_state *rold,
9037 		       const struct bpf_reg_state *rcur,
9038 		       struct bpf_idmap *idmap);
9039 
9040 /*
9041  * Check if scalar registers are exact for the purpose of not widening.
9042  * More lenient than regs_exact()
9043  */
9044 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold,
9045 				    const struct bpf_reg_state *rcur)
9046 {
9047 	return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id));
9048 }
9049 
9050 static void maybe_widen_reg(struct bpf_verifier_env *env,
9051 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur)
9052 {
9053 	if (rold->type != SCALAR_VALUE)
9054 		return;
9055 	if (rold->type != rcur->type)
9056 		return;
9057 	if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur))
9058 		return;
9059 	__mark_reg_unknown(env, rcur);
9060 }
9061 
9062 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
9063 				   struct bpf_verifier_state *old,
9064 				   struct bpf_verifier_state *cur)
9065 {
9066 	struct bpf_func_state *fold, *fcur;
9067 	int i, fr, num_slots;
9068 
9069 	for (fr = old->curframe; fr >= 0; fr--) {
9070 		fold = old->frame[fr];
9071 		fcur = cur->frame[fr];
9072 
9073 		for (i = 0; i < MAX_BPF_REG; i++)
9074 			maybe_widen_reg(env,
9075 					&fold->regs[i],
9076 					&fcur->regs[i]);
9077 
9078 		num_slots = min(fold->allocated_stack / BPF_REG_SIZE,
9079 				fcur->allocated_stack / BPF_REG_SIZE);
9080 		for (i = 0; i < num_slots; i++) {
9081 			if (!is_spilled_reg(&fold->stack[i]) ||
9082 			    !is_spilled_reg(&fcur->stack[i]))
9083 				continue;
9084 
9085 			maybe_widen_reg(env,
9086 					&fold->stack[i].spilled_ptr,
9087 					&fcur->stack[i].spilled_ptr);
9088 		}
9089 	}
9090 	return 0;
9091 }
9092 
9093 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
9094 						 struct bpf_kfunc_call_arg_meta *meta)
9095 {
9096 	int iter_frameno = meta->iter.frameno;
9097 	int iter_spi = meta->iter.spi;
9098 
9099 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
9100 }
9101 
9102 /* process_iter_next_call() is called when verifier gets to iterator's next
9103  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
9104  * to it as just "iter_next()" in comments below.
9105  *
9106  * BPF verifier relies on a crucial contract for any iter_next()
9107  * implementation: it should *eventually* return NULL, and once that happens
9108  * it should keep returning NULL. That is, once iterator exhausts elements to
9109  * iterate, it should never reset or spuriously return new elements.
9110  *
9111  * With the assumption of such contract, process_iter_next_call() simulates
9112  * a fork in the verifier state to validate loop logic correctness and safety
9113  * without having to simulate infinite amount of iterations.
9114  *
9115  * In current state, we first assume that iter_next() returned NULL and
9116  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
9117  * conditions we should not form an infinite loop and should eventually reach
9118  * exit.
9119  *
9120  * Besides that, we also fork current state and enqueue it for later
9121  * verification. In a forked state we keep iterator state as ACTIVE
9122  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
9123  * also bump iteration depth to prevent erroneous infinite loop detection
9124  * later on (see iter_active_depths_differ() comment for details). In this
9125  * state we assume that we'll eventually loop back to another iter_next()
9126  * calls (it could be in exactly same location or in some other instruction,
9127  * it doesn't matter, we don't make any unnecessary assumptions about this,
9128  * everything revolves around iterator state in a stack slot, not which
9129  * instruction is calling iter_next()). When that happens, we either will come
9130  * to iter_next() with equivalent state and can conclude that next iteration
9131  * will proceed in exactly the same way as we just verified, so it's safe to
9132  * assume that loop converges. If not, we'll go on another iteration
9133  * simulation with a different input state, until all possible starting states
9134  * are validated or we reach maximum number of instructions limit.
9135  *
9136  * This way, we will either exhaustively discover all possible input states
9137  * that iterator loop can start with and eventually will converge, or we'll
9138  * effectively regress into bounded loop simulation logic and either reach
9139  * maximum number of instructions if loop is not provably convergent, or there
9140  * is some statically known limit on number of iterations (e.g., if there is
9141  * an explicit `if n > 100 then break;` statement somewhere in the loop).
9142  *
9143  * Iteration convergence logic in is_state_visited() relies on exact
9144  * states comparison, which ignores read and precision marks.
9145  * This is necessary because read and precision marks are not finalized
9146  * while in the loop. Exact comparison might preclude convergence for
9147  * simple programs like below:
9148  *
9149  *     i = 0;
9150  *     while(iter_next(&it))
9151  *       i++;
9152  *
9153  * At each iteration step i++ would produce a new distinct state and
9154  * eventually instruction processing limit would be reached.
9155  *
9156  * To avoid such behavior speculatively forget (widen) range for
9157  * imprecise scalar registers, if those registers were not precise at the
9158  * end of the previous iteration and do not match exactly.
9159  *
9160  * This is a conservative heuristic that allows to verify wide range of programs,
9161  * however it precludes verification of programs that conjure an
9162  * imprecise value on the first loop iteration and use it as precise on a second.
9163  * For example, the following safe program would fail to verify:
9164  *
9165  *     struct bpf_num_iter it;
9166  *     int arr[10];
9167  *     int i = 0, a = 0;
9168  *     bpf_iter_num_new(&it, 0, 10);
9169  *     while (bpf_iter_num_next(&it)) {
9170  *       if (a == 0) {
9171  *         a = 1;
9172  *         i = 7; // Because i changed verifier would forget
9173  *                // it's range on second loop entry.
9174  *       } else {
9175  *         arr[i] = 42; // This would fail to verify.
9176  *       }
9177  *     }
9178  *     bpf_iter_num_destroy(&it);
9179  */
9180 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
9181 				  struct bpf_kfunc_call_arg_meta *meta)
9182 {
9183 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
9184 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
9185 	struct bpf_reg_state *cur_iter, *queued_iter;
9186 
9187 	BTF_TYPE_EMIT(struct bpf_iter);
9188 
9189 	cur_iter = get_iter_from_state(cur_st, meta);
9190 
9191 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
9192 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
9193 		verifier_bug(env, "unexpected iterator state %d (%s)",
9194 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
9195 		return -EFAULT;
9196 	}
9197 
9198 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
9199 		/* Because iter_next() call is a checkpoint is_state_visitied()
9200 		 * should guarantee parent state with same call sites and insn_idx.
9201 		 */
9202 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
9203 		    !same_callsites(cur_st->parent, cur_st)) {
9204 			verifier_bug(env, "bad parent state for iter next call");
9205 			return -EFAULT;
9206 		}
9207 		/* Note cur_st->parent in the call below, it is necessary to skip
9208 		 * checkpoint created for cur_st by is_state_visited()
9209 		 * right at this instruction.
9210 		 */
9211 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
9212 		/* branch out active iter state */
9213 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
9214 		if (IS_ERR(queued_st))
9215 			return PTR_ERR(queued_st);
9216 
9217 		queued_iter = get_iter_from_state(queued_st, meta);
9218 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
9219 		queued_iter->iter.depth++;
9220 		if (prev_st)
9221 			widen_imprecise_scalars(env, prev_st, queued_st);
9222 
9223 		queued_fr = queued_st->frame[queued_st->curframe];
9224 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
9225 	}
9226 
9227 	/* switch to DRAINED state, but keep the depth unchanged */
9228 	/* mark current iter state as drained and assume returned NULL */
9229 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
9230 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
9231 
9232 	return 0;
9233 }
9234 
9235 static bool arg_type_is_mem_size(enum bpf_arg_type type)
9236 {
9237 	return type == ARG_CONST_SIZE ||
9238 	       type == ARG_CONST_SIZE_OR_ZERO;
9239 }
9240 
9241 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
9242 {
9243 	return base_type(type) == ARG_PTR_TO_MEM &&
9244 	       type & MEM_UNINIT;
9245 }
9246 
9247 static bool arg_type_is_release(enum bpf_arg_type type)
9248 {
9249 	return type & OBJ_RELEASE;
9250 }
9251 
9252 static bool arg_type_is_dynptr(enum bpf_arg_type type)
9253 {
9254 	return base_type(type) == ARG_PTR_TO_DYNPTR;
9255 }
9256 
9257 static int resolve_map_arg_type(struct bpf_verifier_env *env,
9258 				 const struct bpf_call_arg_meta *meta,
9259 				 enum bpf_arg_type *arg_type)
9260 {
9261 	if (!meta->map.ptr) {
9262 		/* kernel subsystem misconfigured verifier */
9263 		verifier_bug(env, "invalid map_ptr to access map->type");
9264 		return -EFAULT;
9265 	}
9266 
9267 	switch (meta->map.ptr->map_type) {
9268 	case BPF_MAP_TYPE_SOCKMAP:
9269 	case BPF_MAP_TYPE_SOCKHASH:
9270 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
9271 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
9272 		} else {
9273 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
9274 			return -EINVAL;
9275 		}
9276 		break;
9277 	case BPF_MAP_TYPE_BLOOM_FILTER:
9278 		if (meta->func_id == BPF_FUNC_map_peek_elem)
9279 			*arg_type = ARG_PTR_TO_MAP_VALUE;
9280 		break;
9281 	default:
9282 		break;
9283 	}
9284 	return 0;
9285 }
9286 
9287 struct bpf_reg_types {
9288 	const enum bpf_reg_type types[10];
9289 	u32 *btf_id;
9290 };
9291 
9292 static const struct bpf_reg_types sock_types = {
9293 	.types = {
9294 		PTR_TO_SOCK_COMMON,
9295 		PTR_TO_SOCKET,
9296 		PTR_TO_TCP_SOCK,
9297 		PTR_TO_XDP_SOCK,
9298 	},
9299 };
9300 
9301 #ifdef CONFIG_NET
9302 static const struct bpf_reg_types btf_id_sock_common_types = {
9303 	.types = {
9304 		PTR_TO_SOCK_COMMON,
9305 		PTR_TO_SOCKET,
9306 		PTR_TO_TCP_SOCK,
9307 		PTR_TO_XDP_SOCK,
9308 		PTR_TO_BTF_ID,
9309 		PTR_TO_BTF_ID | PTR_TRUSTED,
9310 	},
9311 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9312 };
9313 #endif
9314 
9315 static const struct bpf_reg_types mem_types = {
9316 	.types = {
9317 		PTR_TO_STACK,
9318 		PTR_TO_PACKET,
9319 		PTR_TO_PACKET_META,
9320 		PTR_TO_MAP_KEY,
9321 		PTR_TO_MAP_VALUE,
9322 		PTR_TO_MEM,
9323 		PTR_TO_MEM | MEM_RINGBUF,
9324 		PTR_TO_BUF,
9325 		PTR_TO_BTF_ID | PTR_TRUSTED,
9326 	},
9327 };
9328 
9329 static const struct bpf_reg_types spin_lock_types = {
9330 	.types = {
9331 		PTR_TO_MAP_VALUE,
9332 		PTR_TO_BTF_ID | MEM_ALLOC,
9333 	}
9334 };
9335 
9336 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
9337 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
9338 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
9339 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
9340 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
9341 static const struct bpf_reg_types btf_ptr_types = {
9342 	.types = {
9343 		PTR_TO_BTF_ID,
9344 		PTR_TO_BTF_ID | PTR_TRUSTED,
9345 		PTR_TO_BTF_ID | MEM_RCU,
9346 	},
9347 };
9348 static const struct bpf_reg_types percpu_btf_ptr_types = {
9349 	.types = {
9350 		PTR_TO_BTF_ID | MEM_PERCPU,
9351 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
9352 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
9353 	}
9354 };
9355 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
9356 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
9357 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
9358 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
9359 static const struct bpf_reg_types kptr_xchg_dest_types = {
9360 	.types = {
9361 		PTR_TO_MAP_VALUE,
9362 		PTR_TO_BTF_ID | MEM_ALLOC
9363 	}
9364 };
9365 static const struct bpf_reg_types dynptr_types = {
9366 	.types = {
9367 		PTR_TO_STACK,
9368 		CONST_PTR_TO_DYNPTR,
9369 	}
9370 };
9371 
9372 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
9373 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
9374 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
9375 	[ARG_CONST_SIZE]		= &scalar_types,
9376 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
9377 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
9378 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
9379 	[ARG_PTR_TO_CTX]		= &context_types,
9380 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
9381 #ifdef CONFIG_NET
9382 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
9383 #endif
9384 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
9385 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
9386 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
9387 	[ARG_PTR_TO_MEM]		= &mem_types,
9388 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
9389 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
9390 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
9391 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
9392 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
9393 	[ARG_PTR_TO_TIMER]		= &timer_types,
9394 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
9395 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
9396 };
9397 
9398 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
9399 			  enum bpf_arg_type arg_type,
9400 			  const u32 *arg_btf_id,
9401 			  struct bpf_call_arg_meta *meta)
9402 {
9403 	struct bpf_reg_state *reg = reg_state(env, regno);
9404 	enum bpf_reg_type expected, type = reg->type;
9405 	const struct bpf_reg_types *compatible;
9406 	int i, j;
9407 
9408 	compatible = compatible_reg_types[base_type(arg_type)];
9409 	if (!compatible) {
9410 		verifier_bug(env, "unsupported arg type %d", arg_type);
9411 		return -EFAULT;
9412 	}
9413 
9414 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
9415 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
9416 	 *
9417 	 * Same for MAYBE_NULL:
9418 	 *
9419 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
9420 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
9421 	 *
9422 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
9423 	 *
9424 	 * Therefore we fold these flags depending on the arg_type before comparison.
9425 	 */
9426 	if (arg_type & MEM_RDONLY)
9427 		type &= ~MEM_RDONLY;
9428 	if (arg_type & PTR_MAYBE_NULL)
9429 		type &= ~PTR_MAYBE_NULL;
9430 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
9431 		type &= ~DYNPTR_TYPE_FLAG_MASK;
9432 
9433 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
9434 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
9435 		type &= ~MEM_ALLOC;
9436 		type &= ~MEM_PERCPU;
9437 	}
9438 
9439 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
9440 		expected = compatible->types[i];
9441 		if (expected == NOT_INIT)
9442 			break;
9443 
9444 		if (type == expected)
9445 			goto found;
9446 	}
9447 
9448 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
9449 	for (j = 0; j + 1 < i; j++)
9450 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
9451 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
9452 	return -EACCES;
9453 
9454 found:
9455 	if (base_type(reg->type) != PTR_TO_BTF_ID)
9456 		return 0;
9457 
9458 	if (compatible == &mem_types) {
9459 		if (!(arg_type & MEM_RDONLY)) {
9460 			verbose(env,
9461 				"%s() may write into memory pointed by R%d type=%s\n",
9462 				func_id_name(meta->func_id),
9463 				regno, reg_type_str(env, reg->type));
9464 			return -EACCES;
9465 		}
9466 		return 0;
9467 	}
9468 
9469 	switch ((int)reg->type) {
9470 	case PTR_TO_BTF_ID:
9471 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9472 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
9473 	case PTR_TO_BTF_ID | MEM_RCU:
9474 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
9475 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
9476 	{
9477 		/* For bpf_sk_release, it needs to match against first member
9478 		 * 'struct sock_common', hence make an exception for it. This
9479 		 * allows bpf_sk_release to work for multiple socket types.
9480 		 */
9481 		bool strict_type_match = arg_type_is_release(arg_type) &&
9482 					 meta->func_id != BPF_FUNC_sk_release;
9483 
9484 		if (type_may_be_null(reg->type) &&
9485 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
9486 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
9487 			return -EACCES;
9488 		}
9489 
9490 		if (!arg_btf_id) {
9491 			if (!compatible->btf_id) {
9492 				verifier_bug(env, "missing arg compatible BTF ID");
9493 				return -EFAULT;
9494 			}
9495 			arg_btf_id = compatible->btf_id;
9496 		}
9497 
9498 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
9499 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9500 				return -EACCES;
9501 		} else {
9502 			if (arg_btf_id == BPF_PTR_POISON) {
9503 				verbose(env, "verifier internal error:");
9504 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
9505 					regno);
9506 				return -EACCES;
9507 			}
9508 
9509 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
9510 						  btf_vmlinux, *arg_btf_id,
9511 						  strict_type_match)) {
9512 				verbose(env, "R%d is of type %s but %s is expected\n",
9513 					regno, btf_type_name(reg->btf, reg->btf_id),
9514 					btf_type_name(btf_vmlinux, *arg_btf_id));
9515 				return -EACCES;
9516 			}
9517 		}
9518 		break;
9519 	}
9520 	case PTR_TO_BTF_ID | MEM_ALLOC:
9521 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
9522 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
9523 		    meta->func_id != BPF_FUNC_kptr_xchg) {
9524 			verifier_bug(env, "unimplemented handling of MEM_ALLOC");
9525 			return -EFAULT;
9526 		}
9527 		/* Check if local kptr in src arg matches kptr in dst arg */
9528 		if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
9529 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9530 				return -EACCES;
9531 		}
9532 		break;
9533 	case PTR_TO_BTF_ID | MEM_PERCPU:
9534 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
9535 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
9536 		/* Handled by helper specific checks */
9537 		break;
9538 	default:
9539 		verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match");
9540 		return -EFAULT;
9541 	}
9542 	return 0;
9543 }
9544 
9545 static struct btf_field *
9546 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
9547 {
9548 	struct btf_field *field;
9549 	struct btf_record *rec;
9550 
9551 	rec = reg_btf_record(reg);
9552 	if (!rec)
9553 		return NULL;
9554 
9555 	field = btf_record_find(rec, off, fields);
9556 	if (!field)
9557 		return NULL;
9558 
9559 	return field;
9560 }
9561 
9562 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
9563 				  const struct bpf_reg_state *reg, int regno,
9564 				  enum bpf_arg_type arg_type)
9565 {
9566 	u32 type = reg->type;
9567 
9568 	/* When referenced register is passed to release function, its fixed
9569 	 * offset must be 0.
9570 	 *
9571 	 * We will check arg_type_is_release reg has ref_obj_id when storing
9572 	 * meta->release_regno.
9573 	 */
9574 	if (arg_type_is_release(arg_type)) {
9575 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
9576 		 * may not directly point to the object being released, but to
9577 		 * dynptr pointing to such object, which might be at some offset
9578 		 * on the stack. In that case, we simply to fallback to the
9579 		 * default handling.
9580 		 */
9581 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
9582 			return 0;
9583 
9584 		/* Doing check_ptr_off_reg check for the offset will catch this
9585 		 * because fixed_off_ok is false, but checking here allows us
9586 		 * to give the user a better error message.
9587 		 */
9588 		if (reg->off) {
9589 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
9590 				regno);
9591 			return -EINVAL;
9592 		}
9593 		return __check_ptr_off_reg(env, reg, regno, false);
9594 	}
9595 
9596 	switch (type) {
9597 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9598 	case PTR_TO_STACK:
9599 	case PTR_TO_PACKET:
9600 	case PTR_TO_PACKET_META:
9601 	case PTR_TO_MAP_KEY:
9602 	case PTR_TO_MAP_VALUE:
9603 	case PTR_TO_MEM:
9604 	case PTR_TO_MEM | MEM_RDONLY:
9605 	case PTR_TO_MEM | MEM_RINGBUF:
9606 	case PTR_TO_BUF:
9607 	case PTR_TO_BUF | MEM_RDONLY:
9608 	case PTR_TO_ARENA:
9609 	case SCALAR_VALUE:
9610 		return 0;
9611 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9612 	 * fixed offset.
9613 	 */
9614 	case PTR_TO_BTF_ID:
9615 	case PTR_TO_BTF_ID | MEM_ALLOC:
9616 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9617 	case PTR_TO_BTF_ID | MEM_RCU:
9618 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9619 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9620 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9621 		 * its fixed offset must be 0. In the other cases, fixed offset
9622 		 * can be non-zero. This was already checked above. So pass
9623 		 * fixed_off_ok as true to allow fixed offset for all other
9624 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
9625 		 * still need to do checks instead of returning.
9626 		 */
9627 		return __check_ptr_off_reg(env, reg, regno, true);
9628 	default:
9629 		return __check_ptr_off_reg(env, reg, regno, false);
9630 	}
9631 }
9632 
9633 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
9634 						const struct bpf_func_proto *fn,
9635 						struct bpf_reg_state *regs)
9636 {
9637 	struct bpf_reg_state *state = NULL;
9638 	int i;
9639 
9640 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
9641 		if (arg_type_is_dynptr(fn->arg_type[i])) {
9642 			if (state) {
9643 				verbose(env, "verifier internal error: multiple dynptr args\n");
9644 				return NULL;
9645 			}
9646 			state = &regs[BPF_REG_1 + i];
9647 		}
9648 
9649 	if (!state)
9650 		verbose(env, "verifier internal error: no dynptr arg found\n");
9651 
9652 	return state;
9653 }
9654 
9655 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9656 {
9657 	struct bpf_func_state *state = func(env, reg);
9658 	int spi;
9659 
9660 	if (reg->type == CONST_PTR_TO_DYNPTR)
9661 		return reg->id;
9662 	spi = dynptr_get_spi(env, reg);
9663 	if (spi < 0)
9664 		return spi;
9665 	return state->stack[spi].spilled_ptr.id;
9666 }
9667 
9668 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9669 {
9670 	struct bpf_func_state *state = func(env, reg);
9671 	int spi;
9672 
9673 	if (reg->type == CONST_PTR_TO_DYNPTR)
9674 		return reg->ref_obj_id;
9675 	spi = dynptr_get_spi(env, reg);
9676 	if (spi < 0)
9677 		return spi;
9678 	return state->stack[spi].spilled_ptr.ref_obj_id;
9679 }
9680 
9681 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
9682 					    struct bpf_reg_state *reg)
9683 {
9684 	struct bpf_func_state *state = func(env, reg);
9685 	int spi;
9686 
9687 	if (reg->type == CONST_PTR_TO_DYNPTR)
9688 		return reg->dynptr.type;
9689 
9690 	spi = __get_spi(reg->off);
9691 	if (spi < 0) {
9692 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
9693 		return BPF_DYNPTR_TYPE_INVALID;
9694 	}
9695 
9696 	return state->stack[spi].spilled_ptr.dynptr.type;
9697 }
9698 
9699 static int check_reg_const_str(struct bpf_verifier_env *env,
9700 			       struct bpf_reg_state *reg, u32 regno)
9701 {
9702 	struct bpf_map *map = reg->map_ptr;
9703 	int err;
9704 	int map_off;
9705 	u64 map_addr;
9706 	char *str_ptr;
9707 
9708 	if (reg->type != PTR_TO_MAP_VALUE)
9709 		return -EINVAL;
9710 
9711 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
9712 		verbose(env, "R%d points to insn_array map which cannot be used as const string\n", regno);
9713 		return -EACCES;
9714 	}
9715 
9716 	if (!bpf_map_is_rdonly(map)) {
9717 		verbose(env, "R%d does not point to a readonly map'\n", regno);
9718 		return -EACCES;
9719 	}
9720 
9721 	if (!tnum_is_const(reg->var_off)) {
9722 		verbose(env, "R%d is not a constant address'\n", regno);
9723 		return -EACCES;
9724 	}
9725 
9726 	if (!map->ops->map_direct_value_addr) {
9727 		verbose(env, "no direct value access support for this map type\n");
9728 		return -EACCES;
9729 	}
9730 
9731 	err = check_map_access(env, regno, reg->off,
9732 			       map->value_size - reg->off, false,
9733 			       ACCESS_HELPER);
9734 	if (err)
9735 		return err;
9736 
9737 	map_off = reg->off + reg->var_off.value;
9738 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9739 	if (err) {
9740 		verbose(env, "direct value access on string failed\n");
9741 		return err;
9742 	}
9743 
9744 	str_ptr = (char *)(long)(map_addr);
9745 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9746 		verbose(env, "string is not zero-terminated\n");
9747 		return -EINVAL;
9748 	}
9749 	return 0;
9750 }
9751 
9752 /* Returns constant key value in `value` if possible, else negative error */
9753 static int get_constant_map_key(struct bpf_verifier_env *env,
9754 				struct bpf_reg_state *key,
9755 				u32 key_size,
9756 				s64 *value)
9757 {
9758 	struct bpf_func_state *state = func(env, key);
9759 	struct bpf_reg_state *reg;
9760 	int slot, spi, off;
9761 	int spill_size = 0;
9762 	int zero_size = 0;
9763 	int stack_off;
9764 	int i, err;
9765 	u8 *stype;
9766 
9767 	if (!env->bpf_capable)
9768 		return -EOPNOTSUPP;
9769 	if (key->type != PTR_TO_STACK)
9770 		return -EOPNOTSUPP;
9771 	if (!tnum_is_const(key->var_off))
9772 		return -EOPNOTSUPP;
9773 
9774 	stack_off = key->off + key->var_off.value;
9775 	slot = -stack_off - 1;
9776 	spi = slot / BPF_REG_SIZE;
9777 	off = slot % BPF_REG_SIZE;
9778 	stype = state->stack[spi].slot_type;
9779 
9780 	/* First handle precisely tracked STACK_ZERO */
9781 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9782 		zero_size++;
9783 	if (zero_size >= key_size) {
9784 		*value = 0;
9785 		return 0;
9786 	}
9787 
9788 	/* Check that stack contains a scalar spill of expected size */
9789 	if (!is_spilled_scalar_reg(&state->stack[spi]))
9790 		return -EOPNOTSUPP;
9791 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9792 		spill_size++;
9793 	if (spill_size != key_size)
9794 		return -EOPNOTSUPP;
9795 
9796 	reg = &state->stack[spi].spilled_ptr;
9797 	if (!tnum_is_const(reg->var_off))
9798 		/* Stack value not statically known */
9799 		return -EOPNOTSUPP;
9800 
9801 	/* We are relying on a constant value. So mark as precise
9802 	 * to prevent pruning on it.
9803 	 */
9804 	bt_set_frame_slot(&env->bt, key->frameno, spi);
9805 	err = mark_chain_precision_batch(env, env->cur_state);
9806 	if (err < 0)
9807 		return err;
9808 
9809 	*value = reg->var_off.value;
9810 	return 0;
9811 }
9812 
9813 static bool can_elide_value_nullness(enum bpf_map_type type);
9814 
9815 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9816 			  struct bpf_call_arg_meta *meta,
9817 			  const struct bpf_func_proto *fn,
9818 			  int insn_idx)
9819 {
9820 	u32 regno = BPF_REG_1 + arg;
9821 	struct bpf_reg_state *reg = reg_state(env, regno);
9822 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9823 	enum bpf_reg_type type = reg->type;
9824 	u32 *arg_btf_id = NULL;
9825 	u32 key_size;
9826 	int err = 0;
9827 
9828 	if (arg_type == ARG_DONTCARE)
9829 		return 0;
9830 
9831 	err = check_reg_arg(env, regno, SRC_OP);
9832 	if (err)
9833 		return err;
9834 
9835 	if (arg_type == ARG_ANYTHING) {
9836 		if (is_pointer_value(env, regno)) {
9837 			verbose(env, "R%d leaks addr into helper function\n",
9838 				regno);
9839 			return -EACCES;
9840 		}
9841 		return 0;
9842 	}
9843 
9844 	if (type_is_pkt_pointer(type) &&
9845 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9846 		verbose(env, "helper access to the packet is not allowed\n");
9847 		return -EACCES;
9848 	}
9849 
9850 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9851 		err = resolve_map_arg_type(env, meta, &arg_type);
9852 		if (err)
9853 			return err;
9854 	}
9855 
9856 	if (register_is_null(reg) && type_may_be_null(arg_type))
9857 		/* A NULL register has a SCALAR_VALUE type, so skip
9858 		 * type checking.
9859 		 */
9860 		goto skip_type_check;
9861 
9862 	/* arg_btf_id and arg_size are in a union. */
9863 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9864 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9865 		arg_btf_id = fn->arg_btf_id[arg];
9866 
9867 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9868 	if (err)
9869 		return err;
9870 
9871 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
9872 	if (err)
9873 		return err;
9874 
9875 skip_type_check:
9876 	if (arg_type_is_release(arg_type)) {
9877 		if (arg_type_is_dynptr(arg_type)) {
9878 			struct bpf_func_state *state = func(env, reg);
9879 			int spi;
9880 
9881 			/* Only dynptr created on stack can be released, thus
9882 			 * the get_spi and stack state checks for spilled_ptr
9883 			 * should only be done before process_dynptr_func for
9884 			 * PTR_TO_STACK.
9885 			 */
9886 			if (reg->type == PTR_TO_STACK) {
9887 				spi = dynptr_get_spi(env, reg);
9888 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9889 					verbose(env, "arg %d is an unacquired reference\n", regno);
9890 					return -EINVAL;
9891 				}
9892 			} else {
9893 				verbose(env, "cannot release unowned const bpf_dynptr\n");
9894 				return -EINVAL;
9895 			}
9896 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
9897 			verbose(env, "R%d must be referenced when passed to release function\n",
9898 				regno);
9899 			return -EINVAL;
9900 		}
9901 		if (meta->release_regno) {
9902 			verifier_bug(env, "more than one release argument");
9903 			return -EFAULT;
9904 		}
9905 		meta->release_regno = regno;
9906 	}
9907 
9908 	if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9909 		if (meta->ref_obj_id) {
9910 			verbose(env, "more than one arg with ref_obj_id R%d %u %u",
9911 				regno, reg->ref_obj_id,
9912 				meta->ref_obj_id);
9913 			return -EACCES;
9914 		}
9915 		meta->ref_obj_id = reg->ref_obj_id;
9916 	}
9917 
9918 	switch (base_type(arg_type)) {
9919 	case ARG_CONST_MAP_PTR:
9920 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9921 		if (meta->map.ptr) {
9922 			/* Use map_uid (which is unique id of inner map) to reject:
9923 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9924 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9925 			 * if (inner_map1 && inner_map2) {
9926 			 *     timer = bpf_map_lookup_elem(inner_map1);
9927 			 *     if (timer)
9928 			 *         // mismatch would have been allowed
9929 			 *         bpf_timer_init(timer, inner_map2);
9930 			 * }
9931 			 *
9932 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
9933 			 */
9934 			if (meta->map.ptr != reg->map_ptr ||
9935 			    meta->map.uid != reg->map_uid) {
9936 				verbose(env,
9937 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9938 					meta->map.uid, reg->map_uid);
9939 				return -EINVAL;
9940 			}
9941 		}
9942 		meta->map.ptr = reg->map_ptr;
9943 		meta->map.uid = reg->map_uid;
9944 		break;
9945 	case ARG_PTR_TO_MAP_KEY:
9946 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9947 		 * check that [key, key + map->key_size) are within
9948 		 * stack limits and initialized
9949 		 */
9950 		if (!meta->map.ptr) {
9951 			/* in function declaration map_ptr must come before
9952 			 * map_key, so that it's verified and known before
9953 			 * we have to check map_key here. Otherwise it means
9954 			 * that kernel subsystem misconfigured verifier
9955 			 */
9956 			verifier_bug(env, "invalid map_ptr to access map->key");
9957 			return -EFAULT;
9958 		}
9959 		key_size = meta->map.ptr->key_size;
9960 		err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL);
9961 		if (err)
9962 			return err;
9963 		if (can_elide_value_nullness(meta->map.ptr->map_type)) {
9964 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9965 			if (err < 0) {
9966 				meta->const_map_key = -1;
9967 				if (err == -EOPNOTSUPP)
9968 					err = 0;
9969 				else
9970 					return err;
9971 			}
9972 		}
9973 		break;
9974 	case ARG_PTR_TO_MAP_VALUE:
9975 		if (type_may_be_null(arg_type) && register_is_null(reg))
9976 			return 0;
9977 
9978 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9979 		 * check [value, value + map->value_size) validity
9980 		 */
9981 		if (!meta->map.ptr) {
9982 			/* kernel subsystem misconfigured verifier */
9983 			verifier_bug(env, "invalid map_ptr to access map->value");
9984 			return -EFAULT;
9985 		}
9986 		meta->raw_mode = arg_type & MEM_UNINIT;
9987 		err = check_helper_mem_access(env, regno, meta->map.ptr->value_size,
9988 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9989 					      false, meta);
9990 		break;
9991 	case ARG_PTR_TO_PERCPU_BTF_ID:
9992 		if (!reg->btf_id) {
9993 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9994 			return -EACCES;
9995 		}
9996 		meta->ret_btf = reg->btf;
9997 		meta->ret_btf_id = reg->btf_id;
9998 		break;
9999 	case ARG_PTR_TO_SPIN_LOCK:
10000 		if (in_rbtree_lock_required_cb(env)) {
10001 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
10002 			return -EACCES;
10003 		}
10004 		if (meta->func_id == BPF_FUNC_spin_lock) {
10005 			err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK);
10006 			if (err)
10007 				return err;
10008 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
10009 			err = process_spin_lock(env, regno, 0);
10010 			if (err)
10011 				return err;
10012 		} else {
10013 			verifier_bug(env, "spin lock arg on unexpected helper");
10014 			return -EFAULT;
10015 		}
10016 		break;
10017 	case ARG_PTR_TO_TIMER:
10018 		err = process_timer_helper(env, regno, meta);
10019 		if (err)
10020 			return err;
10021 		break;
10022 	case ARG_PTR_TO_FUNC:
10023 		meta->subprogno = reg->subprogno;
10024 		break;
10025 	case ARG_PTR_TO_MEM:
10026 		/* The access to this pointer is only checked when we hit the
10027 		 * next is_mem_size argument below.
10028 		 */
10029 		meta->raw_mode = arg_type & MEM_UNINIT;
10030 		if (arg_type & MEM_FIXED_SIZE) {
10031 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
10032 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
10033 						      false, meta);
10034 			if (err)
10035 				return err;
10036 			if (arg_type & MEM_ALIGNED)
10037 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
10038 		}
10039 		break;
10040 	case ARG_CONST_SIZE:
10041 		err = check_mem_size_reg(env, reg, regno,
10042 					 fn->arg_type[arg - 1] & MEM_WRITE ?
10043 					 BPF_WRITE : BPF_READ,
10044 					 false, meta);
10045 		break;
10046 	case ARG_CONST_SIZE_OR_ZERO:
10047 		err = check_mem_size_reg(env, reg, regno,
10048 					 fn->arg_type[arg - 1] & MEM_WRITE ?
10049 					 BPF_WRITE : BPF_READ,
10050 					 true, meta);
10051 		break;
10052 	case ARG_PTR_TO_DYNPTR:
10053 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
10054 		if (err)
10055 			return err;
10056 		break;
10057 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
10058 		if (!tnum_is_const(reg->var_off)) {
10059 			verbose(env, "R%d is not a known constant'\n",
10060 				regno);
10061 			return -EACCES;
10062 		}
10063 		meta->mem_size = reg->var_off.value;
10064 		err = mark_chain_precision(env, regno);
10065 		if (err)
10066 			return err;
10067 		break;
10068 	case ARG_PTR_TO_CONST_STR:
10069 	{
10070 		err = check_reg_const_str(env, reg, regno);
10071 		if (err)
10072 			return err;
10073 		break;
10074 	}
10075 	case ARG_KPTR_XCHG_DEST:
10076 		err = process_kptr_func(env, regno, meta);
10077 		if (err)
10078 			return err;
10079 		break;
10080 	}
10081 
10082 	return err;
10083 }
10084 
10085 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
10086 {
10087 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
10088 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10089 
10090 	if (func_id != BPF_FUNC_map_update_elem &&
10091 	    func_id != BPF_FUNC_map_delete_elem)
10092 		return false;
10093 
10094 	/* It's not possible to get access to a locked struct sock in these
10095 	 * contexts, so updating is safe.
10096 	 */
10097 	switch (type) {
10098 	case BPF_PROG_TYPE_TRACING:
10099 		if (eatype == BPF_TRACE_ITER)
10100 			return true;
10101 		break;
10102 	case BPF_PROG_TYPE_SOCK_OPS:
10103 		/* map_update allowed only via dedicated helpers with event type checks */
10104 		if (func_id == BPF_FUNC_map_delete_elem)
10105 			return true;
10106 		break;
10107 	case BPF_PROG_TYPE_SOCKET_FILTER:
10108 	case BPF_PROG_TYPE_SCHED_CLS:
10109 	case BPF_PROG_TYPE_SCHED_ACT:
10110 	case BPF_PROG_TYPE_XDP:
10111 	case BPF_PROG_TYPE_SK_REUSEPORT:
10112 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
10113 	case BPF_PROG_TYPE_SK_LOOKUP:
10114 		return true;
10115 	default:
10116 		break;
10117 	}
10118 
10119 	verbose(env, "cannot update sockmap in this context\n");
10120 	return false;
10121 }
10122 
10123 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
10124 {
10125 	return env->prog->jit_requested &&
10126 	       bpf_jit_supports_subprog_tailcalls();
10127 }
10128 
10129 static int check_map_func_compatibility(struct bpf_verifier_env *env,
10130 					struct bpf_map *map, int func_id)
10131 {
10132 	if (!map)
10133 		return 0;
10134 
10135 	/* We need a two way check, first is from map perspective ... */
10136 	switch (map->map_type) {
10137 	case BPF_MAP_TYPE_PROG_ARRAY:
10138 		if (func_id != BPF_FUNC_tail_call)
10139 			goto error;
10140 		break;
10141 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
10142 		if (func_id != BPF_FUNC_perf_event_read &&
10143 		    func_id != BPF_FUNC_perf_event_output &&
10144 		    func_id != BPF_FUNC_skb_output &&
10145 		    func_id != BPF_FUNC_perf_event_read_value &&
10146 		    func_id != BPF_FUNC_xdp_output)
10147 			goto error;
10148 		break;
10149 	case BPF_MAP_TYPE_RINGBUF:
10150 		if (func_id != BPF_FUNC_ringbuf_output &&
10151 		    func_id != BPF_FUNC_ringbuf_reserve &&
10152 		    func_id != BPF_FUNC_ringbuf_query &&
10153 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
10154 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
10155 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
10156 			goto error;
10157 		break;
10158 	case BPF_MAP_TYPE_USER_RINGBUF:
10159 		if (func_id != BPF_FUNC_user_ringbuf_drain)
10160 			goto error;
10161 		break;
10162 	case BPF_MAP_TYPE_STACK_TRACE:
10163 		if (func_id != BPF_FUNC_get_stackid)
10164 			goto error;
10165 		break;
10166 	case BPF_MAP_TYPE_CGROUP_ARRAY:
10167 		if (func_id != BPF_FUNC_skb_under_cgroup &&
10168 		    func_id != BPF_FUNC_current_task_under_cgroup)
10169 			goto error;
10170 		break;
10171 	case BPF_MAP_TYPE_CGROUP_STORAGE:
10172 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
10173 		if (func_id != BPF_FUNC_get_local_storage)
10174 			goto error;
10175 		break;
10176 	case BPF_MAP_TYPE_DEVMAP:
10177 	case BPF_MAP_TYPE_DEVMAP_HASH:
10178 		if (func_id != BPF_FUNC_redirect_map &&
10179 		    func_id != BPF_FUNC_map_lookup_elem)
10180 			goto error;
10181 		break;
10182 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
10183 	 * appear.
10184 	 */
10185 	case BPF_MAP_TYPE_CPUMAP:
10186 		if (func_id != BPF_FUNC_redirect_map)
10187 			goto error;
10188 		break;
10189 	case BPF_MAP_TYPE_XSKMAP:
10190 		if (func_id != BPF_FUNC_redirect_map &&
10191 		    func_id != BPF_FUNC_map_lookup_elem)
10192 			goto error;
10193 		break;
10194 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10195 	case BPF_MAP_TYPE_HASH_OF_MAPS:
10196 		if (func_id != BPF_FUNC_map_lookup_elem)
10197 			goto error;
10198 		break;
10199 	case BPF_MAP_TYPE_SOCKMAP:
10200 		if (func_id != BPF_FUNC_sk_redirect_map &&
10201 		    func_id != BPF_FUNC_sock_map_update &&
10202 		    func_id != BPF_FUNC_msg_redirect_map &&
10203 		    func_id != BPF_FUNC_sk_select_reuseport &&
10204 		    func_id != BPF_FUNC_map_lookup_elem &&
10205 		    !may_update_sockmap(env, func_id))
10206 			goto error;
10207 		break;
10208 	case BPF_MAP_TYPE_SOCKHASH:
10209 		if (func_id != BPF_FUNC_sk_redirect_hash &&
10210 		    func_id != BPF_FUNC_sock_hash_update &&
10211 		    func_id != BPF_FUNC_msg_redirect_hash &&
10212 		    func_id != BPF_FUNC_sk_select_reuseport &&
10213 		    func_id != BPF_FUNC_map_lookup_elem &&
10214 		    !may_update_sockmap(env, func_id))
10215 			goto error;
10216 		break;
10217 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
10218 		if (func_id != BPF_FUNC_sk_select_reuseport)
10219 			goto error;
10220 		break;
10221 	case BPF_MAP_TYPE_QUEUE:
10222 	case BPF_MAP_TYPE_STACK:
10223 		if (func_id != BPF_FUNC_map_peek_elem &&
10224 		    func_id != BPF_FUNC_map_pop_elem &&
10225 		    func_id != BPF_FUNC_map_push_elem)
10226 			goto error;
10227 		break;
10228 	case BPF_MAP_TYPE_SK_STORAGE:
10229 		if (func_id != BPF_FUNC_sk_storage_get &&
10230 		    func_id != BPF_FUNC_sk_storage_delete &&
10231 		    func_id != BPF_FUNC_kptr_xchg)
10232 			goto error;
10233 		break;
10234 	case BPF_MAP_TYPE_INODE_STORAGE:
10235 		if (func_id != BPF_FUNC_inode_storage_get &&
10236 		    func_id != BPF_FUNC_inode_storage_delete &&
10237 		    func_id != BPF_FUNC_kptr_xchg)
10238 			goto error;
10239 		break;
10240 	case BPF_MAP_TYPE_TASK_STORAGE:
10241 		if (func_id != BPF_FUNC_task_storage_get &&
10242 		    func_id != BPF_FUNC_task_storage_delete &&
10243 		    func_id != BPF_FUNC_kptr_xchg)
10244 			goto error;
10245 		break;
10246 	case BPF_MAP_TYPE_CGRP_STORAGE:
10247 		if (func_id != BPF_FUNC_cgrp_storage_get &&
10248 		    func_id != BPF_FUNC_cgrp_storage_delete &&
10249 		    func_id != BPF_FUNC_kptr_xchg)
10250 			goto error;
10251 		break;
10252 	case BPF_MAP_TYPE_BLOOM_FILTER:
10253 		if (func_id != BPF_FUNC_map_peek_elem &&
10254 		    func_id != BPF_FUNC_map_push_elem)
10255 			goto error;
10256 		break;
10257 	case BPF_MAP_TYPE_INSN_ARRAY:
10258 		goto error;
10259 	default:
10260 		break;
10261 	}
10262 
10263 	/* ... and second from the function itself. */
10264 	switch (func_id) {
10265 	case BPF_FUNC_tail_call:
10266 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
10267 			goto error;
10268 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
10269 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
10270 			return -EINVAL;
10271 		}
10272 		break;
10273 	case BPF_FUNC_perf_event_read:
10274 	case BPF_FUNC_perf_event_output:
10275 	case BPF_FUNC_perf_event_read_value:
10276 	case BPF_FUNC_skb_output:
10277 	case BPF_FUNC_xdp_output:
10278 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10279 			goto error;
10280 		break;
10281 	case BPF_FUNC_ringbuf_output:
10282 	case BPF_FUNC_ringbuf_reserve:
10283 	case BPF_FUNC_ringbuf_query:
10284 	case BPF_FUNC_ringbuf_reserve_dynptr:
10285 	case BPF_FUNC_ringbuf_submit_dynptr:
10286 	case BPF_FUNC_ringbuf_discard_dynptr:
10287 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
10288 			goto error;
10289 		break;
10290 	case BPF_FUNC_user_ringbuf_drain:
10291 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
10292 			goto error;
10293 		break;
10294 	case BPF_FUNC_get_stackid:
10295 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
10296 			goto error;
10297 		break;
10298 	case BPF_FUNC_current_task_under_cgroup:
10299 	case BPF_FUNC_skb_under_cgroup:
10300 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
10301 			goto error;
10302 		break;
10303 	case BPF_FUNC_redirect_map:
10304 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
10305 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
10306 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
10307 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
10308 			goto error;
10309 		break;
10310 	case BPF_FUNC_sk_redirect_map:
10311 	case BPF_FUNC_msg_redirect_map:
10312 	case BPF_FUNC_sock_map_update:
10313 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10314 			goto error;
10315 		break;
10316 	case BPF_FUNC_sk_redirect_hash:
10317 	case BPF_FUNC_msg_redirect_hash:
10318 	case BPF_FUNC_sock_hash_update:
10319 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10320 			goto error;
10321 		break;
10322 	case BPF_FUNC_get_local_storage:
10323 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10324 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10325 			goto error;
10326 		break;
10327 	case BPF_FUNC_sk_select_reuseport:
10328 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10329 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10330 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
10331 			goto error;
10332 		break;
10333 	case BPF_FUNC_map_pop_elem:
10334 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10335 		    map->map_type != BPF_MAP_TYPE_STACK)
10336 			goto error;
10337 		break;
10338 	case BPF_FUNC_map_peek_elem:
10339 	case BPF_FUNC_map_push_elem:
10340 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10341 		    map->map_type != BPF_MAP_TYPE_STACK &&
10342 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10343 			goto error;
10344 		break;
10345 	case BPF_FUNC_map_lookup_percpu_elem:
10346 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10347 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10348 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10349 			goto error;
10350 		break;
10351 	case BPF_FUNC_sk_storage_get:
10352 	case BPF_FUNC_sk_storage_delete:
10353 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10354 			goto error;
10355 		break;
10356 	case BPF_FUNC_inode_storage_get:
10357 	case BPF_FUNC_inode_storage_delete:
10358 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10359 			goto error;
10360 		break;
10361 	case BPF_FUNC_task_storage_get:
10362 	case BPF_FUNC_task_storage_delete:
10363 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10364 			goto error;
10365 		break;
10366 	case BPF_FUNC_cgrp_storage_get:
10367 	case BPF_FUNC_cgrp_storage_delete:
10368 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10369 			goto error;
10370 		break;
10371 	default:
10372 		break;
10373 	}
10374 
10375 	return 0;
10376 error:
10377 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
10378 		map->map_type, func_id_name(func_id), func_id);
10379 	return -EINVAL;
10380 }
10381 
10382 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
10383 {
10384 	int count = 0;
10385 
10386 	if (arg_type_is_raw_mem(fn->arg1_type))
10387 		count++;
10388 	if (arg_type_is_raw_mem(fn->arg2_type))
10389 		count++;
10390 	if (arg_type_is_raw_mem(fn->arg3_type))
10391 		count++;
10392 	if (arg_type_is_raw_mem(fn->arg4_type))
10393 		count++;
10394 	if (arg_type_is_raw_mem(fn->arg5_type))
10395 		count++;
10396 
10397 	/* We only support one arg being in raw mode at the moment,
10398 	 * which is sufficient for the helper functions we have
10399 	 * right now.
10400 	 */
10401 	return count <= 1;
10402 }
10403 
10404 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10405 {
10406 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10407 	bool has_size = fn->arg_size[arg] != 0;
10408 	bool is_next_size = false;
10409 
10410 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10411 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10412 
10413 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10414 		return is_next_size;
10415 
10416 	return has_size == is_next_size || is_next_size == is_fixed;
10417 }
10418 
10419 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10420 {
10421 	/* bpf_xxx(..., buf, len) call will access 'len'
10422 	 * bytes from memory 'buf'. Both arg types need
10423 	 * to be paired, so make sure there's no buggy
10424 	 * helper function specification.
10425 	 */
10426 	if (arg_type_is_mem_size(fn->arg1_type) ||
10427 	    check_args_pair_invalid(fn, 0) ||
10428 	    check_args_pair_invalid(fn, 1) ||
10429 	    check_args_pair_invalid(fn, 2) ||
10430 	    check_args_pair_invalid(fn, 3) ||
10431 	    check_args_pair_invalid(fn, 4))
10432 		return false;
10433 
10434 	return true;
10435 }
10436 
10437 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10438 {
10439 	int i;
10440 
10441 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10442 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10443 			return !!fn->arg_btf_id[i];
10444 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10445 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
10446 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10447 		    /* arg_btf_id and arg_size are in a union. */
10448 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10449 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10450 			return false;
10451 	}
10452 
10453 	return true;
10454 }
10455 
10456 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn)
10457 {
10458 	int i;
10459 
10460 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10461 		enum bpf_arg_type arg_type = fn->arg_type[i];
10462 
10463 		if (base_type(arg_type) != ARG_PTR_TO_MEM)
10464 			continue;
10465 		if (!(arg_type & (MEM_WRITE | MEM_RDONLY)))
10466 			return false;
10467 	}
10468 
10469 	return true;
10470 }
10471 
10472 static int check_func_proto(const struct bpf_func_proto *fn)
10473 {
10474 	return check_raw_mode_ok(fn) &&
10475 	       check_arg_pair_ok(fn) &&
10476 	       check_mem_arg_rw_flag_ok(fn) &&
10477 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
10478 }
10479 
10480 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
10481  * are now invalid, so turn them into unknown SCALAR_VALUE.
10482  *
10483  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
10484  * since these slices point to packet data.
10485  */
10486 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
10487 {
10488 	struct bpf_func_state *state;
10489 	struct bpf_reg_state *reg;
10490 
10491 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10492 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
10493 			mark_reg_invalid(env, reg);
10494 	}));
10495 }
10496 
10497 enum {
10498 	AT_PKT_END = -1,
10499 	BEYOND_PKT_END = -2,
10500 };
10501 
10502 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
10503 {
10504 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10505 	struct bpf_reg_state *reg = &state->regs[regn];
10506 
10507 	if (reg->type != PTR_TO_PACKET)
10508 		/* PTR_TO_PACKET_META is not supported yet */
10509 		return;
10510 
10511 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
10512 	 * How far beyond pkt_end it goes is unknown.
10513 	 * if (!range_open) it's the case of pkt >= pkt_end
10514 	 * if (range_open) it's the case of pkt > pkt_end
10515 	 * hence this pointer is at least 1 byte bigger than pkt_end
10516 	 */
10517 	if (range_open)
10518 		reg->range = BEYOND_PKT_END;
10519 	else
10520 		reg->range = AT_PKT_END;
10521 }
10522 
10523 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id)
10524 {
10525 	int i;
10526 
10527 	for (i = 0; i < state->acquired_refs; i++) {
10528 		if (state->refs[i].type != REF_TYPE_PTR)
10529 			continue;
10530 		if (state->refs[i].id == ref_obj_id) {
10531 			release_reference_state(state, i);
10532 			return 0;
10533 		}
10534 	}
10535 	return -EINVAL;
10536 }
10537 
10538 /* The pointer with the specified id has released its reference to kernel
10539  * resources. Identify all copies of the same pointer and clear the reference.
10540  *
10541  * This is the release function corresponding to acquire_reference(). Idempotent.
10542  */
10543 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id)
10544 {
10545 	struct bpf_verifier_state *vstate = env->cur_state;
10546 	struct bpf_func_state *state;
10547 	struct bpf_reg_state *reg;
10548 	int err;
10549 
10550 	err = release_reference_nomark(vstate, ref_obj_id);
10551 	if (err)
10552 		return err;
10553 
10554 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10555 		if (reg->ref_obj_id == ref_obj_id)
10556 			mark_reg_invalid(env, reg);
10557 	}));
10558 
10559 	return 0;
10560 }
10561 
10562 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
10563 {
10564 	struct bpf_func_state *unused;
10565 	struct bpf_reg_state *reg;
10566 
10567 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10568 		if (type_is_non_owning_ref(reg->type))
10569 			mark_reg_invalid(env, reg);
10570 	}));
10571 }
10572 
10573 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
10574 				    struct bpf_reg_state *regs)
10575 {
10576 	int i;
10577 
10578 	/* after the call registers r0 - r5 were scratched */
10579 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10580 		mark_reg_not_init(env, regs, caller_saved[i]);
10581 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
10582 	}
10583 }
10584 
10585 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
10586 				   struct bpf_func_state *caller,
10587 				   struct bpf_func_state *callee,
10588 				   int insn_idx);
10589 
10590 static int set_callee_state(struct bpf_verifier_env *env,
10591 			    struct bpf_func_state *caller,
10592 			    struct bpf_func_state *callee, int insn_idx);
10593 
10594 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
10595 			    set_callee_state_fn set_callee_state_cb,
10596 			    struct bpf_verifier_state *state)
10597 {
10598 	struct bpf_func_state *caller, *callee;
10599 	int err;
10600 
10601 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
10602 		verbose(env, "the call stack of %d frames is too deep\n",
10603 			state->curframe + 2);
10604 		return -E2BIG;
10605 	}
10606 
10607 	if (state->frame[state->curframe + 1]) {
10608 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
10609 		return -EFAULT;
10610 	}
10611 
10612 	caller = state->frame[state->curframe];
10613 	callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT);
10614 	if (!callee)
10615 		return -ENOMEM;
10616 	state->frame[state->curframe + 1] = callee;
10617 
10618 	/* callee cannot access r0, r6 - r9 for reading and has to write
10619 	 * into its own stack before reading from it.
10620 	 * callee can read/write into caller's stack
10621 	 */
10622 	init_func_state(env, callee,
10623 			/* remember the callsite, it will be used by bpf_exit */
10624 			callsite,
10625 			state->curframe + 1 /* frameno within this callchain */,
10626 			subprog /* subprog number within this prog */);
10627 	err = set_callee_state_cb(env, caller, callee, callsite);
10628 	if (err)
10629 		goto err_out;
10630 
10631 	/* only increment it after check_reg_arg() finished */
10632 	state->curframe++;
10633 
10634 	return 0;
10635 
10636 err_out:
10637 	free_func_state(callee);
10638 	state->frame[state->curframe + 1] = NULL;
10639 	return err;
10640 }
10641 
10642 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
10643 				    const struct btf *btf,
10644 				    struct bpf_reg_state *regs)
10645 {
10646 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
10647 	struct bpf_verifier_log *log = &env->log;
10648 	u32 i;
10649 	int ret;
10650 
10651 	ret = btf_prepare_func_args(env, subprog);
10652 	if (ret)
10653 		return ret;
10654 
10655 	/* check that BTF function arguments match actual types that the
10656 	 * verifier sees.
10657 	 */
10658 	for (i = 0; i < sub->arg_cnt; i++) {
10659 		u32 regno = i + 1;
10660 		struct bpf_reg_state *reg = &regs[regno];
10661 		struct bpf_subprog_arg_info *arg = &sub->args[i];
10662 
10663 		if (arg->arg_type == ARG_ANYTHING) {
10664 			if (reg->type != SCALAR_VALUE) {
10665 				bpf_log(log, "R%d is not a scalar\n", regno);
10666 				return -EINVAL;
10667 			}
10668 		} else if (arg->arg_type & PTR_UNTRUSTED) {
10669 			/*
10670 			 * Anything is allowed for untrusted arguments, as these are
10671 			 * read-only and probe read instructions would protect against
10672 			 * invalid memory access.
10673 			 */
10674 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
10675 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10676 			if (ret < 0)
10677 				return ret;
10678 			/* If function expects ctx type in BTF check that caller
10679 			 * is passing PTR_TO_CTX.
10680 			 */
10681 			if (reg->type != PTR_TO_CTX) {
10682 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
10683 				return -EINVAL;
10684 			}
10685 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
10686 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10687 			if (ret < 0)
10688 				return ret;
10689 			if (check_mem_reg(env, reg, regno, arg->mem_size))
10690 				return -EINVAL;
10691 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
10692 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
10693 				return -EINVAL;
10694 			}
10695 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
10696 			/*
10697 			 * Can pass any value and the kernel won't crash, but
10698 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
10699 			 * else is a bug in the bpf program. Point it out to
10700 			 * the user at the verification time instead of
10701 			 * run-time debug nightmare.
10702 			 */
10703 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
10704 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
10705 				return -EINVAL;
10706 			}
10707 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
10708 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
10709 			if (ret)
10710 				return ret;
10711 
10712 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
10713 			if (ret)
10714 				return ret;
10715 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
10716 			struct bpf_call_arg_meta meta;
10717 			int err;
10718 
10719 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
10720 				continue;
10721 
10722 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
10723 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
10724 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
10725 			if (err)
10726 				return err;
10727 		} else {
10728 			verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type);
10729 			return -EFAULT;
10730 		}
10731 	}
10732 
10733 	return 0;
10734 }
10735 
10736 /* Compare BTF of a function call with given bpf_reg_state.
10737  * Returns:
10738  * EFAULT - there is a verifier bug. Abort verification.
10739  * EINVAL - there is a type mismatch or BTF is not available.
10740  * 0 - BTF matches with what bpf_reg_state expects.
10741  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
10742  */
10743 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
10744 				  struct bpf_reg_state *regs)
10745 {
10746 	struct bpf_prog *prog = env->prog;
10747 	struct btf *btf = prog->aux->btf;
10748 	u32 btf_id;
10749 	int err;
10750 
10751 	if (!prog->aux->func_info)
10752 		return -EINVAL;
10753 
10754 	btf_id = prog->aux->func_info[subprog].type_id;
10755 	if (!btf_id)
10756 		return -EFAULT;
10757 
10758 	if (prog->aux->func_info_aux[subprog].unreliable)
10759 		return -EINVAL;
10760 
10761 	err = btf_check_func_arg_match(env, subprog, btf, regs);
10762 	/* Compiler optimizations can remove arguments from static functions
10763 	 * or mismatched type can be passed into a global function.
10764 	 * In such cases mark the function as unreliable from BTF point of view.
10765 	 */
10766 	if (err)
10767 		prog->aux->func_info_aux[subprog].unreliable = true;
10768 	return err;
10769 }
10770 
10771 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10772 			      int insn_idx, int subprog,
10773 			      set_callee_state_fn set_callee_state_cb)
10774 {
10775 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
10776 	struct bpf_func_state *caller, *callee;
10777 	int err;
10778 
10779 	caller = state->frame[state->curframe];
10780 	err = btf_check_subprog_call(env, subprog, caller->regs);
10781 	if (err == -EFAULT)
10782 		return err;
10783 
10784 	/* set_callee_state is used for direct subprog calls, but we are
10785 	 * interested in validating only BPF helpers that can call subprogs as
10786 	 * callbacks
10787 	 */
10788 	env->subprog_info[subprog].is_cb = true;
10789 	if (bpf_pseudo_kfunc_call(insn) &&
10790 	    !is_callback_calling_kfunc(insn->imm)) {
10791 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
10792 			     func_id_name(insn->imm), insn->imm);
10793 		return -EFAULT;
10794 	} else if (!bpf_pseudo_kfunc_call(insn) &&
10795 		   !is_callback_calling_function(insn->imm)) { /* helper */
10796 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
10797 			     func_id_name(insn->imm), insn->imm);
10798 		return -EFAULT;
10799 	}
10800 
10801 	if (is_async_callback_calling_insn(insn)) {
10802 		struct bpf_verifier_state *async_cb;
10803 
10804 		/* there is no real recursion here. timer and workqueue callbacks are async */
10805 		env->subprog_info[subprog].is_async_cb = true;
10806 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
10807 					 insn_idx, subprog,
10808 					 is_async_cb_sleepable(env, insn));
10809 		if (IS_ERR(async_cb))
10810 			return PTR_ERR(async_cb);
10811 		callee = async_cb->frame[0];
10812 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
10813 
10814 		/* Convert bpf_timer_set_callback() args into timer callback args */
10815 		err = set_callee_state_cb(env, caller, callee, insn_idx);
10816 		if (err)
10817 			return err;
10818 
10819 		return 0;
10820 	}
10821 
10822 	/* for callback functions enqueue entry to callback and
10823 	 * proceed with next instruction within current frame.
10824 	 */
10825 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
10826 	if (IS_ERR(callback_state))
10827 		return PTR_ERR(callback_state);
10828 
10829 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
10830 			       callback_state);
10831 	if (err)
10832 		return err;
10833 
10834 	callback_state->callback_unroll_depth++;
10835 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
10836 	caller->callback_depth = 0;
10837 	return 0;
10838 }
10839 
10840 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10841 			   int *insn_idx)
10842 {
10843 	struct bpf_verifier_state *state = env->cur_state;
10844 	struct bpf_func_state *caller;
10845 	int err, subprog, target_insn;
10846 
10847 	target_insn = *insn_idx + insn->imm + 1;
10848 	subprog = find_subprog(env, target_insn);
10849 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
10850 			    target_insn))
10851 		return -EFAULT;
10852 
10853 	caller = state->frame[state->curframe];
10854 	err = btf_check_subprog_call(env, subprog, caller->regs);
10855 	if (err == -EFAULT)
10856 		return err;
10857 	if (subprog_is_global(env, subprog)) {
10858 		const char *sub_name = subprog_name(env, subprog);
10859 
10860 		if (env->cur_state->active_locks) {
10861 			verbose(env, "global function calls are not allowed while holding a lock,\n"
10862 				     "use static function instead\n");
10863 			return -EINVAL;
10864 		}
10865 
10866 		if (env->subprog_info[subprog].might_sleep &&
10867 		    (env->cur_state->active_rcu_locks || env->cur_state->active_preempt_locks ||
10868 		     env->cur_state->active_irq_id || !in_sleepable(env))) {
10869 			verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n"
10870 				     "i.e., in a RCU/IRQ/preempt-disabled section, or in\n"
10871 				     "a non-sleepable BPF program context\n");
10872 			return -EINVAL;
10873 		}
10874 
10875 		if (err) {
10876 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10877 				subprog, sub_name);
10878 			return err;
10879 		}
10880 
10881 		if (env->log.level & BPF_LOG_LEVEL)
10882 			verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10883 				subprog, sub_name);
10884 		if (env->subprog_info[subprog].changes_pkt_data)
10885 			clear_all_pkt_pointers(env);
10886 		/* mark global subprog for verifying after main prog */
10887 		subprog_aux(env, subprog)->called = true;
10888 		clear_caller_saved_regs(env, caller->regs);
10889 
10890 		/* All global functions return a 64-bit SCALAR_VALUE */
10891 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
10892 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10893 
10894 		/* continue with next insn after call */
10895 		return 0;
10896 	}
10897 
10898 	/* for regular function entry setup new frame and continue
10899 	 * from that frame.
10900 	 */
10901 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10902 	if (err)
10903 		return err;
10904 
10905 	clear_caller_saved_regs(env, caller->regs);
10906 
10907 	/* and go analyze first insn of the callee */
10908 	*insn_idx = env->subprog_info[subprog].start - 1;
10909 
10910 	bpf_reset_live_stack_callchain(env);
10911 
10912 	if (env->log.level & BPF_LOG_LEVEL) {
10913 		verbose(env, "caller:\n");
10914 		print_verifier_state(env, state, caller->frameno, true);
10915 		verbose(env, "callee:\n");
10916 		print_verifier_state(env, state, state->curframe, true);
10917 	}
10918 
10919 	return 0;
10920 }
10921 
10922 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10923 				   struct bpf_func_state *caller,
10924 				   struct bpf_func_state *callee)
10925 {
10926 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10927 	 *      void *callback_ctx, u64 flags);
10928 	 * callback_fn(struct bpf_map *map, void *key, void *value,
10929 	 *      void *callback_ctx);
10930 	 */
10931 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10932 
10933 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10934 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10935 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10936 
10937 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10938 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10939 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10940 
10941 	/* pointer to stack or null */
10942 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10943 
10944 	/* unused */
10945 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10946 	return 0;
10947 }
10948 
10949 static int set_callee_state(struct bpf_verifier_env *env,
10950 			    struct bpf_func_state *caller,
10951 			    struct bpf_func_state *callee, int insn_idx)
10952 {
10953 	int i;
10954 
10955 	/* copy r1 - r5 args that callee can access.  The copy includes parent
10956 	 * pointers, which connects us up to the liveness chain
10957 	 */
10958 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10959 		callee->regs[i] = caller->regs[i];
10960 	return 0;
10961 }
10962 
10963 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10964 				       struct bpf_func_state *caller,
10965 				       struct bpf_func_state *callee,
10966 				       int insn_idx)
10967 {
10968 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10969 	struct bpf_map *map;
10970 	int err;
10971 
10972 	/* valid map_ptr and poison value does not matter */
10973 	map = insn_aux->map_ptr_state.map_ptr;
10974 	if (!map->ops->map_set_for_each_callback_args ||
10975 	    !map->ops->map_for_each_callback) {
10976 		verbose(env, "callback function not allowed for map\n");
10977 		return -ENOTSUPP;
10978 	}
10979 
10980 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10981 	if (err)
10982 		return err;
10983 
10984 	callee->in_callback_fn = true;
10985 	callee->callback_ret_range = retval_range(0, 1);
10986 	return 0;
10987 }
10988 
10989 static int set_loop_callback_state(struct bpf_verifier_env *env,
10990 				   struct bpf_func_state *caller,
10991 				   struct bpf_func_state *callee,
10992 				   int insn_idx)
10993 {
10994 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10995 	 *	    u64 flags);
10996 	 * callback_fn(u64 index, void *callback_ctx);
10997 	 */
10998 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10999 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
11000 
11001 	/* unused */
11002 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
11003 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11004 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11005 
11006 	callee->in_callback_fn = true;
11007 	callee->callback_ret_range = retval_range(0, 1);
11008 	return 0;
11009 }
11010 
11011 static int set_timer_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 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
11017 
11018 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
11019 	 * callback_fn(struct bpf_map *map, void *key, void *value);
11020 	 */
11021 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
11022 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
11023 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
11024 
11025 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11026 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11027 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
11028 
11029 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11030 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11031 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
11032 
11033 	/* unused */
11034 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11035 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11036 	callee->in_async_callback_fn = true;
11037 	callee->callback_ret_range = retval_range(0, 0);
11038 	return 0;
11039 }
11040 
11041 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
11042 				       struct bpf_func_state *caller,
11043 				       struct bpf_func_state *callee,
11044 				       int insn_idx)
11045 {
11046 	/* bpf_find_vma(struct task_struct *task, u64 addr,
11047 	 *               void *callback_fn, void *callback_ctx, u64 flags)
11048 	 * (callback_fn)(struct task_struct *task,
11049 	 *               struct vm_area_struct *vma, void *callback_ctx);
11050 	 */
11051 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
11052 
11053 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
11054 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11055 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
11056 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
11057 
11058 	/* pointer to stack or null */
11059 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
11060 
11061 	/* unused */
11062 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11063 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11064 	callee->in_callback_fn = true;
11065 	callee->callback_ret_range = retval_range(0, 1);
11066 	return 0;
11067 }
11068 
11069 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
11070 					   struct bpf_func_state *caller,
11071 					   struct bpf_func_state *callee,
11072 					   int insn_idx)
11073 {
11074 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
11075 	 *			  callback_ctx, u64 flags);
11076 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
11077 	 */
11078 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
11079 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
11080 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
11081 
11082 	/* unused */
11083 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
11084 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11085 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11086 
11087 	callee->in_callback_fn = true;
11088 	callee->callback_ret_range = retval_range(0, 1);
11089 	return 0;
11090 }
11091 
11092 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
11093 					 struct bpf_func_state *caller,
11094 					 struct bpf_func_state *callee,
11095 					 int insn_idx)
11096 {
11097 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
11098 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
11099 	 *
11100 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
11101 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
11102 	 * by this point, so look at 'root'
11103 	 */
11104 	struct btf_field *field;
11105 
11106 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
11107 				      BPF_RB_ROOT);
11108 	if (!field || !field->graph_root.value_btf_id)
11109 		return -EFAULT;
11110 
11111 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
11112 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
11113 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
11114 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
11115 
11116 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
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_callback_fn = true;
11120 	callee->callback_ret_range = retval_range(0, 1);
11121 	return 0;
11122 }
11123 
11124 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
11125 						 struct bpf_func_state *caller,
11126 						 struct bpf_func_state *callee,
11127 						 int insn_idx)
11128 {
11129 	struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
11130 
11131 	/*
11132 	 * callback_fn(struct bpf_map *map, void *key, void *value);
11133 	 */
11134 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
11135 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
11136 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
11137 
11138 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11139 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11140 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
11141 
11142 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11143 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11144 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
11145 
11146 	/* unused */
11147 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11148 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11149 	callee->in_async_callback_fn = true;
11150 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
11151 	return 0;
11152 }
11153 
11154 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
11155 
11156 /* Are we currently verifying the callback for a rbtree helper that must
11157  * be called with lock held? If so, no need to complain about unreleased
11158  * lock
11159  */
11160 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
11161 {
11162 	struct bpf_verifier_state *state = env->cur_state;
11163 	struct bpf_insn *insn = env->prog->insnsi;
11164 	struct bpf_func_state *callee;
11165 	int kfunc_btf_id;
11166 
11167 	if (!state->curframe)
11168 		return false;
11169 
11170 	callee = state->frame[state->curframe];
11171 
11172 	if (!callee->in_callback_fn)
11173 		return false;
11174 
11175 	kfunc_btf_id = insn[callee->callsite].imm;
11176 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
11177 }
11178 
11179 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
11180 				bool return_32bit)
11181 {
11182 	if (return_32bit)
11183 		return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
11184 	else
11185 		return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
11186 }
11187 
11188 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
11189 {
11190 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
11191 	struct bpf_func_state *caller, *callee;
11192 	struct bpf_reg_state *r0;
11193 	bool in_callback_fn;
11194 	int err;
11195 
11196 	err = bpf_update_live_stack(env);
11197 	if (err)
11198 		return err;
11199 
11200 	callee = state->frame[state->curframe];
11201 	r0 = &callee->regs[BPF_REG_0];
11202 	if (r0->type == PTR_TO_STACK) {
11203 		/* technically it's ok to return caller's stack pointer
11204 		 * (or caller's caller's pointer) back to the caller,
11205 		 * since these pointers are valid. Only current stack
11206 		 * pointer will be invalid as soon as function exits,
11207 		 * but let's be conservative
11208 		 */
11209 		verbose(env, "cannot return stack pointer to the caller\n");
11210 		return -EINVAL;
11211 	}
11212 
11213 	caller = state->frame[state->curframe - 1];
11214 	if (callee->in_callback_fn) {
11215 		if (r0->type != SCALAR_VALUE) {
11216 			verbose(env, "R0 not a scalar value\n");
11217 			return -EACCES;
11218 		}
11219 
11220 		/* we are going to rely on register's precise value */
11221 		err = mark_chain_precision(env, BPF_REG_0);
11222 		if (err)
11223 			return err;
11224 
11225 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
11226 		if (!retval_range_within(callee->callback_ret_range, r0, false)) {
11227 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
11228 					       "At callback return", "R0");
11229 			return -EINVAL;
11230 		}
11231 		if (!bpf_calls_callback(env, callee->callsite)) {
11232 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
11233 				     *insn_idx, callee->callsite);
11234 			return -EFAULT;
11235 		}
11236 	} else {
11237 		/* return to the caller whatever r0 had in the callee */
11238 		caller->regs[BPF_REG_0] = *r0;
11239 	}
11240 
11241 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
11242 	 * there function call logic would reschedule callback visit. If iteration
11243 	 * converges is_state_visited() would prune that visit eventually.
11244 	 */
11245 	in_callback_fn = callee->in_callback_fn;
11246 	if (in_callback_fn)
11247 		*insn_idx = callee->callsite;
11248 	else
11249 		*insn_idx = callee->callsite + 1;
11250 
11251 	if (env->log.level & BPF_LOG_LEVEL) {
11252 		verbose(env, "returning from callee:\n");
11253 		print_verifier_state(env, state, callee->frameno, true);
11254 		verbose(env, "to caller at %d:\n", *insn_idx);
11255 		print_verifier_state(env, state, caller->frameno, true);
11256 	}
11257 	/* clear everything in the callee. In case of exceptional exits using
11258 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
11259 	free_func_state(callee);
11260 	state->frame[state->curframe--] = NULL;
11261 
11262 	/* for callbacks widen imprecise scalars to make programs like below verify:
11263 	 *
11264 	 *   struct ctx { int i; }
11265 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
11266 	 *   ...
11267 	 *   struct ctx = { .i = 0; }
11268 	 *   bpf_loop(100, cb, &ctx, 0);
11269 	 *
11270 	 * This is similar to what is done in process_iter_next_call() for open
11271 	 * coded iterators.
11272 	 */
11273 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
11274 	if (prev_st) {
11275 		err = widen_imprecise_scalars(env, prev_st, state);
11276 		if (err)
11277 			return err;
11278 	}
11279 	return 0;
11280 }
11281 
11282 static int do_refine_retval_range(struct bpf_verifier_env *env,
11283 				  struct bpf_reg_state *regs, int ret_type,
11284 				  int func_id,
11285 				  struct bpf_call_arg_meta *meta)
11286 {
11287 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
11288 
11289 	if (ret_type != RET_INTEGER)
11290 		return 0;
11291 
11292 	switch (func_id) {
11293 	case BPF_FUNC_get_stack:
11294 	case BPF_FUNC_get_task_stack:
11295 	case BPF_FUNC_probe_read_str:
11296 	case BPF_FUNC_probe_read_kernel_str:
11297 	case BPF_FUNC_probe_read_user_str:
11298 		ret_reg->smax_value = meta->msize_max_value;
11299 		ret_reg->s32_max_value = meta->msize_max_value;
11300 		ret_reg->smin_value = -MAX_ERRNO;
11301 		ret_reg->s32_min_value = -MAX_ERRNO;
11302 		reg_bounds_sync(ret_reg);
11303 		break;
11304 	case BPF_FUNC_get_smp_processor_id:
11305 		ret_reg->umax_value = nr_cpu_ids - 1;
11306 		ret_reg->u32_max_value = nr_cpu_ids - 1;
11307 		ret_reg->smax_value = nr_cpu_ids - 1;
11308 		ret_reg->s32_max_value = nr_cpu_ids - 1;
11309 		ret_reg->umin_value = 0;
11310 		ret_reg->u32_min_value = 0;
11311 		ret_reg->smin_value = 0;
11312 		ret_reg->s32_min_value = 0;
11313 		reg_bounds_sync(ret_reg);
11314 		break;
11315 	}
11316 
11317 	return reg_bounds_sanity_check(env, ret_reg, "retval");
11318 }
11319 
11320 static int
11321 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11322 		int func_id, int insn_idx)
11323 {
11324 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11325 	struct bpf_map *map = meta->map.ptr;
11326 
11327 	if (func_id != BPF_FUNC_tail_call &&
11328 	    func_id != BPF_FUNC_map_lookup_elem &&
11329 	    func_id != BPF_FUNC_map_update_elem &&
11330 	    func_id != BPF_FUNC_map_delete_elem &&
11331 	    func_id != BPF_FUNC_map_push_elem &&
11332 	    func_id != BPF_FUNC_map_pop_elem &&
11333 	    func_id != BPF_FUNC_map_peek_elem &&
11334 	    func_id != BPF_FUNC_for_each_map_elem &&
11335 	    func_id != BPF_FUNC_redirect_map &&
11336 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
11337 		return 0;
11338 
11339 	if (map == NULL) {
11340 		verifier_bug(env, "expected map for helper call");
11341 		return -EFAULT;
11342 	}
11343 
11344 	/* In case of read-only, some additional restrictions
11345 	 * need to be applied in order to prevent altering the
11346 	 * state of the map from program side.
11347 	 */
11348 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
11349 	    (func_id == BPF_FUNC_map_delete_elem ||
11350 	     func_id == BPF_FUNC_map_update_elem ||
11351 	     func_id == BPF_FUNC_map_push_elem ||
11352 	     func_id == BPF_FUNC_map_pop_elem)) {
11353 		verbose(env, "write into map forbidden\n");
11354 		return -EACCES;
11355 	}
11356 
11357 	if (!aux->map_ptr_state.map_ptr)
11358 		bpf_map_ptr_store(aux, meta->map.ptr,
11359 				  !meta->map.ptr->bypass_spec_v1, false);
11360 	else if (aux->map_ptr_state.map_ptr != meta->map.ptr)
11361 		bpf_map_ptr_store(aux, meta->map.ptr,
11362 				  !meta->map.ptr->bypass_spec_v1, true);
11363 	return 0;
11364 }
11365 
11366 static int
11367 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11368 		int func_id, int insn_idx)
11369 {
11370 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11371 	struct bpf_reg_state *reg;
11372 	struct bpf_map *map = meta->map.ptr;
11373 	u64 val, max;
11374 	int err;
11375 
11376 	if (func_id != BPF_FUNC_tail_call)
11377 		return 0;
11378 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
11379 		verbose(env, "expected prog array map for tail call");
11380 		return -EINVAL;
11381 	}
11382 
11383 	reg = reg_state(env, BPF_REG_3);
11384 	val = reg->var_off.value;
11385 	max = map->max_entries;
11386 
11387 	if (!(is_reg_const(reg, false) && val < max)) {
11388 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11389 		return 0;
11390 	}
11391 
11392 	err = mark_chain_precision(env, BPF_REG_3);
11393 	if (err)
11394 		return err;
11395 	if (bpf_map_key_unseen(aux))
11396 		bpf_map_key_store(aux, val);
11397 	else if (!bpf_map_key_poisoned(aux) &&
11398 		  bpf_map_key_immediate(aux) != val)
11399 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11400 	return 0;
11401 }
11402 
11403 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
11404 {
11405 	struct bpf_verifier_state *state = env->cur_state;
11406 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11407 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
11408 	bool refs_lingering = false;
11409 	int i;
11410 
11411 	if (!exception_exit && cur_func(env)->frameno)
11412 		return 0;
11413 
11414 	for (i = 0; i < state->acquired_refs; i++) {
11415 		if (state->refs[i].type != REF_TYPE_PTR)
11416 			continue;
11417 		/* Allow struct_ops programs to return a referenced kptr back to
11418 		 * kernel. Type checks are performed later in check_return_code.
11419 		 */
11420 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
11421 		    reg->ref_obj_id == state->refs[i].id)
11422 			continue;
11423 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
11424 			state->refs[i].id, state->refs[i].insn_idx);
11425 		refs_lingering = true;
11426 	}
11427 	return refs_lingering ? -EINVAL : 0;
11428 }
11429 
11430 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
11431 {
11432 	int err;
11433 
11434 	if (check_lock && env->cur_state->active_locks) {
11435 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
11436 		return -EINVAL;
11437 	}
11438 
11439 	err = check_reference_leak(env, exception_exit);
11440 	if (err) {
11441 		verbose(env, "%s would lead to reference leak\n", prefix);
11442 		return err;
11443 	}
11444 
11445 	if (check_lock && env->cur_state->active_irq_id) {
11446 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
11447 		return -EINVAL;
11448 	}
11449 
11450 	if (check_lock && env->cur_state->active_rcu_locks) {
11451 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
11452 		return -EINVAL;
11453 	}
11454 
11455 	if (check_lock && env->cur_state->active_preempt_locks) {
11456 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
11457 		return -EINVAL;
11458 	}
11459 
11460 	return 0;
11461 }
11462 
11463 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
11464 				   struct bpf_reg_state *regs)
11465 {
11466 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
11467 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
11468 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
11469 	struct bpf_bprintf_data data = {};
11470 	int err, fmt_map_off, num_args;
11471 	u64 fmt_addr;
11472 	char *fmt;
11473 
11474 	/* data must be an array of u64 */
11475 	if (data_len_reg->var_off.value % 8)
11476 		return -EINVAL;
11477 	num_args = data_len_reg->var_off.value / 8;
11478 
11479 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
11480 	 * and map_direct_value_addr is set.
11481 	 */
11482 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
11483 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
11484 						  fmt_map_off);
11485 	if (err) {
11486 		verbose(env, "failed to retrieve map value address\n");
11487 		return -EFAULT;
11488 	}
11489 	fmt = (char *)(long)fmt_addr + fmt_map_off;
11490 
11491 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
11492 	 * can focus on validating the format specifiers.
11493 	 */
11494 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
11495 	if (err < 0)
11496 		verbose(env, "Invalid format string\n");
11497 
11498 	return err;
11499 }
11500 
11501 static int check_get_func_ip(struct bpf_verifier_env *env)
11502 {
11503 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11504 	int func_id = BPF_FUNC_get_func_ip;
11505 
11506 	if (type == BPF_PROG_TYPE_TRACING) {
11507 		if (!bpf_prog_has_trampoline(env->prog)) {
11508 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
11509 				func_id_name(func_id), func_id);
11510 			return -ENOTSUPP;
11511 		}
11512 		return 0;
11513 	} else if (type == BPF_PROG_TYPE_KPROBE) {
11514 		return 0;
11515 	}
11516 
11517 	verbose(env, "func %s#%d not supported for program type %d\n",
11518 		func_id_name(func_id), func_id, type);
11519 	return -ENOTSUPP;
11520 }
11521 
11522 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
11523 {
11524 	return &env->insn_aux_data[env->insn_idx];
11525 }
11526 
11527 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
11528 {
11529 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_4);
11530 	bool reg_is_null = register_is_null(reg);
11531 
11532 	if (reg_is_null)
11533 		mark_chain_precision(env, BPF_REG_4);
11534 
11535 	return reg_is_null;
11536 }
11537 
11538 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
11539 {
11540 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
11541 
11542 	if (!state->initialized) {
11543 		state->initialized = 1;
11544 		state->fit_for_inline = loop_flag_is_zero(env);
11545 		state->callback_subprogno = subprogno;
11546 		return;
11547 	}
11548 
11549 	if (!state->fit_for_inline)
11550 		return;
11551 
11552 	state->fit_for_inline = (loop_flag_is_zero(env) &&
11553 				 state->callback_subprogno == subprogno);
11554 }
11555 
11556 /* Returns whether or not the given map type can potentially elide
11557  * lookup return value nullness check. This is possible if the key
11558  * is statically known.
11559  */
11560 static bool can_elide_value_nullness(enum bpf_map_type type)
11561 {
11562 	switch (type) {
11563 	case BPF_MAP_TYPE_ARRAY:
11564 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11565 		return true;
11566 	default:
11567 		return false;
11568 	}
11569 }
11570 
11571 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
11572 			    const struct bpf_func_proto **ptr)
11573 {
11574 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
11575 		return -ERANGE;
11576 
11577 	if (!env->ops->get_func_proto)
11578 		return -EINVAL;
11579 
11580 	*ptr = env->ops->get_func_proto(func_id, env->prog);
11581 	return *ptr && (*ptr)->func ? 0 : -EINVAL;
11582 }
11583 
11584 /* Check if we're in a sleepable context. */
11585 static inline bool in_sleepable_context(struct bpf_verifier_env *env)
11586 {
11587 	return !env->cur_state->active_rcu_locks &&
11588 	       !env->cur_state->active_preempt_locks &&
11589 	       !env->cur_state->active_locks &&
11590 	       !env->cur_state->active_irq_id &&
11591 	       in_sleepable(env);
11592 }
11593 
11594 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11595 			     int *insn_idx_p)
11596 {
11597 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11598 	bool returns_cpu_specific_alloc_ptr = false;
11599 	const struct bpf_func_proto *fn = NULL;
11600 	enum bpf_return_type ret_type;
11601 	enum bpf_type_flag ret_flag;
11602 	struct bpf_reg_state *regs;
11603 	struct bpf_call_arg_meta meta;
11604 	int insn_idx = *insn_idx_p;
11605 	bool changes_data;
11606 	int i, err, func_id;
11607 
11608 	/* find function prototype */
11609 	func_id = insn->imm;
11610 	err = get_helper_proto(env, insn->imm, &fn);
11611 	if (err == -ERANGE) {
11612 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
11613 		return -EINVAL;
11614 	}
11615 
11616 	if (err) {
11617 		verbose(env, "program of this type cannot use helper %s#%d\n",
11618 			func_id_name(func_id), func_id);
11619 		return err;
11620 	}
11621 
11622 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
11623 	if (!env->prog->gpl_compatible && fn->gpl_only) {
11624 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
11625 		return -EINVAL;
11626 	}
11627 
11628 	if (fn->allowed && !fn->allowed(env->prog)) {
11629 		verbose(env, "helper call is not allowed in probe\n");
11630 		return -EINVAL;
11631 	}
11632 
11633 	if (!in_sleepable(env) && fn->might_sleep) {
11634 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
11635 		return -EINVAL;
11636 	}
11637 
11638 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
11639 	changes_data = bpf_helper_changes_pkt_data(func_id);
11640 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
11641 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
11642 		return -EFAULT;
11643 	}
11644 
11645 	memset(&meta, 0, sizeof(meta));
11646 	meta.pkt_access = fn->pkt_access;
11647 
11648 	err = check_func_proto(fn);
11649 	if (err) {
11650 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
11651 		return err;
11652 	}
11653 
11654 	if (env->cur_state->active_rcu_locks) {
11655 		if (fn->might_sleep) {
11656 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
11657 				func_id_name(func_id), func_id);
11658 			return -EINVAL;
11659 		}
11660 	}
11661 
11662 	if (env->cur_state->active_preempt_locks) {
11663 		if (fn->might_sleep) {
11664 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
11665 				func_id_name(func_id), func_id);
11666 			return -EINVAL;
11667 		}
11668 	}
11669 
11670 	if (env->cur_state->active_irq_id) {
11671 		if (fn->might_sleep) {
11672 			verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n",
11673 				func_id_name(func_id), func_id);
11674 			return -EINVAL;
11675 		}
11676 	}
11677 
11678 	/* Track non-sleepable context for helpers. */
11679 	if (!in_sleepable_context(env))
11680 		env->insn_aux_data[insn_idx].non_sleepable = true;
11681 
11682 	meta.func_id = func_id;
11683 	/* check args */
11684 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
11685 		err = check_func_arg(env, i, &meta, fn, insn_idx);
11686 		if (err)
11687 			return err;
11688 	}
11689 
11690 	err = record_func_map(env, &meta, func_id, insn_idx);
11691 	if (err)
11692 		return err;
11693 
11694 	err = record_func_key(env, &meta, func_id, insn_idx);
11695 	if (err)
11696 		return err;
11697 
11698 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
11699 	 * is inferred from register state.
11700 	 */
11701 	for (i = 0; i < meta.access_size; i++) {
11702 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
11703 				       BPF_WRITE, -1, false, false);
11704 		if (err)
11705 			return err;
11706 	}
11707 
11708 	regs = cur_regs(env);
11709 
11710 	if (meta.release_regno) {
11711 		err = -EINVAL;
11712 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
11713 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
11714 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
11715 			u32 ref_obj_id = meta.ref_obj_id;
11716 			bool in_rcu = in_rcu_cs(env);
11717 			struct bpf_func_state *state;
11718 			struct bpf_reg_state *reg;
11719 
11720 			err = release_reference_nomark(env->cur_state, ref_obj_id);
11721 			if (!err) {
11722 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11723 					if (reg->ref_obj_id == ref_obj_id) {
11724 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11725 							reg->ref_obj_id = 0;
11726 							reg->type &= ~MEM_ALLOC;
11727 							reg->type |= MEM_RCU;
11728 						} else {
11729 							mark_reg_invalid(env, reg);
11730 						}
11731 					}
11732 				}));
11733 			}
11734 		} else if (meta.ref_obj_id) {
11735 			err = release_reference(env, meta.ref_obj_id);
11736 		} else if (register_is_null(&regs[meta.release_regno])) {
11737 			/* meta.ref_obj_id can only be 0 if register that is meant to be
11738 			 * released is NULL, which must be > R0.
11739 			 */
11740 			err = 0;
11741 		}
11742 		if (err) {
11743 			verbose(env, "func %s#%d reference has not been acquired before\n",
11744 				func_id_name(func_id), func_id);
11745 			return err;
11746 		}
11747 	}
11748 
11749 	switch (func_id) {
11750 	case BPF_FUNC_tail_call:
11751 		err = check_resource_leak(env, false, true, "tail_call");
11752 		if (err)
11753 			return err;
11754 		break;
11755 	case BPF_FUNC_get_local_storage:
11756 		/* check that flags argument in get_local_storage(map, flags) is 0,
11757 		 * this is required because get_local_storage() can't return an error.
11758 		 */
11759 		if (!register_is_null(&regs[BPF_REG_2])) {
11760 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
11761 			return -EINVAL;
11762 		}
11763 		break;
11764 	case BPF_FUNC_for_each_map_elem:
11765 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11766 					 set_map_elem_callback_state);
11767 		break;
11768 	case BPF_FUNC_timer_set_callback:
11769 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11770 					 set_timer_callback_state);
11771 		break;
11772 	case BPF_FUNC_find_vma:
11773 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11774 					 set_find_vma_callback_state);
11775 		break;
11776 	case BPF_FUNC_snprintf:
11777 		err = check_bpf_snprintf_call(env, regs);
11778 		break;
11779 	case BPF_FUNC_loop:
11780 		update_loop_inline_state(env, meta.subprogno);
11781 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
11782 		 * is finished, thus mark it precise.
11783 		 */
11784 		err = mark_chain_precision(env, BPF_REG_1);
11785 		if (err)
11786 			return err;
11787 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
11788 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11789 						 set_loop_callback_state);
11790 		} else {
11791 			cur_func(env)->callback_depth = 0;
11792 			if (env->log.level & BPF_LOG_LEVEL2)
11793 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
11794 					env->cur_state->curframe);
11795 		}
11796 		break;
11797 	case BPF_FUNC_dynptr_from_mem:
11798 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
11799 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
11800 				reg_type_str(env, regs[BPF_REG_1].type));
11801 			return -EACCES;
11802 		}
11803 		break;
11804 	case BPF_FUNC_set_retval:
11805 		if (prog_type == BPF_PROG_TYPE_LSM &&
11806 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11807 			if (!env->prog->aux->attach_func_proto->type) {
11808 				/* Make sure programs that attach to void
11809 				 * hooks don't try to modify return value.
11810 				 */
11811 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11812 				return -EINVAL;
11813 			}
11814 		}
11815 		break;
11816 	case BPF_FUNC_dynptr_data:
11817 	{
11818 		struct bpf_reg_state *reg;
11819 		int id, ref_obj_id;
11820 
11821 		reg = get_dynptr_arg_reg(env, fn, regs);
11822 		if (!reg)
11823 			return -EFAULT;
11824 
11825 
11826 		if (meta.dynptr_id) {
11827 			verifier_bug(env, "meta.dynptr_id already set");
11828 			return -EFAULT;
11829 		}
11830 		if (meta.ref_obj_id) {
11831 			verifier_bug(env, "meta.ref_obj_id already set");
11832 			return -EFAULT;
11833 		}
11834 
11835 		id = dynptr_id(env, reg);
11836 		if (id < 0) {
11837 			verifier_bug(env, "failed to obtain dynptr id");
11838 			return id;
11839 		}
11840 
11841 		ref_obj_id = dynptr_ref_obj_id(env, reg);
11842 		if (ref_obj_id < 0) {
11843 			verifier_bug(env, "failed to obtain dynptr ref_obj_id");
11844 			return ref_obj_id;
11845 		}
11846 
11847 		meta.dynptr_id = id;
11848 		meta.ref_obj_id = ref_obj_id;
11849 
11850 		break;
11851 	}
11852 	case BPF_FUNC_dynptr_write:
11853 	{
11854 		enum bpf_dynptr_type dynptr_type;
11855 		struct bpf_reg_state *reg;
11856 
11857 		reg = get_dynptr_arg_reg(env, fn, regs);
11858 		if (!reg)
11859 			return -EFAULT;
11860 
11861 		dynptr_type = dynptr_get_type(env, reg);
11862 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11863 			return -EFAULT;
11864 
11865 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
11866 		    dynptr_type == BPF_DYNPTR_TYPE_SKB_META)
11867 			/* this will trigger clear_all_pkt_pointers(), which will
11868 			 * invalidate all dynptr slices associated with the skb
11869 			 */
11870 			changes_data = true;
11871 
11872 		break;
11873 	}
11874 	case BPF_FUNC_per_cpu_ptr:
11875 	case BPF_FUNC_this_cpu_ptr:
11876 	{
11877 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
11878 		const struct btf_type *type;
11879 
11880 		if (reg->type & MEM_RCU) {
11881 			type = btf_type_by_id(reg->btf, reg->btf_id);
11882 			if (!type || !btf_type_is_struct(type)) {
11883 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
11884 				return -EFAULT;
11885 			}
11886 			returns_cpu_specific_alloc_ptr = true;
11887 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11888 		}
11889 		break;
11890 	}
11891 	case BPF_FUNC_user_ringbuf_drain:
11892 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11893 					 set_user_ringbuf_callback_state);
11894 		break;
11895 	}
11896 
11897 	if (err)
11898 		return err;
11899 
11900 	/* reset caller saved regs */
11901 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11902 		mark_reg_not_init(env, regs, caller_saved[i]);
11903 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11904 	}
11905 
11906 	/* helper call returns 64-bit value. */
11907 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
11908 
11909 	/* update return register (already marked as written above) */
11910 	ret_type = fn->ret_type;
11911 	ret_flag = type_flag(ret_type);
11912 
11913 	switch (base_type(ret_type)) {
11914 	case RET_INTEGER:
11915 		/* sets type to SCALAR_VALUE */
11916 		mark_reg_unknown(env, regs, BPF_REG_0);
11917 		break;
11918 	case RET_VOID:
11919 		regs[BPF_REG_0].type = NOT_INIT;
11920 		break;
11921 	case RET_PTR_TO_MAP_VALUE:
11922 		/* There is no offset yet applied, variable or fixed */
11923 		mark_reg_known_zero(env, regs, BPF_REG_0);
11924 		/* remember map_ptr, so that check_map_access()
11925 		 * can check 'value_size' boundary of memory access
11926 		 * to map element returned from bpf_map_lookup_elem()
11927 		 */
11928 		if (meta.map.ptr == NULL) {
11929 			verifier_bug(env, "unexpected null map_ptr");
11930 			return -EFAULT;
11931 		}
11932 
11933 		if (func_id == BPF_FUNC_map_lookup_elem &&
11934 		    can_elide_value_nullness(meta.map.ptr->map_type) &&
11935 		    meta.const_map_key >= 0 &&
11936 		    meta.const_map_key < meta.map.ptr->max_entries)
11937 			ret_flag &= ~PTR_MAYBE_NULL;
11938 
11939 		regs[BPF_REG_0].map_ptr = meta.map.ptr;
11940 		regs[BPF_REG_0].map_uid = meta.map.uid;
11941 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11942 		if (!type_may_be_null(ret_flag) &&
11943 		    btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
11944 			regs[BPF_REG_0].id = ++env->id_gen;
11945 		}
11946 		break;
11947 	case RET_PTR_TO_SOCKET:
11948 		mark_reg_known_zero(env, regs, BPF_REG_0);
11949 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11950 		break;
11951 	case RET_PTR_TO_SOCK_COMMON:
11952 		mark_reg_known_zero(env, regs, BPF_REG_0);
11953 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11954 		break;
11955 	case RET_PTR_TO_TCP_SOCK:
11956 		mark_reg_known_zero(env, regs, BPF_REG_0);
11957 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11958 		break;
11959 	case RET_PTR_TO_MEM:
11960 		mark_reg_known_zero(env, regs, BPF_REG_0);
11961 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11962 		regs[BPF_REG_0].mem_size = meta.mem_size;
11963 		break;
11964 	case RET_PTR_TO_MEM_OR_BTF_ID:
11965 	{
11966 		const struct btf_type *t;
11967 
11968 		mark_reg_known_zero(env, regs, BPF_REG_0);
11969 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11970 		if (!btf_type_is_struct(t)) {
11971 			u32 tsize;
11972 			const struct btf_type *ret;
11973 			const char *tname;
11974 
11975 			/* resolve the type size of ksym. */
11976 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11977 			if (IS_ERR(ret)) {
11978 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11979 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
11980 					tname, PTR_ERR(ret));
11981 				return -EINVAL;
11982 			}
11983 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11984 			regs[BPF_REG_0].mem_size = tsize;
11985 		} else {
11986 			if (returns_cpu_specific_alloc_ptr) {
11987 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11988 			} else {
11989 				/* MEM_RDONLY may be carried from ret_flag, but it
11990 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11991 				 * it will confuse the check of PTR_TO_BTF_ID in
11992 				 * check_mem_access().
11993 				 */
11994 				ret_flag &= ~MEM_RDONLY;
11995 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11996 			}
11997 
11998 			regs[BPF_REG_0].btf = meta.ret_btf;
11999 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12000 		}
12001 		break;
12002 	}
12003 	case RET_PTR_TO_BTF_ID:
12004 	{
12005 		struct btf *ret_btf;
12006 		int ret_btf_id;
12007 
12008 		mark_reg_known_zero(env, regs, BPF_REG_0);
12009 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
12010 		if (func_id == BPF_FUNC_kptr_xchg) {
12011 			ret_btf = meta.kptr_field->kptr.btf;
12012 			ret_btf_id = meta.kptr_field->kptr.btf_id;
12013 			if (!btf_is_kernel(ret_btf)) {
12014 				regs[BPF_REG_0].type |= MEM_ALLOC;
12015 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
12016 					regs[BPF_REG_0].type |= MEM_PERCPU;
12017 			}
12018 		} else {
12019 			if (fn->ret_btf_id == BPF_PTR_POISON) {
12020 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
12021 					     func_id_name(func_id));
12022 				return -EFAULT;
12023 			}
12024 			ret_btf = btf_vmlinux;
12025 			ret_btf_id = *fn->ret_btf_id;
12026 		}
12027 		if (ret_btf_id == 0) {
12028 			verbose(env, "invalid return type %u of func %s#%d\n",
12029 				base_type(ret_type), func_id_name(func_id),
12030 				func_id);
12031 			return -EINVAL;
12032 		}
12033 		regs[BPF_REG_0].btf = ret_btf;
12034 		regs[BPF_REG_0].btf_id = ret_btf_id;
12035 		break;
12036 	}
12037 	default:
12038 		verbose(env, "unknown return type %u of func %s#%d\n",
12039 			base_type(ret_type), func_id_name(func_id), func_id);
12040 		return -EINVAL;
12041 	}
12042 
12043 	if (type_may_be_null(regs[BPF_REG_0].type))
12044 		regs[BPF_REG_0].id = ++env->id_gen;
12045 
12046 	if (helper_multiple_ref_obj_use(func_id, meta.map.ptr)) {
12047 		verifier_bug(env, "func %s#%d sets ref_obj_id more than once",
12048 			     func_id_name(func_id), func_id);
12049 		return -EFAULT;
12050 	}
12051 
12052 	if (is_dynptr_ref_function(func_id))
12053 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
12054 
12055 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
12056 		/* For release_reference() */
12057 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12058 	} else if (is_acquire_function(func_id, meta.map.ptr)) {
12059 		int id = acquire_reference(env, insn_idx);
12060 
12061 		if (id < 0)
12062 			return id;
12063 		/* For mark_ptr_or_null_reg() */
12064 		regs[BPF_REG_0].id = id;
12065 		/* For release_reference() */
12066 		regs[BPF_REG_0].ref_obj_id = id;
12067 	}
12068 
12069 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
12070 	if (err)
12071 		return err;
12072 
12073 	err = check_map_func_compatibility(env, meta.map.ptr, func_id);
12074 	if (err)
12075 		return err;
12076 
12077 	if ((func_id == BPF_FUNC_get_stack ||
12078 	     func_id == BPF_FUNC_get_task_stack) &&
12079 	    !env->prog->has_callchain_buf) {
12080 		const char *err_str;
12081 
12082 #ifdef CONFIG_PERF_EVENTS
12083 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
12084 		err_str = "cannot get callchain buffer for func %s#%d\n";
12085 #else
12086 		err = -ENOTSUPP;
12087 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
12088 #endif
12089 		if (err) {
12090 			verbose(env, err_str, func_id_name(func_id), func_id);
12091 			return err;
12092 		}
12093 
12094 		env->prog->has_callchain_buf = true;
12095 	}
12096 
12097 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
12098 		env->prog->call_get_stack = true;
12099 
12100 	if (func_id == BPF_FUNC_get_func_ip) {
12101 		if (check_get_func_ip(env))
12102 			return -ENOTSUPP;
12103 		env->prog->call_get_func_ip = true;
12104 	}
12105 
12106 	if (func_id == BPF_FUNC_tail_call) {
12107 		if (env->cur_state->curframe) {
12108 			struct bpf_verifier_state *branch;
12109 
12110 			mark_reg_scratched(env, BPF_REG_0);
12111 			branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
12112 			if (IS_ERR(branch))
12113 				return PTR_ERR(branch);
12114 			clear_all_pkt_pointers(env);
12115 			mark_reg_unknown(env, regs, BPF_REG_0);
12116 			err = prepare_func_exit(env, &env->insn_idx);
12117 			if (err)
12118 				return err;
12119 			env->insn_idx--;
12120 		} else {
12121 			changes_data = false;
12122 		}
12123 	}
12124 
12125 	if (changes_data)
12126 		clear_all_pkt_pointers(env);
12127 	return 0;
12128 }
12129 
12130 /* mark_btf_func_reg_size() is used when the reg size is determined by
12131  * the BTF func_proto's return value size and argument.
12132  */
12133 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
12134 				     u32 regno, size_t reg_size)
12135 {
12136 	struct bpf_reg_state *reg = &regs[regno];
12137 
12138 	if (regno == BPF_REG_0) {
12139 		/* Function return value */
12140 		reg->subreg_def = reg_size == sizeof(u64) ?
12141 			DEF_NOT_SUBREG : env->insn_idx + 1;
12142 	} else if (reg_size == sizeof(u64)) {
12143 		/* Function argument */
12144 		mark_insn_zext(env, reg);
12145 	}
12146 }
12147 
12148 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
12149 				   size_t reg_size)
12150 {
12151 	return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size);
12152 }
12153 
12154 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
12155 {
12156 	return meta->kfunc_flags & KF_ACQUIRE;
12157 }
12158 
12159 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
12160 {
12161 	return meta->kfunc_flags & KF_RELEASE;
12162 }
12163 
12164 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
12165 {
12166 	return meta->kfunc_flags & KF_SLEEPABLE;
12167 }
12168 
12169 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
12170 {
12171 	return meta->kfunc_flags & KF_DESTRUCTIVE;
12172 }
12173 
12174 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
12175 {
12176 	return meta->kfunc_flags & KF_RCU;
12177 }
12178 
12179 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
12180 {
12181 	return meta->kfunc_flags & KF_RCU_PROTECTED;
12182 }
12183 
12184 static bool is_kfunc_arg_mem_size(const struct btf *btf,
12185 				  const struct btf_param *arg,
12186 				  const struct bpf_reg_state *reg)
12187 {
12188 	const struct btf_type *t;
12189 
12190 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12191 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
12192 		return false;
12193 
12194 	return btf_param_match_suffix(btf, arg, "__sz");
12195 }
12196 
12197 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
12198 					const struct btf_param *arg,
12199 					const struct bpf_reg_state *reg)
12200 {
12201 	const struct btf_type *t;
12202 
12203 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12204 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
12205 		return false;
12206 
12207 	return btf_param_match_suffix(btf, arg, "__szk");
12208 }
12209 
12210 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
12211 {
12212 	return btf_param_match_suffix(btf, arg, "__k");
12213 }
12214 
12215 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
12216 {
12217 	return btf_param_match_suffix(btf, arg, "__ign");
12218 }
12219 
12220 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
12221 {
12222 	return btf_param_match_suffix(btf, arg, "__map");
12223 }
12224 
12225 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
12226 {
12227 	return btf_param_match_suffix(btf, arg, "__alloc");
12228 }
12229 
12230 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
12231 {
12232 	return btf_param_match_suffix(btf, arg, "__uninit");
12233 }
12234 
12235 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
12236 {
12237 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
12238 }
12239 
12240 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
12241 {
12242 	return btf_param_match_suffix(btf, arg, "__nullable");
12243 }
12244 
12245 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
12246 {
12247 	return btf_param_match_suffix(btf, arg, "__str");
12248 }
12249 
12250 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
12251 {
12252 	return btf_param_match_suffix(btf, arg, "__irq_flag");
12253 }
12254 
12255 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
12256 					  const struct btf_param *arg,
12257 					  const char *name)
12258 {
12259 	int len, target_len = strlen(name);
12260 	const char *param_name;
12261 
12262 	param_name = btf_name_by_offset(btf, arg->name_off);
12263 	if (str_is_empty(param_name))
12264 		return false;
12265 	len = strlen(param_name);
12266 	if (len != target_len)
12267 		return false;
12268 	if (strcmp(param_name, name))
12269 		return false;
12270 
12271 	return true;
12272 }
12273 
12274 enum {
12275 	KF_ARG_DYNPTR_ID,
12276 	KF_ARG_LIST_HEAD_ID,
12277 	KF_ARG_LIST_NODE_ID,
12278 	KF_ARG_RB_ROOT_ID,
12279 	KF_ARG_RB_NODE_ID,
12280 	KF_ARG_WORKQUEUE_ID,
12281 	KF_ARG_RES_SPIN_LOCK_ID,
12282 	KF_ARG_TASK_WORK_ID,
12283 	KF_ARG_PROG_AUX_ID,
12284 	KF_ARG_TIMER_ID
12285 };
12286 
12287 BTF_ID_LIST(kf_arg_btf_ids)
12288 BTF_ID(struct, bpf_dynptr)
12289 BTF_ID(struct, bpf_list_head)
12290 BTF_ID(struct, bpf_list_node)
12291 BTF_ID(struct, bpf_rb_root)
12292 BTF_ID(struct, bpf_rb_node)
12293 BTF_ID(struct, bpf_wq)
12294 BTF_ID(struct, bpf_res_spin_lock)
12295 BTF_ID(struct, bpf_task_work)
12296 BTF_ID(struct, bpf_prog_aux)
12297 BTF_ID(struct, bpf_timer)
12298 
12299 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
12300 				    const struct btf_param *arg, int type)
12301 {
12302 	const struct btf_type *t;
12303 	u32 res_id;
12304 
12305 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12306 	if (!t)
12307 		return false;
12308 	if (!btf_type_is_ptr(t))
12309 		return false;
12310 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
12311 	if (!t)
12312 		return false;
12313 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
12314 }
12315 
12316 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
12317 {
12318 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
12319 }
12320 
12321 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
12322 {
12323 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
12324 }
12325 
12326 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
12327 {
12328 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
12329 }
12330 
12331 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
12332 {
12333 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
12334 }
12335 
12336 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
12337 {
12338 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
12339 }
12340 
12341 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg)
12342 {
12343 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID);
12344 }
12345 
12346 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
12347 {
12348 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
12349 }
12350 
12351 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
12352 {
12353 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
12354 }
12355 
12356 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
12357 {
12358 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
12359 }
12360 
12361 static bool is_rbtree_node_type(const struct btf_type *t)
12362 {
12363 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
12364 }
12365 
12366 static bool is_list_node_type(const struct btf_type *t)
12367 {
12368 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
12369 }
12370 
12371 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
12372 				  const struct btf_param *arg)
12373 {
12374 	const struct btf_type *t;
12375 
12376 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
12377 	if (!t)
12378 		return false;
12379 
12380 	return true;
12381 }
12382 
12383 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg)
12384 {
12385 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID);
12386 }
12387 
12388 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
12389 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
12390 					const struct btf *btf,
12391 					const struct btf_type *t, int rec)
12392 {
12393 	const struct btf_type *member_type;
12394 	const struct btf_member *member;
12395 	u32 i;
12396 
12397 	if (!btf_type_is_struct(t))
12398 		return false;
12399 
12400 	for_each_member(i, t, member) {
12401 		const struct btf_array *array;
12402 
12403 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
12404 		if (btf_type_is_struct(member_type)) {
12405 			if (rec >= 3) {
12406 				verbose(env, "max struct nesting depth exceeded\n");
12407 				return false;
12408 			}
12409 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
12410 				return false;
12411 			continue;
12412 		}
12413 		if (btf_type_is_array(member_type)) {
12414 			array = btf_array(member_type);
12415 			if (!array->nelems)
12416 				return false;
12417 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
12418 			if (!btf_type_is_scalar(member_type))
12419 				return false;
12420 			continue;
12421 		}
12422 		if (!btf_type_is_scalar(member_type))
12423 			return false;
12424 	}
12425 	return true;
12426 }
12427 
12428 enum kfunc_ptr_arg_type {
12429 	KF_ARG_PTR_TO_CTX,
12430 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
12431 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
12432 	KF_ARG_PTR_TO_DYNPTR,
12433 	KF_ARG_PTR_TO_ITER,
12434 	KF_ARG_PTR_TO_LIST_HEAD,
12435 	KF_ARG_PTR_TO_LIST_NODE,
12436 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
12437 	KF_ARG_PTR_TO_MEM,
12438 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
12439 	KF_ARG_PTR_TO_CALLBACK,
12440 	KF_ARG_PTR_TO_RB_ROOT,
12441 	KF_ARG_PTR_TO_RB_NODE,
12442 	KF_ARG_PTR_TO_NULL,
12443 	KF_ARG_PTR_TO_CONST_STR,
12444 	KF_ARG_PTR_TO_MAP,
12445 	KF_ARG_PTR_TO_TIMER,
12446 	KF_ARG_PTR_TO_WORKQUEUE,
12447 	KF_ARG_PTR_TO_IRQ_FLAG,
12448 	KF_ARG_PTR_TO_RES_SPIN_LOCK,
12449 	KF_ARG_PTR_TO_TASK_WORK,
12450 };
12451 
12452 enum special_kfunc_type {
12453 	KF_bpf_obj_new_impl,
12454 	KF_bpf_obj_drop_impl,
12455 	KF_bpf_refcount_acquire_impl,
12456 	KF_bpf_list_push_front_impl,
12457 	KF_bpf_list_push_back_impl,
12458 	KF_bpf_list_pop_front,
12459 	KF_bpf_list_pop_back,
12460 	KF_bpf_list_front,
12461 	KF_bpf_list_back,
12462 	KF_bpf_cast_to_kern_ctx,
12463 	KF_bpf_rdonly_cast,
12464 	KF_bpf_rcu_read_lock,
12465 	KF_bpf_rcu_read_unlock,
12466 	KF_bpf_rbtree_remove,
12467 	KF_bpf_rbtree_add_impl,
12468 	KF_bpf_rbtree_first,
12469 	KF_bpf_rbtree_root,
12470 	KF_bpf_rbtree_left,
12471 	KF_bpf_rbtree_right,
12472 	KF_bpf_dynptr_from_skb,
12473 	KF_bpf_dynptr_from_xdp,
12474 	KF_bpf_dynptr_from_skb_meta,
12475 	KF_bpf_xdp_pull_data,
12476 	KF_bpf_dynptr_slice,
12477 	KF_bpf_dynptr_slice_rdwr,
12478 	KF_bpf_dynptr_clone,
12479 	KF_bpf_percpu_obj_new_impl,
12480 	KF_bpf_percpu_obj_drop_impl,
12481 	KF_bpf_throw,
12482 	KF_bpf_wq_set_callback,
12483 	KF_bpf_preempt_disable,
12484 	KF_bpf_preempt_enable,
12485 	KF_bpf_iter_css_task_new,
12486 	KF_bpf_session_cookie,
12487 	KF_bpf_get_kmem_cache,
12488 	KF_bpf_local_irq_save,
12489 	KF_bpf_local_irq_restore,
12490 	KF_bpf_iter_num_new,
12491 	KF_bpf_iter_num_next,
12492 	KF_bpf_iter_num_destroy,
12493 	KF_bpf_set_dentry_xattr,
12494 	KF_bpf_remove_dentry_xattr,
12495 	KF_bpf_res_spin_lock,
12496 	KF_bpf_res_spin_unlock,
12497 	KF_bpf_res_spin_lock_irqsave,
12498 	KF_bpf_res_spin_unlock_irqrestore,
12499 	KF_bpf_dynptr_from_file,
12500 	KF_bpf_dynptr_file_discard,
12501 	KF___bpf_trap,
12502 	KF_bpf_task_work_schedule_signal,
12503 	KF_bpf_task_work_schedule_resume,
12504 	KF_bpf_arena_alloc_pages,
12505 	KF_bpf_arena_free_pages,
12506 	KF_bpf_arena_reserve_pages,
12507 	KF_bpf_session_is_return,
12508 	KF_bpf_stream_vprintk,
12509 	KF_bpf_stream_print_stack,
12510 };
12511 
12512 BTF_ID_LIST(special_kfunc_list)
12513 BTF_ID(func, bpf_obj_new_impl)
12514 BTF_ID(func, bpf_obj_drop_impl)
12515 BTF_ID(func, bpf_refcount_acquire_impl)
12516 BTF_ID(func, bpf_list_push_front_impl)
12517 BTF_ID(func, bpf_list_push_back_impl)
12518 BTF_ID(func, bpf_list_pop_front)
12519 BTF_ID(func, bpf_list_pop_back)
12520 BTF_ID(func, bpf_list_front)
12521 BTF_ID(func, bpf_list_back)
12522 BTF_ID(func, bpf_cast_to_kern_ctx)
12523 BTF_ID(func, bpf_rdonly_cast)
12524 BTF_ID(func, bpf_rcu_read_lock)
12525 BTF_ID(func, bpf_rcu_read_unlock)
12526 BTF_ID(func, bpf_rbtree_remove)
12527 BTF_ID(func, bpf_rbtree_add_impl)
12528 BTF_ID(func, bpf_rbtree_first)
12529 BTF_ID(func, bpf_rbtree_root)
12530 BTF_ID(func, bpf_rbtree_left)
12531 BTF_ID(func, bpf_rbtree_right)
12532 #ifdef CONFIG_NET
12533 BTF_ID(func, bpf_dynptr_from_skb)
12534 BTF_ID(func, bpf_dynptr_from_xdp)
12535 BTF_ID(func, bpf_dynptr_from_skb_meta)
12536 BTF_ID(func, bpf_xdp_pull_data)
12537 #else
12538 BTF_ID_UNUSED
12539 BTF_ID_UNUSED
12540 BTF_ID_UNUSED
12541 BTF_ID_UNUSED
12542 #endif
12543 BTF_ID(func, bpf_dynptr_slice)
12544 BTF_ID(func, bpf_dynptr_slice_rdwr)
12545 BTF_ID(func, bpf_dynptr_clone)
12546 BTF_ID(func, bpf_percpu_obj_new_impl)
12547 BTF_ID(func, bpf_percpu_obj_drop_impl)
12548 BTF_ID(func, bpf_throw)
12549 BTF_ID(func, bpf_wq_set_callback)
12550 BTF_ID(func, bpf_preempt_disable)
12551 BTF_ID(func, bpf_preempt_enable)
12552 #ifdef CONFIG_CGROUPS
12553 BTF_ID(func, bpf_iter_css_task_new)
12554 #else
12555 BTF_ID_UNUSED
12556 #endif
12557 #ifdef CONFIG_BPF_EVENTS
12558 BTF_ID(func, bpf_session_cookie)
12559 #else
12560 BTF_ID_UNUSED
12561 #endif
12562 BTF_ID(func, bpf_get_kmem_cache)
12563 BTF_ID(func, bpf_local_irq_save)
12564 BTF_ID(func, bpf_local_irq_restore)
12565 BTF_ID(func, bpf_iter_num_new)
12566 BTF_ID(func, bpf_iter_num_next)
12567 BTF_ID(func, bpf_iter_num_destroy)
12568 #ifdef CONFIG_BPF_LSM
12569 BTF_ID(func, bpf_set_dentry_xattr)
12570 BTF_ID(func, bpf_remove_dentry_xattr)
12571 #else
12572 BTF_ID_UNUSED
12573 BTF_ID_UNUSED
12574 #endif
12575 BTF_ID(func, bpf_res_spin_lock)
12576 BTF_ID(func, bpf_res_spin_unlock)
12577 BTF_ID(func, bpf_res_spin_lock_irqsave)
12578 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
12579 BTF_ID(func, bpf_dynptr_from_file)
12580 BTF_ID(func, bpf_dynptr_file_discard)
12581 BTF_ID(func, __bpf_trap)
12582 BTF_ID(func, bpf_task_work_schedule_signal)
12583 BTF_ID(func, bpf_task_work_schedule_resume)
12584 BTF_ID(func, bpf_arena_alloc_pages)
12585 BTF_ID(func, bpf_arena_free_pages)
12586 BTF_ID(func, bpf_arena_reserve_pages)
12587 BTF_ID(func, bpf_session_is_return)
12588 BTF_ID(func, bpf_stream_vprintk)
12589 BTF_ID(func, bpf_stream_print_stack)
12590 
12591 static bool is_task_work_add_kfunc(u32 func_id)
12592 {
12593 	return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] ||
12594 	       func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume];
12595 }
12596 
12597 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
12598 {
12599 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
12600 	    meta->arg_owning_ref) {
12601 		return false;
12602 	}
12603 
12604 	return meta->kfunc_flags & KF_RET_NULL;
12605 }
12606 
12607 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
12608 {
12609 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
12610 }
12611 
12612 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
12613 {
12614 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
12615 }
12616 
12617 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
12618 {
12619 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
12620 }
12621 
12622 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
12623 {
12624 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
12625 }
12626 
12627 static bool is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta)
12628 {
12629 	return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data];
12630 }
12631 
12632 static enum kfunc_ptr_arg_type
12633 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
12634 		       struct bpf_kfunc_call_arg_meta *meta,
12635 		       const struct btf_type *t, const struct btf_type *ref_t,
12636 		       const char *ref_tname, const struct btf_param *args,
12637 		       int argno, int nargs)
12638 {
12639 	u32 regno = argno + 1;
12640 	struct bpf_reg_state *regs = cur_regs(env);
12641 	struct bpf_reg_state *reg = &regs[regno];
12642 	bool arg_mem_size = false;
12643 
12644 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
12645 	    meta->func_id == special_kfunc_list[KF_bpf_session_is_return] ||
12646 	    meta->func_id == special_kfunc_list[KF_bpf_session_cookie])
12647 		return KF_ARG_PTR_TO_CTX;
12648 
12649 	if (argno + 1 < nargs &&
12650 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
12651 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
12652 		arg_mem_size = true;
12653 
12654 	/* In this function, we verify the kfunc's BTF as per the argument type,
12655 	 * leaving the rest of the verification with respect to the register
12656 	 * type to our caller. When a set of conditions hold in the BTF type of
12657 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
12658 	 */
12659 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
12660 		return KF_ARG_PTR_TO_CTX;
12661 
12662 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg) &&
12663 	    !arg_mem_size)
12664 		return KF_ARG_PTR_TO_NULL;
12665 
12666 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
12667 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
12668 
12669 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
12670 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
12671 
12672 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
12673 		return KF_ARG_PTR_TO_DYNPTR;
12674 
12675 	if (is_kfunc_arg_iter(meta, argno, &args[argno]))
12676 		return KF_ARG_PTR_TO_ITER;
12677 
12678 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
12679 		return KF_ARG_PTR_TO_LIST_HEAD;
12680 
12681 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
12682 		return KF_ARG_PTR_TO_LIST_NODE;
12683 
12684 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
12685 		return KF_ARG_PTR_TO_RB_ROOT;
12686 
12687 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
12688 		return KF_ARG_PTR_TO_RB_NODE;
12689 
12690 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
12691 		return KF_ARG_PTR_TO_CONST_STR;
12692 
12693 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
12694 		return KF_ARG_PTR_TO_MAP;
12695 
12696 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
12697 		return KF_ARG_PTR_TO_WORKQUEUE;
12698 
12699 	if (is_kfunc_arg_timer(meta->btf, &args[argno]))
12700 		return KF_ARG_PTR_TO_TIMER;
12701 
12702 	if (is_kfunc_arg_task_work(meta->btf, &args[argno]))
12703 		return KF_ARG_PTR_TO_TASK_WORK;
12704 
12705 	if (is_kfunc_arg_irq_flag(meta->btf, &args[argno]))
12706 		return KF_ARG_PTR_TO_IRQ_FLAG;
12707 
12708 	if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno]))
12709 		return KF_ARG_PTR_TO_RES_SPIN_LOCK;
12710 
12711 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
12712 		if (!btf_type_is_struct(ref_t)) {
12713 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
12714 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
12715 			return -EINVAL;
12716 		}
12717 		return KF_ARG_PTR_TO_BTF_ID;
12718 	}
12719 
12720 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
12721 		return KF_ARG_PTR_TO_CALLBACK;
12722 
12723 	/* This is the catch all argument type of register types supported by
12724 	 * check_helper_mem_access. However, we only allow when argument type is
12725 	 * pointer to scalar, or struct composed (recursively) of scalars. When
12726 	 * arg_mem_size is true, the pointer can be void *.
12727 	 */
12728 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
12729 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
12730 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
12731 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
12732 		return -EINVAL;
12733 	}
12734 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
12735 }
12736 
12737 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
12738 					struct bpf_reg_state *reg,
12739 					const struct btf_type *ref_t,
12740 					const char *ref_tname, u32 ref_id,
12741 					struct bpf_kfunc_call_arg_meta *meta,
12742 					int argno)
12743 {
12744 	const struct btf_type *reg_ref_t;
12745 	bool strict_type_match = false;
12746 	const struct btf *reg_btf;
12747 	const char *reg_ref_tname;
12748 	bool taking_projection;
12749 	bool struct_same;
12750 	u32 reg_ref_id;
12751 
12752 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
12753 		reg_btf = reg->btf;
12754 		reg_ref_id = reg->btf_id;
12755 	} else {
12756 		reg_btf = btf_vmlinux;
12757 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
12758 	}
12759 
12760 	/* Enforce strict type matching for calls to kfuncs that are acquiring
12761 	 * or releasing a reference, or are no-cast aliases. We do _not_
12762 	 * enforce strict matching for kfuncs by default,
12763 	 * as we want to enable BPF programs to pass types that are bitwise
12764 	 * equivalent without forcing them to explicitly cast with something
12765 	 * like bpf_cast_to_kern_ctx().
12766 	 *
12767 	 * For example, say we had a type like the following:
12768 	 *
12769 	 * struct bpf_cpumask {
12770 	 *	cpumask_t cpumask;
12771 	 *	refcount_t usage;
12772 	 * };
12773 	 *
12774 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
12775 	 * to a struct cpumask, so it would be safe to pass a struct
12776 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
12777 	 *
12778 	 * The philosophy here is similar to how we allow scalars of different
12779 	 * types to be passed to kfuncs as long as the size is the same. The
12780 	 * only difference here is that we're simply allowing
12781 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
12782 	 * resolve types.
12783 	 */
12784 	if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
12785 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
12786 		strict_type_match = true;
12787 
12788 	WARN_ON_ONCE(is_kfunc_release(meta) &&
12789 		     (reg->off || !tnum_is_const(reg->var_off) ||
12790 		      reg->var_off.value));
12791 
12792 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
12793 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
12794 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
12795 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
12796 	 * actually use it -- it must cast to the underlying type. So we allow
12797 	 * caller to pass in the underlying type.
12798 	 */
12799 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
12800 	if (!taking_projection && !struct_same) {
12801 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
12802 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
12803 			btf_type_str(reg_ref_t), reg_ref_tname);
12804 		return -EINVAL;
12805 	}
12806 	return 0;
12807 }
12808 
12809 static int process_irq_flag(struct bpf_verifier_env *env, int regno,
12810 			     struct bpf_kfunc_call_arg_meta *meta)
12811 {
12812 	struct bpf_reg_state *reg = reg_state(env, regno);
12813 	int err, kfunc_class = IRQ_NATIVE_KFUNC;
12814 	bool irq_save;
12815 
12816 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
12817 	    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
12818 		irq_save = true;
12819 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12820 			kfunc_class = IRQ_LOCK_KFUNC;
12821 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
12822 		   meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
12823 		irq_save = false;
12824 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12825 			kfunc_class = IRQ_LOCK_KFUNC;
12826 	} else {
12827 		verifier_bug(env, "unknown irq flags kfunc");
12828 		return -EFAULT;
12829 	}
12830 
12831 	if (irq_save) {
12832 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
12833 			verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1);
12834 			return -EINVAL;
12835 		}
12836 
12837 		err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false);
12838 		if (err)
12839 			return err;
12840 
12841 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
12842 		if (err)
12843 			return err;
12844 	} else {
12845 		err = is_irq_flag_reg_valid_init(env, reg);
12846 		if (err) {
12847 			verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1);
12848 			return err;
12849 		}
12850 
12851 		err = mark_irq_flag_read(env, reg);
12852 		if (err)
12853 			return err;
12854 
12855 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
12856 		if (err)
12857 			return err;
12858 	}
12859 	return 0;
12860 }
12861 
12862 
12863 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12864 {
12865 	struct btf_record *rec = reg_btf_record(reg);
12866 
12867 	if (!env->cur_state->active_locks) {
12868 		verifier_bug(env, "%s w/o active lock", __func__);
12869 		return -EFAULT;
12870 	}
12871 
12872 	if (type_flag(reg->type) & NON_OWN_REF) {
12873 		verifier_bug(env, "NON_OWN_REF already set");
12874 		return -EFAULT;
12875 	}
12876 
12877 	reg->type |= NON_OWN_REF;
12878 	if (rec->refcount_off >= 0)
12879 		reg->type |= MEM_RCU;
12880 
12881 	return 0;
12882 }
12883 
12884 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
12885 {
12886 	struct bpf_verifier_state *state = env->cur_state;
12887 	struct bpf_func_state *unused;
12888 	struct bpf_reg_state *reg;
12889 	int i;
12890 
12891 	if (!ref_obj_id) {
12892 		verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion");
12893 		return -EFAULT;
12894 	}
12895 
12896 	for (i = 0; i < state->acquired_refs; i++) {
12897 		if (state->refs[i].id != ref_obj_id)
12898 			continue;
12899 
12900 		/* Clear ref_obj_id here so release_reference doesn't clobber
12901 		 * the whole reg
12902 		 */
12903 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12904 			if (reg->ref_obj_id == ref_obj_id) {
12905 				reg->ref_obj_id = 0;
12906 				ref_set_non_owning(env, reg);
12907 			}
12908 		}));
12909 		return 0;
12910 	}
12911 
12912 	verifier_bug(env, "ref state missing for ref_obj_id");
12913 	return -EFAULT;
12914 }
12915 
12916 /* Implementation details:
12917  *
12918  * Each register points to some region of memory, which we define as an
12919  * allocation. Each allocation may embed a bpf_spin_lock which protects any
12920  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12921  * allocation. The lock and the data it protects are colocated in the same
12922  * memory region.
12923  *
12924  * Hence, everytime a register holds a pointer value pointing to such
12925  * allocation, the verifier preserves a unique reg->id for it.
12926  *
12927  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12928  * bpf_spin_lock is called.
12929  *
12930  * To enable this, lock state in the verifier captures two values:
12931  *	active_lock.ptr = Register's type specific pointer
12932  *	active_lock.id  = A unique ID for each register pointer value
12933  *
12934  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12935  * supported register types.
12936  *
12937  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12938  * allocated objects is the reg->btf pointer.
12939  *
12940  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12941  * can establish the provenance of the map value statically for each distinct
12942  * lookup into such maps. They always contain a single map value hence unique
12943  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12944  *
12945  * So, in case of global variables, they use array maps with max_entries = 1,
12946  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12947  * into the same map value as max_entries is 1, as described above).
12948  *
12949  * In case of inner map lookups, the inner map pointer has same map_ptr as the
12950  * outer map pointer (in verifier context), but each lookup into an inner map
12951  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12952  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12953  * will get different reg->id assigned to each lookup, hence different
12954  * active_lock.id.
12955  *
12956  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12957  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12958  * returned from bpf_obj_new. Each allocation receives a new reg->id.
12959  */
12960 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12961 {
12962 	struct bpf_reference_state *s;
12963 	void *ptr;
12964 	u32 id;
12965 
12966 	switch ((int)reg->type) {
12967 	case PTR_TO_MAP_VALUE:
12968 		ptr = reg->map_ptr;
12969 		break;
12970 	case PTR_TO_BTF_ID | MEM_ALLOC:
12971 		ptr = reg->btf;
12972 		break;
12973 	default:
12974 		verifier_bug(env, "unknown reg type for lock check");
12975 		return -EFAULT;
12976 	}
12977 	id = reg->id;
12978 
12979 	if (!env->cur_state->active_locks)
12980 		return -EINVAL;
12981 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
12982 	if (!s) {
12983 		verbose(env, "held lock and object are not in the same allocation\n");
12984 		return -EINVAL;
12985 	}
12986 	return 0;
12987 }
12988 
12989 static bool is_bpf_list_api_kfunc(u32 btf_id)
12990 {
12991 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12992 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12993 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12994 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
12995 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
12996 	       btf_id == special_kfunc_list[KF_bpf_list_back];
12997 }
12998 
12999 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
13000 {
13001 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
13002 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
13003 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
13004 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
13005 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
13006 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
13007 }
13008 
13009 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
13010 {
13011 	return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
13012 	       btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
13013 	       btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
13014 }
13015 
13016 static bool is_bpf_graph_api_kfunc(u32 btf_id)
13017 {
13018 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
13019 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
13020 }
13021 
13022 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
13023 {
13024 	return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13025 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
13026 	       btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
13027 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
13028 }
13029 
13030 static bool is_bpf_arena_kfunc(u32 btf_id)
13031 {
13032 	return btf_id == special_kfunc_list[KF_bpf_arena_alloc_pages] ||
13033 	       btf_id == special_kfunc_list[KF_bpf_arena_free_pages] ||
13034 	       btf_id == special_kfunc_list[KF_bpf_arena_reserve_pages];
13035 }
13036 
13037 static bool is_bpf_stream_kfunc(u32 btf_id)
13038 {
13039 	return btf_id == special_kfunc_list[KF_bpf_stream_vprintk] ||
13040 	       btf_id == special_kfunc_list[KF_bpf_stream_print_stack];
13041 }
13042 
13043 static bool kfunc_spin_allowed(u32 btf_id)
13044 {
13045 	return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) ||
13046 	       is_bpf_res_spin_lock_kfunc(btf_id) || is_bpf_arena_kfunc(btf_id) ||
13047 	       is_bpf_stream_kfunc(btf_id);
13048 }
13049 
13050 static bool is_sync_callback_calling_kfunc(u32 btf_id)
13051 {
13052 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
13053 }
13054 
13055 static bool is_async_callback_calling_kfunc(u32 btf_id)
13056 {
13057 	return is_bpf_wq_set_callback_kfunc(btf_id) ||
13058 	       is_task_work_add_kfunc(btf_id);
13059 }
13060 
13061 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
13062 {
13063 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
13064 	       insn->imm == special_kfunc_list[KF_bpf_throw];
13065 }
13066 
13067 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id)
13068 {
13069 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback];
13070 }
13071 
13072 static bool is_callback_calling_kfunc(u32 btf_id)
13073 {
13074 	return is_sync_callback_calling_kfunc(btf_id) ||
13075 	       is_async_callback_calling_kfunc(btf_id);
13076 }
13077 
13078 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
13079 {
13080 	return is_bpf_rbtree_api_kfunc(btf_id);
13081 }
13082 
13083 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
13084 					  enum btf_field_type head_field_type,
13085 					  u32 kfunc_btf_id)
13086 {
13087 	bool ret;
13088 
13089 	switch (head_field_type) {
13090 	case BPF_LIST_HEAD:
13091 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
13092 		break;
13093 	case BPF_RB_ROOT:
13094 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
13095 		break;
13096 	default:
13097 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
13098 			btf_field_type_name(head_field_type));
13099 		return false;
13100 	}
13101 
13102 	if (!ret)
13103 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
13104 			btf_field_type_name(head_field_type));
13105 	return ret;
13106 }
13107 
13108 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
13109 					  enum btf_field_type node_field_type,
13110 					  u32 kfunc_btf_id)
13111 {
13112 	bool ret;
13113 
13114 	switch (node_field_type) {
13115 	case BPF_LIST_NODE:
13116 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
13117 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
13118 		break;
13119 	case BPF_RB_NODE:
13120 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
13121 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
13122 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
13123 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
13124 		break;
13125 	default:
13126 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
13127 			btf_field_type_name(node_field_type));
13128 		return false;
13129 	}
13130 
13131 	if (!ret)
13132 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
13133 			btf_field_type_name(node_field_type));
13134 	return ret;
13135 }
13136 
13137 static int
13138 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
13139 				   struct bpf_reg_state *reg, u32 regno,
13140 				   struct bpf_kfunc_call_arg_meta *meta,
13141 				   enum btf_field_type head_field_type,
13142 				   struct btf_field **head_field)
13143 {
13144 	const char *head_type_name;
13145 	struct btf_field *field;
13146 	struct btf_record *rec;
13147 	u32 head_off;
13148 
13149 	if (meta->btf != btf_vmlinux) {
13150 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
13151 		return -EFAULT;
13152 	}
13153 
13154 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
13155 		return -EFAULT;
13156 
13157 	head_type_name = btf_field_type_name(head_field_type);
13158 	if (!tnum_is_const(reg->var_off)) {
13159 		verbose(env,
13160 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
13161 			regno, head_type_name);
13162 		return -EINVAL;
13163 	}
13164 
13165 	rec = reg_btf_record(reg);
13166 	head_off = reg->off + reg->var_off.value;
13167 	field = btf_record_find(rec, head_off, head_field_type);
13168 	if (!field) {
13169 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
13170 		return -EINVAL;
13171 	}
13172 
13173 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
13174 	if (check_reg_allocation_locked(env, reg)) {
13175 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
13176 			rec->spin_lock_off, head_type_name);
13177 		return -EINVAL;
13178 	}
13179 
13180 	if (*head_field) {
13181 		verifier_bug(env, "repeating %s arg", head_type_name);
13182 		return -EFAULT;
13183 	}
13184 	*head_field = field;
13185 	return 0;
13186 }
13187 
13188 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
13189 					   struct bpf_reg_state *reg, u32 regno,
13190 					   struct bpf_kfunc_call_arg_meta *meta)
13191 {
13192 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
13193 							  &meta->arg_list_head.field);
13194 }
13195 
13196 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
13197 					     struct bpf_reg_state *reg, u32 regno,
13198 					     struct bpf_kfunc_call_arg_meta *meta)
13199 {
13200 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
13201 							  &meta->arg_rbtree_root.field);
13202 }
13203 
13204 static int
13205 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
13206 				   struct bpf_reg_state *reg, u32 regno,
13207 				   struct bpf_kfunc_call_arg_meta *meta,
13208 				   enum btf_field_type head_field_type,
13209 				   enum btf_field_type node_field_type,
13210 				   struct btf_field **node_field)
13211 {
13212 	const char *node_type_name;
13213 	const struct btf_type *et, *t;
13214 	struct btf_field *field;
13215 	u32 node_off;
13216 
13217 	if (meta->btf != btf_vmlinux) {
13218 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
13219 		return -EFAULT;
13220 	}
13221 
13222 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
13223 		return -EFAULT;
13224 
13225 	node_type_name = btf_field_type_name(node_field_type);
13226 	if (!tnum_is_const(reg->var_off)) {
13227 		verbose(env,
13228 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
13229 			regno, node_type_name);
13230 		return -EINVAL;
13231 	}
13232 
13233 	node_off = reg->off + reg->var_off.value;
13234 	field = reg_find_field_offset(reg, node_off, node_field_type);
13235 	if (!field) {
13236 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
13237 		return -EINVAL;
13238 	}
13239 
13240 	field = *node_field;
13241 
13242 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
13243 	t = btf_type_by_id(reg->btf, reg->btf_id);
13244 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
13245 				  field->graph_root.value_btf_id, true)) {
13246 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
13247 			"in struct %s, but arg is at offset=%d in struct %s\n",
13248 			btf_field_type_name(head_field_type),
13249 			btf_field_type_name(node_field_type),
13250 			field->graph_root.node_offset,
13251 			btf_name_by_offset(field->graph_root.btf, et->name_off),
13252 			node_off, btf_name_by_offset(reg->btf, t->name_off));
13253 		return -EINVAL;
13254 	}
13255 	meta->arg_btf = reg->btf;
13256 	meta->arg_btf_id = reg->btf_id;
13257 
13258 	if (node_off != field->graph_root.node_offset) {
13259 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
13260 			node_off, btf_field_type_name(node_field_type),
13261 			field->graph_root.node_offset,
13262 			btf_name_by_offset(field->graph_root.btf, et->name_off));
13263 		return -EINVAL;
13264 	}
13265 
13266 	return 0;
13267 }
13268 
13269 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
13270 					   struct bpf_reg_state *reg, u32 regno,
13271 					   struct bpf_kfunc_call_arg_meta *meta)
13272 {
13273 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13274 						  BPF_LIST_HEAD, BPF_LIST_NODE,
13275 						  &meta->arg_list_head.field);
13276 }
13277 
13278 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
13279 					     struct bpf_reg_state *reg, u32 regno,
13280 					     struct bpf_kfunc_call_arg_meta *meta)
13281 {
13282 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13283 						  BPF_RB_ROOT, BPF_RB_NODE,
13284 						  &meta->arg_rbtree_root.field);
13285 }
13286 
13287 /*
13288  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
13289  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
13290  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
13291  * them can only be attached to some specific hook points.
13292  */
13293 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
13294 {
13295 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13296 
13297 	switch (prog_type) {
13298 	case BPF_PROG_TYPE_LSM:
13299 		return true;
13300 	case BPF_PROG_TYPE_TRACING:
13301 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
13302 			return true;
13303 		fallthrough;
13304 	default:
13305 		return in_sleepable(env);
13306 	}
13307 }
13308 
13309 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13310 			    int insn_idx)
13311 {
13312 	const char *func_name = meta->func_name, *ref_tname;
13313 	const struct btf *btf = meta->btf;
13314 	const struct btf_param *args;
13315 	struct btf_record *rec;
13316 	u32 i, nargs;
13317 	int ret;
13318 
13319 	args = (const struct btf_param *)(meta->func_proto + 1);
13320 	nargs = btf_type_vlen(meta->func_proto);
13321 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
13322 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
13323 			MAX_BPF_FUNC_REG_ARGS);
13324 		return -EINVAL;
13325 	}
13326 
13327 	/* Check that BTF function arguments match actual types that the
13328 	 * verifier sees.
13329 	 */
13330 	for (i = 0; i < nargs; i++) {
13331 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
13332 		const struct btf_type *t, *ref_t, *resolve_ret;
13333 		enum bpf_arg_type arg_type = ARG_DONTCARE;
13334 		u32 regno = i + 1, ref_id, type_size;
13335 		bool is_ret_buf_sz = false;
13336 		int kf_arg_type;
13337 
13338 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
13339 
13340 		if (is_kfunc_arg_ignore(btf, &args[i]))
13341 			continue;
13342 
13343 		if (is_kfunc_arg_prog_aux(btf, &args[i])) {
13344 			/* Reject repeated use bpf_prog_aux */
13345 			if (meta->arg_prog) {
13346 				verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc");
13347 				return -EFAULT;
13348 			}
13349 			meta->arg_prog = true;
13350 			cur_aux(env)->arg_prog = regno;
13351 			continue;
13352 		}
13353 
13354 		if (btf_type_is_scalar(t)) {
13355 			if (reg->type != SCALAR_VALUE) {
13356 				verbose(env, "R%d is not a scalar\n", regno);
13357 				return -EINVAL;
13358 			}
13359 
13360 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
13361 				if (meta->arg_constant.found) {
13362 					verifier_bug(env, "only one constant argument permitted");
13363 					return -EFAULT;
13364 				}
13365 				if (!tnum_is_const(reg->var_off)) {
13366 					verbose(env, "R%d must be a known constant\n", regno);
13367 					return -EINVAL;
13368 				}
13369 				ret = mark_chain_precision(env, regno);
13370 				if (ret < 0)
13371 					return ret;
13372 				meta->arg_constant.found = true;
13373 				meta->arg_constant.value = reg->var_off.value;
13374 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
13375 				meta->r0_rdonly = true;
13376 				is_ret_buf_sz = true;
13377 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
13378 				is_ret_buf_sz = true;
13379 			}
13380 
13381 			if (is_ret_buf_sz) {
13382 				if (meta->r0_size) {
13383 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
13384 					return -EINVAL;
13385 				}
13386 
13387 				if (!tnum_is_const(reg->var_off)) {
13388 					verbose(env, "R%d is not a const\n", regno);
13389 					return -EINVAL;
13390 				}
13391 
13392 				meta->r0_size = reg->var_off.value;
13393 				ret = mark_chain_precision(env, regno);
13394 				if (ret)
13395 					return ret;
13396 			}
13397 			continue;
13398 		}
13399 
13400 		if (!btf_type_is_ptr(t)) {
13401 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
13402 			return -EINVAL;
13403 		}
13404 
13405 		if ((register_is_null(reg) || type_may_be_null(reg->type)) &&
13406 		    !is_kfunc_arg_nullable(meta->btf, &args[i])) {
13407 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
13408 			return -EACCES;
13409 		}
13410 
13411 		if (reg->ref_obj_id) {
13412 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
13413 				verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u",
13414 					     regno, reg->ref_obj_id,
13415 					     meta->ref_obj_id);
13416 				return -EFAULT;
13417 			}
13418 			meta->ref_obj_id = reg->ref_obj_id;
13419 			if (is_kfunc_release(meta))
13420 				meta->release_regno = regno;
13421 		}
13422 
13423 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
13424 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13425 
13426 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
13427 		if (kf_arg_type < 0)
13428 			return kf_arg_type;
13429 
13430 		switch (kf_arg_type) {
13431 		case KF_ARG_PTR_TO_NULL:
13432 			continue;
13433 		case KF_ARG_PTR_TO_MAP:
13434 			if (!reg->map_ptr) {
13435 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
13436 				return -EINVAL;
13437 			}
13438 			if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 ||
13439 					      reg->map_ptr->record->task_work_off >= 0)) {
13440 				/* Use map_uid (which is unique id of inner map) to reject:
13441 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
13442 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
13443 				 * if (inner_map1 && inner_map2) {
13444 				 *     wq = bpf_map_lookup_elem(inner_map1);
13445 				 *     if (wq)
13446 				 *         // mismatch would have been allowed
13447 				 *         bpf_wq_init(wq, inner_map2);
13448 				 * }
13449 				 *
13450 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
13451 				 */
13452 				if (meta->map.ptr != reg->map_ptr ||
13453 				    meta->map.uid != reg->map_uid) {
13454 					if (reg->map_ptr->record->task_work_off >= 0) {
13455 						verbose(env,
13456 							"bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n",
13457 							meta->map.uid, reg->map_uid);
13458 						return -EINVAL;
13459 					}
13460 					verbose(env,
13461 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
13462 						meta->map.uid, reg->map_uid);
13463 					return -EINVAL;
13464 				}
13465 			}
13466 			meta->map.ptr = reg->map_ptr;
13467 			meta->map.uid = reg->map_uid;
13468 			fallthrough;
13469 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13470 		case KF_ARG_PTR_TO_BTF_ID:
13471 			if (!is_trusted_reg(reg)) {
13472 				if (!is_kfunc_rcu(meta)) {
13473 					verbose(env, "R%d must be referenced or trusted\n", regno);
13474 					return -EINVAL;
13475 				}
13476 				if (!is_rcu_reg(reg)) {
13477 					verbose(env, "R%d must be a rcu pointer\n", regno);
13478 					return -EINVAL;
13479 				}
13480 			}
13481 			fallthrough;
13482 		case KF_ARG_PTR_TO_CTX:
13483 		case KF_ARG_PTR_TO_DYNPTR:
13484 		case KF_ARG_PTR_TO_ITER:
13485 		case KF_ARG_PTR_TO_LIST_HEAD:
13486 		case KF_ARG_PTR_TO_LIST_NODE:
13487 		case KF_ARG_PTR_TO_RB_ROOT:
13488 		case KF_ARG_PTR_TO_RB_NODE:
13489 		case KF_ARG_PTR_TO_MEM:
13490 		case KF_ARG_PTR_TO_MEM_SIZE:
13491 		case KF_ARG_PTR_TO_CALLBACK:
13492 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13493 		case KF_ARG_PTR_TO_CONST_STR:
13494 		case KF_ARG_PTR_TO_WORKQUEUE:
13495 		case KF_ARG_PTR_TO_TIMER:
13496 		case KF_ARG_PTR_TO_TASK_WORK:
13497 		case KF_ARG_PTR_TO_IRQ_FLAG:
13498 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13499 			break;
13500 		default:
13501 			verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type);
13502 			return -EFAULT;
13503 		}
13504 
13505 		if (is_kfunc_release(meta) && reg->ref_obj_id)
13506 			arg_type |= OBJ_RELEASE;
13507 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
13508 		if (ret < 0)
13509 			return ret;
13510 
13511 		switch (kf_arg_type) {
13512 		case KF_ARG_PTR_TO_CTX:
13513 			if (reg->type != PTR_TO_CTX) {
13514 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
13515 					i, reg_type_str(env, reg->type));
13516 				return -EINVAL;
13517 			}
13518 
13519 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13520 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
13521 				if (ret < 0)
13522 					return -EINVAL;
13523 				meta->ret_btf_id  = ret;
13524 			}
13525 			break;
13526 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13527 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
13528 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
13529 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
13530 					return -EINVAL;
13531 				}
13532 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
13533 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13534 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
13535 					return -EINVAL;
13536 				}
13537 			} else {
13538 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13539 				return -EINVAL;
13540 			}
13541 			if (!reg->ref_obj_id) {
13542 				verbose(env, "allocated object must be referenced\n");
13543 				return -EINVAL;
13544 			}
13545 			if (meta->btf == btf_vmlinux) {
13546 				meta->arg_btf = reg->btf;
13547 				meta->arg_btf_id = reg->btf_id;
13548 			}
13549 			break;
13550 		case KF_ARG_PTR_TO_DYNPTR:
13551 		{
13552 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
13553 			int clone_ref_obj_id = 0;
13554 
13555 			if (reg->type == CONST_PTR_TO_DYNPTR)
13556 				dynptr_arg_type |= MEM_RDONLY;
13557 
13558 			if (is_kfunc_arg_uninit(btf, &args[i]))
13559 				dynptr_arg_type |= MEM_UNINIT;
13560 
13561 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
13562 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
13563 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
13564 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
13565 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
13566 				dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
13567 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
13568 				dynptr_arg_type |= DYNPTR_TYPE_FILE;
13569 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) {
13570 				dynptr_arg_type |= DYNPTR_TYPE_FILE;
13571 				meta->release_regno = regno;
13572 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
13573 				   (dynptr_arg_type & MEM_UNINIT)) {
13574 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
13575 
13576 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
13577 					verifier_bug(env, "no dynptr type for parent of clone");
13578 					return -EFAULT;
13579 				}
13580 
13581 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
13582 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
13583 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
13584 					verifier_bug(env, "missing ref obj id for parent of clone");
13585 					return -EFAULT;
13586 				}
13587 			}
13588 
13589 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
13590 			if (ret < 0)
13591 				return ret;
13592 
13593 			if (!(dynptr_arg_type & MEM_UNINIT)) {
13594 				int id = dynptr_id(env, reg);
13595 
13596 				if (id < 0) {
13597 					verifier_bug(env, "failed to obtain dynptr id");
13598 					return id;
13599 				}
13600 				meta->initialized_dynptr.id = id;
13601 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
13602 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
13603 			}
13604 
13605 			break;
13606 		}
13607 		case KF_ARG_PTR_TO_ITER:
13608 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
13609 				if (!check_css_task_iter_allowlist(env)) {
13610 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
13611 					return -EINVAL;
13612 				}
13613 			}
13614 			ret = process_iter_arg(env, regno, insn_idx, meta);
13615 			if (ret < 0)
13616 				return ret;
13617 			break;
13618 		case KF_ARG_PTR_TO_LIST_HEAD:
13619 			if (reg->type != PTR_TO_MAP_VALUE &&
13620 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13621 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13622 				return -EINVAL;
13623 			}
13624 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13625 				verbose(env, "allocated object must be referenced\n");
13626 				return -EINVAL;
13627 			}
13628 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
13629 			if (ret < 0)
13630 				return ret;
13631 			break;
13632 		case KF_ARG_PTR_TO_RB_ROOT:
13633 			if (reg->type != PTR_TO_MAP_VALUE &&
13634 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13635 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13636 				return -EINVAL;
13637 			}
13638 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13639 				verbose(env, "allocated object must be referenced\n");
13640 				return -EINVAL;
13641 			}
13642 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
13643 			if (ret < 0)
13644 				return ret;
13645 			break;
13646 		case KF_ARG_PTR_TO_LIST_NODE:
13647 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13648 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13649 				return -EINVAL;
13650 			}
13651 			if (!reg->ref_obj_id) {
13652 				verbose(env, "allocated object must be referenced\n");
13653 				return -EINVAL;
13654 			}
13655 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
13656 			if (ret < 0)
13657 				return ret;
13658 			break;
13659 		case KF_ARG_PTR_TO_RB_NODE:
13660 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13661 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13662 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
13663 					return -EINVAL;
13664 				}
13665 				if (!reg->ref_obj_id) {
13666 					verbose(env, "allocated object must be referenced\n");
13667 					return -EINVAL;
13668 				}
13669 			} else {
13670 				if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) {
13671 					verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
13672 					return -EINVAL;
13673 				}
13674 				if (in_rbtree_lock_required_cb(env)) {
13675 					verbose(env, "%s not allowed in rbtree cb\n", func_name);
13676 					return -EINVAL;
13677 				}
13678 			}
13679 
13680 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
13681 			if (ret < 0)
13682 				return ret;
13683 			break;
13684 		case KF_ARG_PTR_TO_MAP:
13685 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
13686 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
13687 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
13688 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13689 			fallthrough;
13690 		case KF_ARG_PTR_TO_BTF_ID:
13691 			/* Only base_type is checked, further checks are done here */
13692 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
13693 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
13694 			    !reg2btf_ids[base_type(reg->type)]) {
13695 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
13696 				verbose(env, "expected %s or socket\n",
13697 					reg_type_str(env, base_type(reg->type) |
13698 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
13699 				return -EINVAL;
13700 			}
13701 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
13702 			if (ret < 0)
13703 				return ret;
13704 			break;
13705 		case KF_ARG_PTR_TO_MEM:
13706 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
13707 			if (IS_ERR(resolve_ret)) {
13708 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
13709 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
13710 				return -EINVAL;
13711 			}
13712 			ret = check_mem_reg(env, reg, regno, type_size);
13713 			if (ret < 0)
13714 				return ret;
13715 			break;
13716 		case KF_ARG_PTR_TO_MEM_SIZE:
13717 		{
13718 			struct bpf_reg_state *buff_reg = &regs[regno];
13719 			const struct btf_param *buff_arg = &args[i];
13720 			struct bpf_reg_state *size_reg = &regs[regno + 1];
13721 			const struct btf_param *size_arg = &args[i + 1];
13722 
13723 			if (!register_is_null(buff_reg) || !is_kfunc_arg_nullable(meta->btf, buff_arg)) {
13724 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
13725 				if (ret < 0) {
13726 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
13727 					return ret;
13728 				}
13729 			}
13730 
13731 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
13732 				if (meta->arg_constant.found) {
13733 					verifier_bug(env, "only one constant argument permitted");
13734 					return -EFAULT;
13735 				}
13736 				if (!tnum_is_const(size_reg->var_off)) {
13737 					verbose(env, "R%d must be a known constant\n", regno + 1);
13738 					return -EINVAL;
13739 				}
13740 				meta->arg_constant.found = true;
13741 				meta->arg_constant.value = size_reg->var_off.value;
13742 			}
13743 
13744 			/* Skip next '__sz' or '__szk' argument */
13745 			i++;
13746 			break;
13747 		}
13748 		case KF_ARG_PTR_TO_CALLBACK:
13749 			if (reg->type != PTR_TO_FUNC) {
13750 				verbose(env, "arg%d expected pointer to func\n", i);
13751 				return -EINVAL;
13752 			}
13753 			meta->subprogno = reg->subprogno;
13754 			break;
13755 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13756 			if (!type_is_ptr_alloc_obj(reg->type)) {
13757 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
13758 				return -EINVAL;
13759 			}
13760 			if (!type_is_non_owning_ref(reg->type))
13761 				meta->arg_owning_ref = true;
13762 
13763 			rec = reg_btf_record(reg);
13764 			if (!rec) {
13765 				verifier_bug(env, "Couldn't find btf_record");
13766 				return -EFAULT;
13767 			}
13768 
13769 			if (rec->refcount_off < 0) {
13770 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
13771 				return -EINVAL;
13772 			}
13773 
13774 			meta->arg_btf = reg->btf;
13775 			meta->arg_btf_id = reg->btf_id;
13776 			break;
13777 		case KF_ARG_PTR_TO_CONST_STR:
13778 			if (reg->type != PTR_TO_MAP_VALUE) {
13779 				verbose(env, "arg#%d doesn't point to a const string\n", i);
13780 				return -EINVAL;
13781 			}
13782 			ret = check_reg_const_str(env, reg, regno);
13783 			if (ret)
13784 				return ret;
13785 			break;
13786 		case KF_ARG_PTR_TO_WORKQUEUE:
13787 			if (reg->type != PTR_TO_MAP_VALUE) {
13788 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13789 				return -EINVAL;
13790 			}
13791 			ret = check_map_field_pointer(env, regno, BPF_WORKQUEUE, &meta->map);
13792 			if (ret < 0)
13793 				return ret;
13794 			break;
13795 		case KF_ARG_PTR_TO_TIMER:
13796 			if (reg->type != PTR_TO_MAP_VALUE) {
13797 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13798 				return -EINVAL;
13799 			}
13800 			ret = process_timer_kfunc(env, regno, meta);
13801 			if (ret < 0)
13802 				return ret;
13803 			break;
13804 		case KF_ARG_PTR_TO_TASK_WORK:
13805 			if (reg->type != PTR_TO_MAP_VALUE) {
13806 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13807 				return -EINVAL;
13808 			}
13809 			ret = check_map_field_pointer(env, regno, BPF_TASK_WORK, &meta->map);
13810 			if (ret < 0)
13811 				return ret;
13812 			break;
13813 		case KF_ARG_PTR_TO_IRQ_FLAG:
13814 			if (reg->type != PTR_TO_STACK) {
13815 				verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i);
13816 				return -EINVAL;
13817 			}
13818 			ret = process_irq_flag(env, regno, meta);
13819 			if (ret < 0)
13820 				return ret;
13821 			break;
13822 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13823 		{
13824 			int flags = PROCESS_RES_LOCK;
13825 
13826 			if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13827 				verbose(env, "arg#%d doesn't point to map value or allocated object\n", i);
13828 				return -EINVAL;
13829 			}
13830 
13831 			if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
13832 				return -EFAULT;
13833 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13834 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
13835 				flags |= PROCESS_SPIN_LOCK;
13836 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
13837 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
13838 				flags |= PROCESS_LOCK_IRQ;
13839 			ret = process_spin_lock(env, regno, flags);
13840 			if (ret < 0)
13841 				return ret;
13842 			break;
13843 		}
13844 		}
13845 	}
13846 
13847 	if (is_kfunc_release(meta) && !meta->release_regno) {
13848 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
13849 			func_name);
13850 		return -EINVAL;
13851 	}
13852 
13853 	return 0;
13854 }
13855 
13856 static int fetch_kfunc_arg_meta(struct bpf_verifier_env *env,
13857 				s32 func_id,
13858 				s16 offset,
13859 				struct bpf_kfunc_call_arg_meta *meta)
13860 {
13861 	struct bpf_kfunc_meta kfunc;
13862 	int err;
13863 
13864 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
13865 	if (err)
13866 		return err;
13867 
13868 	memset(meta, 0, sizeof(*meta));
13869 	meta->btf = kfunc.btf;
13870 	meta->func_id = kfunc.id;
13871 	meta->func_proto = kfunc.proto;
13872 	meta->func_name = kfunc.name;
13873 
13874 	if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog))
13875 		return -EACCES;
13876 
13877 	meta->kfunc_flags = *kfunc.flags;
13878 
13879 	return 0;
13880 }
13881 
13882 /* check special kfuncs and return:
13883  *  1  - not fall-through to 'else' branch, continue verification
13884  *  0  - fall-through to 'else' branch
13885  * < 0 - not fall-through to 'else' branch, return error
13886  */
13887 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13888 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
13889 			       const struct btf_type *ptr_type, struct btf *desc_btf)
13890 {
13891 	const struct btf_type *ret_t;
13892 	int err = 0;
13893 
13894 	if (meta->btf != btf_vmlinux)
13895 		return 0;
13896 
13897 	if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
13898 	    meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13899 		struct btf_struct_meta *struct_meta;
13900 		struct btf *ret_btf;
13901 		u32 ret_btf_id;
13902 
13903 		if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
13904 			return -ENOMEM;
13905 
13906 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
13907 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13908 			return -EINVAL;
13909 		}
13910 
13911 		ret_btf = env->prog->aux->btf;
13912 		ret_btf_id = meta->arg_constant.value;
13913 
13914 		/* This may be NULL due to user not supplying a BTF */
13915 		if (!ret_btf) {
13916 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13917 			return -EINVAL;
13918 		}
13919 
13920 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13921 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
13922 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13923 			return -EINVAL;
13924 		}
13925 
13926 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13927 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13928 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13929 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13930 				return -EINVAL;
13931 			}
13932 
13933 			if (!bpf_global_percpu_ma_set) {
13934 				mutex_lock(&bpf_percpu_ma_lock);
13935 				if (!bpf_global_percpu_ma_set) {
13936 					/* Charge memory allocated with bpf_global_percpu_ma to
13937 					 * root memcg. The obj_cgroup for root memcg is NULL.
13938 					 */
13939 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13940 					if (!err)
13941 						bpf_global_percpu_ma_set = true;
13942 				}
13943 				mutex_unlock(&bpf_percpu_ma_lock);
13944 				if (err)
13945 					return err;
13946 			}
13947 
13948 			mutex_lock(&bpf_percpu_ma_lock);
13949 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13950 			mutex_unlock(&bpf_percpu_ma_lock);
13951 			if (err)
13952 				return err;
13953 		}
13954 
13955 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13956 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13957 			if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13958 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13959 				return -EINVAL;
13960 			}
13961 
13962 			if (struct_meta) {
13963 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13964 				return -EINVAL;
13965 			}
13966 		}
13967 
13968 		mark_reg_known_zero(env, regs, BPF_REG_0);
13969 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13970 		regs[BPF_REG_0].btf = ret_btf;
13971 		regs[BPF_REG_0].btf_id = ret_btf_id;
13972 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
13973 			regs[BPF_REG_0].type |= MEM_PERCPU;
13974 
13975 		insn_aux->obj_new_size = ret_t->size;
13976 		insn_aux->kptr_struct_meta = struct_meta;
13977 	} else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
13978 		mark_reg_known_zero(env, regs, BPF_REG_0);
13979 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13980 		regs[BPF_REG_0].btf = meta->arg_btf;
13981 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
13982 
13983 		insn_aux->kptr_struct_meta =
13984 			btf_find_struct_meta(meta->arg_btf,
13985 					     meta->arg_btf_id);
13986 	} else if (is_list_node_type(ptr_type)) {
13987 		struct btf_field *field = meta->arg_list_head.field;
13988 
13989 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13990 	} else if (is_rbtree_node_type(ptr_type)) {
13991 		struct btf_field *field = meta->arg_rbtree_root.field;
13992 
13993 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13994 	} else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13995 		mark_reg_known_zero(env, regs, BPF_REG_0);
13996 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13997 		regs[BPF_REG_0].btf = desc_btf;
13998 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
13999 	} else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
14000 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
14001 		if (!ret_t) {
14002 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
14003 				meta->arg_constant.value);
14004 			return -EINVAL;
14005 		} else if (btf_type_is_struct(ret_t)) {
14006 			mark_reg_known_zero(env, regs, BPF_REG_0);
14007 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
14008 			regs[BPF_REG_0].btf = desc_btf;
14009 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
14010 		} else if (btf_type_is_void(ret_t)) {
14011 			mark_reg_known_zero(env, regs, BPF_REG_0);
14012 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
14013 			regs[BPF_REG_0].mem_size = 0;
14014 		} else {
14015 			verbose(env,
14016 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
14017 			return -EINVAL;
14018 		}
14019 	} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
14020 		   meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
14021 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type);
14022 
14023 		mark_reg_known_zero(env, regs, BPF_REG_0);
14024 
14025 		if (!meta->arg_constant.found) {
14026 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
14027 			return -EFAULT;
14028 		}
14029 
14030 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
14031 
14032 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
14033 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
14034 
14035 		if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
14036 			regs[BPF_REG_0].type |= MEM_RDONLY;
14037 		} else {
14038 			/* this will set env->seen_direct_write to true */
14039 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
14040 				verbose(env, "the prog does not allow writes to packet data\n");
14041 				return -EINVAL;
14042 			}
14043 		}
14044 
14045 		if (!meta->initialized_dynptr.id) {
14046 			verifier_bug(env, "no dynptr id");
14047 			return -EFAULT;
14048 		}
14049 		regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id;
14050 
14051 		/* we don't need to set BPF_REG_0's ref obj id
14052 		 * because packet slices are not refcounted (see
14053 		 * dynptr_type_refcounted)
14054 		 */
14055 	} else {
14056 		return 0;
14057 	}
14058 
14059 	return 1;
14060 }
14061 
14062 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
14063 
14064 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
14065 			    int *insn_idx_p)
14066 {
14067 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
14068 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
14069 	struct bpf_reg_state *regs = cur_regs(env);
14070 	const char *func_name, *ptr_type_name;
14071 	const struct btf_type *t, *ptr_type;
14072 	struct bpf_kfunc_call_arg_meta meta;
14073 	struct bpf_insn_aux_data *insn_aux;
14074 	int err, insn_idx = *insn_idx_p;
14075 	const struct btf_param *args;
14076 	struct btf *desc_btf;
14077 
14078 	/* skip for now, but return error when we find this in fixup_kfunc_call */
14079 	if (!insn->imm)
14080 		return 0;
14081 
14082 	err = fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
14083 	if (err == -EACCES && meta.func_name)
14084 		verbose(env, "calling kernel function %s is not allowed\n", meta.func_name);
14085 	if (err)
14086 		return err;
14087 	desc_btf = meta.btf;
14088 	func_name = meta.func_name;
14089 	insn_aux = &env->insn_aux_data[insn_idx];
14090 
14091 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
14092 
14093 	if (!insn->off &&
14094 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
14095 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
14096 		struct bpf_verifier_state *branch;
14097 		struct bpf_reg_state *regs;
14098 
14099 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
14100 		if (IS_ERR(branch)) {
14101 			verbose(env, "failed to push state for failed lock acquisition\n");
14102 			return PTR_ERR(branch);
14103 		}
14104 
14105 		regs = branch->frame[branch->curframe]->regs;
14106 
14107 		/* Clear r0-r5 registers in forked state */
14108 		for (i = 0; i < CALLER_SAVED_REGS; i++)
14109 			mark_reg_not_init(env, regs, caller_saved[i]);
14110 
14111 		mark_reg_unknown(env, regs, BPF_REG_0);
14112 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
14113 		if (err) {
14114 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
14115 			return err;
14116 		}
14117 		__mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32));
14118 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
14119 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
14120 		return -EFAULT;
14121 	}
14122 
14123 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
14124 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
14125 		return -EACCES;
14126 	}
14127 
14128 	sleepable = is_kfunc_sleepable(&meta);
14129 	if (sleepable && !in_sleepable(env)) {
14130 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
14131 		return -EACCES;
14132 	}
14133 
14134 	/* Track non-sleepable context for kfuncs, same as for helpers. */
14135 	if (!in_sleepable_context(env))
14136 		insn_aux->non_sleepable = true;
14137 
14138 	/* Check the arguments */
14139 	err = check_kfunc_args(env, &meta, insn_idx);
14140 	if (err < 0)
14141 		return err;
14142 
14143 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
14144 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14145 					 set_rbtree_add_callback_state);
14146 		if (err) {
14147 			verbose(env, "kfunc %s#%d failed callback verification\n",
14148 				func_name, meta.func_id);
14149 			return err;
14150 		}
14151 	}
14152 
14153 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
14154 		meta.r0_size = sizeof(u64);
14155 		meta.r0_rdonly = false;
14156 	}
14157 
14158 	if (is_bpf_wq_set_callback_kfunc(meta.func_id)) {
14159 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14160 					 set_timer_callback_state);
14161 		if (err) {
14162 			verbose(env, "kfunc %s#%d failed callback verification\n",
14163 				func_name, meta.func_id);
14164 			return err;
14165 		}
14166 	}
14167 
14168 	if (is_task_work_add_kfunc(meta.func_id)) {
14169 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14170 					 set_task_work_schedule_callback_state);
14171 		if (err) {
14172 			verbose(env, "kfunc %s#%d failed callback verification\n",
14173 				func_name, meta.func_id);
14174 			return err;
14175 		}
14176 	}
14177 
14178 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
14179 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
14180 
14181 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
14182 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
14183 
14184 	if (rcu_lock) {
14185 		env->cur_state->active_rcu_locks++;
14186 	} else if (rcu_unlock) {
14187 		struct bpf_func_state *state;
14188 		struct bpf_reg_state *reg;
14189 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
14190 
14191 		if (env->cur_state->active_rcu_locks == 0) {
14192 			verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
14193 			return -EINVAL;
14194 		}
14195 		if (--env->cur_state->active_rcu_locks == 0) {
14196 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
14197 				if (reg->type & MEM_RCU) {
14198 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
14199 					reg->type |= PTR_UNTRUSTED;
14200 				}
14201 			}));
14202 		}
14203 	} else if (sleepable && env->cur_state->active_rcu_locks) {
14204 		verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
14205 		return -EACCES;
14206 	}
14207 
14208 	if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
14209 		verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
14210 		return -EACCES;
14211 	}
14212 
14213 	if (env->cur_state->active_preempt_locks) {
14214 		if (preempt_disable) {
14215 			env->cur_state->active_preempt_locks++;
14216 		} else if (preempt_enable) {
14217 			env->cur_state->active_preempt_locks--;
14218 		} else if (sleepable) {
14219 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
14220 			return -EACCES;
14221 		}
14222 	} else if (preempt_disable) {
14223 		env->cur_state->active_preempt_locks++;
14224 	} else if (preempt_enable) {
14225 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
14226 		return -EINVAL;
14227 	}
14228 
14229 	if (env->cur_state->active_irq_id && sleepable) {
14230 		verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name);
14231 		return -EACCES;
14232 	}
14233 
14234 	if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
14235 		verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
14236 		return -EACCES;
14237 	}
14238 
14239 	/* In case of release function, we get register number of refcounted
14240 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
14241 	 */
14242 	if (meta.release_regno) {
14243 		struct bpf_reg_state *reg = &regs[meta.release_regno];
14244 
14245 		if (meta.initialized_dynptr.ref_obj_id) {
14246 			err = unmark_stack_slots_dynptr(env, reg);
14247 		} else {
14248 			err = release_reference(env, reg->ref_obj_id);
14249 			if (err)
14250 				verbose(env, "kfunc %s#%d reference has not been acquired before\n",
14251 					func_name, meta.func_id);
14252 		}
14253 		if (err)
14254 			return err;
14255 	}
14256 
14257 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
14258 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
14259 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
14260 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
14261 		insn_aux->insert_off = regs[BPF_REG_2].off;
14262 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
14263 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
14264 		if (err) {
14265 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
14266 				func_name, meta.func_id);
14267 			return err;
14268 		}
14269 
14270 		err = release_reference(env, release_ref_obj_id);
14271 		if (err) {
14272 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
14273 				func_name, meta.func_id);
14274 			return err;
14275 		}
14276 	}
14277 
14278 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
14279 		if (!bpf_jit_supports_exceptions()) {
14280 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
14281 				func_name, meta.func_id);
14282 			return -ENOTSUPP;
14283 		}
14284 		env->seen_exception = true;
14285 
14286 		/* In the case of the default callback, the cookie value passed
14287 		 * to bpf_throw becomes the return value of the program.
14288 		 */
14289 		if (!env->exception_callback_subprog) {
14290 			err = check_return_code(env, BPF_REG_1, "R1");
14291 			if (err < 0)
14292 				return err;
14293 		}
14294 	}
14295 
14296 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14297 		u32 regno = caller_saved[i];
14298 
14299 		mark_reg_not_init(env, regs, regno);
14300 		regs[regno].subreg_def = DEF_NOT_SUBREG;
14301 	}
14302 
14303 	/* Check return type */
14304 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
14305 
14306 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
14307 		/* Only exception is bpf_obj_new_impl */
14308 		if (meta.btf != btf_vmlinux ||
14309 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
14310 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
14311 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
14312 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
14313 			return -EINVAL;
14314 		}
14315 	}
14316 
14317 	if (btf_type_is_scalar(t)) {
14318 		mark_reg_unknown(env, regs, BPF_REG_0);
14319 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
14320 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14321 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
14322 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
14323 	} else if (btf_type_is_ptr(t)) {
14324 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
14325 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
14326 		if (err) {
14327 			if (err < 0)
14328 				return err;
14329 		} else if (btf_type_is_void(ptr_type)) {
14330 			/* kfunc returning 'void *' is equivalent to returning scalar */
14331 			mark_reg_unknown(env, regs, BPF_REG_0);
14332 		} else if (!__btf_type_is_struct(ptr_type)) {
14333 			if (!meta.r0_size) {
14334 				__u32 sz;
14335 
14336 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
14337 					meta.r0_size = sz;
14338 					meta.r0_rdonly = true;
14339 				}
14340 			}
14341 			if (!meta.r0_size) {
14342 				ptr_type_name = btf_name_by_offset(desc_btf,
14343 								   ptr_type->name_off);
14344 				verbose(env,
14345 					"kernel function %s returns pointer type %s %s is not supported\n",
14346 					func_name,
14347 					btf_type_str(ptr_type),
14348 					ptr_type_name);
14349 				return -EINVAL;
14350 			}
14351 
14352 			mark_reg_known_zero(env, regs, BPF_REG_0);
14353 			regs[BPF_REG_0].type = PTR_TO_MEM;
14354 			regs[BPF_REG_0].mem_size = meta.r0_size;
14355 
14356 			if (meta.r0_rdonly)
14357 				regs[BPF_REG_0].type |= MEM_RDONLY;
14358 
14359 			/* Ensures we don't access the memory after a release_reference() */
14360 			if (meta.ref_obj_id)
14361 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
14362 
14363 			if (is_kfunc_rcu_protected(&meta))
14364 				regs[BPF_REG_0].type |= MEM_RCU;
14365 		} else {
14366 			enum bpf_reg_type type = PTR_TO_BTF_ID;
14367 
14368 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
14369 				type |= PTR_UNTRUSTED;
14370 			else if (is_kfunc_rcu_protected(&meta) ||
14371 				 (is_iter_next_kfunc(&meta) &&
14372 				  (get_iter_from_state(env->cur_state, &meta)
14373 					   ->type & MEM_RCU))) {
14374 				/*
14375 				 * If the iterator's constructor (the _new
14376 				 * function e.g., bpf_iter_task_new) has been
14377 				 * annotated with BPF kfunc flag
14378 				 * KF_RCU_PROTECTED and was called within a RCU
14379 				 * read-side critical section, also propagate
14380 				 * the MEM_RCU flag to the pointer returned from
14381 				 * the iterator's next function (e.g.,
14382 				 * bpf_iter_task_next).
14383 				 */
14384 				type |= MEM_RCU;
14385 			} else {
14386 				/*
14387 				 * Any PTR_TO_BTF_ID that is returned from a BPF
14388 				 * kfunc should by default be treated as
14389 				 * implicitly trusted.
14390 				 */
14391 				type |= PTR_TRUSTED;
14392 			}
14393 
14394 			mark_reg_known_zero(env, regs, BPF_REG_0);
14395 			regs[BPF_REG_0].btf = desc_btf;
14396 			regs[BPF_REG_0].type = type;
14397 			regs[BPF_REG_0].btf_id = ptr_type_id;
14398 		}
14399 
14400 		if (is_kfunc_ret_null(&meta)) {
14401 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
14402 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
14403 			regs[BPF_REG_0].id = ++env->id_gen;
14404 		}
14405 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
14406 		if (is_kfunc_acquire(&meta)) {
14407 			int id = acquire_reference(env, insn_idx);
14408 
14409 			if (id < 0)
14410 				return id;
14411 			if (is_kfunc_ret_null(&meta))
14412 				regs[BPF_REG_0].id = id;
14413 			regs[BPF_REG_0].ref_obj_id = id;
14414 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
14415 			ref_set_non_owning(env, &regs[BPF_REG_0]);
14416 		}
14417 
14418 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
14419 			regs[BPF_REG_0].id = ++env->id_gen;
14420 	} else if (btf_type_is_void(t)) {
14421 		if (meta.btf == btf_vmlinux) {
14422 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
14423 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
14424 				insn_aux->kptr_struct_meta =
14425 					btf_find_struct_meta(meta.arg_btf,
14426 							     meta.arg_btf_id);
14427 			}
14428 		}
14429 	}
14430 
14431 	if (is_kfunc_pkt_changing(&meta))
14432 		clear_all_pkt_pointers(env);
14433 
14434 	nargs = btf_type_vlen(meta.func_proto);
14435 	args = (const struct btf_param *)(meta.func_proto + 1);
14436 	for (i = 0; i < nargs; i++) {
14437 		u32 regno = i + 1;
14438 
14439 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
14440 		if (btf_type_is_ptr(t))
14441 			mark_btf_func_reg_size(env, regno, sizeof(void *));
14442 		else
14443 			/* scalar. ensured by btf_check_kfunc_arg_match() */
14444 			mark_btf_func_reg_size(env, regno, t->size);
14445 	}
14446 
14447 	if (is_iter_next_kfunc(&meta)) {
14448 		err = process_iter_next_call(env, insn_idx, &meta);
14449 		if (err)
14450 			return err;
14451 	}
14452 
14453 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie])
14454 		env->prog->call_session_cookie = true;
14455 
14456 	return 0;
14457 }
14458 
14459 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
14460 				  const struct bpf_reg_state *reg,
14461 				  enum bpf_reg_type type)
14462 {
14463 	bool known = tnum_is_const(reg->var_off);
14464 	s64 val = reg->var_off.value;
14465 	s64 smin = reg->smin_value;
14466 
14467 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
14468 		verbose(env, "math between %s pointer and %lld is not allowed\n",
14469 			reg_type_str(env, type), val);
14470 		return false;
14471 	}
14472 
14473 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
14474 		verbose(env, "%s pointer offset %d is not allowed\n",
14475 			reg_type_str(env, type), reg->off);
14476 		return false;
14477 	}
14478 
14479 	if (smin == S64_MIN) {
14480 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
14481 			reg_type_str(env, type));
14482 		return false;
14483 	}
14484 
14485 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
14486 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
14487 			smin, reg_type_str(env, type));
14488 		return false;
14489 	}
14490 
14491 	return true;
14492 }
14493 
14494 enum {
14495 	REASON_BOUNDS	= -1,
14496 	REASON_TYPE	= -2,
14497 	REASON_PATHS	= -3,
14498 	REASON_LIMIT	= -4,
14499 	REASON_STACK	= -5,
14500 };
14501 
14502 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
14503 			      u32 *alu_limit, bool mask_to_left)
14504 {
14505 	u32 max = 0, ptr_limit = 0;
14506 
14507 	switch (ptr_reg->type) {
14508 	case PTR_TO_STACK:
14509 		/* Offset 0 is out-of-bounds, but acceptable start for the
14510 		 * left direction, see BPF_REG_FP. Also, unknown scalar
14511 		 * offset where we would need to deal with min/max bounds is
14512 		 * currently prohibited for unprivileged.
14513 		 */
14514 		max = MAX_BPF_STACK + mask_to_left;
14515 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
14516 		break;
14517 	case PTR_TO_MAP_VALUE:
14518 		max = ptr_reg->map_ptr->value_size;
14519 		ptr_limit = (mask_to_left ?
14520 			     ptr_reg->smin_value :
14521 			     ptr_reg->umax_value) + ptr_reg->off;
14522 		break;
14523 	default:
14524 		return REASON_TYPE;
14525 	}
14526 
14527 	if (ptr_limit >= max)
14528 		return REASON_LIMIT;
14529 	*alu_limit = ptr_limit;
14530 	return 0;
14531 }
14532 
14533 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
14534 				    const struct bpf_insn *insn)
14535 {
14536 	return env->bypass_spec_v1 ||
14537 		BPF_SRC(insn->code) == BPF_K ||
14538 		cur_aux(env)->nospec;
14539 }
14540 
14541 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
14542 				       u32 alu_state, u32 alu_limit)
14543 {
14544 	/* If we arrived here from different branches with different
14545 	 * state or limits to sanitize, then this won't work.
14546 	 */
14547 	if (aux->alu_state &&
14548 	    (aux->alu_state != alu_state ||
14549 	     aux->alu_limit != alu_limit))
14550 		return REASON_PATHS;
14551 
14552 	/* Corresponding fixup done in do_misc_fixups(). */
14553 	aux->alu_state = alu_state;
14554 	aux->alu_limit = alu_limit;
14555 	return 0;
14556 }
14557 
14558 static int sanitize_val_alu(struct bpf_verifier_env *env,
14559 			    struct bpf_insn *insn)
14560 {
14561 	struct bpf_insn_aux_data *aux = cur_aux(env);
14562 
14563 	if (can_skip_alu_sanitation(env, insn))
14564 		return 0;
14565 
14566 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
14567 }
14568 
14569 static bool sanitize_needed(u8 opcode)
14570 {
14571 	return opcode == BPF_ADD || opcode == BPF_SUB;
14572 }
14573 
14574 struct bpf_sanitize_info {
14575 	struct bpf_insn_aux_data aux;
14576 	bool mask_to_left;
14577 };
14578 
14579 static int sanitize_speculative_path(struct bpf_verifier_env *env,
14580 				     const struct bpf_insn *insn,
14581 				     u32 next_idx, u32 curr_idx)
14582 {
14583 	struct bpf_verifier_state *branch;
14584 	struct bpf_reg_state *regs;
14585 
14586 	branch = push_stack(env, next_idx, curr_idx, true);
14587 	if (!IS_ERR(branch) && insn) {
14588 		regs = branch->frame[branch->curframe]->regs;
14589 		if (BPF_SRC(insn->code) == BPF_K) {
14590 			mark_reg_unknown(env, regs, insn->dst_reg);
14591 		} else if (BPF_SRC(insn->code) == BPF_X) {
14592 			mark_reg_unknown(env, regs, insn->dst_reg);
14593 			mark_reg_unknown(env, regs, insn->src_reg);
14594 		}
14595 	}
14596 	return PTR_ERR_OR_ZERO(branch);
14597 }
14598 
14599 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
14600 			    struct bpf_insn *insn,
14601 			    const struct bpf_reg_state *ptr_reg,
14602 			    const struct bpf_reg_state *off_reg,
14603 			    struct bpf_reg_state *dst_reg,
14604 			    struct bpf_sanitize_info *info,
14605 			    const bool commit_window)
14606 {
14607 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
14608 	struct bpf_verifier_state *vstate = env->cur_state;
14609 	bool off_is_imm = tnum_is_const(off_reg->var_off);
14610 	bool off_is_neg = off_reg->smin_value < 0;
14611 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
14612 	u8 opcode = BPF_OP(insn->code);
14613 	u32 alu_state, alu_limit;
14614 	struct bpf_reg_state tmp;
14615 	int err;
14616 
14617 	if (can_skip_alu_sanitation(env, insn))
14618 		return 0;
14619 
14620 	/* We already marked aux for masking from non-speculative
14621 	 * paths, thus we got here in the first place. We only care
14622 	 * to explore bad access from here.
14623 	 */
14624 	if (vstate->speculative)
14625 		goto do_sim;
14626 
14627 	if (!commit_window) {
14628 		if (!tnum_is_const(off_reg->var_off) &&
14629 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
14630 			return REASON_BOUNDS;
14631 
14632 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
14633 				     (opcode == BPF_SUB && !off_is_neg);
14634 	}
14635 
14636 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
14637 	if (err < 0)
14638 		return err;
14639 
14640 	if (commit_window) {
14641 		/* In commit phase we narrow the masking window based on
14642 		 * the observed pointer move after the simulated operation.
14643 		 */
14644 		alu_state = info->aux.alu_state;
14645 		alu_limit = abs(info->aux.alu_limit - alu_limit);
14646 	} else {
14647 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
14648 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
14649 		alu_state |= ptr_is_dst_reg ?
14650 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
14651 
14652 		/* Limit pruning on unknown scalars to enable deep search for
14653 		 * potential masking differences from other program paths.
14654 		 */
14655 		if (!off_is_imm)
14656 			env->explore_alu_limits = true;
14657 	}
14658 
14659 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
14660 	if (err < 0)
14661 		return err;
14662 do_sim:
14663 	/* If we're in commit phase, we're done here given we already
14664 	 * pushed the truncated dst_reg into the speculative verification
14665 	 * stack.
14666 	 *
14667 	 * Also, when register is a known constant, we rewrite register-based
14668 	 * operation to immediate-based, and thus do not need masking (and as
14669 	 * a consequence, do not need to simulate the zero-truncation either).
14670 	 */
14671 	if (commit_window || off_is_imm)
14672 		return 0;
14673 
14674 	/* Simulate and find potential out-of-bounds access under
14675 	 * speculative execution from truncation as a result of
14676 	 * masking when off was not within expected range. If off
14677 	 * sits in dst, then we temporarily need to move ptr there
14678 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
14679 	 * for cases where we use K-based arithmetic in one direction
14680 	 * and truncated reg-based in the other in order to explore
14681 	 * bad access.
14682 	 */
14683 	if (!ptr_is_dst_reg) {
14684 		tmp = *dst_reg;
14685 		copy_register_state(dst_reg, ptr_reg);
14686 	}
14687 	err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx);
14688 	if (err < 0)
14689 		return REASON_STACK;
14690 	if (!ptr_is_dst_reg)
14691 		*dst_reg = tmp;
14692 	return 0;
14693 }
14694 
14695 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
14696 {
14697 	struct bpf_verifier_state *vstate = env->cur_state;
14698 
14699 	/* If we simulate paths under speculation, we don't update the
14700 	 * insn as 'seen' such that when we verify unreachable paths in
14701 	 * the non-speculative domain, sanitize_dead_code() can still
14702 	 * rewrite/sanitize them.
14703 	 */
14704 	if (!vstate->speculative)
14705 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
14706 }
14707 
14708 static int sanitize_err(struct bpf_verifier_env *env,
14709 			const struct bpf_insn *insn, int reason,
14710 			const struct bpf_reg_state *off_reg,
14711 			const struct bpf_reg_state *dst_reg)
14712 {
14713 	static const char *err = "pointer arithmetic with it prohibited for !root";
14714 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
14715 	u32 dst = insn->dst_reg, src = insn->src_reg;
14716 
14717 	switch (reason) {
14718 	case REASON_BOUNDS:
14719 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
14720 			off_reg == dst_reg ? dst : src, err);
14721 		break;
14722 	case REASON_TYPE:
14723 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
14724 			off_reg == dst_reg ? src : dst, err);
14725 		break;
14726 	case REASON_PATHS:
14727 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
14728 			dst, op, err);
14729 		break;
14730 	case REASON_LIMIT:
14731 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
14732 			dst, op, err);
14733 		break;
14734 	case REASON_STACK:
14735 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
14736 			dst, err);
14737 		return -ENOMEM;
14738 	default:
14739 		verifier_bug(env, "unknown reason (%d)", reason);
14740 		break;
14741 	}
14742 
14743 	return -EACCES;
14744 }
14745 
14746 /* check that stack access falls within stack limits and that 'reg' doesn't
14747  * have a variable offset.
14748  *
14749  * Variable offset is prohibited for unprivileged mode for simplicity since it
14750  * requires corresponding support in Spectre masking for stack ALU.  See also
14751  * retrieve_ptr_limit().
14752  *
14753  *
14754  * 'off' includes 'reg->off'.
14755  */
14756 static int check_stack_access_for_ptr_arithmetic(
14757 				struct bpf_verifier_env *env,
14758 				int regno,
14759 				const struct bpf_reg_state *reg,
14760 				int off)
14761 {
14762 	if (!tnum_is_const(reg->var_off)) {
14763 		char tn_buf[48];
14764 
14765 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
14766 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
14767 			regno, tn_buf, off);
14768 		return -EACCES;
14769 	}
14770 
14771 	if (off >= 0 || off < -MAX_BPF_STACK) {
14772 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
14773 			"prohibited for !root; off=%d\n", regno, off);
14774 		return -EACCES;
14775 	}
14776 
14777 	return 0;
14778 }
14779 
14780 static int sanitize_check_bounds(struct bpf_verifier_env *env,
14781 				 const struct bpf_insn *insn,
14782 				 const struct bpf_reg_state *dst_reg)
14783 {
14784 	u32 dst = insn->dst_reg;
14785 
14786 	/* For unprivileged we require that resulting offset must be in bounds
14787 	 * in order to be able to sanitize access later on.
14788 	 */
14789 	if (env->bypass_spec_v1)
14790 		return 0;
14791 
14792 	switch (dst_reg->type) {
14793 	case PTR_TO_STACK:
14794 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
14795 					dst_reg->off + dst_reg->var_off.value))
14796 			return -EACCES;
14797 		break;
14798 	case PTR_TO_MAP_VALUE:
14799 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
14800 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
14801 				"prohibited for !root\n", dst);
14802 			return -EACCES;
14803 		}
14804 		break;
14805 	default:
14806 		return -EOPNOTSUPP;
14807 	}
14808 
14809 	return 0;
14810 }
14811 
14812 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
14813  * Caller should also handle BPF_MOV case separately.
14814  * If we return -EACCES, caller may want to try again treating pointer as a
14815  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
14816  */
14817 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
14818 				   struct bpf_insn *insn,
14819 				   const struct bpf_reg_state *ptr_reg,
14820 				   const struct bpf_reg_state *off_reg)
14821 {
14822 	struct bpf_verifier_state *vstate = env->cur_state;
14823 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14824 	struct bpf_reg_state *regs = state->regs, *dst_reg;
14825 	bool known = tnum_is_const(off_reg->var_off);
14826 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
14827 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
14828 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
14829 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
14830 	struct bpf_sanitize_info info = {};
14831 	u8 opcode = BPF_OP(insn->code);
14832 	u32 dst = insn->dst_reg;
14833 	int ret, bounds_ret;
14834 
14835 	dst_reg = &regs[dst];
14836 
14837 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
14838 	    smin_val > smax_val || umin_val > umax_val) {
14839 		/* Taint dst register if offset had invalid bounds derived from
14840 		 * e.g. dead branches.
14841 		 */
14842 		__mark_reg_unknown(env, dst_reg);
14843 		return 0;
14844 	}
14845 
14846 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
14847 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
14848 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14849 			__mark_reg_unknown(env, dst_reg);
14850 			return 0;
14851 		}
14852 
14853 		verbose(env,
14854 			"R%d 32-bit pointer arithmetic prohibited\n",
14855 			dst);
14856 		return -EACCES;
14857 	}
14858 
14859 	if (ptr_reg->type & PTR_MAYBE_NULL) {
14860 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
14861 			dst, reg_type_str(env, ptr_reg->type));
14862 		return -EACCES;
14863 	}
14864 
14865 	/*
14866 	 * Accesses to untrusted PTR_TO_MEM are done through probe
14867 	 * instructions, hence no need to track offsets.
14868 	 */
14869 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
14870 		return 0;
14871 
14872 	switch (base_type(ptr_reg->type)) {
14873 	case PTR_TO_CTX:
14874 	case PTR_TO_MAP_VALUE:
14875 	case PTR_TO_MAP_KEY:
14876 	case PTR_TO_STACK:
14877 	case PTR_TO_PACKET_META:
14878 	case PTR_TO_PACKET:
14879 	case PTR_TO_TP_BUFFER:
14880 	case PTR_TO_BTF_ID:
14881 	case PTR_TO_MEM:
14882 	case PTR_TO_BUF:
14883 	case PTR_TO_FUNC:
14884 	case CONST_PTR_TO_DYNPTR:
14885 		break;
14886 	case PTR_TO_FLOW_KEYS:
14887 		if (known)
14888 			break;
14889 		fallthrough;
14890 	case CONST_PTR_TO_MAP:
14891 		/* smin_val represents the known value */
14892 		if (known && smin_val == 0 && opcode == BPF_ADD)
14893 			break;
14894 		fallthrough;
14895 	default:
14896 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
14897 			dst, reg_type_str(env, ptr_reg->type));
14898 		return -EACCES;
14899 	}
14900 
14901 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
14902 	 * The id may be overwritten later if we create a new variable offset.
14903 	 */
14904 	dst_reg->type = ptr_reg->type;
14905 	dst_reg->id = ptr_reg->id;
14906 
14907 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
14908 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
14909 		return -EINVAL;
14910 
14911 	/* pointer types do not carry 32-bit bounds at the moment. */
14912 	__mark_reg32_unbounded(dst_reg);
14913 
14914 	if (sanitize_needed(opcode)) {
14915 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
14916 				       &info, false);
14917 		if (ret < 0)
14918 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14919 	}
14920 
14921 	switch (opcode) {
14922 	case BPF_ADD:
14923 		/* We can take a fixed offset as long as it doesn't overflow
14924 		 * the s32 'off' field
14925 		 */
14926 		if (known && (ptr_reg->off + smin_val ==
14927 			      (s64)(s32)(ptr_reg->off + smin_val))) {
14928 			/* pointer += K.  Accumulate it into fixed offset */
14929 			dst_reg->smin_value = smin_ptr;
14930 			dst_reg->smax_value = smax_ptr;
14931 			dst_reg->umin_value = umin_ptr;
14932 			dst_reg->umax_value = umax_ptr;
14933 			dst_reg->var_off = ptr_reg->var_off;
14934 			dst_reg->off = ptr_reg->off + smin_val;
14935 			dst_reg->raw = ptr_reg->raw;
14936 			break;
14937 		}
14938 		/* A new variable offset is created.  Note that off_reg->off
14939 		 * == 0, since it's a scalar.
14940 		 * dst_reg gets the pointer type and since some positive
14941 		 * integer value was added to the pointer, give it a new 'id'
14942 		 * if it's a PTR_TO_PACKET.
14943 		 * this creates a new 'base' pointer, off_reg (variable) gets
14944 		 * added into the variable offset, and we copy the fixed offset
14945 		 * from ptr_reg.
14946 		 */
14947 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
14948 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
14949 			dst_reg->smin_value = S64_MIN;
14950 			dst_reg->smax_value = S64_MAX;
14951 		}
14952 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
14953 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
14954 			dst_reg->umin_value = 0;
14955 			dst_reg->umax_value = U64_MAX;
14956 		}
14957 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
14958 		dst_reg->off = ptr_reg->off;
14959 		dst_reg->raw = ptr_reg->raw;
14960 		if (reg_is_pkt_pointer(ptr_reg)) {
14961 			dst_reg->id = ++env->id_gen;
14962 			/* something was added to pkt_ptr, set range to zero */
14963 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14964 		}
14965 		break;
14966 	case BPF_SUB:
14967 		if (dst_reg == off_reg) {
14968 			/* scalar -= pointer.  Creates an unknown scalar */
14969 			verbose(env, "R%d tried to subtract pointer from scalar\n",
14970 				dst);
14971 			return -EACCES;
14972 		}
14973 		/* We don't allow subtraction from FP, because (according to
14974 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
14975 		 * be able to deal with it.
14976 		 */
14977 		if (ptr_reg->type == PTR_TO_STACK) {
14978 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
14979 				dst);
14980 			return -EACCES;
14981 		}
14982 		if (known && (ptr_reg->off - smin_val ==
14983 			      (s64)(s32)(ptr_reg->off - smin_val))) {
14984 			/* pointer -= K.  Subtract it from fixed offset */
14985 			dst_reg->smin_value = smin_ptr;
14986 			dst_reg->smax_value = smax_ptr;
14987 			dst_reg->umin_value = umin_ptr;
14988 			dst_reg->umax_value = umax_ptr;
14989 			dst_reg->var_off = ptr_reg->var_off;
14990 			dst_reg->id = ptr_reg->id;
14991 			dst_reg->off = ptr_reg->off - smin_val;
14992 			dst_reg->raw = ptr_reg->raw;
14993 			break;
14994 		}
14995 		/* A new variable offset is created.  If the subtrahend is known
14996 		 * nonnegative, then any reg->range we had before is still good.
14997 		 */
14998 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
14999 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
15000 			/* Overflow possible, we know nothing */
15001 			dst_reg->smin_value = S64_MIN;
15002 			dst_reg->smax_value = S64_MAX;
15003 		}
15004 		if (umin_ptr < umax_val) {
15005 			/* Overflow possible, we know nothing */
15006 			dst_reg->umin_value = 0;
15007 			dst_reg->umax_value = U64_MAX;
15008 		} else {
15009 			/* Cannot overflow (as long as bounds are consistent) */
15010 			dst_reg->umin_value = umin_ptr - umax_val;
15011 			dst_reg->umax_value = umax_ptr - umin_val;
15012 		}
15013 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
15014 		dst_reg->off = ptr_reg->off;
15015 		dst_reg->raw = ptr_reg->raw;
15016 		if (reg_is_pkt_pointer(ptr_reg)) {
15017 			dst_reg->id = ++env->id_gen;
15018 			/* something was added to pkt_ptr, set range to zero */
15019 			if (smin_val < 0)
15020 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
15021 		}
15022 		break;
15023 	case BPF_AND:
15024 	case BPF_OR:
15025 	case BPF_XOR:
15026 		/* bitwise ops on pointers are troublesome, prohibit. */
15027 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
15028 			dst, bpf_alu_string[opcode >> 4]);
15029 		return -EACCES;
15030 	default:
15031 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
15032 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
15033 			dst, bpf_alu_string[opcode >> 4]);
15034 		return -EACCES;
15035 	}
15036 
15037 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
15038 		return -EINVAL;
15039 	reg_bounds_sync(dst_reg);
15040 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
15041 	if (bounds_ret == -EACCES)
15042 		return bounds_ret;
15043 	if (sanitize_needed(opcode)) {
15044 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
15045 				       &info, true);
15046 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
15047 				    && !env->cur_state->speculative
15048 				    && bounds_ret
15049 				    && !ret,
15050 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
15051 			return -EFAULT;
15052 		}
15053 		if (ret < 0)
15054 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
15055 	}
15056 
15057 	return 0;
15058 }
15059 
15060 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
15061 				 struct bpf_reg_state *src_reg)
15062 {
15063 	s32 *dst_smin = &dst_reg->s32_min_value;
15064 	s32 *dst_smax = &dst_reg->s32_max_value;
15065 	u32 *dst_umin = &dst_reg->u32_min_value;
15066 	u32 *dst_umax = &dst_reg->u32_max_value;
15067 	u32 umin_val = src_reg->u32_min_value;
15068 	u32 umax_val = src_reg->u32_max_value;
15069 	bool min_overflow, max_overflow;
15070 
15071 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
15072 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
15073 		*dst_smin = S32_MIN;
15074 		*dst_smax = S32_MAX;
15075 	}
15076 
15077 	/* If either all additions overflow or no additions overflow, then
15078 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
15079 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
15080 	 * the output bounds to unbounded.
15081 	 */
15082 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
15083 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
15084 
15085 	if (!min_overflow && max_overflow) {
15086 		*dst_umin = 0;
15087 		*dst_umax = U32_MAX;
15088 	}
15089 }
15090 
15091 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
15092 			       struct bpf_reg_state *src_reg)
15093 {
15094 	s64 *dst_smin = &dst_reg->smin_value;
15095 	s64 *dst_smax = &dst_reg->smax_value;
15096 	u64 *dst_umin = &dst_reg->umin_value;
15097 	u64 *dst_umax = &dst_reg->umax_value;
15098 	u64 umin_val = src_reg->umin_value;
15099 	u64 umax_val = src_reg->umax_value;
15100 	bool min_overflow, max_overflow;
15101 
15102 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
15103 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
15104 		*dst_smin = S64_MIN;
15105 		*dst_smax = S64_MAX;
15106 	}
15107 
15108 	/* If either all additions overflow or no additions overflow, then
15109 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
15110 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
15111 	 * the output bounds to unbounded.
15112 	 */
15113 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
15114 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
15115 
15116 	if (!min_overflow && max_overflow) {
15117 		*dst_umin = 0;
15118 		*dst_umax = U64_MAX;
15119 	}
15120 }
15121 
15122 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
15123 				 struct bpf_reg_state *src_reg)
15124 {
15125 	s32 *dst_smin = &dst_reg->s32_min_value;
15126 	s32 *dst_smax = &dst_reg->s32_max_value;
15127 	u32 *dst_umin = &dst_reg->u32_min_value;
15128 	u32 *dst_umax = &dst_reg->u32_max_value;
15129 	u32 umin_val = src_reg->u32_min_value;
15130 	u32 umax_val = src_reg->u32_max_value;
15131 	bool min_underflow, max_underflow;
15132 
15133 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
15134 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
15135 		/* Overflow possible, we know nothing */
15136 		*dst_smin = S32_MIN;
15137 		*dst_smax = S32_MAX;
15138 	}
15139 
15140 	/* If either all subtractions underflow or no subtractions
15141 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
15142 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
15143 	 * underflow), set the output bounds to unbounded.
15144 	 */
15145 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
15146 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
15147 
15148 	if (min_underflow && !max_underflow) {
15149 		*dst_umin = 0;
15150 		*dst_umax = U32_MAX;
15151 	}
15152 }
15153 
15154 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
15155 			       struct bpf_reg_state *src_reg)
15156 {
15157 	s64 *dst_smin = &dst_reg->smin_value;
15158 	s64 *dst_smax = &dst_reg->smax_value;
15159 	u64 *dst_umin = &dst_reg->umin_value;
15160 	u64 *dst_umax = &dst_reg->umax_value;
15161 	u64 umin_val = src_reg->umin_value;
15162 	u64 umax_val = src_reg->umax_value;
15163 	bool min_underflow, max_underflow;
15164 
15165 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
15166 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
15167 		/* Overflow possible, we know nothing */
15168 		*dst_smin = S64_MIN;
15169 		*dst_smax = S64_MAX;
15170 	}
15171 
15172 	/* If either all subtractions underflow or no subtractions
15173 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
15174 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
15175 	 * underflow), set the output bounds to unbounded.
15176 	 */
15177 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
15178 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
15179 
15180 	if (min_underflow && !max_underflow) {
15181 		*dst_umin = 0;
15182 		*dst_umax = U64_MAX;
15183 	}
15184 }
15185 
15186 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
15187 				 struct bpf_reg_state *src_reg)
15188 {
15189 	s32 *dst_smin = &dst_reg->s32_min_value;
15190 	s32 *dst_smax = &dst_reg->s32_max_value;
15191 	u32 *dst_umin = &dst_reg->u32_min_value;
15192 	u32 *dst_umax = &dst_reg->u32_max_value;
15193 	s32 tmp_prod[4];
15194 
15195 	if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) ||
15196 	    check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) {
15197 		/* Overflow possible, we know nothing */
15198 		*dst_umin = 0;
15199 		*dst_umax = U32_MAX;
15200 	}
15201 	if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) ||
15202 	    check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) ||
15203 	    check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) ||
15204 	    check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) {
15205 		/* Overflow possible, we know nothing */
15206 		*dst_smin = S32_MIN;
15207 		*dst_smax = S32_MAX;
15208 	} else {
15209 		*dst_smin = min_array(tmp_prod, 4);
15210 		*dst_smax = max_array(tmp_prod, 4);
15211 	}
15212 }
15213 
15214 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
15215 			       struct bpf_reg_state *src_reg)
15216 {
15217 	s64 *dst_smin = &dst_reg->smin_value;
15218 	s64 *dst_smax = &dst_reg->smax_value;
15219 	u64 *dst_umin = &dst_reg->umin_value;
15220 	u64 *dst_umax = &dst_reg->umax_value;
15221 	s64 tmp_prod[4];
15222 
15223 	if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) ||
15224 	    check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) {
15225 		/* Overflow possible, we know nothing */
15226 		*dst_umin = 0;
15227 		*dst_umax = U64_MAX;
15228 	}
15229 	if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) ||
15230 	    check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) ||
15231 	    check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) ||
15232 	    check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) {
15233 		/* Overflow possible, we know nothing */
15234 		*dst_smin = S64_MIN;
15235 		*dst_smax = S64_MAX;
15236 	} else {
15237 		*dst_smin = min_array(tmp_prod, 4);
15238 		*dst_smax = max_array(tmp_prod, 4);
15239 	}
15240 }
15241 
15242 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg,
15243 				  struct bpf_reg_state *src_reg)
15244 {
15245 	u32 *dst_umin = &dst_reg->u32_min_value;
15246 	u32 *dst_umax = &dst_reg->u32_max_value;
15247 	u32 src_val = src_reg->u32_min_value; /* non-zero, const divisor */
15248 
15249 	*dst_umin = *dst_umin / src_val;
15250 	*dst_umax = *dst_umax / src_val;
15251 
15252 	/* Reset other ranges/tnum to unbounded/unknown. */
15253 	dst_reg->s32_min_value = S32_MIN;
15254 	dst_reg->s32_max_value = S32_MAX;
15255 	reset_reg64_and_tnum(dst_reg);
15256 }
15257 
15258 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg,
15259 				struct bpf_reg_state *src_reg)
15260 {
15261 	u64 *dst_umin = &dst_reg->umin_value;
15262 	u64 *dst_umax = &dst_reg->umax_value;
15263 	u64 src_val = src_reg->umin_value; /* non-zero, const divisor */
15264 
15265 	*dst_umin = div64_u64(*dst_umin, src_val);
15266 	*dst_umax = div64_u64(*dst_umax, src_val);
15267 
15268 	/* Reset other ranges/tnum to unbounded/unknown. */
15269 	dst_reg->smin_value = S64_MIN;
15270 	dst_reg->smax_value = S64_MAX;
15271 	reset_reg32_and_tnum(dst_reg);
15272 }
15273 
15274 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg,
15275 				  struct bpf_reg_state *src_reg)
15276 {
15277 	s32 *dst_smin = &dst_reg->s32_min_value;
15278 	s32 *dst_smax = &dst_reg->s32_max_value;
15279 	s32 src_val = src_reg->s32_min_value; /* non-zero, const divisor */
15280 	s32 res1, res2;
15281 
15282 	/* BPF div specification: S32_MIN / -1 = S32_MIN */
15283 	if (*dst_smin == S32_MIN && src_val == -1) {
15284 		/*
15285 		 * If the dividend range contains more than just S32_MIN,
15286 		 * we cannot precisely track the result, so it becomes unbounded.
15287 		 * e.g., [S32_MIN, S32_MIN+10]/(-1),
15288 		 *     = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)]
15289 		 *     = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX]
15290 		 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN.
15291 		 */
15292 		if (*dst_smax != S32_MIN) {
15293 			*dst_smin = S32_MIN;
15294 			*dst_smax = S32_MAX;
15295 		}
15296 		goto reset;
15297 	}
15298 
15299 	res1 = *dst_smin / src_val;
15300 	res2 = *dst_smax / src_val;
15301 	*dst_smin = min(res1, res2);
15302 	*dst_smax = max(res1, res2);
15303 
15304 reset:
15305 	/* Reset other ranges/tnum to unbounded/unknown. */
15306 	dst_reg->u32_min_value = 0;
15307 	dst_reg->u32_max_value = U32_MAX;
15308 	reset_reg64_and_tnum(dst_reg);
15309 }
15310 
15311 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg,
15312 				struct bpf_reg_state *src_reg)
15313 {
15314 	s64 *dst_smin = &dst_reg->smin_value;
15315 	s64 *dst_smax = &dst_reg->smax_value;
15316 	s64 src_val = src_reg->smin_value; /* non-zero, const divisor */
15317 	s64 res1, res2;
15318 
15319 	/* BPF div specification: S64_MIN / -1 = S64_MIN */
15320 	if (*dst_smin == S64_MIN && src_val == -1) {
15321 		/*
15322 		 * If the dividend range contains more than just S64_MIN,
15323 		 * we cannot precisely track the result, so it becomes unbounded.
15324 		 * e.g., [S64_MIN, S64_MIN+10]/(-1),
15325 		 *     = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)]
15326 		 *     = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX]
15327 		 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN.
15328 		 */
15329 		if (*dst_smax != S64_MIN) {
15330 			*dst_smin = S64_MIN;
15331 			*dst_smax = S64_MAX;
15332 		}
15333 		goto reset;
15334 	}
15335 
15336 	res1 = div64_s64(*dst_smin, src_val);
15337 	res2 = div64_s64(*dst_smax, src_val);
15338 	*dst_smin = min(res1, res2);
15339 	*dst_smax = max(res1, res2);
15340 
15341 reset:
15342 	/* Reset other ranges/tnum to unbounded/unknown. */
15343 	dst_reg->umin_value = 0;
15344 	dst_reg->umax_value = U64_MAX;
15345 	reset_reg32_and_tnum(dst_reg);
15346 }
15347 
15348 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg,
15349 				  struct bpf_reg_state *src_reg)
15350 {
15351 	u32 *dst_umin = &dst_reg->u32_min_value;
15352 	u32 *dst_umax = &dst_reg->u32_max_value;
15353 	u32 src_val = src_reg->u32_min_value; /* non-zero, const divisor */
15354 	u32 res_max = src_val - 1;
15355 
15356 	/*
15357 	 * If dst_umax <= res_max, the result remains unchanged.
15358 	 * e.g., [2, 5] % 10 = [2, 5].
15359 	 */
15360 	if (*dst_umax <= res_max)
15361 		return;
15362 
15363 	*dst_umin = 0;
15364 	*dst_umax = min(*dst_umax, res_max);
15365 
15366 	/* Reset other ranges/tnum to unbounded/unknown. */
15367 	dst_reg->s32_min_value = S32_MIN;
15368 	dst_reg->s32_max_value = S32_MAX;
15369 	reset_reg64_and_tnum(dst_reg);
15370 }
15371 
15372 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg,
15373 				struct bpf_reg_state *src_reg)
15374 {
15375 	u64 *dst_umin = &dst_reg->umin_value;
15376 	u64 *dst_umax = &dst_reg->umax_value;
15377 	u64 src_val = src_reg->umin_value; /* non-zero, const divisor */
15378 	u64 res_max = src_val - 1;
15379 
15380 	/*
15381 	 * If dst_umax <= res_max, the result remains unchanged.
15382 	 * e.g., [2, 5] % 10 = [2, 5].
15383 	 */
15384 	if (*dst_umax <= res_max)
15385 		return;
15386 
15387 	*dst_umin = 0;
15388 	*dst_umax = min(*dst_umax, res_max);
15389 
15390 	/* Reset other ranges/tnum to unbounded/unknown. */
15391 	dst_reg->smin_value = S64_MIN;
15392 	dst_reg->smax_value = S64_MAX;
15393 	reset_reg32_and_tnum(dst_reg);
15394 }
15395 
15396 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg,
15397 				  struct bpf_reg_state *src_reg)
15398 {
15399 	s32 *dst_smin = &dst_reg->s32_min_value;
15400 	s32 *dst_smax = &dst_reg->s32_max_value;
15401 	s32 src_val = src_reg->s32_min_value; /* non-zero, const divisor */
15402 
15403 	/*
15404 	 * Safe absolute value calculation:
15405 	 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648.
15406 	 * Here use unsigned integer to avoid overflow.
15407 	 */
15408 	u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val;
15409 
15410 	/*
15411 	 * Calculate the maximum possible absolute value of the result.
15412 	 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives
15413 	 * 2147483647 (S32_MAX), which fits perfectly in s32.
15414 	 */
15415 	s32 res_max_abs = src_abs - 1;
15416 
15417 	/*
15418 	 * If the dividend is already within the result range,
15419 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
15420 	 */
15421 	if (*dst_smin >= -res_max_abs && *dst_smax <= res_max_abs)
15422 		return;
15423 
15424 	/* General case: result has the same sign as the dividend. */
15425 	if (*dst_smin >= 0) {
15426 		*dst_smin = 0;
15427 		*dst_smax = min(*dst_smax, res_max_abs);
15428 	} else if (*dst_smax <= 0) {
15429 		*dst_smax = 0;
15430 		*dst_smin = max(*dst_smin, -res_max_abs);
15431 	} else {
15432 		*dst_smin = -res_max_abs;
15433 		*dst_smax = res_max_abs;
15434 	}
15435 
15436 	/* Reset other ranges/tnum to unbounded/unknown. */
15437 	dst_reg->u32_min_value = 0;
15438 	dst_reg->u32_max_value = U32_MAX;
15439 	reset_reg64_and_tnum(dst_reg);
15440 }
15441 
15442 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg,
15443 				struct bpf_reg_state *src_reg)
15444 {
15445 	s64 *dst_smin = &dst_reg->smin_value;
15446 	s64 *dst_smax = &dst_reg->smax_value;
15447 	s64 src_val = src_reg->smin_value; /* non-zero, const divisor */
15448 
15449 	/*
15450 	 * Safe absolute value calculation:
15451 	 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63.
15452 	 * Here use unsigned integer to avoid overflow.
15453 	 */
15454 	u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val;
15455 
15456 	/*
15457 	 * Calculate the maximum possible absolute value of the result.
15458 	 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives
15459 	 * 2^63 - 1 (S64_MAX), which fits perfectly in s64.
15460 	 */
15461 	s64 res_max_abs = src_abs - 1;
15462 
15463 	/*
15464 	 * If the dividend is already within the result range,
15465 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
15466 	 */
15467 	if (*dst_smin >= -res_max_abs && *dst_smax <= res_max_abs)
15468 		return;
15469 
15470 	/* General case: result has the same sign as the dividend. */
15471 	if (*dst_smin >= 0) {
15472 		*dst_smin = 0;
15473 		*dst_smax = min(*dst_smax, res_max_abs);
15474 	} else if (*dst_smax <= 0) {
15475 		*dst_smax = 0;
15476 		*dst_smin = max(*dst_smin, -res_max_abs);
15477 	} else {
15478 		*dst_smin = -res_max_abs;
15479 		*dst_smax = res_max_abs;
15480 	}
15481 
15482 	/* Reset other ranges/tnum to unbounded/unknown. */
15483 	dst_reg->umin_value = 0;
15484 	dst_reg->umax_value = U64_MAX;
15485 	reset_reg32_and_tnum(dst_reg);
15486 }
15487 
15488 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
15489 				 struct bpf_reg_state *src_reg)
15490 {
15491 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15492 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15493 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15494 	u32 umax_val = src_reg->u32_max_value;
15495 
15496 	if (src_known && dst_known) {
15497 		__mark_reg32_known(dst_reg, var32_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->u32_min_value = var32_off.value;
15505 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
15506 
15507 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15508 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15509 	 */
15510 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15511 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15512 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15513 	} else {
15514 		dst_reg->s32_min_value = S32_MIN;
15515 		dst_reg->s32_max_value = S32_MAX;
15516 	}
15517 }
15518 
15519 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
15520 			       struct bpf_reg_state *src_reg)
15521 {
15522 	bool src_known = tnum_is_const(src_reg->var_off);
15523 	bool dst_known = tnum_is_const(dst_reg->var_off);
15524 	u64 umax_val = src_reg->umax_value;
15525 
15526 	if (src_known && dst_known) {
15527 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15528 		return;
15529 	}
15530 
15531 	/* We get our minimum from the var_off, since that's inherently
15532 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
15533 	 */
15534 	dst_reg->umin_value = dst_reg->var_off.value;
15535 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
15536 
15537 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15538 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15539 	 */
15540 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15541 		dst_reg->smin_value = dst_reg->umin_value;
15542 		dst_reg->smax_value = dst_reg->umax_value;
15543 	} else {
15544 		dst_reg->smin_value = S64_MIN;
15545 		dst_reg->smax_value = S64_MAX;
15546 	}
15547 	/* We may learn something more from the var_off */
15548 	__update_reg_bounds(dst_reg);
15549 }
15550 
15551 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
15552 				struct bpf_reg_state *src_reg)
15553 {
15554 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15555 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15556 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15557 	u32 umin_val = src_reg->u32_min_value;
15558 
15559 	if (src_known && dst_known) {
15560 		__mark_reg32_known(dst_reg, var32_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->u32_min_value = max(dst_reg->u32_min_value, umin_val);
15568 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15569 
15570 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15571 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15572 	 */
15573 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15574 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15575 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15576 	} else {
15577 		dst_reg->s32_min_value = S32_MIN;
15578 		dst_reg->s32_max_value = S32_MAX;
15579 	}
15580 }
15581 
15582 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
15583 			      struct bpf_reg_state *src_reg)
15584 {
15585 	bool src_known = tnum_is_const(src_reg->var_off);
15586 	bool dst_known = tnum_is_const(dst_reg->var_off);
15587 	u64 umin_val = src_reg->umin_value;
15588 
15589 	if (src_known && dst_known) {
15590 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15591 		return;
15592 	}
15593 
15594 	/* We get our maximum from the var_off, and our minimum is the
15595 	 * maximum of the operands' minima
15596 	 */
15597 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
15598 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15599 
15600 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15601 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15602 	 */
15603 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15604 		dst_reg->smin_value = dst_reg->umin_value;
15605 		dst_reg->smax_value = dst_reg->umax_value;
15606 	} else {
15607 		dst_reg->smin_value = S64_MIN;
15608 		dst_reg->smax_value = S64_MAX;
15609 	}
15610 	/* We may learn something more from the var_off */
15611 	__update_reg_bounds(dst_reg);
15612 }
15613 
15614 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
15615 				 struct bpf_reg_state *src_reg)
15616 {
15617 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15618 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15619 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15620 
15621 	if (src_known && dst_known) {
15622 		__mark_reg32_known(dst_reg, var32_off.value);
15623 		return;
15624 	}
15625 
15626 	/* We get both minimum and maximum from the var32_off. */
15627 	dst_reg->u32_min_value = var32_off.value;
15628 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15629 
15630 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15631 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15632 	 */
15633 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15634 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15635 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15636 	} else {
15637 		dst_reg->s32_min_value = S32_MIN;
15638 		dst_reg->s32_max_value = S32_MAX;
15639 	}
15640 }
15641 
15642 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
15643 			       struct bpf_reg_state *src_reg)
15644 {
15645 	bool src_known = tnum_is_const(src_reg->var_off);
15646 	bool dst_known = tnum_is_const(dst_reg->var_off);
15647 
15648 	if (src_known && dst_known) {
15649 		/* dst_reg->var_off.value has been updated earlier */
15650 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15651 		return;
15652 	}
15653 
15654 	/* We get both minimum and maximum from the var_off. */
15655 	dst_reg->umin_value = dst_reg->var_off.value;
15656 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15657 
15658 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15659 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15660 	 */
15661 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15662 		dst_reg->smin_value = dst_reg->umin_value;
15663 		dst_reg->smax_value = dst_reg->umax_value;
15664 	} else {
15665 		dst_reg->smin_value = S64_MIN;
15666 		dst_reg->smax_value = S64_MAX;
15667 	}
15668 
15669 	__update_reg_bounds(dst_reg);
15670 }
15671 
15672 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15673 				   u64 umin_val, u64 umax_val)
15674 {
15675 	/* We lose all sign bit information (except what we can pick
15676 	 * up from var_off)
15677 	 */
15678 	dst_reg->s32_min_value = S32_MIN;
15679 	dst_reg->s32_max_value = S32_MAX;
15680 	/* If we might shift our top bit out, then we know nothing */
15681 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
15682 		dst_reg->u32_min_value = 0;
15683 		dst_reg->u32_max_value = U32_MAX;
15684 	} else {
15685 		dst_reg->u32_min_value <<= umin_val;
15686 		dst_reg->u32_max_value <<= umax_val;
15687 	}
15688 }
15689 
15690 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15691 				 struct bpf_reg_state *src_reg)
15692 {
15693 	u32 umax_val = src_reg->u32_max_value;
15694 	u32 umin_val = src_reg->u32_min_value;
15695 	/* u32 alu operation will zext upper bits */
15696 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15697 
15698 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15699 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
15700 	/* Not required but being careful mark reg64 bounds as unknown so
15701 	 * that we are forced to pick them up from tnum and zext later and
15702 	 * if some path skips this step we are still safe.
15703 	 */
15704 	__mark_reg64_unbounded(dst_reg);
15705 	__update_reg32_bounds(dst_reg);
15706 }
15707 
15708 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
15709 				   u64 umin_val, u64 umax_val)
15710 {
15711 	/* Special case <<32 because it is a common compiler pattern to sign
15712 	 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct
15713 	 * because s32 bounds don't flip sign when shifting to the left by
15714 	 * 32bits.
15715 	 */
15716 	if (umin_val == 32 && umax_val == 32) {
15717 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
15718 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
15719 	} else {
15720 		dst_reg->smax_value = S64_MAX;
15721 		dst_reg->smin_value = S64_MIN;
15722 	}
15723 
15724 	/* If we might shift our top bit out, then we know nothing */
15725 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
15726 		dst_reg->umin_value = 0;
15727 		dst_reg->umax_value = U64_MAX;
15728 	} else {
15729 		dst_reg->umin_value <<= umin_val;
15730 		dst_reg->umax_value <<= umax_val;
15731 	}
15732 }
15733 
15734 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
15735 			       struct bpf_reg_state *src_reg)
15736 {
15737 	u64 umax_val = src_reg->umax_value;
15738 	u64 umin_val = src_reg->umin_value;
15739 
15740 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
15741 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
15742 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15743 
15744 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
15745 	/* We may learn something more from the var_off */
15746 	__update_reg_bounds(dst_reg);
15747 }
15748 
15749 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
15750 				 struct bpf_reg_state *src_reg)
15751 {
15752 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15753 	u32 umax_val = src_reg->u32_max_value;
15754 	u32 umin_val = src_reg->u32_min_value;
15755 
15756 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15757 	 * be negative, then either:
15758 	 * 1) src_reg might be zero, so the sign bit of the result is
15759 	 *    unknown, so we lose our signed bounds
15760 	 * 2) it's known negative, thus the unsigned bounds capture the
15761 	 *    signed bounds
15762 	 * 3) the signed bounds cross zero, so they tell us nothing
15763 	 *    about the result
15764 	 * If the value in dst_reg is known nonnegative, then again the
15765 	 * unsigned bounds capture the signed bounds.
15766 	 * Thus, in all cases it suffices to blow away our signed bounds
15767 	 * and rely on inferring new ones from the unsigned bounds and
15768 	 * var_off of the result.
15769 	 */
15770 	dst_reg->s32_min_value = S32_MIN;
15771 	dst_reg->s32_max_value = S32_MAX;
15772 
15773 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
15774 	dst_reg->u32_min_value >>= umax_val;
15775 	dst_reg->u32_max_value >>= umin_val;
15776 
15777 	__mark_reg64_unbounded(dst_reg);
15778 	__update_reg32_bounds(dst_reg);
15779 }
15780 
15781 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
15782 			       struct bpf_reg_state *src_reg)
15783 {
15784 	u64 umax_val = src_reg->umax_value;
15785 	u64 umin_val = src_reg->umin_value;
15786 
15787 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15788 	 * be negative, then either:
15789 	 * 1) src_reg might be zero, so the sign bit of the result is
15790 	 *    unknown, so we lose our signed bounds
15791 	 * 2) it's known negative, thus the unsigned bounds capture the
15792 	 *    signed bounds
15793 	 * 3) the signed bounds cross zero, so they tell us nothing
15794 	 *    about the result
15795 	 * If the value in dst_reg is known nonnegative, then again the
15796 	 * unsigned bounds capture the signed bounds.
15797 	 * Thus, in all cases it suffices to blow away our signed bounds
15798 	 * and rely on inferring new ones from the unsigned bounds and
15799 	 * var_off of the result.
15800 	 */
15801 	dst_reg->smin_value = S64_MIN;
15802 	dst_reg->smax_value = S64_MAX;
15803 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
15804 	dst_reg->umin_value >>= umax_val;
15805 	dst_reg->umax_value >>= umin_val;
15806 
15807 	/* Its not easy to operate on alu32 bounds here because it depends
15808 	 * on bits being shifted in. Take easy way out and mark unbounded
15809 	 * so we can recalculate later from tnum.
15810 	 */
15811 	__mark_reg32_unbounded(dst_reg);
15812 	__update_reg_bounds(dst_reg);
15813 }
15814 
15815 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
15816 				  struct bpf_reg_state *src_reg)
15817 {
15818 	u64 umin_val = src_reg->u32_min_value;
15819 
15820 	/* Upon reaching here, src_known is true and
15821 	 * umax_val is equal to umin_val.
15822 	 */
15823 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
15824 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
15825 
15826 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
15827 
15828 	/* blow away the dst_reg umin_value/umax_value and rely on
15829 	 * dst_reg var_off to refine the result.
15830 	 */
15831 	dst_reg->u32_min_value = 0;
15832 	dst_reg->u32_max_value = U32_MAX;
15833 
15834 	__mark_reg64_unbounded(dst_reg);
15835 	__update_reg32_bounds(dst_reg);
15836 }
15837 
15838 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
15839 				struct bpf_reg_state *src_reg)
15840 {
15841 	u64 umin_val = src_reg->umin_value;
15842 
15843 	/* Upon reaching here, src_known is true and umax_val is equal
15844 	 * to umin_val.
15845 	 */
15846 	dst_reg->smin_value >>= umin_val;
15847 	dst_reg->smax_value >>= umin_val;
15848 
15849 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
15850 
15851 	/* blow away the dst_reg umin_value/umax_value and rely on
15852 	 * dst_reg var_off to refine the result.
15853 	 */
15854 	dst_reg->umin_value = 0;
15855 	dst_reg->umax_value = U64_MAX;
15856 
15857 	/* Its not easy to operate on alu32 bounds here because it depends
15858 	 * on bits being shifted in from upper 32-bits. Take easy way out
15859 	 * and mark unbounded so we can recalculate later from tnum.
15860 	 */
15861 	__mark_reg32_unbounded(dst_reg);
15862 	__update_reg_bounds(dst_reg);
15863 }
15864 
15865 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn)
15866 {
15867 	/*
15868 	 * Byte swap operation - update var_off using tnum_bswap.
15869 	 * Three cases:
15870 	 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE)
15871 	 *    unconditional swap
15872 	 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE)
15873 	 *    swap on big-endian, truncation or no-op on little-endian
15874 	 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE)
15875 	 *    swap on little-endian, truncation or no-op on big-endian
15876 	 */
15877 
15878 	bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64;
15879 	bool to_le = BPF_SRC(insn->code) == BPF_TO_LE;
15880 	bool is_big_endian;
15881 #ifdef CONFIG_CPU_BIG_ENDIAN
15882 	is_big_endian = true;
15883 #else
15884 	is_big_endian = false;
15885 #endif
15886 	/* Apply bswap if alu64 or switch between big-endian and little-endian machines */
15887 	bool need_bswap = alu64 || (to_le == is_big_endian);
15888 
15889 	if (need_bswap) {
15890 		if (insn->imm == 16)
15891 			dst_reg->var_off = tnum_bswap16(dst_reg->var_off);
15892 		else if (insn->imm == 32)
15893 			dst_reg->var_off = tnum_bswap32(dst_reg->var_off);
15894 		else if (insn->imm == 64)
15895 			dst_reg->var_off = tnum_bswap64(dst_reg->var_off);
15896 		/*
15897 		 * Byteswap scrambles the range, so we must reset bounds.
15898 		 * Bounds will be re-derived from the new tnum later.
15899 		 */
15900 		__mark_reg_unbounded(dst_reg);
15901 	}
15902 	/* For bswap16/32, truncate dst register to match the swapped size */
15903 	if (insn->imm == 16 || insn->imm == 32)
15904 		coerce_reg_to_size(dst_reg, insn->imm / 8);
15905 }
15906 
15907 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
15908 					     const struct bpf_reg_state *src_reg)
15909 {
15910 	bool src_is_const = false;
15911 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
15912 
15913 	if (insn_bitness == 32) {
15914 		if (tnum_subreg_is_const(src_reg->var_off)
15915 		    && src_reg->s32_min_value == src_reg->s32_max_value
15916 		    && src_reg->u32_min_value == src_reg->u32_max_value)
15917 			src_is_const = true;
15918 	} else {
15919 		if (tnum_is_const(src_reg->var_off)
15920 		    && src_reg->smin_value == src_reg->smax_value
15921 		    && src_reg->umin_value == src_reg->umax_value)
15922 			src_is_const = true;
15923 	}
15924 
15925 	switch (BPF_OP(insn->code)) {
15926 	case BPF_ADD:
15927 	case BPF_SUB:
15928 	case BPF_NEG:
15929 	case BPF_AND:
15930 	case BPF_XOR:
15931 	case BPF_OR:
15932 	case BPF_MUL:
15933 	case BPF_END:
15934 		return true;
15935 
15936 	/*
15937 	 * Division and modulo operators range is only safe to compute when the
15938 	 * divisor is a constant.
15939 	 */
15940 	case BPF_DIV:
15941 	case BPF_MOD:
15942 		return src_is_const;
15943 
15944 	/* Shift operators range is only computable if shift dimension operand
15945 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
15946 	 * includes shifts by a negative number.
15947 	 */
15948 	case BPF_LSH:
15949 	case BPF_RSH:
15950 	case BPF_ARSH:
15951 		return (src_is_const && src_reg->umax_value < insn_bitness);
15952 	default:
15953 		return false;
15954 	}
15955 }
15956 
15957 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn,
15958 			      struct bpf_reg_state *dst_reg)
15959 {
15960 	struct bpf_verifier_state *branch;
15961 	struct bpf_reg_state *regs;
15962 	bool alu32;
15963 
15964 	if (dst_reg->smin_value == -1 && dst_reg->smax_value == 0)
15965 		alu32 = false;
15966 	else if (dst_reg->s32_min_value == -1 && dst_reg->s32_max_value == 0)
15967 		alu32 = true;
15968 	else
15969 		return 0;
15970 
15971 	branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
15972 	if (IS_ERR(branch))
15973 		return PTR_ERR(branch);
15974 
15975 	regs = branch->frame[branch->curframe]->regs;
15976 	if (alu32) {
15977 		__mark_reg32_known(&regs[insn->dst_reg], 0);
15978 		__mark_reg32_known(dst_reg, -1ull);
15979 	} else {
15980 		__mark_reg_known(&regs[insn->dst_reg], 0);
15981 		__mark_reg_known(dst_reg, -1ull);
15982 	}
15983 	return 0;
15984 }
15985 
15986 /* WARNING: This function does calculations on 64-bit values, but the actual
15987  * execution may occur on 32-bit values. Therefore, things like bitshifts
15988  * need extra checks in the 32-bit case.
15989  */
15990 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
15991 				      struct bpf_insn *insn,
15992 				      struct bpf_reg_state *dst_reg,
15993 				      struct bpf_reg_state src_reg)
15994 {
15995 	u8 opcode = BPF_OP(insn->code);
15996 	s16 off = insn->off;
15997 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15998 	int ret;
15999 
16000 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
16001 		__mark_reg_unknown(env, dst_reg);
16002 		return 0;
16003 	}
16004 
16005 	if (sanitize_needed(opcode)) {
16006 		ret = sanitize_val_alu(env, insn);
16007 		if (ret < 0)
16008 			return sanitize_err(env, insn, ret, NULL, NULL);
16009 	}
16010 
16011 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
16012 	 * There are two classes of instructions: The first class we track both
16013 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
16014 	 * greatest amount of precision when alu operations are mixed with jmp32
16015 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
16016 	 * and BPF_OR. This is possible because these ops have fairly easy to
16017 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
16018 	 * See alu32 verifier tests for examples. The second class of
16019 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
16020 	 * with regards to tracking sign/unsigned bounds because the bits may
16021 	 * cross subreg boundaries in the alu64 case. When this happens we mark
16022 	 * the reg unbounded in the subreg bound space and use the resulting
16023 	 * tnum to calculate an approximation of the sign/unsigned bounds.
16024 	 */
16025 	switch (opcode) {
16026 	case BPF_ADD:
16027 		scalar32_min_max_add(dst_reg, &src_reg);
16028 		scalar_min_max_add(dst_reg, &src_reg);
16029 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
16030 		break;
16031 	case BPF_SUB:
16032 		scalar32_min_max_sub(dst_reg, &src_reg);
16033 		scalar_min_max_sub(dst_reg, &src_reg);
16034 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
16035 		break;
16036 	case BPF_NEG:
16037 		env->fake_reg[0] = *dst_reg;
16038 		__mark_reg_known(dst_reg, 0);
16039 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
16040 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
16041 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
16042 		break;
16043 	case BPF_MUL:
16044 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
16045 		scalar32_min_max_mul(dst_reg, &src_reg);
16046 		scalar_min_max_mul(dst_reg, &src_reg);
16047 		break;
16048 	case BPF_DIV:
16049 		/* BPF div specification: x / 0 = 0 */
16050 		if ((alu32 && src_reg.u32_min_value == 0) || (!alu32 && src_reg.umin_value == 0)) {
16051 			___mark_reg_known(dst_reg, 0);
16052 			break;
16053 		}
16054 		if (alu32)
16055 			if (off == 1)
16056 				scalar32_min_max_sdiv(dst_reg, &src_reg);
16057 			else
16058 				scalar32_min_max_udiv(dst_reg, &src_reg);
16059 		else
16060 			if (off == 1)
16061 				scalar_min_max_sdiv(dst_reg, &src_reg);
16062 			else
16063 				scalar_min_max_udiv(dst_reg, &src_reg);
16064 		break;
16065 	case BPF_MOD:
16066 		/* BPF mod specification: x % 0 = x */
16067 		if ((alu32 && src_reg.u32_min_value == 0) || (!alu32 && src_reg.umin_value == 0))
16068 			break;
16069 		if (alu32)
16070 			if (off == 1)
16071 				scalar32_min_max_smod(dst_reg, &src_reg);
16072 			else
16073 				scalar32_min_max_umod(dst_reg, &src_reg);
16074 		else
16075 			if (off == 1)
16076 				scalar_min_max_smod(dst_reg, &src_reg);
16077 			else
16078 				scalar_min_max_umod(dst_reg, &src_reg);
16079 		break;
16080 	case BPF_AND:
16081 		if (tnum_is_const(src_reg.var_off)) {
16082 			ret = maybe_fork_scalars(env, insn, dst_reg);
16083 			if (ret)
16084 				return ret;
16085 		}
16086 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
16087 		scalar32_min_max_and(dst_reg, &src_reg);
16088 		scalar_min_max_and(dst_reg, &src_reg);
16089 		break;
16090 	case BPF_OR:
16091 		if (tnum_is_const(src_reg.var_off)) {
16092 			ret = maybe_fork_scalars(env, insn, dst_reg);
16093 			if (ret)
16094 				return ret;
16095 		}
16096 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
16097 		scalar32_min_max_or(dst_reg, &src_reg);
16098 		scalar_min_max_or(dst_reg, &src_reg);
16099 		break;
16100 	case BPF_XOR:
16101 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
16102 		scalar32_min_max_xor(dst_reg, &src_reg);
16103 		scalar_min_max_xor(dst_reg, &src_reg);
16104 		break;
16105 	case BPF_LSH:
16106 		if (alu32)
16107 			scalar32_min_max_lsh(dst_reg, &src_reg);
16108 		else
16109 			scalar_min_max_lsh(dst_reg, &src_reg);
16110 		break;
16111 	case BPF_RSH:
16112 		if (alu32)
16113 			scalar32_min_max_rsh(dst_reg, &src_reg);
16114 		else
16115 			scalar_min_max_rsh(dst_reg, &src_reg);
16116 		break;
16117 	case BPF_ARSH:
16118 		if (alu32)
16119 			scalar32_min_max_arsh(dst_reg, &src_reg);
16120 		else
16121 			scalar_min_max_arsh(dst_reg, &src_reg);
16122 		break;
16123 	case BPF_END:
16124 		scalar_byte_swap(dst_reg, insn);
16125 		break;
16126 	default:
16127 		break;
16128 	}
16129 
16130 	/*
16131 	 * ALU32 ops are zero extended into 64bit register.
16132 	 *
16133 	 * BPF_END is already handled inside the helper (truncation),
16134 	 * so skip zext here to avoid unexpected zero extension.
16135 	 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40
16136 	 * This is a 64bit byte swap operation with alu32==true,
16137 	 * but we should not zero extend the result.
16138 	 */
16139 	if (alu32 && opcode != BPF_END)
16140 		zext_32_to_64(dst_reg);
16141 	reg_bounds_sync(dst_reg);
16142 	return 0;
16143 }
16144 
16145 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
16146  * and var_off.
16147  */
16148 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
16149 				   struct bpf_insn *insn)
16150 {
16151 	struct bpf_verifier_state *vstate = env->cur_state;
16152 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
16153 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
16154 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
16155 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
16156 	u8 opcode = BPF_OP(insn->code);
16157 	int err;
16158 
16159 	dst_reg = &regs[insn->dst_reg];
16160 	src_reg = NULL;
16161 
16162 	if (dst_reg->type == PTR_TO_ARENA) {
16163 		struct bpf_insn_aux_data *aux = cur_aux(env);
16164 
16165 		if (BPF_CLASS(insn->code) == BPF_ALU64)
16166 			/*
16167 			 * 32-bit operations zero upper bits automatically.
16168 			 * 64-bit operations need to be converted to 32.
16169 			 */
16170 			aux->needs_zext = true;
16171 
16172 		/* Any arithmetic operations are allowed on arena pointers */
16173 		return 0;
16174 	}
16175 
16176 	if (dst_reg->type != SCALAR_VALUE)
16177 		ptr_reg = dst_reg;
16178 
16179 	if (BPF_SRC(insn->code) == BPF_X) {
16180 		src_reg = &regs[insn->src_reg];
16181 		if (src_reg->type != SCALAR_VALUE) {
16182 			if (dst_reg->type != SCALAR_VALUE) {
16183 				/* Combining two pointers by any ALU op yields
16184 				 * an arbitrary scalar. Disallow all math except
16185 				 * pointer subtraction
16186 				 */
16187 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
16188 					mark_reg_unknown(env, regs, insn->dst_reg);
16189 					return 0;
16190 				}
16191 				verbose(env, "R%d pointer %s pointer prohibited\n",
16192 					insn->dst_reg,
16193 					bpf_alu_string[opcode >> 4]);
16194 				return -EACCES;
16195 			} else {
16196 				/* scalar += pointer
16197 				 * This is legal, but we have to reverse our
16198 				 * src/dest handling in computing the range
16199 				 */
16200 				err = mark_chain_precision(env, insn->dst_reg);
16201 				if (err)
16202 					return err;
16203 				return adjust_ptr_min_max_vals(env, insn,
16204 							       src_reg, dst_reg);
16205 			}
16206 		} else if (ptr_reg) {
16207 			/* pointer += scalar */
16208 			err = mark_chain_precision(env, insn->src_reg);
16209 			if (err)
16210 				return err;
16211 			return adjust_ptr_min_max_vals(env, insn,
16212 						       dst_reg, src_reg);
16213 		} else if (dst_reg->precise) {
16214 			/* if dst_reg is precise, src_reg should be precise as well */
16215 			err = mark_chain_precision(env, insn->src_reg);
16216 			if (err)
16217 				return err;
16218 		}
16219 	} else {
16220 		/* Pretend the src is a reg with a known value, since we only
16221 		 * need to be able to read from this state.
16222 		 */
16223 		off_reg.type = SCALAR_VALUE;
16224 		__mark_reg_known(&off_reg, insn->imm);
16225 		src_reg = &off_reg;
16226 		if (ptr_reg) /* pointer += K */
16227 			return adjust_ptr_min_max_vals(env, insn,
16228 						       ptr_reg, src_reg);
16229 	}
16230 
16231 	/* Got here implies adding two SCALAR_VALUEs */
16232 	if (WARN_ON_ONCE(ptr_reg)) {
16233 		print_verifier_state(env, vstate, vstate->curframe, true);
16234 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
16235 		return -EFAULT;
16236 	}
16237 	if (WARN_ON(!src_reg)) {
16238 		print_verifier_state(env, vstate, vstate->curframe, true);
16239 		verbose(env, "verifier internal error: no src_reg\n");
16240 		return -EFAULT;
16241 	}
16242 	/*
16243 	 * For alu32 linked register tracking, we need to check dst_reg's
16244 	 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(),
16245 	 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX.
16246 	 */
16247 	u64 dst_umax = dst_reg->umax_value;
16248 
16249 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
16250 	if (err)
16251 		return err;
16252 	/*
16253 	 * Compilers can generate the code
16254 	 * r1 = r2
16255 	 * r1 += 0x1
16256 	 * if r2 < 1000 goto ...
16257 	 * use r1 in memory access
16258 	 * So remember constant delta between r2 and r1 and update r1 after
16259 	 * 'if' condition.
16260 	 */
16261 	if (env->bpf_capable &&
16262 	    (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) &&
16263 	    dst_reg->id && is_reg_const(src_reg, alu32)) {
16264 		u64 val = reg_const_value(src_reg, alu32);
16265 		s32 off;
16266 
16267 		if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX))
16268 			goto clear_id;
16269 
16270 		if (alu32 && (dst_umax > U32_MAX))
16271 			goto clear_id;
16272 
16273 		off = (s32)val;
16274 
16275 		if (BPF_OP(insn->code) == BPF_SUB) {
16276 			/* Negating S32_MIN would overflow */
16277 			if (off == S32_MIN)
16278 				goto clear_id;
16279 			off = -off;
16280 		}
16281 
16282 		if (dst_reg->id & BPF_ADD_CONST) {
16283 			/*
16284 			 * If the register already went through rX += val
16285 			 * we cannot accumulate another val into rx->off.
16286 			 */
16287 clear_id:
16288 			dst_reg->off = 0;
16289 			dst_reg->id = 0;
16290 		} else {
16291 			if (alu32)
16292 				dst_reg->id |= BPF_ADD_CONST32;
16293 			else
16294 				dst_reg->id |= BPF_ADD_CONST64;
16295 			dst_reg->off = off;
16296 		}
16297 	} else {
16298 		/*
16299 		 * Make sure ID is cleared otherwise dst_reg min/max could be
16300 		 * incorrectly propagated into other registers by sync_linked_regs()
16301 		 */
16302 		dst_reg->id = 0;
16303 	}
16304 	return 0;
16305 }
16306 
16307 /* check validity of 32-bit and 64-bit arithmetic operations */
16308 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
16309 {
16310 	struct bpf_reg_state *regs = cur_regs(env);
16311 	u8 opcode = BPF_OP(insn->code);
16312 	int err;
16313 
16314 	if (opcode == BPF_END || opcode == BPF_NEG) {
16315 		if (opcode == BPF_NEG) {
16316 			if (BPF_SRC(insn->code) != BPF_K ||
16317 			    insn->src_reg != BPF_REG_0 ||
16318 			    insn->off != 0 || insn->imm != 0) {
16319 				verbose(env, "BPF_NEG uses reserved fields\n");
16320 				return -EINVAL;
16321 			}
16322 		} else {
16323 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
16324 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
16325 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
16326 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
16327 				verbose(env, "BPF_END uses reserved fields\n");
16328 				return -EINVAL;
16329 			}
16330 		}
16331 
16332 		/* check src operand */
16333 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16334 		if (err)
16335 			return err;
16336 
16337 		if (is_pointer_value(env, insn->dst_reg)) {
16338 			verbose(env, "R%d pointer arithmetic prohibited\n",
16339 				insn->dst_reg);
16340 			return -EACCES;
16341 		}
16342 
16343 		/* check dest operand */
16344 		if ((opcode == BPF_NEG || opcode == BPF_END) &&
16345 		    regs[insn->dst_reg].type == SCALAR_VALUE) {
16346 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16347 			err = err ?: adjust_scalar_min_max_vals(env, insn,
16348 							 &regs[insn->dst_reg],
16349 							 regs[insn->dst_reg]);
16350 		} else {
16351 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
16352 		}
16353 		if (err)
16354 			return err;
16355 
16356 	} else if (opcode == BPF_MOV) {
16357 
16358 		if (BPF_SRC(insn->code) == BPF_X) {
16359 			if (BPF_CLASS(insn->code) == BPF_ALU) {
16360 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
16361 				    insn->imm) {
16362 					verbose(env, "BPF_MOV uses reserved fields\n");
16363 					return -EINVAL;
16364 				}
16365 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
16366 				if (insn->imm != 1 && insn->imm != 1u << 16) {
16367 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
16368 					return -EINVAL;
16369 				}
16370 				if (!env->prog->aux->arena) {
16371 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
16372 					return -EINVAL;
16373 				}
16374 			} else {
16375 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
16376 				     insn->off != 32) || insn->imm) {
16377 					verbose(env, "BPF_MOV uses reserved fields\n");
16378 					return -EINVAL;
16379 				}
16380 			}
16381 
16382 			/* check src operand */
16383 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16384 			if (err)
16385 				return err;
16386 		} else {
16387 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
16388 				verbose(env, "BPF_MOV uses reserved fields\n");
16389 				return -EINVAL;
16390 			}
16391 		}
16392 
16393 		/* check dest operand, mark as required later */
16394 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16395 		if (err)
16396 			return err;
16397 
16398 		if (BPF_SRC(insn->code) == BPF_X) {
16399 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
16400 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
16401 
16402 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
16403 				if (insn->imm) {
16404 					/* off == BPF_ADDR_SPACE_CAST */
16405 					mark_reg_unknown(env, regs, insn->dst_reg);
16406 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
16407 						dst_reg->type = PTR_TO_ARENA;
16408 						/* PTR_TO_ARENA is 32-bit */
16409 						dst_reg->subreg_def = env->insn_idx + 1;
16410 					}
16411 				} else if (insn->off == 0) {
16412 					/* case: R1 = R2
16413 					 * copy register state to dest reg
16414 					 */
16415 					assign_scalar_id_before_mov(env, src_reg);
16416 					copy_register_state(dst_reg, src_reg);
16417 					dst_reg->subreg_def = DEF_NOT_SUBREG;
16418 				} else {
16419 					/* case: R1 = (s8, s16 s32)R2 */
16420 					if (is_pointer_value(env, insn->src_reg)) {
16421 						verbose(env,
16422 							"R%d sign-extension part of pointer\n",
16423 							insn->src_reg);
16424 						return -EACCES;
16425 					} else if (src_reg->type == SCALAR_VALUE) {
16426 						bool no_sext;
16427 
16428 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
16429 						if (no_sext)
16430 							assign_scalar_id_before_mov(env, src_reg);
16431 						copy_register_state(dst_reg, src_reg);
16432 						if (!no_sext)
16433 							dst_reg->id = 0;
16434 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
16435 						dst_reg->subreg_def = DEF_NOT_SUBREG;
16436 					} else {
16437 						mark_reg_unknown(env, regs, insn->dst_reg);
16438 					}
16439 				}
16440 			} else {
16441 				/* R1 = (u32) R2 */
16442 				if (is_pointer_value(env, insn->src_reg)) {
16443 					verbose(env,
16444 						"R%d partial copy of pointer\n",
16445 						insn->src_reg);
16446 					return -EACCES;
16447 				} else if (src_reg->type == SCALAR_VALUE) {
16448 					if (insn->off == 0) {
16449 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
16450 
16451 						if (is_src_reg_u32)
16452 							assign_scalar_id_before_mov(env, src_reg);
16453 						copy_register_state(dst_reg, src_reg);
16454 						/* Make sure ID is cleared if src_reg is not in u32
16455 						 * range otherwise dst_reg min/max could be incorrectly
16456 						 * propagated into src_reg by sync_linked_regs()
16457 						 */
16458 						if (!is_src_reg_u32)
16459 							dst_reg->id = 0;
16460 						dst_reg->subreg_def = env->insn_idx + 1;
16461 					} else {
16462 						/* case: W1 = (s8, s16)W2 */
16463 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
16464 
16465 						if (no_sext)
16466 							assign_scalar_id_before_mov(env, src_reg);
16467 						copy_register_state(dst_reg, src_reg);
16468 						if (!no_sext)
16469 							dst_reg->id = 0;
16470 						dst_reg->subreg_def = env->insn_idx + 1;
16471 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
16472 					}
16473 				} else {
16474 					mark_reg_unknown(env, regs,
16475 							 insn->dst_reg);
16476 				}
16477 				zext_32_to_64(dst_reg);
16478 				reg_bounds_sync(dst_reg);
16479 			}
16480 		} else {
16481 			/* case: R = imm
16482 			 * remember the value we stored into this reg
16483 			 */
16484 			/* clear any state __mark_reg_known doesn't set */
16485 			mark_reg_unknown(env, regs, insn->dst_reg);
16486 			regs[insn->dst_reg].type = SCALAR_VALUE;
16487 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
16488 				__mark_reg_known(regs + insn->dst_reg,
16489 						 insn->imm);
16490 			} else {
16491 				__mark_reg_known(regs + insn->dst_reg,
16492 						 (u32)insn->imm);
16493 			}
16494 		}
16495 
16496 	} else if (opcode > BPF_END) {
16497 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
16498 		return -EINVAL;
16499 
16500 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
16501 
16502 		if (BPF_SRC(insn->code) == BPF_X) {
16503 			if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
16504 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
16505 				verbose(env, "BPF_ALU uses reserved fields\n");
16506 				return -EINVAL;
16507 			}
16508 			/* check src1 operand */
16509 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16510 			if (err)
16511 				return err;
16512 		} else {
16513 			if (insn->src_reg != BPF_REG_0 || (insn->off != 0 && insn->off != 1) ||
16514 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
16515 				verbose(env, "BPF_ALU uses reserved fields\n");
16516 				return -EINVAL;
16517 			}
16518 		}
16519 
16520 		/* check src2 operand */
16521 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16522 		if (err)
16523 			return err;
16524 
16525 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
16526 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
16527 			verbose(env, "div by zero\n");
16528 			return -EINVAL;
16529 		}
16530 
16531 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
16532 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
16533 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
16534 
16535 			if (insn->imm < 0 || insn->imm >= size) {
16536 				verbose(env, "invalid shift %d\n", insn->imm);
16537 				return -EINVAL;
16538 			}
16539 		}
16540 
16541 		/* check dest operand */
16542 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16543 		err = err ?: adjust_reg_min_max_vals(env, insn);
16544 		if (err)
16545 			return err;
16546 	}
16547 
16548 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
16549 }
16550 
16551 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
16552 				   struct bpf_reg_state *dst_reg,
16553 				   enum bpf_reg_type type,
16554 				   bool range_right_open)
16555 {
16556 	struct bpf_func_state *state;
16557 	struct bpf_reg_state *reg;
16558 	int new_range;
16559 
16560 	if (dst_reg->off < 0 ||
16561 	    (dst_reg->off == 0 && range_right_open))
16562 		/* This doesn't give us any range */
16563 		return;
16564 
16565 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
16566 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
16567 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
16568 		 * than pkt_end, but that's because it's also less than pkt.
16569 		 */
16570 		return;
16571 
16572 	new_range = dst_reg->off;
16573 	if (range_right_open)
16574 		new_range++;
16575 
16576 	/* Examples for register markings:
16577 	 *
16578 	 * pkt_data in dst register:
16579 	 *
16580 	 *   r2 = r3;
16581 	 *   r2 += 8;
16582 	 *   if (r2 > pkt_end) goto <handle exception>
16583 	 *   <access okay>
16584 	 *
16585 	 *   r2 = r3;
16586 	 *   r2 += 8;
16587 	 *   if (r2 < pkt_end) goto <access okay>
16588 	 *   <handle exception>
16589 	 *
16590 	 *   Where:
16591 	 *     r2 == dst_reg, pkt_end == src_reg
16592 	 *     r2=pkt(id=n,off=8,r=0)
16593 	 *     r3=pkt(id=n,off=0,r=0)
16594 	 *
16595 	 * pkt_data in src register:
16596 	 *
16597 	 *   r2 = r3;
16598 	 *   r2 += 8;
16599 	 *   if (pkt_end >= r2) goto <access okay>
16600 	 *   <handle exception>
16601 	 *
16602 	 *   r2 = r3;
16603 	 *   r2 += 8;
16604 	 *   if (pkt_end <= r2) goto <handle exception>
16605 	 *   <access okay>
16606 	 *
16607 	 *   Where:
16608 	 *     pkt_end == dst_reg, r2 == src_reg
16609 	 *     r2=pkt(id=n,off=8,r=0)
16610 	 *     r3=pkt(id=n,off=0,r=0)
16611 	 *
16612 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
16613 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
16614 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
16615 	 * the check.
16616 	 */
16617 
16618 	/* If our ids match, then we must have the same max_value.  And we
16619 	 * don't care about the other reg's fixed offset, since if it's too big
16620 	 * the range won't allow anything.
16621 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
16622 	 */
16623 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16624 		if (reg->type == type && reg->id == dst_reg->id)
16625 			/* keep the maximum range already checked */
16626 			reg->range = max(reg->range, new_range);
16627 	}));
16628 }
16629 
16630 /*
16631  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
16632  */
16633 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16634 				  u8 opcode, bool is_jmp32)
16635 {
16636 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
16637 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
16638 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
16639 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
16640 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
16641 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
16642 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
16643 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
16644 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
16645 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
16646 
16647 	if (reg1 == reg2) {
16648 		switch (opcode) {
16649 		case BPF_JGE:
16650 		case BPF_JLE:
16651 		case BPF_JSGE:
16652 		case BPF_JSLE:
16653 		case BPF_JEQ:
16654 			return 1;
16655 		case BPF_JGT:
16656 		case BPF_JLT:
16657 		case BPF_JSGT:
16658 		case BPF_JSLT:
16659 		case BPF_JNE:
16660 			return 0;
16661 		case BPF_JSET:
16662 			if (tnum_is_const(t1))
16663 				return t1.value != 0;
16664 			else
16665 				return (smin1 <= 0 && smax1 >= 0) ? -1 : 1;
16666 		default:
16667 			return -1;
16668 		}
16669 	}
16670 
16671 	switch (opcode) {
16672 	case BPF_JEQ:
16673 		/* constants, umin/umax and smin/smax checks would be
16674 		 * redundant in this case because they all should match
16675 		 */
16676 		if (tnum_is_const(t1) && tnum_is_const(t2))
16677 			return t1.value == t2.value;
16678 		if (!tnum_overlap(t1, t2))
16679 			return 0;
16680 		/* non-overlapping ranges */
16681 		if (umin1 > umax2 || umax1 < umin2)
16682 			return 0;
16683 		if (smin1 > smax2 || smax1 < smin2)
16684 			return 0;
16685 		if (!is_jmp32) {
16686 			/* if 64-bit ranges are inconclusive, see if we can
16687 			 * utilize 32-bit subrange knowledge to eliminate
16688 			 * branches that can't be taken a priori
16689 			 */
16690 			if (reg1->u32_min_value > reg2->u32_max_value ||
16691 			    reg1->u32_max_value < reg2->u32_min_value)
16692 				return 0;
16693 			if (reg1->s32_min_value > reg2->s32_max_value ||
16694 			    reg1->s32_max_value < reg2->s32_min_value)
16695 				return 0;
16696 		}
16697 		break;
16698 	case BPF_JNE:
16699 		/* constants, umin/umax and smin/smax checks would be
16700 		 * redundant in this case because they all should match
16701 		 */
16702 		if (tnum_is_const(t1) && tnum_is_const(t2))
16703 			return t1.value != t2.value;
16704 		if (!tnum_overlap(t1, t2))
16705 			return 1;
16706 		/* non-overlapping ranges */
16707 		if (umin1 > umax2 || umax1 < umin2)
16708 			return 1;
16709 		if (smin1 > smax2 || smax1 < smin2)
16710 			return 1;
16711 		if (!is_jmp32) {
16712 			/* if 64-bit ranges are inconclusive, see if we can
16713 			 * utilize 32-bit subrange knowledge to eliminate
16714 			 * branches that can't be taken a priori
16715 			 */
16716 			if (reg1->u32_min_value > reg2->u32_max_value ||
16717 			    reg1->u32_max_value < reg2->u32_min_value)
16718 				return 1;
16719 			if (reg1->s32_min_value > reg2->s32_max_value ||
16720 			    reg1->s32_max_value < reg2->s32_min_value)
16721 				return 1;
16722 		}
16723 		break;
16724 	case BPF_JSET:
16725 		if (!is_reg_const(reg2, is_jmp32)) {
16726 			swap(reg1, reg2);
16727 			swap(t1, t2);
16728 		}
16729 		if (!is_reg_const(reg2, is_jmp32))
16730 			return -1;
16731 		if ((~t1.mask & t1.value) & t2.value)
16732 			return 1;
16733 		if (!((t1.mask | t1.value) & t2.value))
16734 			return 0;
16735 		break;
16736 	case BPF_JGT:
16737 		if (umin1 > umax2)
16738 			return 1;
16739 		else if (umax1 <= umin2)
16740 			return 0;
16741 		break;
16742 	case BPF_JSGT:
16743 		if (smin1 > smax2)
16744 			return 1;
16745 		else if (smax1 <= smin2)
16746 			return 0;
16747 		break;
16748 	case BPF_JLT:
16749 		if (umax1 < umin2)
16750 			return 1;
16751 		else if (umin1 >= umax2)
16752 			return 0;
16753 		break;
16754 	case BPF_JSLT:
16755 		if (smax1 < smin2)
16756 			return 1;
16757 		else if (smin1 >= smax2)
16758 			return 0;
16759 		break;
16760 	case BPF_JGE:
16761 		if (umin1 >= umax2)
16762 			return 1;
16763 		else if (umax1 < umin2)
16764 			return 0;
16765 		break;
16766 	case BPF_JSGE:
16767 		if (smin1 >= smax2)
16768 			return 1;
16769 		else if (smax1 < smin2)
16770 			return 0;
16771 		break;
16772 	case BPF_JLE:
16773 		if (umax1 <= umin2)
16774 			return 1;
16775 		else if (umin1 > umax2)
16776 			return 0;
16777 		break;
16778 	case BPF_JSLE:
16779 		if (smax1 <= smin2)
16780 			return 1;
16781 		else if (smin1 > smax2)
16782 			return 0;
16783 		break;
16784 	}
16785 
16786 	return -1;
16787 }
16788 
16789 static int flip_opcode(u32 opcode)
16790 {
16791 	/* How can we transform "a <op> b" into "b <op> a"? */
16792 	static const u8 opcode_flip[16] = {
16793 		/* these stay the same */
16794 		[BPF_JEQ  >> 4] = BPF_JEQ,
16795 		[BPF_JNE  >> 4] = BPF_JNE,
16796 		[BPF_JSET >> 4] = BPF_JSET,
16797 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
16798 		[BPF_JGE  >> 4] = BPF_JLE,
16799 		[BPF_JGT  >> 4] = BPF_JLT,
16800 		[BPF_JLE  >> 4] = BPF_JGE,
16801 		[BPF_JLT  >> 4] = BPF_JGT,
16802 		[BPF_JSGE >> 4] = BPF_JSLE,
16803 		[BPF_JSGT >> 4] = BPF_JSLT,
16804 		[BPF_JSLE >> 4] = BPF_JSGE,
16805 		[BPF_JSLT >> 4] = BPF_JSGT
16806 	};
16807 	return opcode_flip[opcode >> 4];
16808 }
16809 
16810 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
16811 				   struct bpf_reg_state *src_reg,
16812 				   u8 opcode)
16813 {
16814 	struct bpf_reg_state *pkt;
16815 
16816 	if (src_reg->type == PTR_TO_PACKET_END) {
16817 		pkt = dst_reg;
16818 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
16819 		pkt = src_reg;
16820 		opcode = flip_opcode(opcode);
16821 	} else {
16822 		return -1;
16823 	}
16824 
16825 	if (pkt->range >= 0)
16826 		return -1;
16827 
16828 	switch (opcode) {
16829 	case BPF_JLE:
16830 		/* pkt <= pkt_end */
16831 		fallthrough;
16832 	case BPF_JGT:
16833 		/* pkt > pkt_end */
16834 		if (pkt->range == BEYOND_PKT_END)
16835 			/* pkt has at last one extra byte beyond pkt_end */
16836 			return opcode == BPF_JGT;
16837 		break;
16838 	case BPF_JLT:
16839 		/* pkt < pkt_end */
16840 		fallthrough;
16841 	case BPF_JGE:
16842 		/* pkt >= pkt_end */
16843 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
16844 			return opcode == BPF_JGE;
16845 		break;
16846 	}
16847 	return -1;
16848 }
16849 
16850 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
16851  * and return:
16852  *  1 - branch will be taken and "goto target" will be executed
16853  *  0 - branch will not be taken and fall-through to next insn
16854  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
16855  *      range [0,10]
16856  */
16857 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16858 			   u8 opcode, bool is_jmp32)
16859 {
16860 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
16861 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
16862 
16863 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
16864 		u64 val;
16865 
16866 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
16867 		if (!is_reg_const(reg2, is_jmp32)) {
16868 			opcode = flip_opcode(opcode);
16869 			swap(reg1, reg2);
16870 		}
16871 		/* and ensure that reg2 is a constant */
16872 		if (!is_reg_const(reg2, is_jmp32))
16873 			return -1;
16874 
16875 		if (!reg_not_null(reg1))
16876 			return -1;
16877 
16878 		/* If pointer is valid tests against zero will fail so we can
16879 		 * use this to direct branch taken.
16880 		 */
16881 		val = reg_const_value(reg2, is_jmp32);
16882 		if (val != 0)
16883 			return -1;
16884 
16885 		switch (opcode) {
16886 		case BPF_JEQ:
16887 			return 0;
16888 		case BPF_JNE:
16889 			return 1;
16890 		default:
16891 			return -1;
16892 		}
16893 	}
16894 
16895 	/* now deal with two scalars, but not necessarily constants */
16896 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
16897 }
16898 
16899 /* Opcode that corresponds to a *false* branch condition.
16900  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
16901  */
16902 static u8 rev_opcode(u8 opcode)
16903 {
16904 	switch (opcode) {
16905 	case BPF_JEQ:		return BPF_JNE;
16906 	case BPF_JNE:		return BPF_JEQ;
16907 	/* JSET doesn't have it's reverse opcode in BPF, so add
16908 	 * BPF_X flag to denote the reverse of that operation
16909 	 */
16910 	case BPF_JSET:		return BPF_JSET | BPF_X;
16911 	case BPF_JSET | BPF_X:	return BPF_JSET;
16912 	case BPF_JGE:		return BPF_JLT;
16913 	case BPF_JGT:		return BPF_JLE;
16914 	case BPF_JLE:		return BPF_JGT;
16915 	case BPF_JLT:		return BPF_JGE;
16916 	case BPF_JSGE:		return BPF_JSLT;
16917 	case BPF_JSGT:		return BPF_JSLE;
16918 	case BPF_JSLE:		return BPF_JSGT;
16919 	case BPF_JSLT:		return BPF_JSGE;
16920 	default:		return 0;
16921 	}
16922 }
16923 
16924 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
16925 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16926 				u8 opcode, bool is_jmp32)
16927 {
16928 	struct tnum t;
16929 	u64 val;
16930 
16931 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
16932 	switch (opcode) {
16933 	case BPF_JGE:
16934 	case BPF_JGT:
16935 	case BPF_JSGE:
16936 	case BPF_JSGT:
16937 		opcode = flip_opcode(opcode);
16938 		swap(reg1, reg2);
16939 		break;
16940 	default:
16941 		break;
16942 	}
16943 
16944 	switch (opcode) {
16945 	case BPF_JEQ:
16946 		if (is_jmp32) {
16947 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16948 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16949 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16950 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16951 			reg2->u32_min_value = reg1->u32_min_value;
16952 			reg2->u32_max_value = reg1->u32_max_value;
16953 			reg2->s32_min_value = reg1->s32_min_value;
16954 			reg2->s32_max_value = reg1->s32_max_value;
16955 
16956 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
16957 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16958 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
16959 		} else {
16960 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
16961 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16962 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
16963 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16964 			reg2->umin_value = reg1->umin_value;
16965 			reg2->umax_value = reg1->umax_value;
16966 			reg2->smin_value = reg1->smin_value;
16967 			reg2->smax_value = reg1->smax_value;
16968 
16969 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
16970 			reg2->var_off = reg1->var_off;
16971 		}
16972 		break;
16973 	case BPF_JNE:
16974 		if (!is_reg_const(reg2, is_jmp32))
16975 			swap(reg1, reg2);
16976 		if (!is_reg_const(reg2, is_jmp32))
16977 			break;
16978 
16979 		/* try to recompute the bound of reg1 if reg2 is a const and
16980 		 * is exactly the edge of reg1.
16981 		 */
16982 		val = reg_const_value(reg2, is_jmp32);
16983 		if (is_jmp32) {
16984 			/* u32_min_value is not equal to 0xffffffff at this point,
16985 			 * because otherwise u32_max_value is 0xffffffff as well,
16986 			 * in such a case both reg1 and reg2 would be constants,
16987 			 * jump would be predicted and reg_set_min_max() won't
16988 			 * be called.
16989 			 *
16990 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
16991 			 * below.
16992 			 */
16993 			if (reg1->u32_min_value == (u32)val)
16994 				reg1->u32_min_value++;
16995 			if (reg1->u32_max_value == (u32)val)
16996 				reg1->u32_max_value--;
16997 			if (reg1->s32_min_value == (s32)val)
16998 				reg1->s32_min_value++;
16999 			if (reg1->s32_max_value == (s32)val)
17000 				reg1->s32_max_value--;
17001 		} else {
17002 			if (reg1->umin_value == (u64)val)
17003 				reg1->umin_value++;
17004 			if (reg1->umax_value == (u64)val)
17005 				reg1->umax_value--;
17006 			if (reg1->smin_value == (s64)val)
17007 				reg1->smin_value++;
17008 			if (reg1->smax_value == (s64)val)
17009 				reg1->smax_value--;
17010 		}
17011 		break;
17012 	case BPF_JSET:
17013 		if (!is_reg_const(reg2, is_jmp32))
17014 			swap(reg1, reg2);
17015 		if (!is_reg_const(reg2, is_jmp32))
17016 			break;
17017 		val = reg_const_value(reg2, is_jmp32);
17018 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
17019 		 * requires single bit to learn something useful. E.g., if we
17020 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
17021 		 * are actually set? We can learn something definite only if
17022 		 * it's a single-bit value to begin with.
17023 		 *
17024 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
17025 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
17026 		 * bit 1 is set, which we can readily use in adjustments.
17027 		 */
17028 		if (!is_power_of_2(val))
17029 			break;
17030 		if (is_jmp32) {
17031 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
17032 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
17033 		} else {
17034 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
17035 		}
17036 		break;
17037 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
17038 		if (!is_reg_const(reg2, is_jmp32))
17039 			swap(reg1, reg2);
17040 		if (!is_reg_const(reg2, is_jmp32))
17041 			break;
17042 		val = reg_const_value(reg2, is_jmp32);
17043 		/* Forget the ranges before narrowing tnums, to avoid invariant
17044 		 * violations if we're on a dead branch.
17045 		 */
17046 		__mark_reg_unbounded(reg1);
17047 		if (is_jmp32) {
17048 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
17049 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
17050 		} else {
17051 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
17052 		}
17053 		break;
17054 	case BPF_JLE:
17055 		if (is_jmp32) {
17056 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
17057 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
17058 		} else {
17059 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
17060 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
17061 		}
17062 		break;
17063 	case BPF_JLT:
17064 		if (is_jmp32) {
17065 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
17066 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
17067 		} else {
17068 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
17069 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
17070 		}
17071 		break;
17072 	case BPF_JSLE:
17073 		if (is_jmp32) {
17074 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
17075 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
17076 		} else {
17077 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
17078 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
17079 		}
17080 		break;
17081 	case BPF_JSLT:
17082 		if (is_jmp32) {
17083 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
17084 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
17085 		} else {
17086 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
17087 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
17088 		}
17089 		break;
17090 	default:
17091 		return;
17092 	}
17093 }
17094 
17095 /* Adjusts the register min/max values in the case that the dst_reg and
17096  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
17097  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
17098  * Technically we can do similar adjustments for pointers to the same object,
17099  * but we don't support that right now.
17100  */
17101 static int reg_set_min_max(struct bpf_verifier_env *env,
17102 			   struct bpf_reg_state *true_reg1,
17103 			   struct bpf_reg_state *true_reg2,
17104 			   struct bpf_reg_state *false_reg1,
17105 			   struct bpf_reg_state *false_reg2,
17106 			   u8 opcode, bool is_jmp32)
17107 {
17108 	int err;
17109 
17110 	/* If either register is a pointer, we can't learn anything about its
17111 	 * variable offset from the compare (unless they were a pointer into
17112 	 * the same object, but we don't bother with that).
17113 	 */
17114 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
17115 		return 0;
17116 
17117 	/* We compute branch direction for same SCALAR_VALUE registers in
17118 	 * is_scalar_branch_taken(). For unknown branch directions (e.g., BPF_JSET)
17119 	 * on the same registers, we don't need to adjust the min/max values.
17120 	 */
17121 	if (false_reg1 == false_reg2)
17122 		return 0;
17123 
17124 	/* fallthrough (FALSE) branch */
17125 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
17126 	reg_bounds_sync(false_reg1);
17127 	reg_bounds_sync(false_reg2);
17128 
17129 	/* jump (TRUE) branch */
17130 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
17131 	reg_bounds_sync(true_reg1);
17132 	reg_bounds_sync(true_reg2);
17133 
17134 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
17135 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
17136 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
17137 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
17138 	return err;
17139 }
17140 
17141 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
17142 				 struct bpf_reg_state *reg, u32 id,
17143 				 bool is_null)
17144 {
17145 	if (type_may_be_null(reg->type) && reg->id == id &&
17146 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
17147 		/* Old offset (both fixed and variable parts) should have been
17148 		 * known-zero, because we don't allow pointer arithmetic on
17149 		 * pointers that might be NULL. If we see this happening, don't
17150 		 * convert the register.
17151 		 *
17152 		 * But in some cases, some helpers that return local kptrs
17153 		 * advance offset for the returned pointer. In those cases, it
17154 		 * is fine to expect to see reg->off.
17155 		 */
17156 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
17157 			return;
17158 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
17159 		    WARN_ON_ONCE(reg->off))
17160 			return;
17161 
17162 		if (is_null) {
17163 			reg->type = SCALAR_VALUE;
17164 			/* We don't need id and ref_obj_id from this point
17165 			 * onwards anymore, thus we should better reset it,
17166 			 * so that state pruning has chances to take effect.
17167 			 */
17168 			reg->id = 0;
17169 			reg->ref_obj_id = 0;
17170 
17171 			return;
17172 		}
17173 
17174 		mark_ptr_not_null_reg(reg);
17175 
17176 		if (!reg_may_point_to_spin_lock(reg)) {
17177 			/* For not-NULL ptr, reg->ref_obj_id will be reset
17178 			 * in release_reference().
17179 			 *
17180 			 * reg->id is still used by spin_lock ptr. Other
17181 			 * than spin_lock ptr type, reg->id can be reset.
17182 			 */
17183 			reg->id = 0;
17184 		}
17185 	}
17186 }
17187 
17188 /* The logic is similar to find_good_pkt_pointers(), both could eventually
17189  * be folded together at some point.
17190  */
17191 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
17192 				  bool is_null)
17193 {
17194 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
17195 	struct bpf_reg_state *regs = state->regs, *reg;
17196 	u32 ref_obj_id = regs[regno].ref_obj_id;
17197 	u32 id = regs[regno].id;
17198 
17199 	if (ref_obj_id && ref_obj_id == id && is_null)
17200 		/* regs[regno] is in the " == NULL" branch.
17201 		 * No one could have freed the reference state before
17202 		 * doing the NULL check.
17203 		 */
17204 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
17205 
17206 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
17207 		mark_ptr_or_null_reg(state, reg, id, is_null);
17208 	}));
17209 }
17210 
17211 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
17212 				   struct bpf_reg_state *dst_reg,
17213 				   struct bpf_reg_state *src_reg,
17214 				   struct bpf_verifier_state *this_branch,
17215 				   struct bpf_verifier_state *other_branch)
17216 {
17217 	if (BPF_SRC(insn->code) != BPF_X)
17218 		return false;
17219 
17220 	/* Pointers are always 64-bit. */
17221 	if (BPF_CLASS(insn->code) == BPF_JMP32)
17222 		return false;
17223 
17224 	switch (BPF_OP(insn->code)) {
17225 	case BPF_JGT:
17226 		if ((dst_reg->type == PTR_TO_PACKET &&
17227 		     src_reg->type == PTR_TO_PACKET_END) ||
17228 		    (dst_reg->type == PTR_TO_PACKET_META &&
17229 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
17230 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
17231 			find_good_pkt_pointers(this_branch, dst_reg,
17232 					       dst_reg->type, false);
17233 			mark_pkt_end(other_branch, insn->dst_reg, true);
17234 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
17235 			    src_reg->type == PTR_TO_PACKET) ||
17236 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
17237 			    src_reg->type == PTR_TO_PACKET_META)) {
17238 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
17239 			find_good_pkt_pointers(other_branch, src_reg,
17240 					       src_reg->type, true);
17241 			mark_pkt_end(this_branch, insn->src_reg, false);
17242 		} else {
17243 			return false;
17244 		}
17245 		break;
17246 	case BPF_JLT:
17247 		if ((dst_reg->type == PTR_TO_PACKET &&
17248 		     src_reg->type == PTR_TO_PACKET_END) ||
17249 		    (dst_reg->type == PTR_TO_PACKET_META &&
17250 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
17251 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
17252 			find_good_pkt_pointers(other_branch, dst_reg,
17253 					       dst_reg->type, true);
17254 			mark_pkt_end(this_branch, insn->dst_reg, false);
17255 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
17256 			    src_reg->type == PTR_TO_PACKET) ||
17257 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
17258 			    src_reg->type == PTR_TO_PACKET_META)) {
17259 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
17260 			find_good_pkt_pointers(this_branch, src_reg,
17261 					       src_reg->type, false);
17262 			mark_pkt_end(other_branch, insn->src_reg, true);
17263 		} else {
17264 			return false;
17265 		}
17266 		break;
17267 	case BPF_JGE:
17268 		if ((dst_reg->type == PTR_TO_PACKET &&
17269 		     src_reg->type == PTR_TO_PACKET_END) ||
17270 		    (dst_reg->type == PTR_TO_PACKET_META &&
17271 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
17272 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
17273 			find_good_pkt_pointers(this_branch, dst_reg,
17274 					       dst_reg->type, true);
17275 			mark_pkt_end(other_branch, insn->dst_reg, false);
17276 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
17277 			    src_reg->type == PTR_TO_PACKET) ||
17278 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
17279 			    src_reg->type == PTR_TO_PACKET_META)) {
17280 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
17281 			find_good_pkt_pointers(other_branch, src_reg,
17282 					       src_reg->type, false);
17283 			mark_pkt_end(this_branch, insn->src_reg, true);
17284 		} else {
17285 			return false;
17286 		}
17287 		break;
17288 	case BPF_JLE:
17289 		if ((dst_reg->type == PTR_TO_PACKET &&
17290 		     src_reg->type == PTR_TO_PACKET_END) ||
17291 		    (dst_reg->type == PTR_TO_PACKET_META &&
17292 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
17293 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
17294 			find_good_pkt_pointers(other_branch, dst_reg,
17295 					       dst_reg->type, false);
17296 			mark_pkt_end(this_branch, insn->dst_reg, true);
17297 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
17298 			    src_reg->type == PTR_TO_PACKET) ||
17299 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
17300 			    src_reg->type == PTR_TO_PACKET_META)) {
17301 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
17302 			find_good_pkt_pointers(this_branch, src_reg,
17303 					       src_reg->type, true);
17304 			mark_pkt_end(other_branch, insn->src_reg, false);
17305 		} else {
17306 			return false;
17307 		}
17308 		break;
17309 	default:
17310 		return false;
17311 	}
17312 
17313 	return true;
17314 }
17315 
17316 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
17317 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
17318 {
17319 	struct linked_reg *e;
17320 
17321 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
17322 		return;
17323 
17324 	e = linked_regs_push(reg_set);
17325 	if (e) {
17326 		e->frameno = frameno;
17327 		e->is_reg = is_reg;
17328 		e->regno = spi_or_reg;
17329 	} else {
17330 		reg->id = 0;
17331 	}
17332 }
17333 
17334 /* For all R being scalar registers or spilled scalar registers
17335  * in verifier state, save R in linked_regs if R->id == id.
17336  * If there are too many Rs sharing same id, reset id for leftover Rs.
17337  */
17338 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
17339 				struct linked_regs *linked_regs)
17340 {
17341 	struct bpf_func_state *func;
17342 	struct bpf_reg_state *reg;
17343 	int i, j;
17344 
17345 	id = id & ~BPF_ADD_CONST;
17346 	for (i = vstate->curframe; i >= 0; i--) {
17347 		func = vstate->frame[i];
17348 		for (j = 0; j < BPF_REG_FP; j++) {
17349 			reg = &func->regs[j];
17350 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
17351 		}
17352 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
17353 			if (!is_spilled_reg(&func->stack[j]))
17354 				continue;
17355 			reg = &func->stack[j].spilled_ptr;
17356 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
17357 		}
17358 	}
17359 }
17360 
17361 /* For all R in linked_regs, copy known_reg range into R
17362  * if R->id == known_reg->id.
17363  */
17364 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,
17365 			     struct bpf_reg_state *known_reg, struct linked_regs *linked_regs)
17366 {
17367 	struct bpf_reg_state fake_reg;
17368 	struct bpf_reg_state *reg;
17369 	struct linked_reg *e;
17370 	int i;
17371 
17372 	for (i = 0; i < linked_regs->cnt; ++i) {
17373 		e = &linked_regs->entries[i];
17374 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
17375 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
17376 		if (reg->type != SCALAR_VALUE || reg == known_reg)
17377 			continue;
17378 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
17379 			continue;
17380 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
17381 		    reg->off == known_reg->off) {
17382 			s32 saved_subreg_def = reg->subreg_def;
17383 
17384 			copy_register_state(reg, known_reg);
17385 			reg->subreg_def = saved_subreg_def;
17386 		} else {
17387 			s32 saved_subreg_def = reg->subreg_def;
17388 			s32 saved_off = reg->off;
17389 			u32 saved_id = reg->id;
17390 
17391 			fake_reg.type = SCALAR_VALUE;
17392 			__mark_reg_known(&fake_reg, (s64)reg->off - (s64)known_reg->off);
17393 
17394 			/* reg = known_reg; reg += delta */
17395 			copy_register_state(reg, known_reg);
17396 			/*
17397 			 * Must preserve off, id and subreg_def flag,
17398 			 * otherwise another sync_linked_regs() will be incorrect.
17399 			 */
17400 			reg->off = saved_off;
17401 			reg->id = saved_id;
17402 			reg->subreg_def = saved_subreg_def;
17403 
17404 			scalar32_min_max_add(reg, &fake_reg);
17405 			scalar_min_max_add(reg, &fake_reg);
17406 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
17407 			if (known_reg->id & BPF_ADD_CONST32)
17408 				zext_32_to_64(reg);
17409 			reg_bounds_sync(reg);
17410 		}
17411 		if (e->is_reg)
17412 			mark_reg_scratched(env, e->regno);
17413 		else
17414 			mark_stack_slot_scratched(env, e->spi);
17415 	}
17416 }
17417 
17418 static int check_cond_jmp_op(struct bpf_verifier_env *env,
17419 			     struct bpf_insn *insn, int *insn_idx)
17420 {
17421 	struct bpf_verifier_state *this_branch = env->cur_state;
17422 	struct bpf_verifier_state *other_branch;
17423 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
17424 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17425 	struct bpf_reg_state *eq_branch_regs;
17426 	struct linked_regs linked_regs = {};
17427 	u8 opcode = BPF_OP(insn->code);
17428 	int insn_flags = 0;
17429 	bool is_jmp32;
17430 	int pred = -1;
17431 	int err;
17432 
17433 	/* Only conditional jumps are expected to reach here. */
17434 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
17435 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17436 		return -EINVAL;
17437 	}
17438 
17439 	if (opcode == BPF_JCOND) {
17440 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
17441 		int idx = *insn_idx;
17442 
17443 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
17444 		    insn->src_reg != BPF_MAY_GOTO ||
17445 		    insn->dst_reg || insn->imm) {
17446 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
17447 			return -EINVAL;
17448 		}
17449 		prev_st = find_prev_entry(env, cur_st->parent, idx);
17450 
17451 		/* branch out 'fallthrough' insn as a new state to explore */
17452 		queued_st = push_stack(env, idx + 1, idx, false);
17453 		if (IS_ERR(queued_st))
17454 			return PTR_ERR(queued_st);
17455 
17456 		queued_st->may_goto_depth++;
17457 		if (prev_st)
17458 			widen_imprecise_scalars(env, prev_st, queued_st);
17459 		*insn_idx += insn->off;
17460 		return 0;
17461 	}
17462 
17463 	/* check src2 operand */
17464 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17465 	if (err)
17466 		return err;
17467 
17468 	dst_reg = &regs[insn->dst_reg];
17469 	if (BPF_SRC(insn->code) == BPF_X) {
17470 		if (insn->imm != 0) {
17471 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17472 			return -EINVAL;
17473 		}
17474 
17475 		/* check src1 operand */
17476 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
17477 		if (err)
17478 			return err;
17479 
17480 		src_reg = &regs[insn->src_reg];
17481 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
17482 		    is_pointer_value(env, insn->src_reg)) {
17483 			verbose(env, "R%d pointer comparison prohibited\n",
17484 				insn->src_reg);
17485 			return -EACCES;
17486 		}
17487 
17488 		if (src_reg->type == PTR_TO_STACK)
17489 			insn_flags |= INSN_F_SRC_REG_STACK;
17490 		if (dst_reg->type == PTR_TO_STACK)
17491 			insn_flags |= INSN_F_DST_REG_STACK;
17492 	} else {
17493 		if (insn->src_reg != BPF_REG_0) {
17494 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17495 			return -EINVAL;
17496 		}
17497 		src_reg = &env->fake_reg[0];
17498 		memset(src_reg, 0, sizeof(*src_reg));
17499 		src_reg->type = SCALAR_VALUE;
17500 		__mark_reg_known(src_reg, insn->imm);
17501 
17502 		if (dst_reg->type == PTR_TO_STACK)
17503 			insn_flags |= INSN_F_DST_REG_STACK;
17504 	}
17505 
17506 	if (insn_flags) {
17507 		err = push_jmp_history(env, this_branch, insn_flags, 0);
17508 		if (err)
17509 			return err;
17510 	}
17511 
17512 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
17513 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
17514 	if (pred >= 0) {
17515 		/* If we get here with a dst_reg pointer type it is because
17516 		 * above is_branch_taken() special cased the 0 comparison.
17517 		 */
17518 		if (!__is_pointer_value(false, dst_reg))
17519 			err = mark_chain_precision(env, insn->dst_reg);
17520 		if (BPF_SRC(insn->code) == BPF_X && !err &&
17521 		    !__is_pointer_value(false, src_reg))
17522 			err = mark_chain_precision(env, insn->src_reg);
17523 		if (err)
17524 			return err;
17525 	}
17526 
17527 	if (pred == 1) {
17528 		/* Only follow the goto, ignore fall-through. If needed, push
17529 		 * the fall-through branch for simulation under speculative
17530 		 * execution.
17531 		 */
17532 		if (!env->bypass_spec_v1) {
17533 			err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx);
17534 			if (err < 0)
17535 				return err;
17536 		}
17537 		if (env->log.level & BPF_LOG_LEVEL)
17538 			print_insn_state(env, this_branch, this_branch->curframe);
17539 		*insn_idx += insn->off;
17540 		return 0;
17541 	} else if (pred == 0) {
17542 		/* Only follow the fall-through branch, since that's where the
17543 		 * program will go. If needed, push the goto branch for
17544 		 * simulation under speculative execution.
17545 		 */
17546 		if (!env->bypass_spec_v1) {
17547 			err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1,
17548 							*insn_idx);
17549 			if (err < 0)
17550 				return err;
17551 		}
17552 		if (env->log.level & BPF_LOG_LEVEL)
17553 			print_insn_state(env, this_branch, this_branch->curframe);
17554 		return 0;
17555 	}
17556 
17557 	/* Push scalar registers sharing same ID to jump history,
17558 	 * do this before creating 'other_branch', so that both
17559 	 * 'this_branch' and 'other_branch' share this history
17560 	 * if parent state is created.
17561 	 */
17562 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
17563 		collect_linked_regs(this_branch, src_reg->id, &linked_regs);
17564 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
17565 		collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
17566 	if (linked_regs.cnt > 1) {
17567 		err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
17568 		if (err)
17569 			return err;
17570 	}
17571 
17572 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
17573 	if (IS_ERR(other_branch))
17574 		return PTR_ERR(other_branch);
17575 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17576 
17577 	if (BPF_SRC(insn->code) == BPF_X) {
17578 		err = reg_set_min_max(env,
17579 				      &other_branch_regs[insn->dst_reg],
17580 				      &other_branch_regs[insn->src_reg],
17581 				      dst_reg, src_reg, opcode, is_jmp32);
17582 	} else /* BPF_SRC(insn->code) == BPF_K */ {
17583 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
17584 		 * so that these are two different memory locations. The
17585 		 * src_reg is not used beyond here in context of K.
17586 		 */
17587 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
17588 		       sizeof(env->fake_reg[0]));
17589 		err = reg_set_min_max(env,
17590 				      &other_branch_regs[insn->dst_reg],
17591 				      &env->fake_reg[0],
17592 				      dst_reg, &env->fake_reg[1],
17593 				      opcode, is_jmp32);
17594 	}
17595 	if (err)
17596 		return err;
17597 
17598 	if (BPF_SRC(insn->code) == BPF_X &&
17599 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
17600 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
17601 		sync_linked_regs(env, this_branch, src_reg, &linked_regs);
17602 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg],
17603 				 &linked_regs);
17604 	}
17605 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
17606 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
17607 		sync_linked_regs(env, this_branch, dst_reg, &linked_regs);
17608 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg],
17609 				 &linked_regs);
17610 	}
17611 
17612 	/* if one pointer register is compared to another pointer
17613 	 * register check if PTR_MAYBE_NULL could be lifted.
17614 	 * E.g. register A - maybe null
17615 	 *      register B - not null
17616 	 * for JNE A, B, ... - A is not null in the false branch;
17617 	 * for JEQ A, B, ... - A is not null in the true branch.
17618 	 *
17619 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
17620 	 * not need to be null checked by the BPF program, i.e.,
17621 	 * could be null even without PTR_MAYBE_NULL marking, so
17622 	 * only propagate nullness when neither reg is that type.
17623 	 */
17624 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
17625 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
17626 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
17627 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
17628 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
17629 		eq_branch_regs = NULL;
17630 		switch (opcode) {
17631 		case BPF_JEQ:
17632 			eq_branch_regs = other_branch_regs;
17633 			break;
17634 		case BPF_JNE:
17635 			eq_branch_regs = regs;
17636 			break;
17637 		default:
17638 			/* do nothing */
17639 			break;
17640 		}
17641 		if (eq_branch_regs) {
17642 			if (type_may_be_null(src_reg->type))
17643 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
17644 			else
17645 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
17646 		}
17647 	}
17648 
17649 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
17650 	 * NOTE: these optimizations below are related with pointer comparison
17651 	 *       which will never be JMP32.
17652 	 */
17653 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
17654 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
17655 	    type_may_be_null(dst_reg->type)) {
17656 		/* Mark all identical registers in each branch as either
17657 		 * safe or unknown depending R == 0 or R != 0 conditional.
17658 		 */
17659 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
17660 				      opcode == BPF_JNE);
17661 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
17662 				      opcode == BPF_JEQ);
17663 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
17664 					   this_branch, other_branch) &&
17665 		   is_pointer_value(env, insn->dst_reg)) {
17666 		verbose(env, "R%d pointer comparison prohibited\n",
17667 			insn->dst_reg);
17668 		return -EACCES;
17669 	}
17670 	if (env->log.level & BPF_LOG_LEVEL)
17671 		print_insn_state(env, this_branch, this_branch->curframe);
17672 	return 0;
17673 }
17674 
17675 /* verify BPF_LD_IMM64 instruction */
17676 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17677 {
17678 	struct bpf_insn_aux_data *aux = cur_aux(env);
17679 	struct bpf_reg_state *regs = cur_regs(env);
17680 	struct bpf_reg_state *dst_reg;
17681 	struct bpf_map *map;
17682 	int err;
17683 
17684 	if (BPF_SIZE(insn->code) != BPF_DW) {
17685 		verbose(env, "invalid BPF_LD_IMM insn\n");
17686 		return -EINVAL;
17687 	}
17688 	if (insn->off != 0) {
17689 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17690 		return -EINVAL;
17691 	}
17692 
17693 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
17694 	if (err)
17695 		return err;
17696 
17697 	dst_reg = &regs[insn->dst_reg];
17698 	if (insn->src_reg == 0) {
17699 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
17700 
17701 		dst_reg->type = SCALAR_VALUE;
17702 		__mark_reg_known(&regs[insn->dst_reg], imm);
17703 		return 0;
17704 	}
17705 
17706 	/* All special src_reg cases are listed below. From this point onwards
17707 	 * we either succeed and assign a corresponding dst_reg->type after
17708 	 * zeroing the offset, or fail and reject the program.
17709 	 */
17710 	mark_reg_known_zero(env, regs, insn->dst_reg);
17711 
17712 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
17713 		dst_reg->type = aux->btf_var.reg_type;
17714 		switch (base_type(dst_reg->type)) {
17715 		case PTR_TO_MEM:
17716 			dst_reg->mem_size = aux->btf_var.mem_size;
17717 			break;
17718 		case PTR_TO_BTF_ID:
17719 			dst_reg->btf = aux->btf_var.btf;
17720 			dst_reg->btf_id = aux->btf_var.btf_id;
17721 			break;
17722 		default:
17723 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
17724 			return -EFAULT;
17725 		}
17726 		return 0;
17727 	}
17728 
17729 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
17730 		struct bpf_prog_aux *aux = env->prog->aux;
17731 		u32 subprogno = find_subprog(env,
17732 					     env->insn_idx + insn->imm + 1);
17733 
17734 		if (!aux->func_info) {
17735 			verbose(env, "missing btf func_info\n");
17736 			return -EINVAL;
17737 		}
17738 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
17739 			verbose(env, "callback function not static\n");
17740 			return -EINVAL;
17741 		}
17742 
17743 		dst_reg->type = PTR_TO_FUNC;
17744 		dst_reg->subprogno = subprogno;
17745 		return 0;
17746 	}
17747 
17748 	map = env->used_maps[aux->map_index];
17749 	dst_reg->map_ptr = map;
17750 
17751 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
17752 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
17753 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
17754 			__mark_reg_unknown(env, dst_reg);
17755 			return 0;
17756 		}
17757 		dst_reg->type = PTR_TO_MAP_VALUE;
17758 		dst_reg->off = aux->map_off;
17759 		WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY &&
17760 			     map->max_entries != 1);
17761 		/* We want reg->id to be same (0) as map_value is not distinct */
17762 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
17763 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
17764 		dst_reg->type = CONST_PTR_TO_MAP;
17765 	} else {
17766 		verifier_bug(env, "unexpected src reg value for ldimm64");
17767 		return -EFAULT;
17768 	}
17769 
17770 	return 0;
17771 }
17772 
17773 static bool may_access_skb(enum bpf_prog_type type)
17774 {
17775 	switch (type) {
17776 	case BPF_PROG_TYPE_SOCKET_FILTER:
17777 	case BPF_PROG_TYPE_SCHED_CLS:
17778 	case BPF_PROG_TYPE_SCHED_ACT:
17779 		return true;
17780 	default:
17781 		return false;
17782 	}
17783 }
17784 
17785 /* verify safety of LD_ABS|LD_IND instructions:
17786  * - they can only appear in the programs where ctx == skb
17787  * - since they are wrappers of function calls, they scratch R1-R5 registers,
17788  *   preserve R6-R9, and store return value into R0
17789  *
17790  * Implicit input:
17791  *   ctx == skb == R6 == CTX
17792  *
17793  * Explicit input:
17794  *   SRC == any register
17795  *   IMM == 32-bit immediate
17796  *
17797  * Output:
17798  *   R0 - 8/16/32-bit skb data converted to cpu endianness
17799  */
17800 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
17801 {
17802 	struct bpf_reg_state *regs = cur_regs(env);
17803 	static const int ctx_reg = BPF_REG_6;
17804 	u8 mode = BPF_MODE(insn->code);
17805 	int i, err;
17806 
17807 	if (!may_access_skb(resolve_prog_type(env->prog))) {
17808 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
17809 		return -EINVAL;
17810 	}
17811 
17812 	if (!env->ops->gen_ld_abs) {
17813 		verifier_bug(env, "gen_ld_abs is null");
17814 		return -EFAULT;
17815 	}
17816 
17817 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
17818 	    BPF_SIZE(insn->code) == BPF_DW ||
17819 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
17820 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
17821 		return -EINVAL;
17822 	}
17823 
17824 	/* check whether implicit source operand (register R6) is readable */
17825 	err = check_reg_arg(env, ctx_reg, SRC_OP);
17826 	if (err)
17827 		return err;
17828 
17829 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
17830 	 * gen_ld_abs() may terminate the program at runtime, leading to
17831 	 * reference leak.
17832 	 */
17833 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
17834 	if (err)
17835 		return err;
17836 
17837 	if (regs[ctx_reg].type != PTR_TO_CTX) {
17838 		verbose(env,
17839 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
17840 		return -EINVAL;
17841 	}
17842 
17843 	if (mode == BPF_IND) {
17844 		/* check explicit source operand */
17845 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
17846 		if (err)
17847 			return err;
17848 	}
17849 
17850 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
17851 	if (err < 0)
17852 		return err;
17853 
17854 	/* reset caller saved regs to unreadable */
17855 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
17856 		mark_reg_not_init(env, regs, caller_saved[i]);
17857 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
17858 	}
17859 
17860 	/* mark destination R0 register as readable, since it contains
17861 	 * the value fetched from the packet.
17862 	 * Already marked as written above.
17863 	 */
17864 	mark_reg_unknown(env, regs, BPF_REG_0);
17865 	/* ld_abs load up to 32-bit skb data. */
17866 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
17867 	return 0;
17868 }
17869 
17870 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
17871 {
17872 	const char *exit_ctx = "At program exit";
17873 	struct tnum enforce_attach_type_range = tnum_unknown;
17874 	const struct bpf_prog *prog = env->prog;
17875 	struct bpf_reg_state *reg = reg_state(env, regno);
17876 	struct bpf_retval_range range = retval_range(0, 1);
17877 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17878 	int err;
17879 	struct bpf_func_state *frame = env->cur_state->frame[0];
17880 	const bool is_subprog = frame->subprogno;
17881 	bool return_32bit = false;
17882 	const struct btf_type *reg_type, *ret_type = NULL;
17883 
17884 	/* LSM and struct_ops func-ptr's return type could be "void" */
17885 	if (!is_subprog || frame->in_exception_callback_fn) {
17886 		switch (prog_type) {
17887 		case BPF_PROG_TYPE_LSM:
17888 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
17889 				/* See below, can be 0 or 0-1 depending on hook. */
17890 				break;
17891 			if (!prog->aux->attach_func_proto->type)
17892 				return 0;
17893 			break;
17894 		case BPF_PROG_TYPE_STRUCT_OPS:
17895 			if (!prog->aux->attach_func_proto->type)
17896 				return 0;
17897 
17898 			if (frame->in_exception_callback_fn)
17899 				break;
17900 
17901 			/* Allow a struct_ops program to return a referenced kptr if it
17902 			 * matches the operator's return type and is in its unmodified
17903 			 * form. A scalar zero (i.e., a null pointer) is also allowed.
17904 			 */
17905 			reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
17906 			ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
17907 							prog->aux->attach_func_proto->type,
17908 							NULL);
17909 			if (ret_type && ret_type == reg_type && reg->ref_obj_id)
17910 				return __check_ptr_off_reg(env, reg, regno, false);
17911 			break;
17912 		default:
17913 			break;
17914 		}
17915 	}
17916 
17917 	/* eBPF calling convention is such that R0 is used
17918 	 * to return the value from eBPF program.
17919 	 * Make sure that it's readable at this time
17920 	 * of bpf_exit, which means that program wrote
17921 	 * something into it earlier
17922 	 */
17923 	err = check_reg_arg(env, regno, SRC_OP);
17924 	if (err)
17925 		return err;
17926 
17927 	if (is_pointer_value(env, regno)) {
17928 		verbose(env, "R%d leaks addr as return value\n", regno);
17929 		return -EACCES;
17930 	}
17931 
17932 	if (frame->in_async_callback_fn) {
17933 		exit_ctx = "At async callback return";
17934 		range = frame->callback_ret_range;
17935 		goto enforce_retval;
17936 	}
17937 
17938 	if (is_subprog && !frame->in_exception_callback_fn) {
17939 		if (reg->type != SCALAR_VALUE) {
17940 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
17941 				regno, reg_type_str(env, reg->type));
17942 			return -EINVAL;
17943 		}
17944 		return 0;
17945 	}
17946 
17947 	switch (prog_type) {
17948 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
17949 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
17950 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
17951 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
17952 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
17953 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
17954 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
17955 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
17956 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
17957 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
17958 			range = retval_range(1, 1);
17959 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
17960 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
17961 			range = retval_range(0, 3);
17962 		break;
17963 	case BPF_PROG_TYPE_CGROUP_SKB:
17964 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
17965 			range = retval_range(0, 3);
17966 			enforce_attach_type_range = tnum_range(2, 3);
17967 		}
17968 		break;
17969 	case BPF_PROG_TYPE_CGROUP_SOCK:
17970 	case BPF_PROG_TYPE_SOCK_OPS:
17971 	case BPF_PROG_TYPE_CGROUP_DEVICE:
17972 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
17973 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
17974 		break;
17975 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17976 		if (!env->prog->aux->attach_btf_id)
17977 			return 0;
17978 		range = retval_range(0, 0);
17979 		break;
17980 	case BPF_PROG_TYPE_TRACING:
17981 		switch (env->prog->expected_attach_type) {
17982 		case BPF_TRACE_FENTRY:
17983 		case BPF_TRACE_FEXIT:
17984 		case BPF_TRACE_FSESSION:
17985 			range = retval_range(0, 0);
17986 			break;
17987 		case BPF_TRACE_RAW_TP:
17988 		case BPF_MODIFY_RETURN:
17989 			return 0;
17990 		case BPF_TRACE_ITER:
17991 			break;
17992 		default:
17993 			return -ENOTSUPP;
17994 		}
17995 		break;
17996 	case BPF_PROG_TYPE_KPROBE:
17997 		switch (env->prog->expected_attach_type) {
17998 		case BPF_TRACE_KPROBE_SESSION:
17999 		case BPF_TRACE_UPROBE_SESSION:
18000 			range = retval_range(0, 1);
18001 			break;
18002 		default:
18003 			return 0;
18004 		}
18005 		break;
18006 	case BPF_PROG_TYPE_SK_LOOKUP:
18007 		range = retval_range(SK_DROP, SK_PASS);
18008 		break;
18009 
18010 	case BPF_PROG_TYPE_LSM:
18011 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
18012 			/* no range found, any return value is allowed */
18013 			if (!get_func_retval_range(env->prog, &range))
18014 				return 0;
18015 			/* no restricted range, any return value is allowed */
18016 			if (range.minval == S32_MIN && range.maxval == S32_MAX)
18017 				return 0;
18018 			return_32bit = true;
18019 		} else if (!env->prog->aux->attach_func_proto->type) {
18020 			/* Make sure programs that attach to void
18021 			 * hooks don't try to modify return value.
18022 			 */
18023 			range = retval_range(1, 1);
18024 		}
18025 		break;
18026 
18027 	case BPF_PROG_TYPE_NETFILTER:
18028 		range = retval_range(NF_DROP, NF_ACCEPT);
18029 		break;
18030 	case BPF_PROG_TYPE_STRUCT_OPS:
18031 		if (!ret_type)
18032 			return 0;
18033 		range = retval_range(0, 0);
18034 		break;
18035 	case BPF_PROG_TYPE_EXT:
18036 		/* freplace program can return anything as its return value
18037 		 * depends on the to-be-replaced kernel func or bpf program.
18038 		 */
18039 	default:
18040 		return 0;
18041 	}
18042 
18043 enforce_retval:
18044 	if (reg->type != SCALAR_VALUE) {
18045 		verbose(env, "%s the register R%d is not a known value (%s)\n",
18046 			exit_ctx, regno, reg_type_str(env, reg->type));
18047 		return -EINVAL;
18048 	}
18049 
18050 	err = mark_chain_precision(env, regno);
18051 	if (err)
18052 		return err;
18053 
18054 	if (!retval_range_within(range, reg, return_32bit)) {
18055 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
18056 		if (!is_subprog &&
18057 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
18058 		    prog_type == BPF_PROG_TYPE_LSM &&
18059 		    !prog->aux->attach_func_proto->type)
18060 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
18061 		return -EINVAL;
18062 	}
18063 
18064 	if (!tnum_is_unknown(enforce_attach_type_range) &&
18065 	    tnum_in(enforce_attach_type_range, reg->var_off))
18066 		env->prog->enforce_expected_attach_type = 1;
18067 	return 0;
18068 }
18069 
18070 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
18071 {
18072 	struct bpf_subprog_info *subprog;
18073 
18074 	subprog = bpf_find_containing_subprog(env, off);
18075 	subprog->changes_pkt_data = true;
18076 }
18077 
18078 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off)
18079 {
18080 	struct bpf_subprog_info *subprog;
18081 
18082 	subprog = bpf_find_containing_subprog(env, off);
18083 	subprog->might_sleep = true;
18084 }
18085 
18086 /* 't' is an index of a call-site.
18087  * 'w' is a callee entry point.
18088  * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
18089  * Rely on DFS traversal order and absence of recursive calls to guarantee that
18090  * callee's change_pkt_data marks would be correct at that moment.
18091  */
18092 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
18093 {
18094 	struct bpf_subprog_info *caller, *callee;
18095 
18096 	caller = bpf_find_containing_subprog(env, t);
18097 	callee = bpf_find_containing_subprog(env, w);
18098 	caller->changes_pkt_data |= callee->changes_pkt_data;
18099 	caller->might_sleep |= callee->might_sleep;
18100 }
18101 
18102 /* non-recursive DFS pseudo code
18103  * 1  procedure DFS-iterative(G,v):
18104  * 2      label v as discovered
18105  * 3      let S be a stack
18106  * 4      S.push(v)
18107  * 5      while S is not empty
18108  * 6            t <- S.peek()
18109  * 7            if t is what we're looking for:
18110  * 8                return t
18111  * 9            for all edges e in G.adjacentEdges(t) do
18112  * 10               if edge e is already labelled
18113  * 11                   continue with the next edge
18114  * 12               w <- G.adjacentVertex(t,e)
18115  * 13               if vertex w is not discovered and not explored
18116  * 14                   label e as tree-edge
18117  * 15                   label w as discovered
18118  * 16                   S.push(w)
18119  * 17                   continue at 5
18120  * 18               else if vertex w is discovered
18121  * 19                   label e as back-edge
18122  * 20               else
18123  * 21                   // vertex w is explored
18124  * 22                   label e as forward- or cross-edge
18125  * 23           label t as explored
18126  * 24           S.pop()
18127  *
18128  * convention:
18129  * 0x10 - discovered
18130  * 0x11 - discovered and fall-through edge labelled
18131  * 0x12 - discovered and fall-through and branch edges labelled
18132  * 0x20 - explored
18133  */
18134 
18135 enum {
18136 	DISCOVERED = 0x10,
18137 	EXPLORED = 0x20,
18138 	FALLTHROUGH = 1,
18139 	BRANCH = 2,
18140 };
18141 
18142 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
18143 {
18144 	env->insn_aux_data[idx].prune_point = true;
18145 }
18146 
18147 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
18148 {
18149 	return env->insn_aux_data[insn_idx].prune_point;
18150 }
18151 
18152 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
18153 {
18154 	env->insn_aux_data[idx].force_checkpoint = true;
18155 }
18156 
18157 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
18158 {
18159 	return env->insn_aux_data[insn_idx].force_checkpoint;
18160 }
18161 
18162 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
18163 {
18164 	env->insn_aux_data[idx].calls_callback = true;
18165 }
18166 
18167 bool bpf_calls_callback(struct bpf_verifier_env *env, int insn_idx)
18168 {
18169 	return env->insn_aux_data[insn_idx].calls_callback;
18170 }
18171 
18172 enum {
18173 	DONE_EXPLORING = 0,
18174 	KEEP_EXPLORING = 1,
18175 };
18176 
18177 /* t, w, e - match pseudo-code above:
18178  * t - index of current instruction
18179  * w - next instruction
18180  * e - edge
18181  */
18182 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
18183 {
18184 	int *insn_stack = env->cfg.insn_stack;
18185 	int *insn_state = env->cfg.insn_state;
18186 
18187 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
18188 		return DONE_EXPLORING;
18189 
18190 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
18191 		return DONE_EXPLORING;
18192 
18193 	if (w < 0 || w >= env->prog->len) {
18194 		verbose_linfo(env, t, "%d: ", t);
18195 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
18196 		return -EINVAL;
18197 	}
18198 
18199 	if (e == BRANCH) {
18200 		/* mark branch target for state pruning */
18201 		mark_prune_point(env, w);
18202 		mark_jmp_point(env, w);
18203 	}
18204 
18205 	if (insn_state[w] == 0) {
18206 		/* tree-edge */
18207 		insn_state[t] = DISCOVERED | e;
18208 		insn_state[w] = DISCOVERED;
18209 		if (env->cfg.cur_stack >= env->prog->len)
18210 			return -E2BIG;
18211 		insn_stack[env->cfg.cur_stack++] = w;
18212 		return KEEP_EXPLORING;
18213 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
18214 		if (env->bpf_capable)
18215 			return DONE_EXPLORING;
18216 		verbose_linfo(env, t, "%d: ", t);
18217 		verbose_linfo(env, w, "%d: ", w);
18218 		verbose(env, "back-edge from insn %d to %d\n", t, w);
18219 		return -EINVAL;
18220 	} else if (insn_state[w] == EXPLORED) {
18221 		/* forward- or cross-edge */
18222 		insn_state[t] = DISCOVERED | e;
18223 	} else {
18224 		verifier_bug(env, "insn state internal bug");
18225 		return -EFAULT;
18226 	}
18227 	return DONE_EXPLORING;
18228 }
18229 
18230 static int visit_func_call_insn(int t, struct bpf_insn *insns,
18231 				struct bpf_verifier_env *env,
18232 				bool visit_callee)
18233 {
18234 	int ret, insn_sz;
18235 	int w;
18236 
18237 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
18238 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
18239 	if (ret)
18240 		return ret;
18241 
18242 	mark_prune_point(env, t + insn_sz);
18243 	/* when we exit from subprog, we need to record non-linear history */
18244 	mark_jmp_point(env, t + insn_sz);
18245 
18246 	if (visit_callee) {
18247 		w = t + insns[t].imm + 1;
18248 		mark_prune_point(env, t);
18249 		merge_callee_effects(env, t, w);
18250 		ret = push_insn(t, w, BRANCH, env);
18251 	}
18252 	return ret;
18253 }
18254 
18255 /* Bitmask with 1s for all caller saved registers */
18256 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
18257 
18258 /* True if do_misc_fixups() replaces calls to helper number 'imm',
18259  * replacement patch is presumed to follow bpf_fastcall contract
18260  * (see mark_fastcall_pattern_for_call() below).
18261  */
18262 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
18263 {
18264 	switch (imm) {
18265 #ifdef CONFIG_X86_64
18266 	case BPF_FUNC_get_smp_processor_id:
18267 #ifdef CONFIG_SMP
18268 	case BPF_FUNC_get_current_task_btf:
18269 	case BPF_FUNC_get_current_task:
18270 #endif
18271 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
18272 #endif
18273 	default:
18274 		return false;
18275 	}
18276 }
18277 
18278 struct call_summary {
18279 	u8 num_params;
18280 	bool is_void;
18281 	bool fastcall;
18282 };
18283 
18284 /* If @call is a kfunc or helper call, fills @cs and returns true,
18285  * otherwise returns false.
18286  */
18287 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
18288 			     struct call_summary *cs)
18289 {
18290 	struct bpf_kfunc_call_arg_meta meta;
18291 	const struct bpf_func_proto *fn;
18292 	int i;
18293 
18294 	if (bpf_helper_call(call)) {
18295 
18296 		if (get_helper_proto(env, call->imm, &fn) < 0)
18297 			/* error would be reported later */
18298 			return false;
18299 		cs->fastcall = fn->allow_fastcall &&
18300 			       (verifier_inlines_helper_call(env, call->imm) ||
18301 				bpf_jit_inlines_helper_call(call->imm));
18302 		cs->is_void = fn->ret_type == RET_VOID;
18303 		cs->num_params = 0;
18304 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
18305 			if (fn->arg_type[i] == ARG_DONTCARE)
18306 				break;
18307 			cs->num_params++;
18308 		}
18309 		return true;
18310 	}
18311 
18312 	if (bpf_pseudo_kfunc_call(call)) {
18313 		int err;
18314 
18315 		err = fetch_kfunc_arg_meta(env, call->imm, call->off, &meta);
18316 		if (err < 0)
18317 			/* error would be reported later */
18318 			return false;
18319 		cs->num_params = btf_type_vlen(meta.func_proto);
18320 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
18321 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
18322 		return true;
18323 	}
18324 
18325 	return false;
18326 }
18327 
18328 /* LLVM define a bpf_fastcall function attribute.
18329  * This attribute means that function scratches only some of
18330  * the caller saved registers defined by ABI.
18331  * For BPF the set of such registers could be defined as follows:
18332  * - R0 is scratched only if function is non-void;
18333  * - R1-R5 are scratched only if corresponding parameter type is defined
18334  *   in the function prototype.
18335  *
18336  * The contract between kernel and clang allows to simultaneously use
18337  * such functions and maintain backwards compatibility with old
18338  * kernels that don't understand bpf_fastcall calls:
18339  *
18340  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
18341  *   registers are not scratched by the call;
18342  *
18343  * - as a post-processing step, clang visits each bpf_fastcall call and adds
18344  *   spill/fill for every live r0-r5;
18345  *
18346  * - stack offsets used for the spill/fill are allocated as lowest
18347  *   stack offsets in whole function and are not used for any other
18348  *   purposes;
18349  *
18350  * - when kernel loads a program, it looks for such patterns
18351  *   (bpf_fastcall function surrounded by spills/fills) and checks if
18352  *   spill/fill stack offsets are used exclusively in fastcall patterns;
18353  *
18354  * - if so, and if verifier or current JIT inlines the call to the
18355  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
18356  *   spill/fill pairs;
18357  *
18358  * - when old kernel loads a program, presence of spill/fill pairs
18359  *   keeps BPF program valid, albeit slightly less efficient.
18360  *
18361  * For example:
18362  *
18363  *   r1 = 1;
18364  *   r2 = 2;
18365  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
18366  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
18367  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
18368  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
18369  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
18370  *   r0 = r1;                            exit;
18371  *   r0 += r2;
18372  *   exit;
18373  *
18374  * The purpose of mark_fastcall_pattern_for_call is to:
18375  * - look for such patterns;
18376  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
18377  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
18378  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
18379  *   at which bpf_fastcall spill/fill stack slots start;
18380  * - update env->subprog_info[*]->keep_fastcall_stack.
18381  *
18382  * The .fastcall_pattern and .fastcall_stack_off are used by
18383  * check_fastcall_stack_contract() to check if every stack access to
18384  * fastcall spill/fill stack slot originates from spill/fill
18385  * instructions, members of fastcall patterns.
18386  *
18387  * If such condition holds true for a subprogram, fastcall patterns could
18388  * be rewritten by remove_fastcall_spills_fills().
18389  * Otherwise bpf_fastcall patterns are not changed in the subprogram
18390  * (code, presumably, generated by an older clang version).
18391  *
18392  * For example, it is *not* safe to remove spill/fill below:
18393  *
18394  *   r1 = 1;
18395  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
18396  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
18397  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
18398  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
18399  *   r0 += r1;                           exit;
18400  *   exit;
18401  */
18402 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
18403 					   struct bpf_subprog_info *subprog,
18404 					   int insn_idx, s16 lowest_off)
18405 {
18406 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
18407 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
18408 	u32 clobbered_regs_mask;
18409 	struct call_summary cs;
18410 	u32 expected_regs_mask;
18411 	s16 off;
18412 	int i;
18413 
18414 	if (!get_call_summary(env, call, &cs))
18415 		return;
18416 
18417 	/* A bitmask specifying which caller saved registers are clobbered
18418 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
18419 	 * bpf_fastcall contract:
18420 	 * - includes R0 if function is non-void;
18421 	 * - includes R1-R5 if corresponding parameter has is described
18422 	 *   in the function prototype.
18423 	 */
18424 	clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
18425 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
18426 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
18427 
18428 	/* match pairs of form:
18429 	 *
18430 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
18431 	 * ...
18432 	 * call %[to_be_inlined]
18433 	 * ...
18434 	 * rX = *(u64 *)(r10 - Y)
18435 	 */
18436 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
18437 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
18438 			break;
18439 		stx = &insns[insn_idx - i];
18440 		ldx = &insns[insn_idx + i];
18441 		/* must be a stack spill/fill pair */
18442 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
18443 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
18444 		    stx->dst_reg != BPF_REG_10 ||
18445 		    ldx->src_reg != BPF_REG_10)
18446 			break;
18447 		/* must be a spill/fill for the same reg */
18448 		if (stx->src_reg != ldx->dst_reg)
18449 			break;
18450 		/* must be one of the previously unseen registers */
18451 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
18452 			break;
18453 		/* must be a spill/fill for the same expected offset,
18454 		 * no need to check offset alignment, BPF_DW stack access
18455 		 * is always 8-byte aligned.
18456 		 */
18457 		if (stx->off != off || ldx->off != off)
18458 			break;
18459 		expected_regs_mask &= ~BIT(stx->src_reg);
18460 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
18461 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
18462 	}
18463 	if (i == 1)
18464 		return;
18465 
18466 	/* Conditionally set 'fastcall_spills_num' to allow forward
18467 	 * compatibility when more helper functions are marked as
18468 	 * bpf_fastcall at compile time than current kernel supports, e.g:
18469 	 *
18470 	 *   1: *(u64 *)(r10 - 8) = r1
18471 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
18472 	 *   3: r1 = *(u64 *)(r10 - 8)
18473 	 *   4: *(u64 *)(r10 - 8) = r1
18474 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
18475 	 *   6: r1 = *(u64 *)(r10 - 8)
18476 	 *
18477 	 * There is no need to block bpf_fastcall rewrite for such program.
18478 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
18479 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
18480 	 * does not remove spill/fill pair {4,6}.
18481 	 */
18482 	if (cs.fastcall)
18483 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
18484 	else
18485 		subprog->keep_fastcall_stack = 1;
18486 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
18487 }
18488 
18489 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
18490 {
18491 	struct bpf_subprog_info *subprog = env->subprog_info;
18492 	struct bpf_insn *insn;
18493 	s16 lowest_off;
18494 	int s, i;
18495 
18496 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
18497 		/* find lowest stack spill offset used in this subprog */
18498 		lowest_off = 0;
18499 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
18500 			insn = env->prog->insnsi + i;
18501 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
18502 			    insn->dst_reg != BPF_REG_10)
18503 				continue;
18504 			lowest_off = min(lowest_off, insn->off);
18505 		}
18506 		/* use this offset to find fastcall patterns */
18507 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
18508 			insn = env->prog->insnsi + i;
18509 			if (insn->code != (BPF_JMP | BPF_CALL))
18510 				continue;
18511 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
18512 		}
18513 	}
18514 	return 0;
18515 }
18516 
18517 static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem)
18518 {
18519 	size_t new_size = sizeof(struct bpf_iarray) + n_elem * sizeof(old->items[0]);
18520 	struct bpf_iarray *new;
18521 
18522 	new = kvrealloc(old, new_size, GFP_KERNEL_ACCOUNT);
18523 	if (!new) {
18524 		/* this is what callers always want, so simplify the call site */
18525 		kvfree(old);
18526 		return NULL;
18527 	}
18528 
18529 	new->cnt = n_elem;
18530 	return new;
18531 }
18532 
18533 static int copy_insn_array(struct bpf_map *map, u32 start, u32 end, u32 *items)
18534 {
18535 	struct bpf_insn_array_value *value;
18536 	u32 i;
18537 
18538 	for (i = start; i <= end; i++) {
18539 		value = map->ops->map_lookup_elem(map, &i);
18540 		/*
18541 		 * map_lookup_elem of an array map will never return an error,
18542 		 * but not checking it makes some static analysers to worry
18543 		 */
18544 		if (IS_ERR(value))
18545 			return PTR_ERR(value);
18546 		else if (!value)
18547 			return -EINVAL;
18548 		items[i - start] = value->xlated_off;
18549 	}
18550 	return 0;
18551 }
18552 
18553 static int cmp_ptr_to_u32(const void *a, const void *b)
18554 {
18555 	return *(u32 *)a - *(u32 *)b;
18556 }
18557 
18558 static int sort_insn_array_uniq(u32 *items, int cnt)
18559 {
18560 	int unique = 1;
18561 	int i;
18562 
18563 	sort(items, cnt, sizeof(items[0]), cmp_ptr_to_u32, NULL);
18564 
18565 	for (i = 1; i < cnt; i++)
18566 		if (items[i] != items[unique - 1])
18567 			items[unique++] = items[i];
18568 
18569 	return unique;
18570 }
18571 
18572 /*
18573  * sort_unique({map[start], ..., map[end]}) into off
18574  */
18575 static int copy_insn_array_uniq(struct bpf_map *map, u32 start, u32 end, u32 *off)
18576 {
18577 	u32 n = end - start + 1;
18578 	int err;
18579 
18580 	err = copy_insn_array(map, start, end, off);
18581 	if (err)
18582 		return err;
18583 
18584 	return sort_insn_array_uniq(off, n);
18585 }
18586 
18587 /*
18588  * Copy all unique offsets from the map
18589  */
18590 static struct bpf_iarray *jt_from_map(struct bpf_map *map)
18591 {
18592 	struct bpf_iarray *jt;
18593 	int err;
18594 	int n;
18595 
18596 	jt = iarray_realloc(NULL, map->max_entries);
18597 	if (!jt)
18598 		return ERR_PTR(-ENOMEM);
18599 
18600 	n = copy_insn_array_uniq(map, 0, map->max_entries - 1, jt->items);
18601 	if (n < 0) {
18602 		err = n;
18603 		goto err_free;
18604 	}
18605 	if (n == 0) {
18606 		err = -EINVAL;
18607 		goto err_free;
18608 	}
18609 	jt->cnt = n;
18610 	return jt;
18611 
18612 err_free:
18613 	kvfree(jt);
18614 	return ERR_PTR(err);
18615 }
18616 
18617 /*
18618  * Find and collect all maps which fit in the subprog. Return the result as one
18619  * combined jump table in jt->items (allocated with kvcalloc)
18620  */
18621 static struct bpf_iarray *jt_from_subprog(struct bpf_verifier_env *env,
18622 					  int subprog_start, int subprog_end)
18623 {
18624 	struct bpf_iarray *jt = NULL;
18625 	struct bpf_map *map;
18626 	struct bpf_iarray *jt_cur;
18627 	int i;
18628 
18629 	for (i = 0; i < env->insn_array_map_cnt; i++) {
18630 		/*
18631 		 * TODO (when needed): collect only jump tables, not static keys
18632 		 * or maps for indirect calls
18633 		 */
18634 		map = env->insn_array_maps[i];
18635 
18636 		jt_cur = jt_from_map(map);
18637 		if (IS_ERR(jt_cur)) {
18638 			kvfree(jt);
18639 			return jt_cur;
18640 		}
18641 
18642 		/*
18643 		 * This is enough to check one element. The full table is
18644 		 * checked to fit inside the subprog later in create_jt()
18645 		 */
18646 		if (jt_cur->items[0] >= subprog_start && jt_cur->items[0] < subprog_end) {
18647 			u32 old_cnt = jt ? jt->cnt : 0;
18648 			jt = iarray_realloc(jt, old_cnt + jt_cur->cnt);
18649 			if (!jt) {
18650 				kvfree(jt_cur);
18651 				return ERR_PTR(-ENOMEM);
18652 			}
18653 			memcpy(jt->items + old_cnt, jt_cur->items, jt_cur->cnt << 2);
18654 		}
18655 
18656 		kvfree(jt_cur);
18657 	}
18658 
18659 	if (!jt) {
18660 		verbose(env, "no jump tables found for subprog starting at %u\n", subprog_start);
18661 		return ERR_PTR(-EINVAL);
18662 	}
18663 
18664 	jt->cnt = sort_insn_array_uniq(jt->items, jt->cnt);
18665 	return jt;
18666 }
18667 
18668 static struct bpf_iarray *
18669 create_jt(int t, struct bpf_verifier_env *env)
18670 {
18671 	static struct bpf_subprog_info *subprog;
18672 	int subprog_start, subprog_end;
18673 	struct bpf_iarray *jt;
18674 	int i;
18675 
18676 	subprog = bpf_find_containing_subprog(env, t);
18677 	subprog_start = subprog->start;
18678 	subprog_end = (subprog + 1)->start;
18679 	jt = jt_from_subprog(env, subprog_start, subprog_end);
18680 	if (IS_ERR(jt))
18681 		return jt;
18682 
18683 	/* Check that the every element of the jump table fits within the given subprogram */
18684 	for (i = 0; i < jt->cnt; i++) {
18685 		if (jt->items[i] < subprog_start || jt->items[i] >= subprog_end) {
18686 			verbose(env, "jump table for insn %d points outside of the subprog [%u,%u]\n",
18687 					t, subprog_start, subprog_end);
18688 			kvfree(jt);
18689 			return ERR_PTR(-EINVAL);
18690 		}
18691 	}
18692 
18693 	return jt;
18694 }
18695 
18696 /* "conditional jump with N edges" */
18697 static int visit_gotox_insn(int t, struct bpf_verifier_env *env)
18698 {
18699 	int *insn_stack = env->cfg.insn_stack;
18700 	int *insn_state = env->cfg.insn_state;
18701 	bool keep_exploring = false;
18702 	struct bpf_iarray *jt;
18703 	int i, w;
18704 
18705 	jt = env->insn_aux_data[t].jt;
18706 	if (!jt) {
18707 		jt = create_jt(t, env);
18708 		if (IS_ERR(jt))
18709 			return PTR_ERR(jt);
18710 
18711 		env->insn_aux_data[t].jt = jt;
18712 	}
18713 
18714 	mark_prune_point(env, t);
18715 	for (i = 0; i < jt->cnt; i++) {
18716 		w = jt->items[i];
18717 		if (w < 0 || w >= env->prog->len) {
18718 			verbose(env, "indirect jump out of range from insn %d to %d\n", t, w);
18719 			return -EINVAL;
18720 		}
18721 
18722 		mark_jmp_point(env, w);
18723 
18724 		/* EXPLORED || DISCOVERED */
18725 		if (insn_state[w])
18726 			continue;
18727 
18728 		if (env->cfg.cur_stack >= env->prog->len)
18729 			return -E2BIG;
18730 
18731 		insn_stack[env->cfg.cur_stack++] = w;
18732 		insn_state[w] |= DISCOVERED;
18733 		keep_exploring = true;
18734 	}
18735 
18736 	return keep_exploring ? KEEP_EXPLORING : DONE_EXPLORING;
18737 }
18738 
18739 static int visit_tailcall_insn(struct bpf_verifier_env *env, int t)
18740 {
18741 	static struct bpf_subprog_info *subprog;
18742 	struct bpf_iarray *jt;
18743 
18744 	if (env->insn_aux_data[t].jt)
18745 		return 0;
18746 
18747 	jt = iarray_realloc(NULL, 2);
18748 	if (!jt)
18749 		return -ENOMEM;
18750 
18751 	subprog = bpf_find_containing_subprog(env, t);
18752 	jt->items[0] = t + 1;
18753 	jt->items[1] = subprog->exit_idx;
18754 	env->insn_aux_data[t].jt = jt;
18755 	return 0;
18756 }
18757 
18758 /* Visits the instruction at index t and returns one of the following:
18759  *  < 0 - an error occurred
18760  *  DONE_EXPLORING - the instruction was fully explored
18761  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
18762  */
18763 static int visit_insn(int t, struct bpf_verifier_env *env)
18764 {
18765 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
18766 	int ret, off, insn_sz;
18767 
18768 	if (bpf_pseudo_func(insn))
18769 		return visit_func_call_insn(t, insns, env, true);
18770 
18771 	/* All non-branch instructions have a single fall-through edge. */
18772 	if (BPF_CLASS(insn->code) != BPF_JMP &&
18773 	    BPF_CLASS(insn->code) != BPF_JMP32) {
18774 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
18775 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
18776 	}
18777 
18778 	switch (BPF_OP(insn->code)) {
18779 	case BPF_EXIT:
18780 		return DONE_EXPLORING;
18781 
18782 	case BPF_CALL:
18783 		if (is_async_callback_calling_insn(insn))
18784 			/* Mark this call insn as a prune point to trigger
18785 			 * is_state_visited() check before call itself is
18786 			 * processed by __check_func_call(). Otherwise new
18787 			 * async state will be pushed for further exploration.
18788 			 */
18789 			mark_prune_point(env, t);
18790 		/* For functions that invoke callbacks it is not known how many times
18791 		 * callback would be called. Verifier models callback calling functions
18792 		 * by repeatedly visiting callback bodies and returning to origin call
18793 		 * instruction.
18794 		 * In order to stop such iteration verifier needs to identify when a
18795 		 * state identical some state from a previous iteration is reached.
18796 		 * Check below forces creation of checkpoint before callback calling
18797 		 * instruction to allow search for such identical states.
18798 		 */
18799 		if (is_sync_callback_calling_insn(insn)) {
18800 			mark_calls_callback(env, t);
18801 			mark_force_checkpoint(env, t);
18802 			mark_prune_point(env, t);
18803 			mark_jmp_point(env, t);
18804 		}
18805 		if (bpf_helper_call(insn)) {
18806 			const struct bpf_func_proto *fp;
18807 
18808 			ret = get_helper_proto(env, insn->imm, &fp);
18809 			/* If called in a non-sleepable context program will be
18810 			 * rejected anyway, so we should end up with precise
18811 			 * sleepable marks on subprogs, except for dead code
18812 			 * elimination.
18813 			 */
18814 			if (ret == 0 && fp->might_sleep)
18815 				mark_subprog_might_sleep(env, t);
18816 			if (bpf_helper_changes_pkt_data(insn->imm))
18817 				mark_subprog_changes_pkt_data(env, t);
18818 			if (insn->imm == BPF_FUNC_tail_call)
18819 				visit_tailcall_insn(env, t);
18820 		} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18821 			struct bpf_kfunc_call_arg_meta meta;
18822 
18823 			ret = fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
18824 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
18825 				mark_prune_point(env, t);
18826 				/* Checking and saving state checkpoints at iter_next() call
18827 				 * is crucial for fast convergence of open-coded iterator loop
18828 				 * logic, so we need to force it. If we don't do that,
18829 				 * is_state_visited() might skip saving a checkpoint, causing
18830 				 * unnecessarily long sequence of not checkpointed
18831 				 * instructions and jumps, leading to exhaustion of jump
18832 				 * history buffer, and potentially other undesired outcomes.
18833 				 * It is expected that with correct open-coded iterators
18834 				 * convergence will happen quickly, so we don't run a risk of
18835 				 * exhausting memory.
18836 				 */
18837 				mark_force_checkpoint(env, t);
18838 			}
18839 			/* Same as helpers, if called in a non-sleepable context
18840 			 * program will be rejected anyway, so we should end up
18841 			 * with precise sleepable marks on subprogs, except for
18842 			 * dead code elimination.
18843 			 */
18844 			if (ret == 0 && is_kfunc_sleepable(&meta))
18845 				mark_subprog_might_sleep(env, t);
18846 			if (ret == 0 && is_kfunc_pkt_changing(&meta))
18847 				mark_subprog_changes_pkt_data(env, t);
18848 		}
18849 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
18850 
18851 	case BPF_JA:
18852 		if (BPF_SRC(insn->code) == BPF_X)
18853 			return visit_gotox_insn(t, env);
18854 
18855 		if (BPF_CLASS(insn->code) == BPF_JMP)
18856 			off = insn->off;
18857 		else
18858 			off = insn->imm;
18859 
18860 		/* unconditional jump with single edge */
18861 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
18862 		if (ret)
18863 			return ret;
18864 
18865 		mark_prune_point(env, t + off + 1);
18866 		mark_jmp_point(env, t + off + 1);
18867 
18868 		return ret;
18869 
18870 	default:
18871 		/* conditional jump with two edges */
18872 		mark_prune_point(env, t);
18873 		if (is_may_goto_insn(insn))
18874 			mark_force_checkpoint(env, t);
18875 
18876 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
18877 		if (ret)
18878 			return ret;
18879 
18880 		return push_insn(t, t + insn->off + 1, BRANCH, env);
18881 	}
18882 }
18883 
18884 /* non-recursive depth-first-search to detect loops in BPF program
18885  * loop == back-edge in directed graph
18886  */
18887 static int check_cfg(struct bpf_verifier_env *env)
18888 {
18889 	int insn_cnt = env->prog->len;
18890 	int *insn_stack, *insn_state;
18891 	int ex_insn_beg, i, ret = 0;
18892 
18893 	insn_state = env->cfg.insn_state = kvzalloc_objs(int, insn_cnt,
18894 							 GFP_KERNEL_ACCOUNT);
18895 	if (!insn_state)
18896 		return -ENOMEM;
18897 
18898 	insn_stack = env->cfg.insn_stack = kvzalloc_objs(int, insn_cnt,
18899 							 GFP_KERNEL_ACCOUNT);
18900 	if (!insn_stack) {
18901 		kvfree(insn_state);
18902 		return -ENOMEM;
18903 	}
18904 
18905 	ex_insn_beg = env->exception_callback_subprog
18906 		      ? env->subprog_info[env->exception_callback_subprog].start
18907 		      : 0;
18908 
18909 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
18910 	insn_stack[0] = 0; /* 0 is the first instruction */
18911 	env->cfg.cur_stack = 1;
18912 
18913 walk_cfg:
18914 	while (env->cfg.cur_stack > 0) {
18915 		int t = insn_stack[env->cfg.cur_stack - 1];
18916 
18917 		ret = visit_insn(t, env);
18918 		switch (ret) {
18919 		case DONE_EXPLORING:
18920 			insn_state[t] = EXPLORED;
18921 			env->cfg.cur_stack--;
18922 			break;
18923 		case KEEP_EXPLORING:
18924 			break;
18925 		default:
18926 			if (ret > 0) {
18927 				verifier_bug(env, "visit_insn internal bug");
18928 				ret = -EFAULT;
18929 			}
18930 			goto err_free;
18931 		}
18932 	}
18933 
18934 	if (env->cfg.cur_stack < 0) {
18935 		verifier_bug(env, "pop stack internal bug");
18936 		ret = -EFAULT;
18937 		goto err_free;
18938 	}
18939 
18940 	if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) {
18941 		insn_state[ex_insn_beg] = DISCOVERED;
18942 		insn_stack[0] = ex_insn_beg;
18943 		env->cfg.cur_stack = 1;
18944 		goto walk_cfg;
18945 	}
18946 
18947 	for (i = 0; i < insn_cnt; i++) {
18948 		struct bpf_insn *insn = &env->prog->insnsi[i];
18949 
18950 		if (insn_state[i] != EXPLORED) {
18951 			verbose(env, "unreachable insn %d\n", i);
18952 			ret = -EINVAL;
18953 			goto err_free;
18954 		}
18955 		if (bpf_is_ldimm64(insn)) {
18956 			if (insn_state[i + 1] != 0) {
18957 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
18958 				ret = -EINVAL;
18959 				goto err_free;
18960 			}
18961 			i++; /* skip second half of ldimm64 */
18962 		}
18963 	}
18964 	ret = 0; /* cfg looks good */
18965 	env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
18966 	env->prog->aux->might_sleep = env->subprog_info[0].might_sleep;
18967 
18968 err_free:
18969 	kvfree(insn_state);
18970 	kvfree(insn_stack);
18971 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
18972 	return ret;
18973 }
18974 
18975 /*
18976  * For each subprogram 'i' fill array env->cfg.insn_subprogram sub-range
18977  * [env->subprog_info[i].postorder_start, env->subprog_info[i+1].postorder_start)
18978  * with indices of 'i' instructions in postorder.
18979  */
18980 static int compute_postorder(struct bpf_verifier_env *env)
18981 {
18982 	u32 cur_postorder, i, top, stack_sz, s;
18983 	int *stack = NULL, *postorder = NULL, *state = NULL;
18984 	struct bpf_iarray *succ;
18985 
18986 	postorder = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT);
18987 	state = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT);
18988 	stack = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT);
18989 	if (!postorder || !state || !stack) {
18990 		kvfree(postorder);
18991 		kvfree(state);
18992 		kvfree(stack);
18993 		return -ENOMEM;
18994 	}
18995 	cur_postorder = 0;
18996 	for (i = 0; i < env->subprog_cnt; i++) {
18997 		env->subprog_info[i].postorder_start = cur_postorder;
18998 		stack[0] = env->subprog_info[i].start;
18999 		stack_sz = 1;
19000 		do {
19001 			top = stack[stack_sz - 1];
19002 			state[top] |= DISCOVERED;
19003 			if (state[top] & EXPLORED) {
19004 				postorder[cur_postorder++] = top;
19005 				stack_sz--;
19006 				continue;
19007 			}
19008 			succ = bpf_insn_successors(env, top);
19009 			for (s = 0; s < succ->cnt; ++s) {
19010 				if (!state[succ->items[s]]) {
19011 					stack[stack_sz++] = succ->items[s];
19012 					state[succ->items[s]] |= DISCOVERED;
19013 				}
19014 			}
19015 			state[top] |= EXPLORED;
19016 		} while (stack_sz);
19017 	}
19018 	env->subprog_info[i].postorder_start = cur_postorder;
19019 	env->cfg.insn_postorder = postorder;
19020 	env->cfg.cur_postorder = cur_postorder;
19021 	kvfree(stack);
19022 	kvfree(state);
19023 	return 0;
19024 }
19025 
19026 static int check_abnormal_return(struct bpf_verifier_env *env)
19027 {
19028 	int i;
19029 
19030 	for (i = 1; i < env->subprog_cnt; i++) {
19031 		if (env->subprog_info[i].has_ld_abs) {
19032 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
19033 			return -EINVAL;
19034 		}
19035 		if (env->subprog_info[i].has_tail_call) {
19036 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
19037 			return -EINVAL;
19038 		}
19039 	}
19040 	return 0;
19041 }
19042 
19043 /* The minimum supported BTF func info size */
19044 #define MIN_BPF_FUNCINFO_SIZE	8
19045 #define MAX_FUNCINFO_REC_SIZE	252
19046 
19047 static int check_btf_func_early(struct bpf_verifier_env *env,
19048 				const union bpf_attr *attr,
19049 				bpfptr_t uattr)
19050 {
19051 	u32 krec_size = sizeof(struct bpf_func_info);
19052 	const struct btf_type *type, *func_proto;
19053 	u32 i, nfuncs, urec_size, min_size;
19054 	struct bpf_func_info *krecord;
19055 	struct bpf_prog *prog;
19056 	const struct btf *btf;
19057 	u32 prev_offset = 0;
19058 	bpfptr_t urecord;
19059 	int ret = -ENOMEM;
19060 
19061 	nfuncs = attr->func_info_cnt;
19062 	if (!nfuncs) {
19063 		if (check_abnormal_return(env))
19064 			return -EINVAL;
19065 		return 0;
19066 	}
19067 
19068 	urec_size = attr->func_info_rec_size;
19069 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
19070 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
19071 	    urec_size % sizeof(u32)) {
19072 		verbose(env, "invalid func info rec size %u\n", urec_size);
19073 		return -EINVAL;
19074 	}
19075 
19076 	prog = env->prog;
19077 	btf = prog->aux->btf;
19078 
19079 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
19080 	min_size = min_t(u32, krec_size, urec_size);
19081 
19082 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
19083 	if (!krecord)
19084 		return -ENOMEM;
19085 
19086 	for (i = 0; i < nfuncs; i++) {
19087 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
19088 		if (ret) {
19089 			if (ret == -E2BIG) {
19090 				verbose(env, "nonzero tailing record in func info");
19091 				/* set the size kernel expects so loader can zero
19092 				 * out the rest of the record.
19093 				 */
19094 				if (copy_to_bpfptr_offset(uattr,
19095 							  offsetof(union bpf_attr, func_info_rec_size),
19096 							  &min_size, sizeof(min_size)))
19097 					ret = -EFAULT;
19098 			}
19099 			goto err_free;
19100 		}
19101 
19102 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
19103 			ret = -EFAULT;
19104 			goto err_free;
19105 		}
19106 
19107 		/* check insn_off */
19108 		ret = -EINVAL;
19109 		if (i == 0) {
19110 			if (krecord[i].insn_off) {
19111 				verbose(env,
19112 					"nonzero insn_off %u for the first func info record",
19113 					krecord[i].insn_off);
19114 				goto err_free;
19115 			}
19116 		} else if (krecord[i].insn_off <= prev_offset) {
19117 			verbose(env,
19118 				"same or smaller insn offset (%u) than previous func info record (%u)",
19119 				krecord[i].insn_off, prev_offset);
19120 			goto err_free;
19121 		}
19122 
19123 		/* check type_id */
19124 		type = btf_type_by_id(btf, krecord[i].type_id);
19125 		if (!type || !btf_type_is_func(type)) {
19126 			verbose(env, "invalid type id %d in func info",
19127 				krecord[i].type_id);
19128 			goto err_free;
19129 		}
19130 
19131 		func_proto = btf_type_by_id(btf, type->type);
19132 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
19133 			/* btf_func_check() already verified it during BTF load */
19134 			goto err_free;
19135 
19136 		prev_offset = krecord[i].insn_off;
19137 		bpfptr_add(&urecord, urec_size);
19138 	}
19139 
19140 	prog->aux->func_info = krecord;
19141 	prog->aux->func_info_cnt = nfuncs;
19142 	return 0;
19143 
19144 err_free:
19145 	kvfree(krecord);
19146 	return ret;
19147 }
19148 
19149 static int check_btf_func(struct bpf_verifier_env *env,
19150 			  const union bpf_attr *attr,
19151 			  bpfptr_t uattr)
19152 {
19153 	const struct btf_type *type, *func_proto, *ret_type;
19154 	u32 i, nfuncs, urec_size;
19155 	struct bpf_func_info *krecord;
19156 	struct bpf_func_info_aux *info_aux = NULL;
19157 	struct bpf_prog *prog;
19158 	const struct btf *btf;
19159 	bpfptr_t urecord;
19160 	bool scalar_return;
19161 	int ret = -ENOMEM;
19162 
19163 	nfuncs = attr->func_info_cnt;
19164 	if (!nfuncs) {
19165 		if (check_abnormal_return(env))
19166 			return -EINVAL;
19167 		return 0;
19168 	}
19169 	if (nfuncs != env->subprog_cnt) {
19170 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
19171 		return -EINVAL;
19172 	}
19173 
19174 	urec_size = attr->func_info_rec_size;
19175 
19176 	prog = env->prog;
19177 	btf = prog->aux->btf;
19178 
19179 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
19180 
19181 	krecord = prog->aux->func_info;
19182 	info_aux = kzalloc_objs(*info_aux, nfuncs,
19183 				GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
19184 	if (!info_aux)
19185 		return -ENOMEM;
19186 
19187 	for (i = 0; i < nfuncs; i++) {
19188 		/* check insn_off */
19189 		ret = -EINVAL;
19190 
19191 		if (env->subprog_info[i].start != krecord[i].insn_off) {
19192 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
19193 			goto err_free;
19194 		}
19195 
19196 		/* Already checked type_id */
19197 		type = btf_type_by_id(btf, krecord[i].type_id);
19198 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
19199 		/* Already checked func_proto */
19200 		func_proto = btf_type_by_id(btf, type->type);
19201 
19202 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
19203 		scalar_return =
19204 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
19205 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
19206 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
19207 			goto err_free;
19208 		}
19209 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
19210 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
19211 			goto err_free;
19212 		}
19213 
19214 		bpfptr_add(&urecord, urec_size);
19215 	}
19216 
19217 	prog->aux->func_info_aux = info_aux;
19218 	return 0;
19219 
19220 err_free:
19221 	kfree(info_aux);
19222 	return ret;
19223 }
19224 
19225 static void adjust_btf_func(struct bpf_verifier_env *env)
19226 {
19227 	struct bpf_prog_aux *aux = env->prog->aux;
19228 	int i;
19229 
19230 	if (!aux->func_info)
19231 		return;
19232 
19233 	/* func_info is not available for hidden subprogs */
19234 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
19235 		aux->func_info[i].insn_off = env->subprog_info[i].start;
19236 }
19237 
19238 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
19239 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
19240 
19241 static int check_btf_line(struct bpf_verifier_env *env,
19242 			  const union bpf_attr *attr,
19243 			  bpfptr_t uattr)
19244 {
19245 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
19246 	struct bpf_subprog_info *sub;
19247 	struct bpf_line_info *linfo;
19248 	struct bpf_prog *prog;
19249 	const struct btf *btf;
19250 	bpfptr_t ulinfo;
19251 	int err;
19252 
19253 	nr_linfo = attr->line_info_cnt;
19254 	if (!nr_linfo)
19255 		return 0;
19256 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
19257 		return -EINVAL;
19258 
19259 	rec_size = attr->line_info_rec_size;
19260 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
19261 	    rec_size > MAX_LINEINFO_REC_SIZE ||
19262 	    rec_size & (sizeof(u32) - 1))
19263 		return -EINVAL;
19264 
19265 	/* Need to zero it in case the userspace may
19266 	 * pass in a smaller bpf_line_info object.
19267 	 */
19268 	linfo = kvzalloc_objs(struct bpf_line_info, nr_linfo,
19269 			      GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
19270 	if (!linfo)
19271 		return -ENOMEM;
19272 
19273 	prog = env->prog;
19274 	btf = prog->aux->btf;
19275 
19276 	s = 0;
19277 	sub = env->subprog_info;
19278 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
19279 	expected_size = sizeof(struct bpf_line_info);
19280 	ncopy = min_t(u32, expected_size, rec_size);
19281 	for (i = 0; i < nr_linfo; i++) {
19282 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
19283 		if (err) {
19284 			if (err == -E2BIG) {
19285 				verbose(env, "nonzero tailing record in line_info");
19286 				if (copy_to_bpfptr_offset(uattr,
19287 							  offsetof(union bpf_attr, line_info_rec_size),
19288 							  &expected_size, sizeof(expected_size)))
19289 					err = -EFAULT;
19290 			}
19291 			goto err_free;
19292 		}
19293 
19294 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
19295 			err = -EFAULT;
19296 			goto err_free;
19297 		}
19298 
19299 		/*
19300 		 * Check insn_off to ensure
19301 		 * 1) strictly increasing AND
19302 		 * 2) bounded by prog->len
19303 		 *
19304 		 * The linfo[0].insn_off == 0 check logically falls into
19305 		 * the later "missing bpf_line_info for func..." case
19306 		 * because the first linfo[0].insn_off must be the
19307 		 * first sub also and the first sub must have
19308 		 * subprog_info[0].start == 0.
19309 		 */
19310 		if ((i && linfo[i].insn_off <= prev_offset) ||
19311 		    linfo[i].insn_off >= prog->len) {
19312 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
19313 				i, linfo[i].insn_off, prev_offset,
19314 				prog->len);
19315 			err = -EINVAL;
19316 			goto err_free;
19317 		}
19318 
19319 		if (!prog->insnsi[linfo[i].insn_off].code) {
19320 			verbose(env,
19321 				"Invalid insn code at line_info[%u].insn_off\n",
19322 				i);
19323 			err = -EINVAL;
19324 			goto err_free;
19325 		}
19326 
19327 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
19328 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
19329 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
19330 			err = -EINVAL;
19331 			goto err_free;
19332 		}
19333 
19334 		if (s != env->subprog_cnt) {
19335 			if (linfo[i].insn_off == sub[s].start) {
19336 				sub[s].linfo_idx = i;
19337 				s++;
19338 			} else if (sub[s].start < linfo[i].insn_off) {
19339 				verbose(env, "missing bpf_line_info for func#%u\n", s);
19340 				err = -EINVAL;
19341 				goto err_free;
19342 			}
19343 		}
19344 
19345 		prev_offset = linfo[i].insn_off;
19346 		bpfptr_add(&ulinfo, rec_size);
19347 	}
19348 
19349 	if (s != env->subprog_cnt) {
19350 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
19351 			env->subprog_cnt - s, s);
19352 		err = -EINVAL;
19353 		goto err_free;
19354 	}
19355 
19356 	prog->aux->linfo = linfo;
19357 	prog->aux->nr_linfo = nr_linfo;
19358 
19359 	return 0;
19360 
19361 err_free:
19362 	kvfree(linfo);
19363 	return err;
19364 }
19365 
19366 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
19367 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
19368 
19369 static int check_core_relo(struct bpf_verifier_env *env,
19370 			   const union bpf_attr *attr,
19371 			   bpfptr_t uattr)
19372 {
19373 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
19374 	struct bpf_core_relo core_relo = {};
19375 	struct bpf_prog *prog = env->prog;
19376 	const struct btf *btf = prog->aux->btf;
19377 	struct bpf_core_ctx ctx = {
19378 		.log = &env->log,
19379 		.btf = btf,
19380 	};
19381 	bpfptr_t u_core_relo;
19382 	int err;
19383 
19384 	nr_core_relo = attr->core_relo_cnt;
19385 	if (!nr_core_relo)
19386 		return 0;
19387 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
19388 		return -EINVAL;
19389 
19390 	rec_size = attr->core_relo_rec_size;
19391 	if (rec_size < MIN_CORE_RELO_SIZE ||
19392 	    rec_size > MAX_CORE_RELO_SIZE ||
19393 	    rec_size % sizeof(u32))
19394 		return -EINVAL;
19395 
19396 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
19397 	expected_size = sizeof(struct bpf_core_relo);
19398 	ncopy = min_t(u32, expected_size, rec_size);
19399 
19400 	/* Unlike func_info and line_info, copy and apply each CO-RE
19401 	 * relocation record one at a time.
19402 	 */
19403 	for (i = 0; i < nr_core_relo; i++) {
19404 		/* future proofing when sizeof(bpf_core_relo) changes */
19405 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
19406 		if (err) {
19407 			if (err == -E2BIG) {
19408 				verbose(env, "nonzero tailing record in core_relo");
19409 				if (copy_to_bpfptr_offset(uattr,
19410 							  offsetof(union bpf_attr, core_relo_rec_size),
19411 							  &expected_size, sizeof(expected_size)))
19412 					err = -EFAULT;
19413 			}
19414 			break;
19415 		}
19416 
19417 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
19418 			err = -EFAULT;
19419 			break;
19420 		}
19421 
19422 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
19423 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
19424 				i, core_relo.insn_off, prog->len);
19425 			err = -EINVAL;
19426 			break;
19427 		}
19428 
19429 		err = bpf_core_apply(&ctx, &core_relo, i,
19430 				     &prog->insnsi[core_relo.insn_off / 8]);
19431 		if (err)
19432 			break;
19433 		bpfptr_add(&u_core_relo, rec_size);
19434 	}
19435 	return err;
19436 }
19437 
19438 static int check_btf_info_early(struct bpf_verifier_env *env,
19439 				const union bpf_attr *attr,
19440 				bpfptr_t uattr)
19441 {
19442 	struct btf *btf;
19443 	int err;
19444 
19445 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
19446 		if (check_abnormal_return(env))
19447 			return -EINVAL;
19448 		return 0;
19449 	}
19450 
19451 	btf = btf_get_by_fd(attr->prog_btf_fd);
19452 	if (IS_ERR(btf))
19453 		return PTR_ERR(btf);
19454 	if (btf_is_kernel(btf)) {
19455 		btf_put(btf);
19456 		return -EACCES;
19457 	}
19458 	env->prog->aux->btf = btf;
19459 
19460 	err = check_btf_func_early(env, attr, uattr);
19461 	if (err)
19462 		return err;
19463 	return 0;
19464 }
19465 
19466 static int check_btf_info(struct bpf_verifier_env *env,
19467 			  const union bpf_attr *attr,
19468 			  bpfptr_t uattr)
19469 {
19470 	int err;
19471 
19472 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
19473 		if (check_abnormal_return(env))
19474 			return -EINVAL;
19475 		return 0;
19476 	}
19477 
19478 	err = check_btf_func(env, attr, uattr);
19479 	if (err)
19480 		return err;
19481 
19482 	err = check_btf_line(env, attr, uattr);
19483 	if (err)
19484 		return err;
19485 
19486 	err = check_core_relo(env, attr, uattr);
19487 	if (err)
19488 		return err;
19489 
19490 	return 0;
19491 }
19492 
19493 /* check %cur's range satisfies %old's */
19494 static bool range_within(const struct bpf_reg_state *old,
19495 			 const struct bpf_reg_state *cur)
19496 {
19497 	return old->umin_value <= cur->umin_value &&
19498 	       old->umax_value >= cur->umax_value &&
19499 	       old->smin_value <= cur->smin_value &&
19500 	       old->smax_value >= cur->smax_value &&
19501 	       old->u32_min_value <= cur->u32_min_value &&
19502 	       old->u32_max_value >= cur->u32_max_value &&
19503 	       old->s32_min_value <= cur->s32_min_value &&
19504 	       old->s32_max_value >= cur->s32_max_value;
19505 }
19506 
19507 /* If in the old state two registers had the same id, then they need to have
19508  * the same id in the new state as well.  But that id could be different from
19509  * the old state, so we need to track the mapping from old to new ids.
19510  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
19511  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
19512  * regs with a different old id could still have new id 9, we don't care about
19513  * that.
19514  * So we look through our idmap to see if this old id has been seen before.  If
19515  * so, we require the new id to match; otherwise, we add the id pair to the map.
19516  */
19517 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
19518 {
19519 	struct bpf_id_pair *map = idmap->map;
19520 	unsigned int i;
19521 
19522 	/* either both IDs should be set or both should be zero */
19523 	if (!!old_id != !!cur_id)
19524 		return false;
19525 
19526 	if (old_id == 0) /* cur_id == 0 as well */
19527 		return true;
19528 
19529 	for (i = 0; i < idmap->cnt; i++) {
19530 		if (map[i].old == old_id)
19531 			return map[i].cur == cur_id;
19532 		if (map[i].cur == cur_id)
19533 			return false;
19534 	}
19535 
19536 	/* Reached the end of known mappings; haven't seen this id before */
19537 	if (idmap->cnt < BPF_ID_MAP_SIZE) {
19538 		map[idmap->cnt].old = old_id;
19539 		map[idmap->cnt].cur = cur_id;
19540 		idmap->cnt++;
19541 		return true;
19542 	}
19543 
19544 	/* We ran out of idmap slots, which should be impossible */
19545 	WARN_ON_ONCE(1);
19546 	return false;
19547 }
19548 
19549 /*
19550  * Compare scalar register IDs for state equivalence.
19551  *
19552  * When old_id == 0, the old register is independent - not linked to any
19553  * other register. Any linking in the current state only adds constraints,
19554  * making it more restrictive. Since the old state didn't rely on any ID
19555  * relationships for this register, it's always safe to accept cur regardless
19556  * of its ID. Hence, return true immediately.
19557  *
19558  * When old_id != 0 but cur_id == 0, we need to ensure that different
19559  * independent registers in cur don't incorrectly satisfy the ID matching
19560  * requirements of linked registers in old.
19561  *
19562  * Example: if old has r6.id=X and r7.id=X (linked), but cur has r6.id=0
19563  * and r7.id=0 (both independent), without temp IDs both would map old_id=X
19564  * to cur_id=0 and pass. With temp IDs: r6 maps X->temp1, r7 tries to map
19565  * X->temp2, but X is already mapped to temp1, so the check fails correctly.
19566  */
19567 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
19568 {
19569 	if (!old_id)
19570 		return true;
19571 
19572 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
19573 
19574 	return check_ids(old_id, cur_id, idmap);
19575 }
19576 
19577 static void clean_func_state(struct bpf_verifier_env *env,
19578 			     struct bpf_func_state *st,
19579 			     u32 ip)
19580 {
19581 	u16 live_regs = env->insn_aux_data[ip].live_regs_before;
19582 	int i, j;
19583 
19584 	for (i = 0; i < BPF_REG_FP; i++) {
19585 		/* liveness must not touch this register anymore */
19586 		if (!(live_regs & BIT(i)))
19587 			/* since the register is unused, clear its state
19588 			 * to make further comparison simpler
19589 			 */
19590 			__mark_reg_not_init(env, &st->regs[i]);
19591 	}
19592 
19593 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
19594 		if (!bpf_stack_slot_alive(env, st->frameno, i)) {
19595 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
19596 			for (j = 0; j < BPF_REG_SIZE; j++)
19597 				st->stack[i].slot_type[j] = STACK_INVALID;
19598 		}
19599 	}
19600 }
19601 
19602 static void clean_verifier_state(struct bpf_verifier_env *env,
19603 				 struct bpf_verifier_state *st)
19604 {
19605 	int i, ip;
19606 
19607 	bpf_live_stack_query_init(env, st);
19608 	st->cleaned = true;
19609 	for (i = 0; i <= st->curframe; i++) {
19610 		ip = frame_insn_idx(st, i);
19611 		clean_func_state(env, st->frame[i], ip);
19612 	}
19613 }
19614 
19615 /* the parentage chains form a tree.
19616  * the verifier states are added to state lists at given insn and
19617  * pushed into state stack for future exploration.
19618  * when the verifier reaches bpf_exit insn some of the verifier states
19619  * stored in the state lists have their final liveness state already,
19620  * but a lot of states will get revised from liveness point of view when
19621  * the verifier explores other branches.
19622  * Example:
19623  * 1: *(u64)(r10 - 8) = 1
19624  * 2: if r1 == 100 goto pc+1
19625  * 3: *(u64)(r10 - 8) = 2
19626  * 4: r0 = *(u64)(r10 - 8)
19627  * 5: exit
19628  * when the verifier reaches exit insn the stack slot -8 in the state list of
19629  * insn 2 is not yet marked alive. Then the verifier pops the other_branch
19630  * of insn 2 and goes exploring further. After the insn 4 read, liveness
19631  * analysis would propagate read mark for -8 at insn 2.
19632  *
19633  * Since the verifier pushes the branch states as it sees them while exploring
19634  * the program the condition of walking the branch instruction for the second
19635  * time means that all states below this branch were already explored and
19636  * their final liveness marks are already propagated.
19637  * Hence when the verifier completes the search of state list in is_state_visited()
19638  * we can call this clean_live_states() function to clear dead the registers and stack
19639  * slots to simplify state merging.
19640  *
19641  * Important note here that walking the same branch instruction in the callee
19642  * doesn't meant that the states are DONE. The verifier has to compare
19643  * the callsites
19644  */
19645 
19646 /* Find id in idset and increment its count, or add new entry */
19647 static void idset_cnt_inc(struct bpf_idset *idset, u32 id)
19648 {
19649 	u32 i;
19650 
19651 	for (i = 0; i < idset->num_ids; i++) {
19652 		if (idset->entries[i].id == id) {
19653 			idset->entries[i].cnt++;
19654 			return;
19655 		}
19656 	}
19657 	/* New id */
19658 	if (idset->num_ids < BPF_ID_MAP_SIZE) {
19659 		idset->entries[idset->num_ids].id = id;
19660 		idset->entries[idset->num_ids].cnt = 1;
19661 		idset->num_ids++;
19662 	}
19663 }
19664 
19665 /* Find id in idset and return its count, or 0 if not found */
19666 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id)
19667 {
19668 	u32 i;
19669 
19670 	for (i = 0; i < idset->num_ids; i++) {
19671 		if (idset->entries[i].id == id)
19672 			return idset->entries[i].cnt;
19673 	}
19674 	return 0;
19675 }
19676 
19677 /*
19678  * Clear singular scalar ids in a state.
19679  * A register with a non-zero id is called singular if no other register shares
19680  * the same base id. Such registers can be treated as independent (id=0).
19681  */
19682 static void clear_singular_ids(struct bpf_verifier_env *env,
19683 			       struct bpf_verifier_state *st)
19684 {
19685 	struct bpf_idset *idset = &env->idset_scratch;
19686 	struct bpf_func_state *func;
19687 	struct bpf_reg_state *reg;
19688 
19689 	idset->num_ids = 0;
19690 
19691 	bpf_for_each_reg_in_vstate(st, func, reg, ({
19692 		if (reg->type != SCALAR_VALUE)
19693 			continue;
19694 		if (!reg->id)
19695 			continue;
19696 		idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST);
19697 	}));
19698 
19699 	bpf_for_each_reg_in_vstate(st, func, reg, ({
19700 		if (reg->type != SCALAR_VALUE)
19701 			continue;
19702 		if (!reg->id)
19703 			continue;
19704 		if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1) {
19705 			reg->id = 0;
19706 			reg->off = 0;
19707 		}
19708 	}));
19709 }
19710 
19711 static void clean_live_states(struct bpf_verifier_env *env, int insn,
19712 			      struct bpf_verifier_state *cur)
19713 {
19714 	struct bpf_verifier_state_list *sl;
19715 	struct list_head *pos, *head;
19716 
19717 	head = explored_state(env, insn);
19718 	list_for_each(pos, head) {
19719 		sl = container_of(pos, struct bpf_verifier_state_list, node);
19720 		if (sl->state.branches)
19721 			continue;
19722 		if (sl->state.insn_idx != insn ||
19723 		    !same_callsites(&sl->state, cur))
19724 			continue;
19725 		if (sl->state.cleaned)
19726 			/* all regs in this state in all frames were already marked */
19727 			continue;
19728 		if (incomplete_read_marks(env, &sl->state))
19729 			continue;
19730 		clean_verifier_state(env, &sl->state);
19731 	}
19732 }
19733 
19734 static bool regs_exact(const struct bpf_reg_state *rold,
19735 		       const struct bpf_reg_state *rcur,
19736 		       struct bpf_idmap *idmap)
19737 {
19738 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
19739 	       check_ids(rold->id, rcur->id, idmap) &&
19740 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
19741 }
19742 
19743 enum exact_level {
19744 	NOT_EXACT,
19745 	EXACT,
19746 	RANGE_WITHIN
19747 };
19748 
19749 /* Returns true if (rold safe implies rcur safe) */
19750 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
19751 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
19752 		    enum exact_level exact)
19753 {
19754 	if (exact == EXACT)
19755 		return regs_exact(rold, rcur, idmap);
19756 
19757 	if (rold->type == NOT_INIT)
19758 		/* explored state can't have used this */
19759 		return true;
19760 
19761 	/* Enforce that register types have to match exactly, including their
19762 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
19763 	 * rule.
19764 	 *
19765 	 * One can make a point that using a pointer register as unbounded
19766 	 * SCALAR would be technically acceptable, but this could lead to
19767 	 * pointer leaks because scalars are allowed to leak while pointers
19768 	 * are not. We could make this safe in special cases if root is
19769 	 * calling us, but it's probably not worth the hassle.
19770 	 *
19771 	 * Also, register types that are *not* MAYBE_NULL could technically be
19772 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
19773 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
19774 	 * to the same map).
19775 	 * However, if the old MAYBE_NULL register then got NULL checked,
19776 	 * doing so could have affected others with the same id, and we can't
19777 	 * check for that because we lost the id when we converted to
19778 	 * a non-MAYBE_NULL variant.
19779 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
19780 	 * non-MAYBE_NULL registers as well.
19781 	 */
19782 	if (rold->type != rcur->type)
19783 		return false;
19784 
19785 	switch (base_type(rold->type)) {
19786 	case SCALAR_VALUE:
19787 		if (env->explore_alu_limits) {
19788 			/* explore_alu_limits disables tnum_in() and range_within()
19789 			 * logic and requires everything to be strict
19790 			 */
19791 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
19792 			       check_scalar_ids(rold->id, rcur->id, idmap);
19793 		}
19794 		if (!rold->precise && exact == NOT_EXACT)
19795 			return true;
19796 		/*
19797 		 * Linked register tracking uses rold->id to detect relationships.
19798 		 * When rold->id == 0, the register is independent and any linking
19799 		 * in rcur only adds constraints. When rold->id != 0, we must verify
19800 		 * id mapping and (for BPF_ADD_CONST) offset consistency.
19801 		 *
19802 		 * +------------------+-----------+------------------+---------------+
19803 		 * |                  | rold->id  | rold + ADD_CONST | rold->id == 0 |
19804 		 * |------------------+-----------+------------------+---------------|
19805 		 * | rcur->id         | range,ids | false            | range         |
19806 		 * | rcur + ADD_CONST | false     | range,ids,off    | range         |
19807 		 * | rcur->id == 0    | range,ids | false            | range         |
19808 		 * +------------------+-----------+------------------+---------------+
19809 		 *
19810 		 * Why check_ids() for scalar registers?
19811 		 *
19812 		 * Consider the following BPF code:
19813 		 *   1: r6 = ... unbound scalar, ID=a ...
19814 		 *   2: r7 = ... unbound scalar, ID=b ...
19815 		 *   3: if (r6 > r7) goto +1
19816 		 *   4: r6 = r7
19817 		 *   5: if (r6 > X) goto ...
19818 		 *   6: ... memory operation using r7 ...
19819 		 *
19820 		 * First verification path is [1-6]:
19821 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
19822 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
19823 		 *   r7 <= X, because r6 and r7 share same id.
19824 		 * Next verification path is [1-4, 6].
19825 		 *
19826 		 * Instruction (6) would be reached in two states:
19827 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
19828 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
19829 		 *
19830 		 * Use check_ids() to distinguish these states.
19831 		 * ---
19832 		 * Also verify that new value satisfies old value range knowledge.
19833 		 */
19834 
19835 		/* ADD_CONST mismatch: different linking semantics */
19836 		if ((rold->id & BPF_ADD_CONST) && !(rcur->id & BPF_ADD_CONST))
19837 			return false;
19838 
19839 		if (rold->id && !(rold->id & BPF_ADD_CONST) && (rcur->id & BPF_ADD_CONST))
19840 			return false;
19841 
19842 		/* Both have offset linkage: offsets must match */
19843 		if ((rold->id & BPF_ADD_CONST) && rold->off != rcur->off)
19844 			return false;
19845 
19846 		if (!check_scalar_ids(rold->id, rcur->id, idmap))
19847 			return false;
19848 
19849 		return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off);
19850 	case PTR_TO_MAP_KEY:
19851 	case PTR_TO_MAP_VALUE:
19852 	case PTR_TO_MEM:
19853 	case PTR_TO_BUF:
19854 	case PTR_TO_TP_BUFFER:
19855 		/* If the new min/max/var_off satisfy the old ones and
19856 		 * everything else matches, we are OK.
19857 		 */
19858 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
19859 		       range_within(rold, rcur) &&
19860 		       tnum_in(rold->var_off, rcur->var_off) &&
19861 		       check_ids(rold->id, rcur->id, idmap) &&
19862 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
19863 	case PTR_TO_PACKET_META:
19864 	case PTR_TO_PACKET:
19865 		/* We must have at least as much range as the old ptr
19866 		 * did, so that any accesses which were safe before are
19867 		 * still safe.  This is true even if old range < old off,
19868 		 * since someone could have accessed through (ptr - k), or
19869 		 * even done ptr -= k in a register, to get a safe access.
19870 		 */
19871 		if (rold->range > rcur->range)
19872 			return false;
19873 		/* If the offsets don't match, we can't trust our alignment;
19874 		 * nor can we be sure that we won't fall out of range.
19875 		 */
19876 		if (rold->off != rcur->off)
19877 			return false;
19878 		/* id relations must be preserved */
19879 		if (!check_ids(rold->id, rcur->id, idmap))
19880 			return false;
19881 		/* new val must satisfy old val knowledge */
19882 		return range_within(rold, rcur) &&
19883 		       tnum_in(rold->var_off, rcur->var_off);
19884 	case PTR_TO_STACK:
19885 		/* two stack pointers are equal only if they're pointing to
19886 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
19887 		 */
19888 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
19889 	case PTR_TO_ARENA:
19890 		return true;
19891 	case PTR_TO_INSN:
19892 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
19893 			rold->off == rcur->off && range_within(rold, rcur) &&
19894 			tnum_in(rold->var_off, rcur->var_off);
19895 	default:
19896 		return regs_exact(rold, rcur, idmap);
19897 	}
19898 }
19899 
19900 static struct bpf_reg_state unbound_reg;
19901 
19902 static __init int unbound_reg_init(void)
19903 {
19904 	__mark_reg_unknown_imprecise(&unbound_reg);
19905 	return 0;
19906 }
19907 late_initcall(unbound_reg_init);
19908 
19909 static bool is_stack_all_misc(struct bpf_verifier_env *env,
19910 			      struct bpf_stack_state *stack)
19911 {
19912 	u32 i;
19913 
19914 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
19915 		if ((stack->slot_type[i] == STACK_MISC) ||
19916 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
19917 			continue;
19918 		return false;
19919 	}
19920 
19921 	return true;
19922 }
19923 
19924 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
19925 						  struct bpf_stack_state *stack)
19926 {
19927 	if (is_spilled_scalar_reg64(stack))
19928 		return &stack->spilled_ptr;
19929 
19930 	if (is_stack_all_misc(env, stack))
19931 		return &unbound_reg;
19932 
19933 	return NULL;
19934 }
19935 
19936 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
19937 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
19938 		      enum exact_level exact)
19939 {
19940 	int i, spi;
19941 
19942 	/* walk slots of the explored stack and ignore any additional
19943 	 * slots in the current stack, since explored(safe) state
19944 	 * didn't use them
19945 	 */
19946 	for (i = 0; i < old->allocated_stack; i++) {
19947 		struct bpf_reg_state *old_reg, *cur_reg;
19948 
19949 		spi = i / BPF_REG_SIZE;
19950 
19951 		if (exact == EXACT &&
19952 		    (i >= cur->allocated_stack ||
19953 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
19954 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
19955 			return false;
19956 
19957 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
19958 			continue;
19959 
19960 		if (env->allow_uninit_stack &&
19961 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
19962 			continue;
19963 
19964 		/* explored stack has more populated slots than current stack
19965 		 * and these slots were used
19966 		 */
19967 		if (i >= cur->allocated_stack)
19968 			return false;
19969 
19970 		/* 64-bit scalar spill vs all slots MISC and vice versa.
19971 		 * Load from all slots MISC produces unbound scalar.
19972 		 * Construct a fake register for such stack and call
19973 		 * regsafe() to ensure scalar ids are compared.
19974 		 */
19975 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
19976 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
19977 		if (old_reg && cur_reg) {
19978 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
19979 				return false;
19980 			i += BPF_REG_SIZE - 1;
19981 			continue;
19982 		}
19983 
19984 		/* if old state was safe with misc data in the stack
19985 		 * it will be safe with zero-initialized stack.
19986 		 * The opposite is not true
19987 		 */
19988 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
19989 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
19990 			continue;
19991 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
19992 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
19993 			/* Ex: old explored (safe) state has STACK_SPILL in
19994 			 * this stack slot, but current has STACK_MISC ->
19995 			 * this verifier states are not equivalent,
19996 			 * return false to continue verification of this path
19997 			 */
19998 			return false;
19999 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
20000 			continue;
20001 		/* Both old and cur are having same slot_type */
20002 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
20003 		case STACK_SPILL:
20004 			/* when explored and current stack slot are both storing
20005 			 * spilled registers, check that stored pointers types
20006 			 * are the same as well.
20007 			 * Ex: explored safe path could have stored
20008 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
20009 			 * but current path has stored:
20010 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
20011 			 * such verifier states are not equivalent.
20012 			 * return false to continue verification of this path
20013 			 */
20014 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
20015 				     &cur->stack[spi].spilled_ptr, idmap, exact))
20016 				return false;
20017 			break;
20018 		case STACK_DYNPTR:
20019 			old_reg = &old->stack[spi].spilled_ptr;
20020 			cur_reg = &cur->stack[spi].spilled_ptr;
20021 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
20022 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
20023 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
20024 				return false;
20025 			break;
20026 		case STACK_ITER:
20027 			old_reg = &old->stack[spi].spilled_ptr;
20028 			cur_reg = &cur->stack[spi].spilled_ptr;
20029 			/* iter.depth is not compared between states as it
20030 			 * doesn't matter for correctness and would otherwise
20031 			 * prevent convergence; we maintain it only to prevent
20032 			 * infinite loop check triggering, see
20033 			 * iter_active_depths_differ()
20034 			 */
20035 			if (old_reg->iter.btf != cur_reg->iter.btf ||
20036 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
20037 			    old_reg->iter.state != cur_reg->iter.state ||
20038 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
20039 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
20040 				return false;
20041 			break;
20042 		case STACK_IRQ_FLAG:
20043 			old_reg = &old->stack[spi].spilled_ptr;
20044 			cur_reg = &cur->stack[spi].spilled_ptr;
20045 			if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) ||
20046 			    old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class)
20047 				return false;
20048 			break;
20049 		case STACK_MISC:
20050 		case STACK_ZERO:
20051 		case STACK_INVALID:
20052 			continue;
20053 		/* Ensure that new unhandled slot types return false by default */
20054 		default:
20055 			return false;
20056 		}
20057 	}
20058 	return true;
20059 }
20060 
20061 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
20062 		    struct bpf_idmap *idmap)
20063 {
20064 	int i;
20065 
20066 	if (old->acquired_refs != cur->acquired_refs)
20067 		return false;
20068 
20069 	if (old->active_locks != cur->active_locks)
20070 		return false;
20071 
20072 	if (old->active_preempt_locks != cur->active_preempt_locks)
20073 		return false;
20074 
20075 	if (old->active_rcu_locks != cur->active_rcu_locks)
20076 		return false;
20077 
20078 	if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
20079 		return false;
20080 
20081 	if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) ||
20082 	    old->active_lock_ptr != cur->active_lock_ptr)
20083 		return false;
20084 
20085 	for (i = 0; i < old->acquired_refs; i++) {
20086 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
20087 		    old->refs[i].type != cur->refs[i].type)
20088 			return false;
20089 		switch (old->refs[i].type) {
20090 		case REF_TYPE_PTR:
20091 		case REF_TYPE_IRQ:
20092 			break;
20093 		case REF_TYPE_LOCK:
20094 		case REF_TYPE_RES_LOCK:
20095 		case REF_TYPE_RES_LOCK_IRQ:
20096 			if (old->refs[i].ptr != cur->refs[i].ptr)
20097 				return false;
20098 			break;
20099 		default:
20100 			WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
20101 			return false;
20102 		}
20103 	}
20104 
20105 	return true;
20106 }
20107 
20108 /* compare two verifier states
20109  *
20110  * all states stored in state_list are known to be valid, since
20111  * verifier reached 'bpf_exit' instruction through them
20112  *
20113  * this function is called when verifier exploring different branches of
20114  * execution popped from the state stack. If it sees an old state that has
20115  * more strict register state and more strict stack state then this execution
20116  * branch doesn't need to be explored further, since verifier already
20117  * concluded that more strict state leads to valid finish.
20118  *
20119  * Therefore two states are equivalent if register state is more conservative
20120  * and explored stack state is more conservative than the current one.
20121  * Example:
20122  *       explored                   current
20123  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
20124  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
20125  *
20126  * In other words if current stack state (one being explored) has more
20127  * valid slots than old one that already passed validation, it means
20128  * the verifier can stop exploring and conclude that current state is valid too
20129  *
20130  * Similarly with registers. If explored state has register type as invalid
20131  * whereas register type in current state is meaningful, it means that
20132  * the current state will reach 'bpf_exit' instruction safely
20133  */
20134 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
20135 			      struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact)
20136 {
20137 	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
20138 	u16 i;
20139 
20140 	if (old->callback_depth > cur->callback_depth)
20141 		return false;
20142 
20143 	for (i = 0; i < MAX_BPF_REG; i++)
20144 		if (((1 << i) & live_regs) &&
20145 		    !regsafe(env, &old->regs[i], &cur->regs[i],
20146 			     &env->idmap_scratch, exact))
20147 			return false;
20148 
20149 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
20150 		return false;
20151 
20152 	return true;
20153 }
20154 
20155 static void reset_idmap_scratch(struct bpf_verifier_env *env)
20156 {
20157 	struct bpf_idmap *idmap = &env->idmap_scratch;
20158 
20159 	idmap->tmp_id_gen = env->id_gen;
20160 	idmap->cnt = 0;
20161 }
20162 
20163 static bool states_equal(struct bpf_verifier_env *env,
20164 			 struct bpf_verifier_state *old,
20165 			 struct bpf_verifier_state *cur,
20166 			 enum exact_level exact)
20167 {
20168 	u32 insn_idx;
20169 	int i;
20170 
20171 	if (old->curframe != cur->curframe)
20172 		return false;
20173 
20174 	reset_idmap_scratch(env);
20175 
20176 	/* Verification state from speculative execution simulation
20177 	 * must never prune a non-speculative execution one.
20178 	 */
20179 	if (old->speculative && !cur->speculative)
20180 		return false;
20181 
20182 	if (old->in_sleepable != cur->in_sleepable)
20183 		return false;
20184 
20185 	if (!refsafe(old, cur, &env->idmap_scratch))
20186 		return false;
20187 
20188 	/* for states to be equal callsites have to be the same
20189 	 * and all frame states need to be equivalent
20190 	 */
20191 	for (i = 0; i <= old->curframe; i++) {
20192 		insn_idx = frame_insn_idx(old, i);
20193 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
20194 			return false;
20195 		if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
20196 			return false;
20197 	}
20198 	return true;
20199 }
20200 
20201 /* find precise scalars in the previous equivalent state and
20202  * propagate them into the current state
20203  */
20204 static int propagate_precision(struct bpf_verifier_env *env,
20205 			       const struct bpf_verifier_state *old,
20206 			       struct bpf_verifier_state *cur,
20207 			       bool *changed)
20208 {
20209 	struct bpf_reg_state *state_reg;
20210 	struct bpf_func_state *state;
20211 	int i, err = 0, fr;
20212 	bool first;
20213 
20214 	for (fr = old->curframe; fr >= 0; fr--) {
20215 		state = old->frame[fr];
20216 		state_reg = state->regs;
20217 		first = true;
20218 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
20219 			if (state_reg->type != SCALAR_VALUE ||
20220 			    !state_reg->precise)
20221 				continue;
20222 			if (env->log.level & BPF_LOG_LEVEL2) {
20223 				if (first)
20224 					verbose(env, "frame %d: propagating r%d", fr, i);
20225 				else
20226 					verbose(env, ",r%d", i);
20227 			}
20228 			bt_set_frame_reg(&env->bt, fr, i);
20229 			first = false;
20230 		}
20231 
20232 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
20233 			if (!is_spilled_reg(&state->stack[i]))
20234 				continue;
20235 			state_reg = &state->stack[i].spilled_ptr;
20236 			if (state_reg->type != SCALAR_VALUE ||
20237 			    !state_reg->precise)
20238 				continue;
20239 			if (env->log.level & BPF_LOG_LEVEL2) {
20240 				if (first)
20241 					verbose(env, "frame %d: propagating fp%d",
20242 						fr, (-i - 1) * BPF_REG_SIZE);
20243 				else
20244 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
20245 			}
20246 			bt_set_frame_slot(&env->bt, fr, i);
20247 			first = false;
20248 		}
20249 		if (!first && (env->log.level & BPF_LOG_LEVEL2))
20250 			verbose(env, "\n");
20251 	}
20252 
20253 	err = __mark_chain_precision(env, cur, -1, changed);
20254 	if (err < 0)
20255 		return err;
20256 
20257 	return 0;
20258 }
20259 
20260 #define MAX_BACKEDGE_ITERS 64
20261 
20262 /* Propagate read and precision marks from visit->backedges[*].state->equal_state
20263  * to corresponding parent states of visit->backedges[*].state until fixed point is reached,
20264  * then free visit->backedges.
20265  * After execution of this function incomplete_read_marks() will return false
20266  * for all states corresponding to @visit->callchain.
20267  */
20268 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit)
20269 {
20270 	struct bpf_scc_backedge *backedge;
20271 	struct bpf_verifier_state *st;
20272 	bool changed;
20273 	int i, err;
20274 
20275 	i = 0;
20276 	do {
20277 		if (i++ > MAX_BACKEDGE_ITERS) {
20278 			if (env->log.level & BPF_LOG_LEVEL2)
20279 				verbose(env, "%s: too many iterations\n", __func__);
20280 			for (backedge = visit->backedges; backedge; backedge = backedge->next)
20281 				mark_all_scalars_precise(env, &backedge->state);
20282 			break;
20283 		}
20284 		changed = false;
20285 		for (backedge = visit->backedges; backedge; backedge = backedge->next) {
20286 			st = &backedge->state;
20287 			err = propagate_precision(env, st->equal_state, st, &changed);
20288 			if (err)
20289 				return err;
20290 		}
20291 	} while (changed);
20292 
20293 	free_backedges(visit);
20294 	return 0;
20295 }
20296 
20297 static bool states_maybe_looping(struct bpf_verifier_state *old,
20298 				 struct bpf_verifier_state *cur)
20299 {
20300 	struct bpf_func_state *fold, *fcur;
20301 	int i, fr = cur->curframe;
20302 
20303 	if (old->curframe != fr)
20304 		return false;
20305 
20306 	fold = old->frame[fr];
20307 	fcur = cur->frame[fr];
20308 	for (i = 0; i < MAX_BPF_REG; i++)
20309 		if (memcmp(&fold->regs[i], &fcur->regs[i],
20310 			   offsetof(struct bpf_reg_state, frameno)))
20311 			return false;
20312 	return true;
20313 }
20314 
20315 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
20316 {
20317 	return env->insn_aux_data[insn_idx].is_iter_next;
20318 }
20319 
20320 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
20321  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
20322  * states to match, which otherwise would look like an infinite loop. So while
20323  * iter_next() calls are taken care of, we still need to be careful and
20324  * prevent erroneous and too eager declaration of "infinite loop", when
20325  * iterators are involved.
20326  *
20327  * Here's a situation in pseudo-BPF assembly form:
20328  *
20329  *   0: again:                          ; set up iter_next() call args
20330  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
20331  *   2:   call bpf_iter_num_next        ; this is iter_next() call
20332  *   3:   if r0 == 0 goto done
20333  *   4:   ... something useful here ...
20334  *   5:   goto again                    ; another iteration
20335  *   6: done:
20336  *   7:   r1 = &it
20337  *   8:   call bpf_iter_num_destroy     ; clean up iter state
20338  *   9:   exit
20339  *
20340  * This is a typical loop. Let's assume that we have a prune point at 1:,
20341  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
20342  * again`, assuming other heuristics don't get in a way).
20343  *
20344  * When we first time come to 1:, let's say we have some state X. We proceed
20345  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
20346  * Now we come back to validate that forked ACTIVE state. We proceed through
20347  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
20348  * are converging. But the problem is that we don't know that yet, as this
20349  * convergence has to happen at iter_next() call site only. So if nothing is
20350  * done, at 1: verifier will use bounded loop logic and declare infinite
20351  * looping (and would be *technically* correct, if not for iterator's
20352  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
20353  * don't want that. So what we do in process_iter_next_call() when we go on
20354  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
20355  * a different iteration. So when we suspect an infinite loop, we additionally
20356  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
20357  * pretend we are not looping and wait for next iter_next() call.
20358  *
20359  * This only applies to ACTIVE state. In DRAINED state we don't expect to
20360  * loop, because that would actually mean infinite loop, as DRAINED state is
20361  * "sticky", and so we'll keep returning into the same instruction with the
20362  * same state (at least in one of possible code paths).
20363  *
20364  * This approach allows to keep infinite loop heuristic even in the face of
20365  * active iterator. E.g., C snippet below is and will be detected as
20366  * infinitely looping:
20367  *
20368  *   struct bpf_iter_num it;
20369  *   int *p, x;
20370  *
20371  *   bpf_iter_num_new(&it, 0, 10);
20372  *   while ((p = bpf_iter_num_next(&t))) {
20373  *       x = p;
20374  *       while (x--) {} // <<-- infinite loop here
20375  *   }
20376  *
20377  */
20378 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
20379 {
20380 	struct bpf_reg_state *slot, *cur_slot;
20381 	struct bpf_func_state *state;
20382 	int i, fr;
20383 
20384 	for (fr = old->curframe; fr >= 0; fr--) {
20385 		state = old->frame[fr];
20386 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
20387 			if (state->stack[i].slot_type[0] != STACK_ITER)
20388 				continue;
20389 
20390 			slot = &state->stack[i].spilled_ptr;
20391 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
20392 				continue;
20393 
20394 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
20395 			if (cur_slot->iter.depth != slot->iter.depth)
20396 				return true;
20397 		}
20398 	}
20399 	return false;
20400 }
20401 
20402 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
20403 {
20404 	struct bpf_verifier_state_list *new_sl;
20405 	struct bpf_verifier_state_list *sl;
20406 	struct bpf_verifier_state *cur = env->cur_state, *new;
20407 	bool force_new_state, add_new_state, loop;
20408 	int n, err, states_cnt = 0;
20409 	struct list_head *pos, *tmp, *head;
20410 
20411 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
20412 			  /* Avoid accumulating infinitely long jmp history */
20413 			  cur->jmp_history_cnt > 40;
20414 
20415 	/* bpf progs typically have pruning point every 4 instructions
20416 	 * http://vger.kernel.org/bpfconf2019.html#session-1
20417 	 * Do not add new state for future pruning if the verifier hasn't seen
20418 	 * at least 2 jumps and at least 8 instructions.
20419 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
20420 	 * In tests that amounts to up to 50% reduction into total verifier
20421 	 * memory consumption and 20% verifier time speedup.
20422 	 */
20423 	add_new_state = force_new_state;
20424 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
20425 	    env->insn_processed - env->prev_insn_processed >= 8)
20426 		add_new_state = true;
20427 
20428 	clean_live_states(env, insn_idx, cur);
20429 
20430 	loop = false;
20431 	head = explored_state(env, insn_idx);
20432 	list_for_each_safe(pos, tmp, head) {
20433 		sl = container_of(pos, struct bpf_verifier_state_list, node);
20434 		states_cnt++;
20435 		if (sl->state.insn_idx != insn_idx)
20436 			continue;
20437 
20438 		if (sl->state.branches) {
20439 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
20440 
20441 			if (frame->in_async_callback_fn &&
20442 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
20443 				/* Different async_entry_cnt means that the verifier is
20444 				 * processing another entry into async callback.
20445 				 * Seeing the same state is not an indication of infinite
20446 				 * loop or infinite recursion.
20447 				 * But finding the same state doesn't mean that it's safe
20448 				 * to stop processing the current state. The previous state
20449 				 * hasn't yet reached bpf_exit, since state.branches > 0.
20450 				 * Checking in_async_callback_fn alone is not enough either.
20451 				 * Since the verifier still needs to catch infinite loops
20452 				 * inside async callbacks.
20453 				 */
20454 				goto skip_inf_loop_check;
20455 			}
20456 			/* BPF open-coded iterators loop detection is special.
20457 			 * states_maybe_looping() logic is too simplistic in detecting
20458 			 * states that *might* be equivalent, because it doesn't know
20459 			 * about ID remapping, so don't even perform it.
20460 			 * See process_iter_next_call() and iter_active_depths_differ()
20461 			 * for overview of the logic. When current and one of parent
20462 			 * states are detected as equivalent, it's a good thing: we prove
20463 			 * convergence and can stop simulating further iterations.
20464 			 * It's safe to assume that iterator loop will finish, taking into
20465 			 * account iter_next() contract of eventually returning
20466 			 * sticky NULL result.
20467 			 *
20468 			 * Note, that states have to be compared exactly in this case because
20469 			 * read and precision marks might not be finalized inside the loop.
20470 			 * E.g. as in the program below:
20471 			 *
20472 			 *     1. r7 = -16
20473 			 *     2. r6 = bpf_get_prandom_u32()
20474 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
20475 			 *     4.   if (r6 != 42) {
20476 			 *     5.     r7 = -32
20477 			 *     6.     r6 = bpf_get_prandom_u32()
20478 			 *     7.     continue
20479 			 *     8.   }
20480 			 *     9.   r0 = r10
20481 			 *    10.   r0 += r7
20482 			 *    11.   r8 = *(u64 *)(r0 + 0)
20483 			 *    12.   r6 = bpf_get_prandom_u32()
20484 			 *    13. }
20485 			 *
20486 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
20487 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
20488 			 * not have read or precision mark for r7 yet, thus inexact states
20489 			 * comparison would discard current state with r7=-32
20490 			 * => unsafe memory access at 11 would not be caught.
20491 			 */
20492 			if (is_iter_next_insn(env, insn_idx)) {
20493 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
20494 					struct bpf_func_state *cur_frame;
20495 					struct bpf_reg_state *iter_state, *iter_reg;
20496 					int spi;
20497 
20498 					cur_frame = cur->frame[cur->curframe];
20499 					/* btf_check_iter_kfuncs() enforces that
20500 					 * iter state pointer is always the first arg
20501 					 */
20502 					iter_reg = &cur_frame->regs[BPF_REG_1];
20503 					/* current state is valid due to states_equal(),
20504 					 * so we can assume valid iter and reg state,
20505 					 * no need for extra (re-)validations
20506 					 */
20507 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
20508 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
20509 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
20510 						loop = true;
20511 						goto hit;
20512 					}
20513 				}
20514 				goto skip_inf_loop_check;
20515 			}
20516 			if (is_may_goto_insn_at(env, insn_idx)) {
20517 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
20518 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
20519 					loop = true;
20520 					goto hit;
20521 				}
20522 			}
20523 			if (bpf_calls_callback(env, insn_idx)) {
20524 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
20525 					loop = true;
20526 					goto hit;
20527 				}
20528 				goto skip_inf_loop_check;
20529 			}
20530 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
20531 			if (states_maybe_looping(&sl->state, cur) &&
20532 			    states_equal(env, &sl->state, cur, EXACT) &&
20533 			    !iter_active_depths_differ(&sl->state, cur) &&
20534 			    sl->state.may_goto_depth == cur->may_goto_depth &&
20535 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
20536 				verbose_linfo(env, insn_idx, "; ");
20537 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
20538 				verbose(env, "cur state:");
20539 				print_verifier_state(env, cur, cur->curframe, true);
20540 				verbose(env, "old state:");
20541 				print_verifier_state(env, &sl->state, cur->curframe, true);
20542 				return -EINVAL;
20543 			}
20544 			/* if the verifier is processing a loop, avoid adding new state
20545 			 * too often, since different loop iterations have distinct
20546 			 * states and may not help future pruning.
20547 			 * This threshold shouldn't be too low to make sure that
20548 			 * a loop with large bound will be rejected quickly.
20549 			 * The most abusive loop will be:
20550 			 * r1 += 1
20551 			 * if r1 < 1000000 goto pc-2
20552 			 * 1M insn_procssed limit / 100 == 10k peak states.
20553 			 * This threshold shouldn't be too high either, since states
20554 			 * at the end of the loop are likely to be useful in pruning.
20555 			 */
20556 skip_inf_loop_check:
20557 			if (!force_new_state &&
20558 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
20559 			    env->insn_processed - env->prev_insn_processed < 100)
20560 				add_new_state = false;
20561 			goto miss;
20562 		}
20563 		/* See comments for mark_all_regs_read_and_precise() */
20564 		loop = incomplete_read_marks(env, &sl->state);
20565 		if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) {
20566 hit:
20567 			sl->hit_cnt++;
20568 
20569 			/* if previous state reached the exit with precision and
20570 			 * current state is equivalent to it (except precision marks)
20571 			 * the precision needs to be propagated back in
20572 			 * the current state.
20573 			 */
20574 			err = 0;
20575 			if (is_jmp_point(env, env->insn_idx))
20576 				err = push_jmp_history(env, cur, 0, 0);
20577 			err = err ? : propagate_precision(env, &sl->state, cur, NULL);
20578 			if (err)
20579 				return err;
20580 			/* When processing iterator based loops above propagate_liveness and
20581 			 * propagate_precision calls are not sufficient to transfer all relevant
20582 			 * read and precision marks. E.g. consider the following case:
20583 			 *
20584 			 *  .-> A --.  Assume the states are visited in the order A, B, C.
20585 			 *  |   |   |  Assume that state B reaches a state equivalent to state A.
20586 			 *  |   v   v  At this point, state C is not processed yet, so state A
20587 			 *  '-- B   C  has not received any read or precision marks from C.
20588 			 *             Thus, marks propagated from A to B are incomplete.
20589 			 *
20590 			 * The verifier mitigates this by performing the following steps:
20591 			 *
20592 			 * - Prior to the main verification pass, strongly connected components
20593 			 *   (SCCs) are computed over the program's control flow graph,
20594 			 *   intraprocedurally.
20595 			 *
20596 			 * - During the main verification pass, `maybe_enter_scc()` checks
20597 			 *   whether the current verifier state is entering an SCC. If so, an
20598 			 *   instance of a `bpf_scc_visit` object is created, and the state
20599 			 *   entering the SCC is recorded as the entry state.
20600 			 *
20601 			 * - This instance is associated not with the SCC itself, but with a
20602 			 *   `bpf_scc_callchain`: a tuple consisting of the call sites leading to
20603 			 *   the SCC and the SCC id. See `compute_scc_callchain()`.
20604 			 *
20605 			 * - When a verification path encounters a `states_equal(...,
20606 			 *   RANGE_WITHIN)` condition, there exists a call chain describing the
20607 			 *   current state and a corresponding `bpf_scc_visit` instance. A copy
20608 			 *   of the current state is created and added to
20609 			 *   `bpf_scc_visit->backedges`.
20610 			 *
20611 			 * - When a verification path terminates, `maybe_exit_scc()` is called
20612 			 *   from `update_branch_counts()`. For states with `branches == 0`, it
20613 			 *   checks whether the state is the entry state of any `bpf_scc_visit`
20614 			 *   instance. If it is, this indicates that all paths originating from
20615 			 *   this SCC visit have been explored. `propagate_backedges()` is then
20616 			 *   called, which propagates read and precision marks through the
20617 			 *   backedges until a fixed point is reached.
20618 			 *   (In the earlier example, this would propagate marks from A to B,
20619 			 *    from C to A, and then again from A to B.)
20620 			 *
20621 			 * A note on callchains
20622 			 * --------------------
20623 			 *
20624 			 * Consider the following example:
20625 			 *
20626 			 *     void foo() { loop { ... SCC#1 ... } }
20627 			 *     void main() {
20628 			 *       A: foo();
20629 			 *       B: ...
20630 			 *       C: foo();
20631 			 *     }
20632 			 *
20633 			 * Here, there are two distinct callchains leading to SCC#1:
20634 			 * - (A, SCC#1)
20635 			 * - (C, SCC#1)
20636 			 *
20637 			 * Each callchain identifies a separate `bpf_scc_visit` instance that
20638 			 * accumulates backedge states. The `propagate_{liveness,precision}()`
20639 			 * functions traverse the parent state of each backedge state, which
20640 			 * means these parent states must remain valid (i.e., not freed) while
20641 			 * the corresponding `bpf_scc_visit` instance exists.
20642 			 *
20643 			 * Associating `bpf_scc_visit` instances directly with SCCs instead of
20644 			 * callchains would break this invariant:
20645 			 * - States explored during `C: foo()` would contribute backedges to
20646 			 *   SCC#1, but SCC#1 would only be exited once the exploration of
20647 			 *   `A: foo()` completes.
20648 			 * - By that time, the states explored between `A: foo()` and `C: foo()`
20649 			 *   (i.e., `B: ...`) may have already been freed, causing the parent
20650 			 *   links for states from `C: foo()` to become invalid.
20651 			 */
20652 			if (loop) {
20653 				struct bpf_scc_backedge *backedge;
20654 
20655 				backedge = kzalloc_obj(*backedge,
20656 						       GFP_KERNEL_ACCOUNT);
20657 				if (!backedge)
20658 					return -ENOMEM;
20659 				err = copy_verifier_state(&backedge->state, cur);
20660 				backedge->state.equal_state = &sl->state;
20661 				backedge->state.insn_idx = insn_idx;
20662 				err = err ?: add_scc_backedge(env, &sl->state, backedge);
20663 				if (err) {
20664 					free_verifier_state(&backedge->state, false);
20665 					kfree(backedge);
20666 					return err;
20667 				}
20668 			}
20669 			return 1;
20670 		}
20671 miss:
20672 		/* when new state is not going to be added do not increase miss count.
20673 		 * Otherwise several loop iterations will remove the state
20674 		 * recorded earlier. The goal of these heuristics is to have
20675 		 * states from some iterations of the loop (some in the beginning
20676 		 * and some at the end) to help pruning.
20677 		 */
20678 		if (add_new_state)
20679 			sl->miss_cnt++;
20680 		/* heuristic to determine whether this state is beneficial
20681 		 * to keep checking from state equivalence point of view.
20682 		 * Higher numbers increase max_states_per_insn and verification time,
20683 		 * but do not meaningfully decrease insn_processed.
20684 		 * 'n' controls how many times state could miss before eviction.
20685 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
20686 		 * too early would hinder iterator convergence.
20687 		 */
20688 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
20689 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
20690 			/* the state is unlikely to be useful. Remove it to
20691 			 * speed up verification
20692 			 */
20693 			sl->in_free_list = true;
20694 			list_del(&sl->node);
20695 			list_add(&sl->node, &env->free_list);
20696 			env->free_list_size++;
20697 			env->explored_states_size--;
20698 			maybe_free_verifier_state(env, sl);
20699 		}
20700 	}
20701 
20702 	if (env->max_states_per_insn < states_cnt)
20703 		env->max_states_per_insn = states_cnt;
20704 
20705 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
20706 		return 0;
20707 
20708 	if (!add_new_state)
20709 		return 0;
20710 
20711 	/* There were no equivalent states, remember the current one.
20712 	 * Technically the current state is not proven to be safe yet,
20713 	 * but it will either reach outer most bpf_exit (which means it's safe)
20714 	 * or it will be rejected. When there are no loops the verifier won't be
20715 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
20716 	 * again on the way to bpf_exit.
20717 	 * When looping the sl->state.branches will be > 0 and this state
20718 	 * will not be considered for equivalence until branches == 0.
20719 	 */
20720 	new_sl = kzalloc_obj(struct bpf_verifier_state_list, GFP_KERNEL_ACCOUNT);
20721 	if (!new_sl)
20722 		return -ENOMEM;
20723 	env->total_states++;
20724 	env->explored_states_size++;
20725 	update_peak_states(env);
20726 	env->prev_jmps_processed = env->jmps_processed;
20727 	env->prev_insn_processed = env->insn_processed;
20728 
20729 	/* forget precise markings we inherited, see __mark_chain_precision */
20730 	if (env->bpf_capable)
20731 		mark_all_scalars_imprecise(env, cur);
20732 
20733 	clear_singular_ids(env, cur);
20734 
20735 	/* add new state to the head of linked list */
20736 	new = &new_sl->state;
20737 	err = copy_verifier_state(new, cur);
20738 	if (err) {
20739 		free_verifier_state(new, false);
20740 		kfree(new_sl);
20741 		return err;
20742 	}
20743 	new->insn_idx = insn_idx;
20744 	verifier_bug_if(new->branches != 1, env,
20745 			"%s:branches_to_explore=%d insn %d",
20746 			__func__, new->branches, insn_idx);
20747 	err = maybe_enter_scc(env, new);
20748 	if (err) {
20749 		free_verifier_state(new, false);
20750 		kfree(new_sl);
20751 		return err;
20752 	}
20753 
20754 	cur->parent = new;
20755 	cur->first_insn_idx = insn_idx;
20756 	cur->dfs_depth = new->dfs_depth + 1;
20757 	clear_jmp_history(cur);
20758 	list_add(&new_sl->node, head);
20759 	return 0;
20760 }
20761 
20762 /* Return true if it's OK to have the same insn return a different type. */
20763 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
20764 {
20765 	switch (base_type(type)) {
20766 	case PTR_TO_CTX:
20767 	case PTR_TO_SOCKET:
20768 	case PTR_TO_SOCK_COMMON:
20769 	case PTR_TO_TCP_SOCK:
20770 	case PTR_TO_XDP_SOCK:
20771 	case PTR_TO_BTF_ID:
20772 	case PTR_TO_ARENA:
20773 		return false;
20774 	default:
20775 		return true;
20776 	}
20777 }
20778 
20779 /* If an instruction was previously used with particular pointer types, then we
20780  * need to be careful to avoid cases such as the below, where it may be ok
20781  * for one branch accessing the pointer, but not ok for the other branch:
20782  *
20783  * R1 = sock_ptr
20784  * goto X;
20785  * ...
20786  * R1 = some_other_valid_ptr;
20787  * goto X;
20788  * ...
20789  * R2 = *(u32 *)(R1 + 0);
20790  */
20791 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
20792 {
20793 	return src != prev && (!reg_type_mismatch_ok(src) ||
20794 			       !reg_type_mismatch_ok(prev));
20795 }
20796 
20797 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
20798 {
20799 	switch (base_type(type)) {
20800 	case PTR_TO_MEM:
20801 	case PTR_TO_BTF_ID:
20802 		return true;
20803 	default:
20804 		return false;
20805 	}
20806 }
20807 
20808 static bool is_ptr_to_mem(enum bpf_reg_type type)
20809 {
20810 	return base_type(type) == PTR_TO_MEM;
20811 }
20812 
20813 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
20814 			     bool allow_trust_mismatch)
20815 {
20816 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
20817 	enum bpf_reg_type merged_type;
20818 
20819 	if (*prev_type == NOT_INIT) {
20820 		/* Saw a valid insn
20821 		 * dst_reg = *(u32 *)(src_reg + off)
20822 		 * save type to validate intersecting paths
20823 		 */
20824 		*prev_type = type;
20825 	} else if (reg_type_mismatch(type, *prev_type)) {
20826 		/* Abuser program is trying to use the same insn
20827 		 * dst_reg = *(u32*) (src_reg + off)
20828 		 * with different pointer types:
20829 		 * src_reg == ctx in one branch and
20830 		 * src_reg == stack|map in some other branch.
20831 		 * Reject it.
20832 		 */
20833 		if (allow_trust_mismatch &&
20834 		    is_ptr_to_mem_or_btf_id(type) &&
20835 		    is_ptr_to_mem_or_btf_id(*prev_type)) {
20836 			/*
20837 			 * Have to support a use case when one path through
20838 			 * the program yields TRUSTED pointer while another
20839 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
20840 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
20841 			 * Same behavior of MEM_RDONLY flag.
20842 			 */
20843 			if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type))
20844 				merged_type = PTR_TO_MEM;
20845 			else
20846 				merged_type = PTR_TO_BTF_ID;
20847 			if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED))
20848 				merged_type |= PTR_UNTRUSTED;
20849 			if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY))
20850 				merged_type |= MEM_RDONLY;
20851 			*prev_type = merged_type;
20852 		} else {
20853 			verbose(env, "same insn cannot be used with different pointers\n");
20854 			return -EINVAL;
20855 		}
20856 	}
20857 
20858 	return 0;
20859 }
20860 
20861 enum {
20862 	PROCESS_BPF_EXIT = 1
20863 };
20864 
20865 static int process_bpf_exit_full(struct bpf_verifier_env *env,
20866 				 bool *do_print_state,
20867 				 bool exception_exit)
20868 {
20869 	/* We must do check_reference_leak here before
20870 	 * prepare_func_exit to handle the case when
20871 	 * state->curframe > 0, it may be a callback function,
20872 	 * for which reference_state must match caller reference
20873 	 * state when it exits.
20874 	 */
20875 	int err = check_resource_leak(env, exception_exit,
20876 				      !env->cur_state->curframe,
20877 				      "BPF_EXIT instruction in main prog");
20878 	if (err)
20879 		return err;
20880 
20881 	/* The side effect of the prepare_func_exit which is
20882 	 * being skipped is that it frees bpf_func_state.
20883 	 * Typically, process_bpf_exit will only be hit with
20884 	 * outermost exit. copy_verifier_state in pop_stack will
20885 	 * handle freeing of any extra bpf_func_state left over
20886 	 * from not processing all nested function exits. We
20887 	 * also skip return code checks as they are not needed
20888 	 * for exceptional exits.
20889 	 */
20890 	if (exception_exit)
20891 		return PROCESS_BPF_EXIT;
20892 
20893 	if (env->cur_state->curframe) {
20894 		/* exit from nested function */
20895 		err = prepare_func_exit(env, &env->insn_idx);
20896 		if (err)
20897 			return err;
20898 		*do_print_state = true;
20899 		return 0;
20900 	}
20901 
20902 	err = check_return_code(env, BPF_REG_0, "R0");
20903 	if (err)
20904 		return err;
20905 	return PROCESS_BPF_EXIT;
20906 }
20907 
20908 static int indirect_jump_min_max_index(struct bpf_verifier_env *env,
20909 				       int regno,
20910 				       struct bpf_map *map,
20911 				       u32 *pmin_index, u32 *pmax_index)
20912 {
20913 	struct bpf_reg_state *reg = reg_state(env, regno);
20914 	u64 min_index, max_index;
20915 	const u32 size = 8;
20916 
20917 	if (check_add_overflow(reg->umin_value, reg->off, &min_index) ||
20918 		(min_index > (u64) U32_MAX * size)) {
20919 		verbose(env, "the sum of R%u umin_value %llu and off %u is too big\n",
20920 			     regno, reg->umin_value, reg->off);
20921 		return -ERANGE;
20922 	}
20923 	if (check_add_overflow(reg->umax_value, reg->off, &max_index) ||
20924 		(max_index > (u64) U32_MAX * size)) {
20925 		verbose(env, "the sum of R%u umax_value %llu and off %u is too big\n",
20926 			     regno, reg->umax_value, reg->off);
20927 		return -ERANGE;
20928 	}
20929 
20930 	min_index /= size;
20931 	max_index /= size;
20932 
20933 	if (max_index >= map->max_entries) {
20934 		verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n",
20935 			     regno, min_index, max_index, map->max_entries);
20936 		return -EINVAL;
20937 	}
20938 
20939 	*pmin_index = min_index;
20940 	*pmax_index = max_index;
20941 	return 0;
20942 }
20943 
20944 /* gotox *dst_reg */
20945 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
20946 {
20947 	struct bpf_verifier_state *other_branch;
20948 	struct bpf_reg_state *dst_reg;
20949 	struct bpf_map *map;
20950 	u32 min_index, max_index;
20951 	int err = 0;
20952 	int n;
20953 	int i;
20954 
20955 	dst_reg = reg_state(env, insn->dst_reg);
20956 	if (dst_reg->type != PTR_TO_INSN) {
20957 		verbose(env, "R%d has type %s, expected PTR_TO_INSN\n",
20958 			     insn->dst_reg, reg_type_str(env, dst_reg->type));
20959 		return -EINVAL;
20960 	}
20961 
20962 	map = dst_reg->map_ptr;
20963 	if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg))
20964 		return -EFAULT;
20965 
20966 	if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env,
20967 			    "R%d has incorrect map type %d", insn->dst_reg, map->map_type))
20968 		return -EFAULT;
20969 
20970 	err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
20971 	if (err)
20972 		return err;
20973 
20974 	/* Ensure that the buffer is large enough */
20975 	if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) {
20976 		env->gotox_tmp_buf = iarray_realloc(env->gotox_tmp_buf,
20977 						    max_index - min_index + 1);
20978 		if (!env->gotox_tmp_buf)
20979 			return -ENOMEM;
20980 	}
20981 
20982 	n = copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items);
20983 	if (n < 0)
20984 		return n;
20985 	if (n == 0) {
20986 		verbose(env, "register R%d doesn't point to any offset in map id=%d\n",
20987 			     insn->dst_reg, map->id);
20988 		return -EINVAL;
20989 	}
20990 
20991 	for (i = 0; i < n - 1; i++) {
20992 		other_branch = push_stack(env, env->gotox_tmp_buf->items[i],
20993 					  env->insn_idx, env->cur_state->speculative);
20994 		if (IS_ERR(other_branch))
20995 			return PTR_ERR(other_branch);
20996 	}
20997 	env->insn_idx = env->gotox_tmp_buf->items[n-1];
20998 	return 0;
20999 }
21000 
21001 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
21002 {
21003 	int err;
21004 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
21005 	u8 class = BPF_CLASS(insn->code);
21006 
21007 	if (class == BPF_ALU || class == BPF_ALU64) {
21008 		err = check_alu_op(env, insn);
21009 		if (err)
21010 			return err;
21011 
21012 	} else if (class == BPF_LDX) {
21013 		bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX;
21014 
21015 		/* Check for reserved fields is already done in
21016 		 * resolve_pseudo_ldimm64().
21017 		 */
21018 		err = check_load_mem(env, insn, false, is_ldsx, true, "ldx");
21019 		if (err)
21020 			return err;
21021 	} else if (class == BPF_STX) {
21022 		if (BPF_MODE(insn->code) == BPF_ATOMIC) {
21023 			err = check_atomic(env, insn);
21024 			if (err)
21025 				return err;
21026 			env->insn_idx++;
21027 			return 0;
21028 		}
21029 
21030 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
21031 			verbose(env, "BPF_STX uses reserved fields\n");
21032 			return -EINVAL;
21033 		}
21034 
21035 		err = check_store_reg(env, insn, false);
21036 		if (err)
21037 			return err;
21038 	} else if (class == BPF_ST) {
21039 		enum bpf_reg_type dst_reg_type;
21040 
21041 		if (BPF_MODE(insn->code) != BPF_MEM ||
21042 		    insn->src_reg != BPF_REG_0) {
21043 			verbose(env, "BPF_ST uses reserved fields\n");
21044 			return -EINVAL;
21045 		}
21046 		/* check src operand */
21047 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
21048 		if (err)
21049 			return err;
21050 
21051 		dst_reg_type = cur_regs(env)[insn->dst_reg].type;
21052 
21053 		/* check that memory (dst_reg + off) is writeable */
21054 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
21055 				       insn->off, BPF_SIZE(insn->code),
21056 				       BPF_WRITE, -1, false, false);
21057 		if (err)
21058 			return err;
21059 
21060 		err = save_aux_ptr_type(env, dst_reg_type, false);
21061 		if (err)
21062 			return err;
21063 	} else if (class == BPF_JMP || class == BPF_JMP32) {
21064 		u8 opcode = BPF_OP(insn->code);
21065 
21066 		env->jmps_processed++;
21067 		if (opcode == BPF_CALL) {
21068 			if (BPF_SRC(insn->code) != BPF_K ||
21069 			    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL &&
21070 			     insn->off != 0) ||
21071 			    (insn->src_reg != BPF_REG_0 &&
21072 			     insn->src_reg != BPF_PSEUDO_CALL &&
21073 			     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
21074 			    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
21075 				verbose(env, "BPF_CALL uses reserved fields\n");
21076 				return -EINVAL;
21077 			}
21078 
21079 			if (env->cur_state->active_locks) {
21080 				if ((insn->src_reg == BPF_REG_0 &&
21081 				     insn->imm != BPF_FUNC_spin_unlock) ||
21082 				    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
21083 				     (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
21084 					verbose(env,
21085 						"function calls are not allowed while holding a lock\n");
21086 					return -EINVAL;
21087 				}
21088 			}
21089 			if (insn->src_reg == BPF_PSEUDO_CALL) {
21090 				err = check_func_call(env, insn, &env->insn_idx);
21091 			} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
21092 				err = check_kfunc_call(env, insn, &env->insn_idx);
21093 				if (!err && is_bpf_throw_kfunc(insn))
21094 					return process_bpf_exit_full(env, do_print_state, true);
21095 			} else {
21096 				err = check_helper_call(env, insn, &env->insn_idx);
21097 			}
21098 			if (err)
21099 				return err;
21100 
21101 			mark_reg_scratched(env, BPF_REG_0);
21102 		} else if (opcode == BPF_JA) {
21103 			if (BPF_SRC(insn->code) == BPF_X) {
21104 				if (insn->src_reg != BPF_REG_0 ||
21105 				    insn->imm != 0 || insn->off != 0) {
21106 					verbose(env, "BPF_JA|BPF_X uses reserved fields\n");
21107 					return -EINVAL;
21108 				}
21109 				return check_indirect_jump(env, insn);
21110 			}
21111 
21112 			if (BPF_SRC(insn->code) != BPF_K ||
21113 			    insn->src_reg != BPF_REG_0 ||
21114 			    insn->dst_reg != BPF_REG_0 ||
21115 			    (class == BPF_JMP && insn->imm != 0) ||
21116 			    (class == BPF_JMP32 && insn->off != 0)) {
21117 				verbose(env, "BPF_JA uses reserved fields\n");
21118 				return -EINVAL;
21119 			}
21120 
21121 			if (class == BPF_JMP)
21122 				env->insn_idx += insn->off + 1;
21123 			else
21124 				env->insn_idx += insn->imm + 1;
21125 			return 0;
21126 		} else if (opcode == BPF_EXIT) {
21127 			if (BPF_SRC(insn->code) != BPF_K ||
21128 			    insn->imm != 0 ||
21129 			    insn->src_reg != BPF_REG_0 ||
21130 			    insn->dst_reg != BPF_REG_0 ||
21131 			    class == BPF_JMP32) {
21132 				verbose(env, "BPF_EXIT uses reserved fields\n");
21133 				return -EINVAL;
21134 			}
21135 			return process_bpf_exit_full(env, do_print_state, false);
21136 		} else {
21137 			err = check_cond_jmp_op(env, insn, &env->insn_idx);
21138 			if (err)
21139 				return err;
21140 		}
21141 	} else if (class == BPF_LD) {
21142 		u8 mode = BPF_MODE(insn->code);
21143 
21144 		if (mode == BPF_ABS || mode == BPF_IND) {
21145 			err = check_ld_abs(env, insn);
21146 			if (err)
21147 				return err;
21148 
21149 		} else if (mode == BPF_IMM) {
21150 			err = check_ld_imm(env, insn);
21151 			if (err)
21152 				return err;
21153 
21154 			env->insn_idx++;
21155 			sanitize_mark_insn_seen(env);
21156 		} else {
21157 			verbose(env, "invalid BPF_LD mode\n");
21158 			return -EINVAL;
21159 		}
21160 	} else {
21161 		verbose(env, "unknown insn class %d\n", class);
21162 		return -EINVAL;
21163 	}
21164 
21165 	env->insn_idx++;
21166 	return 0;
21167 }
21168 
21169 static int do_check(struct bpf_verifier_env *env)
21170 {
21171 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
21172 	struct bpf_verifier_state *state = env->cur_state;
21173 	struct bpf_insn *insns = env->prog->insnsi;
21174 	int insn_cnt = env->prog->len;
21175 	bool do_print_state = false;
21176 	int prev_insn_idx = -1;
21177 
21178 	for (;;) {
21179 		struct bpf_insn *insn;
21180 		struct bpf_insn_aux_data *insn_aux;
21181 		int err, marks_err;
21182 
21183 		/* reset current history entry on each new instruction */
21184 		env->cur_hist_ent = NULL;
21185 
21186 		env->prev_insn_idx = prev_insn_idx;
21187 		if (env->insn_idx >= insn_cnt) {
21188 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
21189 				env->insn_idx, insn_cnt);
21190 			return -EFAULT;
21191 		}
21192 
21193 		insn = &insns[env->insn_idx];
21194 		insn_aux = &env->insn_aux_data[env->insn_idx];
21195 
21196 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
21197 			verbose(env,
21198 				"BPF program is too large. Processed %d insn\n",
21199 				env->insn_processed);
21200 			return -E2BIG;
21201 		}
21202 
21203 		state->last_insn_idx = env->prev_insn_idx;
21204 		state->insn_idx = env->insn_idx;
21205 
21206 		if (is_prune_point(env, env->insn_idx)) {
21207 			err = is_state_visited(env, env->insn_idx);
21208 			if (err < 0)
21209 				return err;
21210 			if (err == 1) {
21211 				/* found equivalent state, can prune the search */
21212 				if (env->log.level & BPF_LOG_LEVEL) {
21213 					if (do_print_state)
21214 						verbose(env, "\nfrom %d to %d%s: safe\n",
21215 							env->prev_insn_idx, env->insn_idx,
21216 							env->cur_state->speculative ?
21217 							" (speculative execution)" : "");
21218 					else
21219 						verbose(env, "%d: safe\n", env->insn_idx);
21220 				}
21221 				goto process_bpf_exit;
21222 			}
21223 		}
21224 
21225 		if (is_jmp_point(env, env->insn_idx)) {
21226 			err = push_jmp_history(env, state, 0, 0);
21227 			if (err)
21228 				return err;
21229 		}
21230 
21231 		if (signal_pending(current))
21232 			return -EAGAIN;
21233 
21234 		if (need_resched())
21235 			cond_resched();
21236 
21237 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
21238 			verbose(env, "\nfrom %d to %d%s:",
21239 				env->prev_insn_idx, env->insn_idx,
21240 				env->cur_state->speculative ?
21241 				" (speculative execution)" : "");
21242 			print_verifier_state(env, state, state->curframe, true);
21243 			do_print_state = false;
21244 		}
21245 
21246 		if (env->log.level & BPF_LOG_LEVEL) {
21247 			if (verifier_state_scratched(env))
21248 				print_insn_state(env, state, state->curframe);
21249 
21250 			verbose_linfo(env, env->insn_idx, "; ");
21251 			env->prev_log_pos = env->log.end_pos;
21252 			verbose(env, "%d: ", env->insn_idx);
21253 			verbose_insn(env, insn);
21254 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
21255 			env->prev_log_pos = env->log.end_pos;
21256 		}
21257 
21258 		if (bpf_prog_is_offloaded(env->prog->aux)) {
21259 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
21260 							   env->prev_insn_idx);
21261 			if (err)
21262 				return err;
21263 		}
21264 
21265 		sanitize_mark_insn_seen(env);
21266 		prev_insn_idx = env->insn_idx;
21267 
21268 		/* Reduce verification complexity by stopping speculative path
21269 		 * verification when a nospec is encountered.
21270 		 */
21271 		if (state->speculative && insn_aux->nospec)
21272 			goto process_bpf_exit;
21273 
21274 		err = bpf_reset_stack_write_marks(env, env->insn_idx);
21275 		if (err)
21276 			return err;
21277 		err = do_check_insn(env, &do_print_state);
21278 		if (err >= 0 || error_recoverable_with_nospec(err)) {
21279 			marks_err = bpf_commit_stack_write_marks(env);
21280 			if (marks_err)
21281 				return marks_err;
21282 		}
21283 		if (error_recoverable_with_nospec(err) && state->speculative) {
21284 			/* Prevent this speculative path from ever reaching the
21285 			 * insn that would have been unsafe to execute.
21286 			 */
21287 			insn_aux->nospec = true;
21288 			/* If it was an ADD/SUB insn, potentially remove any
21289 			 * markings for alu sanitization.
21290 			 */
21291 			insn_aux->alu_state = 0;
21292 			goto process_bpf_exit;
21293 		} else if (err < 0) {
21294 			return err;
21295 		} else if (err == PROCESS_BPF_EXIT) {
21296 			goto process_bpf_exit;
21297 		}
21298 		WARN_ON_ONCE(err);
21299 
21300 		if (state->speculative && insn_aux->nospec_result) {
21301 			/* If we are on a path that performed a jump-op, this
21302 			 * may skip a nospec patched-in after the jump. This can
21303 			 * currently never happen because nospec_result is only
21304 			 * used for the write-ops
21305 			 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper
21306 			 * calls. These must never skip the following insn
21307 			 * (i.e., bpf_insn_successors()'s opcode_info.can_jump
21308 			 * is false). Still, add a warning to document this in
21309 			 * case nospec_result is used elsewhere in the future.
21310 			 *
21311 			 * All non-branch instructions have a single
21312 			 * fall-through edge. For these, nospec_result should
21313 			 * already work.
21314 			 */
21315 			if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP ||
21316 					     BPF_CLASS(insn->code) == BPF_JMP32) &&
21317 					    BPF_OP(insn->code) != BPF_CALL, env,
21318 					    "speculation barrier after jump instruction may not have the desired effect"))
21319 				return -EFAULT;
21320 process_bpf_exit:
21321 			mark_verifier_state_scratched(env);
21322 			err = update_branch_counts(env, env->cur_state);
21323 			if (err)
21324 				return err;
21325 			err = bpf_update_live_stack(env);
21326 			if (err)
21327 				return err;
21328 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
21329 					pop_log);
21330 			if (err < 0) {
21331 				if (err != -ENOENT)
21332 					return err;
21333 				break;
21334 			} else {
21335 				do_print_state = true;
21336 				continue;
21337 			}
21338 		}
21339 	}
21340 
21341 	return 0;
21342 }
21343 
21344 static int find_btf_percpu_datasec(struct btf *btf)
21345 {
21346 	const struct btf_type *t;
21347 	const char *tname;
21348 	int i, n;
21349 
21350 	/*
21351 	 * Both vmlinux and module each have their own ".data..percpu"
21352 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
21353 	 * types to look at only module's own BTF types.
21354 	 */
21355 	n = btf_nr_types(btf);
21356 	for (i = btf_named_start_id(btf, true); i < n; i++) {
21357 		t = btf_type_by_id(btf, i);
21358 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
21359 			continue;
21360 
21361 		tname = btf_name_by_offset(btf, t->name_off);
21362 		if (!strcmp(tname, ".data..percpu"))
21363 			return i;
21364 	}
21365 
21366 	return -ENOENT;
21367 }
21368 
21369 /*
21370  * Add btf to the env->used_btfs array. If needed, refcount the
21371  * corresponding kernel module. To simplify caller's logic
21372  * in case of error or if btf was added before the function
21373  * decreases the btf refcount.
21374  */
21375 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
21376 {
21377 	struct btf_mod_pair *btf_mod;
21378 	int ret = 0;
21379 	int i;
21380 
21381 	/* check whether we recorded this BTF (and maybe module) already */
21382 	for (i = 0; i < env->used_btf_cnt; i++)
21383 		if (env->used_btfs[i].btf == btf)
21384 			goto ret_put;
21385 
21386 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
21387 		verbose(env, "The total number of btfs per program has reached the limit of %u\n",
21388 			MAX_USED_BTFS);
21389 		ret = -E2BIG;
21390 		goto ret_put;
21391 	}
21392 
21393 	btf_mod = &env->used_btfs[env->used_btf_cnt];
21394 	btf_mod->btf = btf;
21395 	btf_mod->module = NULL;
21396 
21397 	/* if we reference variables from kernel module, bump its refcount */
21398 	if (btf_is_module(btf)) {
21399 		btf_mod->module = btf_try_get_module(btf);
21400 		if (!btf_mod->module) {
21401 			ret = -ENXIO;
21402 			goto ret_put;
21403 		}
21404 	}
21405 
21406 	env->used_btf_cnt++;
21407 	return 0;
21408 
21409 ret_put:
21410 	/* Either error or this BTF was already added */
21411 	btf_put(btf);
21412 	return ret;
21413 }
21414 
21415 /* replace pseudo btf_id with kernel symbol address */
21416 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
21417 				 struct bpf_insn *insn,
21418 				 struct bpf_insn_aux_data *aux,
21419 				 struct btf *btf)
21420 {
21421 	const struct btf_var_secinfo *vsi;
21422 	const struct btf_type *datasec;
21423 	const struct btf_type *t;
21424 	const char *sym_name;
21425 	bool percpu = false;
21426 	u32 type, id = insn->imm;
21427 	s32 datasec_id;
21428 	u64 addr;
21429 	int i;
21430 
21431 	t = btf_type_by_id(btf, id);
21432 	if (!t) {
21433 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
21434 		return -ENOENT;
21435 	}
21436 
21437 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
21438 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
21439 		return -EINVAL;
21440 	}
21441 
21442 	sym_name = btf_name_by_offset(btf, t->name_off);
21443 	addr = kallsyms_lookup_name(sym_name);
21444 	if (!addr) {
21445 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
21446 			sym_name);
21447 		return -ENOENT;
21448 	}
21449 	insn[0].imm = (u32)addr;
21450 	insn[1].imm = addr >> 32;
21451 
21452 	if (btf_type_is_func(t)) {
21453 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
21454 		aux->btf_var.mem_size = 0;
21455 		return 0;
21456 	}
21457 
21458 	datasec_id = find_btf_percpu_datasec(btf);
21459 	if (datasec_id > 0) {
21460 		datasec = btf_type_by_id(btf, datasec_id);
21461 		for_each_vsi(i, datasec, vsi) {
21462 			if (vsi->type == id) {
21463 				percpu = true;
21464 				break;
21465 			}
21466 		}
21467 	}
21468 
21469 	type = t->type;
21470 	t = btf_type_skip_modifiers(btf, type, NULL);
21471 	if (percpu) {
21472 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
21473 		aux->btf_var.btf = btf;
21474 		aux->btf_var.btf_id = type;
21475 	} else if (!btf_type_is_struct(t)) {
21476 		const struct btf_type *ret;
21477 		const char *tname;
21478 		u32 tsize;
21479 
21480 		/* resolve the type size of ksym. */
21481 		ret = btf_resolve_size(btf, t, &tsize);
21482 		if (IS_ERR(ret)) {
21483 			tname = btf_name_by_offset(btf, t->name_off);
21484 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
21485 				tname, PTR_ERR(ret));
21486 			return -EINVAL;
21487 		}
21488 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
21489 		aux->btf_var.mem_size = tsize;
21490 	} else {
21491 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
21492 		aux->btf_var.btf = btf;
21493 		aux->btf_var.btf_id = type;
21494 	}
21495 
21496 	return 0;
21497 }
21498 
21499 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
21500 			       struct bpf_insn *insn,
21501 			       struct bpf_insn_aux_data *aux)
21502 {
21503 	struct btf *btf;
21504 	int btf_fd;
21505 	int err;
21506 
21507 	btf_fd = insn[1].imm;
21508 	if (btf_fd) {
21509 		btf = btf_get_by_fd(btf_fd);
21510 		if (IS_ERR(btf)) {
21511 			verbose(env, "invalid module BTF object FD specified.\n");
21512 			return -EINVAL;
21513 		}
21514 	} else {
21515 		if (!btf_vmlinux) {
21516 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
21517 			return -EINVAL;
21518 		}
21519 		btf_get(btf_vmlinux);
21520 		btf = btf_vmlinux;
21521 	}
21522 
21523 	err = __check_pseudo_btf_id(env, insn, aux, btf);
21524 	if (err) {
21525 		btf_put(btf);
21526 		return err;
21527 	}
21528 
21529 	return __add_used_btf(env, btf);
21530 }
21531 
21532 static bool is_tracing_prog_type(enum bpf_prog_type type)
21533 {
21534 	switch (type) {
21535 	case BPF_PROG_TYPE_KPROBE:
21536 	case BPF_PROG_TYPE_TRACEPOINT:
21537 	case BPF_PROG_TYPE_PERF_EVENT:
21538 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
21539 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
21540 		return true;
21541 	default:
21542 		return false;
21543 	}
21544 }
21545 
21546 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
21547 {
21548 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
21549 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
21550 }
21551 
21552 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
21553 					struct bpf_map *map,
21554 					struct bpf_prog *prog)
21555 
21556 {
21557 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
21558 
21559 	if (map->excl_prog_sha &&
21560 	    memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) {
21561 		verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
21562 		return -EACCES;
21563 	}
21564 
21565 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
21566 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
21567 		if (is_tracing_prog_type(prog_type)) {
21568 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
21569 			return -EINVAL;
21570 		}
21571 	}
21572 
21573 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
21574 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
21575 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
21576 			return -EINVAL;
21577 		}
21578 
21579 		if (is_tracing_prog_type(prog_type)) {
21580 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
21581 			return -EINVAL;
21582 		}
21583 	}
21584 
21585 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
21586 	    !bpf_offload_prog_map_match(prog, map)) {
21587 		verbose(env, "offload device mismatch between prog and map\n");
21588 		return -EINVAL;
21589 	}
21590 
21591 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
21592 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
21593 		return -EINVAL;
21594 	}
21595 
21596 	if (prog->sleepable)
21597 		switch (map->map_type) {
21598 		case BPF_MAP_TYPE_HASH:
21599 		case BPF_MAP_TYPE_LRU_HASH:
21600 		case BPF_MAP_TYPE_ARRAY:
21601 		case BPF_MAP_TYPE_PERCPU_HASH:
21602 		case BPF_MAP_TYPE_PERCPU_ARRAY:
21603 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
21604 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
21605 		case BPF_MAP_TYPE_HASH_OF_MAPS:
21606 		case BPF_MAP_TYPE_RINGBUF:
21607 		case BPF_MAP_TYPE_USER_RINGBUF:
21608 		case BPF_MAP_TYPE_INODE_STORAGE:
21609 		case BPF_MAP_TYPE_SK_STORAGE:
21610 		case BPF_MAP_TYPE_TASK_STORAGE:
21611 		case BPF_MAP_TYPE_CGRP_STORAGE:
21612 		case BPF_MAP_TYPE_QUEUE:
21613 		case BPF_MAP_TYPE_STACK:
21614 		case BPF_MAP_TYPE_ARENA:
21615 		case BPF_MAP_TYPE_INSN_ARRAY:
21616 		case BPF_MAP_TYPE_PROG_ARRAY:
21617 			break;
21618 		default:
21619 			verbose(env,
21620 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
21621 			return -EINVAL;
21622 		}
21623 
21624 	if (bpf_map_is_cgroup_storage(map) &&
21625 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
21626 		verbose(env, "only one cgroup storage of each type is allowed\n");
21627 		return -EBUSY;
21628 	}
21629 
21630 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
21631 		if (env->prog->aux->arena) {
21632 			verbose(env, "Only one arena per program\n");
21633 			return -EBUSY;
21634 		}
21635 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
21636 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
21637 			return -EPERM;
21638 		}
21639 		if (!env->prog->jit_requested) {
21640 			verbose(env, "JIT is required to use arena\n");
21641 			return -EOPNOTSUPP;
21642 		}
21643 		if (!bpf_jit_supports_arena()) {
21644 			verbose(env, "JIT doesn't support arena\n");
21645 			return -EOPNOTSUPP;
21646 		}
21647 		env->prog->aux->arena = (void *)map;
21648 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
21649 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
21650 			return -EINVAL;
21651 		}
21652 	}
21653 
21654 	return 0;
21655 }
21656 
21657 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
21658 {
21659 	int i, err;
21660 
21661 	/* check whether we recorded this map already */
21662 	for (i = 0; i < env->used_map_cnt; i++)
21663 		if (env->used_maps[i] == map)
21664 			return i;
21665 
21666 	if (env->used_map_cnt >= MAX_USED_MAPS) {
21667 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
21668 			MAX_USED_MAPS);
21669 		return -E2BIG;
21670 	}
21671 
21672 	err = check_map_prog_compatibility(env, map, env->prog);
21673 	if (err)
21674 		return err;
21675 
21676 	if (env->prog->sleepable)
21677 		atomic64_inc(&map->sleepable_refcnt);
21678 
21679 	/* hold the map. If the program is rejected by verifier,
21680 	 * the map will be released by release_maps() or it
21681 	 * will be used by the valid program until it's unloaded
21682 	 * and all maps are released in bpf_free_used_maps()
21683 	 */
21684 	bpf_map_inc(map);
21685 
21686 	env->used_maps[env->used_map_cnt++] = map;
21687 
21688 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
21689 		err = bpf_insn_array_init(map, env->prog);
21690 		if (err) {
21691 			verbose(env, "Failed to properly initialize insn array\n");
21692 			return err;
21693 		}
21694 		env->insn_array_maps[env->insn_array_map_cnt++] = map;
21695 	}
21696 
21697 	return env->used_map_cnt - 1;
21698 }
21699 
21700 /* Add map behind fd to used maps list, if it's not already there, and return
21701  * its index.
21702  * Returns <0 on error, or >= 0 index, on success.
21703  */
21704 static int add_used_map(struct bpf_verifier_env *env, int fd)
21705 {
21706 	struct bpf_map *map;
21707 	CLASS(fd, f)(fd);
21708 
21709 	map = __bpf_map_get(f);
21710 	if (IS_ERR(map)) {
21711 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
21712 		return PTR_ERR(map);
21713 	}
21714 
21715 	return __add_used_map(env, map);
21716 }
21717 
21718 /* find and rewrite pseudo imm in ld_imm64 instructions:
21719  *
21720  * 1. if it accesses map FD, replace it with actual map pointer.
21721  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
21722  *
21723  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
21724  */
21725 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
21726 {
21727 	struct bpf_insn *insn = env->prog->insnsi;
21728 	int insn_cnt = env->prog->len;
21729 	int i, err;
21730 
21731 	err = bpf_prog_calc_tag(env->prog);
21732 	if (err)
21733 		return err;
21734 
21735 	for (i = 0; i < insn_cnt; i++, insn++) {
21736 		if (BPF_CLASS(insn->code) == BPF_LDX &&
21737 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
21738 		    insn->imm != 0)) {
21739 			verbose(env, "BPF_LDX uses reserved fields\n");
21740 			return -EINVAL;
21741 		}
21742 
21743 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
21744 			struct bpf_insn_aux_data *aux;
21745 			struct bpf_map *map;
21746 			int map_idx;
21747 			u64 addr;
21748 			u32 fd;
21749 
21750 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
21751 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
21752 			    insn[1].off != 0) {
21753 				verbose(env, "invalid bpf_ld_imm64 insn\n");
21754 				return -EINVAL;
21755 			}
21756 
21757 			if (insn[0].src_reg == 0)
21758 				/* valid generic load 64-bit imm */
21759 				goto next_insn;
21760 
21761 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
21762 				aux = &env->insn_aux_data[i];
21763 				err = check_pseudo_btf_id(env, insn, aux);
21764 				if (err)
21765 					return err;
21766 				goto next_insn;
21767 			}
21768 
21769 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
21770 				aux = &env->insn_aux_data[i];
21771 				aux->ptr_type = PTR_TO_FUNC;
21772 				goto next_insn;
21773 			}
21774 
21775 			/* In final convert_pseudo_ld_imm64() step, this is
21776 			 * converted into regular 64-bit imm load insn.
21777 			 */
21778 			switch (insn[0].src_reg) {
21779 			case BPF_PSEUDO_MAP_VALUE:
21780 			case BPF_PSEUDO_MAP_IDX_VALUE:
21781 				break;
21782 			case BPF_PSEUDO_MAP_FD:
21783 			case BPF_PSEUDO_MAP_IDX:
21784 				if (insn[1].imm == 0)
21785 					break;
21786 				fallthrough;
21787 			default:
21788 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
21789 				return -EINVAL;
21790 			}
21791 
21792 			switch (insn[0].src_reg) {
21793 			case BPF_PSEUDO_MAP_IDX_VALUE:
21794 			case BPF_PSEUDO_MAP_IDX:
21795 				if (bpfptr_is_null(env->fd_array)) {
21796 					verbose(env, "fd_idx without fd_array is invalid\n");
21797 					return -EPROTO;
21798 				}
21799 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
21800 							    insn[0].imm * sizeof(fd),
21801 							    sizeof(fd)))
21802 					return -EFAULT;
21803 				break;
21804 			default:
21805 				fd = insn[0].imm;
21806 				break;
21807 			}
21808 
21809 			map_idx = add_used_map(env, fd);
21810 			if (map_idx < 0)
21811 				return map_idx;
21812 			map = env->used_maps[map_idx];
21813 
21814 			aux = &env->insn_aux_data[i];
21815 			aux->map_index = map_idx;
21816 
21817 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
21818 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
21819 				addr = (unsigned long)map;
21820 			} else {
21821 				u32 off = insn[1].imm;
21822 
21823 				if (!map->ops->map_direct_value_addr) {
21824 					verbose(env, "no direct value access support for this map type\n");
21825 					return -EINVAL;
21826 				}
21827 
21828 				err = map->ops->map_direct_value_addr(map, &addr, off);
21829 				if (err) {
21830 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
21831 						map->value_size, off);
21832 					return err;
21833 				}
21834 
21835 				aux->map_off = off;
21836 				addr += off;
21837 			}
21838 
21839 			insn[0].imm = (u32)addr;
21840 			insn[1].imm = addr >> 32;
21841 
21842 next_insn:
21843 			insn++;
21844 			i++;
21845 			continue;
21846 		}
21847 
21848 		/* Basic sanity check before we invest more work here. */
21849 		if (!bpf_opcode_in_insntable(insn->code)) {
21850 			verbose(env, "unknown opcode %02x\n", insn->code);
21851 			return -EINVAL;
21852 		}
21853 	}
21854 
21855 	/* now all pseudo BPF_LD_IMM64 instructions load valid
21856 	 * 'struct bpf_map *' into a register instead of user map_fd.
21857 	 * These pointers will be used later by verifier to validate map access.
21858 	 */
21859 	return 0;
21860 }
21861 
21862 /* drop refcnt of maps used by the rejected program */
21863 static void release_maps(struct bpf_verifier_env *env)
21864 {
21865 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
21866 			     env->used_map_cnt);
21867 }
21868 
21869 /* drop refcnt of maps used by the rejected program */
21870 static void release_btfs(struct bpf_verifier_env *env)
21871 {
21872 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
21873 }
21874 
21875 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
21876 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
21877 {
21878 	struct bpf_insn *insn = env->prog->insnsi;
21879 	int insn_cnt = env->prog->len;
21880 	int i;
21881 
21882 	for (i = 0; i < insn_cnt; i++, insn++) {
21883 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
21884 			continue;
21885 		if (insn->src_reg == BPF_PSEUDO_FUNC)
21886 			continue;
21887 		insn->src_reg = 0;
21888 	}
21889 }
21890 
21891 /* single env->prog->insni[off] instruction was replaced with the range
21892  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
21893  * [0, off) and [off, end) to new locations, so the patched range stays zero
21894  */
21895 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
21896 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
21897 {
21898 	struct bpf_insn_aux_data *data = env->insn_aux_data;
21899 	struct bpf_insn *insn = new_prog->insnsi;
21900 	u32 old_seen = data[off].seen;
21901 	u32 prog_len;
21902 	int i;
21903 
21904 	/* aux info at OFF always needs adjustment, no matter fast path
21905 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
21906 	 * original insn at old prog.
21907 	 */
21908 	data[off].zext_dst = insn_has_def32(insn + off + cnt - 1);
21909 
21910 	if (cnt == 1)
21911 		return;
21912 	prog_len = new_prog->len;
21913 
21914 	memmove(data + off + cnt - 1, data + off,
21915 		sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
21916 	memset(data + off, 0, sizeof(struct bpf_insn_aux_data) * (cnt - 1));
21917 	for (i = off; i < off + cnt - 1; i++) {
21918 		/* Expand insni[off]'s seen count to the patched range. */
21919 		data[i].seen = old_seen;
21920 		data[i].zext_dst = insn_has_def32(insn + i);
21921 	}
21922 }
21923 
21924 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
21925 {
21926 	int i;
21927 
21928 	if (len == 1)
21929 		return;
21930 	/* NOTE: fake 'exit' subprog should be updated as well. */
21931 	for (i = 0; i <= env->subprog_cnt; i++) {
21932 		if (env->subprog_info[i].start <= off)
21933 			continue;
21934 		env->subprog_info[i].start += len - 1;
21935 	}
21936 }
21937 
21938 static void release_insn_arrays(struct bpf_verifier_env *env)
21939 {
21940 	int i;
21941 
21942 	for (i = 0; i < env->insn_array_map_cnt; i++)
21943 		bpf_insn_array_release(env->insn_array_maps[i]);
21944 }
21945 
21946 static void adjust_insn_arrays(struct bpf_verifier_env *env, u32 off, u32 len)
21947 {
21948 	int i;
21949 
21950 	if (len == 1)
21951 		return;
21952 
21953 	for (i = 0; i < env->insn_array_map_cnt; i++)
21954 		bpf_insn_array_adjust(env->insn_array_maps[i], off, len);
21955 }
21956 
21957 static void adjust_insn_arrays_after_remove(struct bpf_verifier_env *env, u32 off, u32 len)
21958 {
21959 	int i;
21960 
21961 	for (i = 0; i < env->insn_array_map_cnt; i++)
21962 		bpf_insn_array_adjust_after_remove(env->insn_array_maps[i], off, len);
21963 }
21964 
21965 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
21966 {
21967 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
21968 	int i, sz = prog->aux->size_poke_tab;
21969 	struct bpf_jit_poke_descriptor *desc;
21970 
21971 	for (i = 0; i < sz; i++) {
21972 		desc = &tab[i];
21973 		if (desc->insn_idx <= off)
21974 			continue;
21975 		desc->insn_idx += len - 1;
21976 	}
21977 }
21978 
21979 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
21980 					    const struct bpf_insn *patch, u32 len)
21981 {
21982 	struct bpf_prog *new_prog;
21983 	struct bpf_insn_aux_data *new_data = NULL;
21984 
21985 	if (len > 1) {
21986 		new_data = vrealloc(env->insn_aux_data,
21987 				    array_size(env->prog->len + len - 1,
21988 					       sizeof(struct bpf_insn_aux_data)),
21989 				    GFP_KERNEL_ACCOUNT | __GFP_ZERO);
21990 		if (!new_data)
21991 			return NULL;
21992 
21993 		env->insn_aux_data = new_data;
21994 	}
21995 
21996 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
21997 	if (IS_ERR(new_prog)) {
21998 		if (PTR_ERR(new_prog) == -ERANGE)
21999 			verbose(env,
22000 				"insn %d cannot be patched due to 16-bit range\n",
22001 				env->insn_aux_data[off].orig_idx);
22002 		return NULL;
22003 	}
22004 	adjust_insn_aux_data(env, new_prog, off, len);
22005 	adjust_subprog_starts(env, off, len);
22006 	adjust_insn_arrays(env, off, len);
22007 	adjust_poke_descs(new_prog, off, len);
22008 	return new_prog;
22009 }
22010 
22011 /*
22012  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
22013  * jump offset by 'delta'.
22014  */
22015 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
22016 {
22017 	struct bpf_insn *insn = prog->insnsi;
22018 	u32 insn_cnt = prog->len, i;
22019 	s32 imm;
22020 	s16 off;
22021 
22022 	for (i = 0; i < insn_cnt; i++, insn++) {
22023 		u8 code = insn->code;
22024 
22025 		if (tgt_idx <= i && i < tgt_idx + delta)
22026 			continue;
22027 
22028 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
22029 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
22030 			continue;
22031 
22032 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
22033 			if (i + 1 + insn->imm != tgt_idx)
22034 				continue;
22035 			if (check_add_overflow(insn->imm, delta, &imm))
22036 				return -ERANGE;
22037 			insn->imm = imm;
22038 		} else {
22039 			if (i + 1 + insn->off != tgt_idx)
22040 				continue;
22041 			if (check_add_overflow(insn->off, delta, &off))
22042 				return -ERANGE;
22043 			insn->off = off;
22044 		}
22045 	}
22046 	return 0;
22047 }
22048 
22049 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
22050 					      u32 off, u32 cnt)
22051 {
22052 	int i, j;
22053 
22054 	/* find first prog starting at or after off (first to remove) */
22055 	for (i = 0; i < env->subprog_cnt; i++)
22056 		if (env->subprog_info[i].start >= off)
22057 			break;
22058 	/* find first prog starting at or after off + cnt (first to stay) */
22059 	for (j = i; j < env->subprog_cnt; j++)
22060 		if (env->subprog_info[j].start >= off + cnt)
22061 			break;
22062 	/* if j doesn't start exactly at off + cnt, we are just removing
22063 	 * the front of previous prog
22064 	 */
22065 	if (env->subprog_info[j].start != off + cnt)
22066 		j--;
22067 
22068 	if (j > i) {
22069 		struct bpf_prog_aux *aux = env->prog->aux;
22070 		int move;
22071 
22072 		/* move fake 'exit' subprog as well */
22073 		move = env->subprog_cnt + 1 - j;
22074 
22075 		memmove(env->subprog_info + i,
22076 			env->subprog_info + j,
22077 			sizeof(*env->subprog_info) * move);
22078 		env->subprog_cnt -= j - i;
22079 
22080 		/* remove func_info */
22081 		if (aux->func_info) {
22082 			move = aux->func_info_cnt - j;
22083 
22084 			memmove(aux->func_info + i,
22085 				aux->func_info + j,
22086 				sizeof(*aux->func_info) * move);
22087 			aux->func_info_cnt -= j - i;
22088 			/* func_info->insn_off is set after all code rewrites,
22089 			 * in adjust_btf_func() - no need to adjust
22090 			 */
22091 		}
22092 	} else {
22093 		/* convert i from "first prog to remove" to "first to adjust" */
22094 		if (env->subprog_info[i].start == off)
22095 			i++;
22096 	}
22097 
22098 	/* update fake 'exit' subprog as well */
22099 	for (; i <= env->subprog_cnt; i++)
22100 		env->subprog_info[i].start -= cnt;
22101 
22102 	return 0;
22103 }
22104 
22105 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
22106 				      u32 cnt)
22107 {
22108 	struct bpf_prog *prog = env->prog;
22109 	u32 i, l_off, l_cnt, nr_linfo;
22110 	struct bpf_line_info *linfo;
22111 
22112 	nr_linfo = prog->aux->nr_linfo;
22113 	if (!nr_linfo)
22114 		return 0;
22115 
22116 	linfo = prog->aux->linfo;
22117 
22118 	/* find first line info to remove, count lines to be removed */
22119 	for (i = 0; i < nr_linfo; i++)
22120 		if (linfo[i].insn_off >= off)
22121 			break;
22122 
22123 	l_off = i;
22124 	l_cnt = 0;
22125 	for (; i < nr_linfo; i++)
22126 		if (linfo[i].insn_off < off + cnt)
22127 			l_cnt++;
22128 		else
22129 			break;
22130 
22131 	/* First live insn doesn't match first live linfo, it needs to "inherit"
22132 	 * last removed linfo.  prog is already modified, so prog->len == off
22133 	 * means no live instructions after (tail of the program was removed).
22134 	 */
22135 	if (prog->len != off && l_cnt &&
22136 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
22137 		l_cnt--;
22138 		linfo[--i].insn_off = off + cnt;
22139 	}
22140 
22141 	/* remove the line info which refer to the removed instructions */
22142 	if (l_cnt) {
22143 		memmove(linfo + l_off, linfo + i,
22144 			sizeof(*linfo) * (nr_linfo - i));
22145 
22146 		prog->aux->nr_linfo -= l_cnt;
22147 		nr_linfo = prog->aux->nr_linfo;
22148 	}
22149 
22150 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
22151 	for (i = l_off; i < nr_linfo; i++)
22152 		linfo[i].insn_off -= cnt;
22153 
22154 	/* fix up all subprogs (incl. 'exit') which start >= off */
22155 	for (i = 0; i <= env->subprog_cnt; i++)
22156 		if (env->subprog_info[i].linfo_idx > l_off) {
22157 			/* program may have started in the removed region but
22158 			 * may not be fully removed
22159 			 */
22160 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
22161 				env->subprog_info[i].linfo_idx -= l_cnt;
22162 			else
22163 				env->subprog_info[i].linfo_idx = l_off;
22164 		}
22165 
22166 	return 0;
22167 }
22168 
22169 /*
22170  * Clean up dynamically allocated fields of aux data for instructions [start, ...]
22171  */
22172 static void clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
22173 {
22174 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
22175 	struct bpf_insn *insns = env->prog->insnsi;
22176 	int end = start + len;
22177 	int i;
22178 
22179 	for (i = start; i < end; i++) {
22180 		if (aux_data[i].jt) {
22181 			kvfree(aux_data[i].jt);
22182 			aux_data[i].jt = NULL;
22183 		}
22184 
22185 		if (bpf_is_ldimm64(&insns[i]))
22186 			i++;
22187 	}
22188 }
22189 
22190 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
22191 {
22192 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
22193 	unsigned int orig_prog_len = env->prog->len;
22194 	int err;
22195 
22196 	if (bpf_prog_is_offloaded(env->prog->aux))
22197 		bpf_prog_offload_remove_insns(env, off, cnt);
22198 
22199 	/* Should be called before bpf_remove_insns, as it uses prog->insnsi */
22200 	clear_insn_aux_data(env, off, cnt);
22201 
22202 	err = bpf_remove_insns(env->prog, off, cnt);
22203 	if (err)
22204 		return err;
22205 
22206 	err = adjust_subprog_starts_after_remove(env, off, cnt);
22207 	if (err)
22208 		return err;
22209 
22210 	err = bpf_adj_linfo_after_remove(env, off, cnt);
22211 	if (err)
22212 		return err;
22213 
22214 	adjust_insn_arrays_after_remove(env, off, cnt);
22215 
22216 	memmove(aux_data + off,	aux_data + off + cnt,
22217 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
22218 
22219 	return 0;
22220 }
22221 
22222 /* The verifier does more data flow analysis than llvm and will not
22223  * explore branches that are dead at run time. Malicious programs can
22224  * have dead code too. Therefore replace all dead at-run-time code
22225  * with 'ja -1'.
22226  *
22227  * Just nops are not optimal, e.g. if they would sit at the end of the
22228  * program and through another bug we would manage to jump there, then
22229  * we'd execute beyond program memory otherwise. Returning exception
22230  * code also wouldn't work since we can have subprogs where the dead
22231  * code could be located.
22232  */
22233 static void sanitize_dead_code(struct bpf_verifier_env *env)
22234 {
22235 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
22236 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
22237 	struct bpf_insn *insn = env->prog->insnsi;
22238 	const int insn_cnt = env->prog->len;
22239 	int i;
22240 
22241 	for (i = 0; i < insn_cnt; i++) {
22242 		if (aux_data[i].seen)
22243 			continue;
22244 		memcpy(insn + i, &trap, sizeof(trap));
22245 		aux_data[i].zext_dst = false;
22246 	}
22247 }
22248 
22249 static bool insn_is_cond_jump(u8 code)
22250 {
22251 	u8 op;
22252 
22253 	op = BPF_OP(code);
22254 	if (BPF_CLASS(code) == BPF_JMP32)
22255 		return op != BPF_JA;
22256 
22257 	if (BPF_CLASS(code) != BPF_JMP)
22258 		return false;
22259 
22260 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
22261 }
22262 
22263 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
22264 {
22265 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
22266 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
22267 	struct bpf_insn *insn = env->prog->insnsi;
22268 	const int insn_cnt = env->prog->len;
22269 	int i;
22270 
22271 	for (i = 0; i < insn_cnt; i++, insn++) {
22272 		if (!insn_is_cond_jump(insn->code))
22273 			continue;
22274 
22275 		if (!aux_data[i + 1].seen)
22276 			ja.off = insn->off;
22277 		else if (!aux_data[i + 1 + insn->off].seen)
22278 			ja.off = 0;
22279 		else
22280 			continue;
22281 
22282 		if (bpf_prog_is_offloaded(env->prog->aux))
22283 			bpf_prog_offload_replace_insn(env, i, &ja);
22284 
22285 		memcpy(insn, &ja, sizeof(ja));
22286 	}
22287 }
22288 
22289 static int opt_remove_dead_code(struct bpf_verifier_env *env)
22290 {
22291 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
22292 	int insn_cnt = env->prog->len;
22293 	int i, err;
22294 
22295 	for (i = 0; i < insn_cnt; i++) {
22296 		int j;
22297 
22298 		j = 0;
22299 		while (i + j < insn_cnt && !aux_data[i + j].seen)
22300 			j++;
22301 		if (!j)
22302 			continue;
22303 
22304 		err = verifier_remove_insns(env, i, j);
22305 		if (err)
22306 			return err;
22307 		insn_cnt = env->prog->len;
22308 	}
22309 
22310 	return 0;
22311 }
22312 
22313 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
22314 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0);
22315 
22316 static int opt_remove_nops(struct bpf_verifier_env *env)
22317 {
22318 	struct bpf_insn *insn = env->prog->insnsi;
22319 	int insn_cnt = env->prog->len;
22320 	bool is_may_goto_0, is_ja;
22321 	int i, err;
22322 
22323 	for (i = 0; i < insn_cnt; i++) {
22324 		is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
22325 		is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP));
22326 
22327 		if (!is_may_goto_0 && !is_ja)
22328 			continue;
22329 
22330 		err = verifier_remove_insns(env, i, 1);
22331 		if (err)
22332 			return err;
22333 		insn_cnt--;
22334 		/* Go back one insn to catch may_goto +1; may_goto +0 sequence */
22335 		i -= (is_may_goto_0 && i > 0) ? 2 : 1;
22336 	}
22337 
22338 	return 0;
22339 }
22340 
22341 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
22342 					 const union bpf_attr *attr)
22343 {
22344 	struct bpf_insn *patch;
22345 	/* use env->insn_buf as two independent buffers */
22346 	struct bpf_insn *zext_patch = env->insn_buf;
22347 	struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2];
22348 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
22349 	int i, patch_len, delta = 0, len = env->prog->len;
22350 	struct bpf_insn *insns = env->prog->insnsi;
22351 	struct bpf_prog *new_prog;
22352 	bool rnd_hi32;
22353 
22354 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
22355 	zext_patch[1] = BPF_ZEXT_REG(0);
22356 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
22357 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
22358 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
22359 	for (i = 0; i < len; i++) {
22360 		int adj_idx = i + delta;
22361 		struct bpf_insn insn;
22362 		int load_reg;
22363 
22364 		insn = insns[adj_idx];
22365 		load_reg = insn_def_regno(&insn);
22366 		if (!aux[adj_idx].zext_dst) {
22367 			u8 code, class;
22368 			u32 imm_rnd;
22369 
22370 			if (!rnd_hi32)
22371 				continue;
22372 
22373 			code = insn.code;
22374 			class = BPF_CLASS(code);
22375 			if (load_reg == -1)
22376 				continue;
22377 
22378 			/* NOTE: arg "reg" (the fourth one) is only used for
22379 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
22380 			 *       here.
22381 			 */
22382 			if (is_reg64(&insn, load_reg, NULL, DST_OP)) {
22383 				if (class == BPF_LD &&
22384 				    BPF_MODE(code) == BPF_IMM)
22385 					i++;
22386 				continue;
22387 			}
22388 
22389 			/* ctx load could be transformed into wider load. */
22390 			if (class == BPF_LDX &&
22391 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
22392 				continue;
22393 
22394 			imm_rnd = get_random_u32();
22395 			rnd_hi32_patch[0] = insn;
22396 			rnd_hi32_patch[1].imm = imm_rnd;
22397 			rnd_hi32_patch[3].dst_reg = load_reg;
22398 			patch = rnd_hi32_patch;
22399 			patch_len = 4;
22400 			goto apply_patch_buffer;
22401 		}
22402 
22403 		/* Add in an zero-extend instruction if a) the JIT has requested
22404 		 * it or b) it's a CMPXCHG.
22405 		 *
22406 		 * The latter is because: BPF_CMPXCHG always loads a value into
22407 		 * R0, therefore always zero-extends. However some archs'
22408 		 * equivalent instruction only does this load when the
22409 		 * comparison is successful. This detail of CMPXCHG is
22410 		 * orthogonal to the general zero-extension behaviour of the
22411 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
22412 		 */
22413 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
22414 			continue;
22415 
22416 		/* Zero-extension is done by the caller. */
22417 		if (bpf_pseudo_kfunc_call(&insn))
22418 			continue;
22419 
22420 		if (verifier_bug_if(load_reg == -1, env,
22421 				    "zext_dst is set, but no reg is defined"))
22422 			return -EFAULT;
22423 
22424 		zext_patch[0] = insn;
22425 		zext_patch[1].dst_reg = load_reg;
22426 		zext_patch[1].src_reg = load_reg;
22427 		patch = zext_patch;
22428 		patch_len = 2;
22429 apply_patch_buffer:
22430 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
22431 		if (!new_prog)
22432 			return -ENOMEM;
22433 		env->prog = new_prog;
22434 		insns = new_prog->insnsi;
22435 		aux = env->insn_aux_data;
22436 		delta += patch_len - 1;
22437 	}
22438 
22439 	return 0;
22440 }
22441 
22442 /* convert load instructions that access fields of a context type into a
22443  * sequence of instructions that access fields of the underlying structure:
22444  *     struct __sk_buff    -> struct sk_buff
22445  *     struct bpf_sock_ops -> struct sock
22446  */
22447 static int convert_ctx_accesses(struct bpf_verifier_env *env)
22448 {
22449 	struct bpf_subprog_info *subprogs = env->subprog_info;
22450 	const struct bpf_verifier_ops *ops = env->ops;
22451 	int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
22452 	const int insn_cnt = env->prog->len;
22453 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
22454 	struct bpf_insn *insn_buf = env->insn_buf;
22455 	struct bpf_insn *insn;
22456 	u32 target_size, size_default, off;
22457 	struct bpf_prog *new_prog;
22458 	enum bpf_access_type type;
22459 	bool is_narrower_load;
22460 	int epilogue_idx = 0;
22461 
22462 	if (ops->gen_epilogue) {
22463 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
22464 						 -(subprogs[0].stack_depth + 8));
22465 		if (epilogue_cnt >= INSN_BUF_SIZE) {
22466 			verifier_bug(env, "epilogue is too long");
22467 			return -EFAULT;
22468 		} else if (epilogue_cnt) {
22469 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
22470 			cnt = 0;
22471 			subprogs[0].stack_depth += 8;
22472 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
22473 						      -subprogs[0].stack_depth);
22474 			insn_buf[cnt++] = env->prog->insnsi[0];
22475 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
22476 			if (!new_prog)
22477 				return -ENOMEM;
22478 			env->prog = new_prog;
22479 			delta += cnt - 1;
22480 
22481 			ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
22482 			if (ret < 0)
22483 				return ret;
22484 		}
22485 	}
22486 
22487 	if (ops->gen_prologue || env->seen_direct_write) {
22488 		if (!ops->gen_prologue) {
22489 			verifier_bug(env, "gen_prologue is null");
22490 			return -EFAULT;
22491 		}
22492 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
22493 					env->prog);
22494 		if (cnt >= INSN_BUF_SIZE) {
22495 			verifier_bug(env, "prologue is too long");
22496 			return -EFAULT;
22497 		} else if (cnt) {
22498 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
22499 			if (!new_prog)
22500 				return -ENOMEM;
22501 
22502 			env->prog = new_prog;
22503 			delta += cnt - 1;
22504 
22505 			ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
22506 			if (ret < 0)
22507 				return ret;
22508 		}
22509 	}
22510 
22511 	if (delta)
22512 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
22513 
22514 	if (bpf_prog_is_offloaded(env->prog->aux))
22515 		return 0;
22516 
22517 	insn = env->prog->insnsi + delta;
22518 
22519 	for (i = 0; i < insn_cnt; i++, insn++) {
22520 		bpf_convert_ctx_access_t convert_ctx_access;
22521 		u8 mode;
22522 
22523 		if (env->insn_aux_data[i + delta].nospec) {
22524 			WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state);
22525 			struct bpf_insn *patch = insn_buf;
22526 
22527 			*patch++ = BPF_ST_NOSPEC();
22528 			*patch++ = *insn;
22529 			cnt = patch - insn_buf;
22530 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22531 			if (!new_prog)
22532 				return -ENOMEM;
22533 
22534 			delta    += cnt - 1;
22535 			env->prog = new_prog;
22536 			insn      = new_prog->insnsi + i + delta;
22537 			/* This can not be easily merged with the
22538 			 * nospec_result-case, because an insn may require a
22539 			 * nospec before and after itself. Therefore also do not
22540 			 * 'continue' here but potentially apply further
22541 			 * patching to insn. *insn should equal patch[1] now.
22542 			 */
22543 		}
22544 
22545 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
22546 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
22547 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
22548 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
22549 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
22550 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
22551 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
22552 			type = BPF_READ;
22553 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
22554 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
22555 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
22556 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
22557 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
22558 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
22559 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
22560 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
22561 			type = BPF_WRITE;
22562 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) ||
22563 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) ||
22564 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
22565 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
22566 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
22567 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
22568 			env->prog->aux->num_exentries++;
22569 			continue;
22570 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
22571 			   epilogue_cnt &&
22572 			   i + delta < subprogs[1].start) {
22573 			/* Generate epilogue for the main prog */
22574 			if (epilogue_idx) {
22575 				/* jump back to the earlier generated epilogue */
22576 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
22577 				cnt = 1;
22578 			} else {
22579 				memcpy(insn_buf, epilogue_buf,
22580 				       epilogue_cnt * sizeof(*epilogue_buf));
22581 				cnt = epilogue_cnt;
22582 				/* epilogue_idx cannot be 0. It must have at
22583 				 * least one ctx ptr saving insn before the
22584 				 * epilogue.
22585 				 */
22586 				epilogue_idx = i + delta;
22587 			}
22588 			goto patch_insn_buf;
22589 		} else {
22590 			continue;
22591 		}
22592 
22593 		if (type == BPF_WRITE &&
22594 		    env->insn_aux_data[i + delta].nospec_result) {
22595 			/* nospec_result is only used to mitigate Spectre v4 and
22596 			 * to limit verification-time for Spectre v1.
22597 			 */
22598 			struct bpf_insn *patch = insn_buf;
22599 
22600 			*patch++ = *insn;
22601 			*patch++ = BPF_ST_NOSPEC();
22602 			cnt = patch - insn_buf;
22603 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22604 			if (!new_prog)
22605 				return -ENOMEM;
22606 
22607 			delta    += cnt - 1;
22608 			env->prog = new_prog;
22609 			insn      = new_prog->insnsi + i + delta;
22610 			continue;
22611 		}
22612 
22613 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
22614 		case PTR_TO_CTX:
22615 			if (!ops->convert_ctx_access)
22616 				continue;
22617 			convert_ctx_access = ops->convert_ctx_access;
22618 			break;
22619 		case PTR_TO_SOCKET:
22620 		case PTR_TO_SOCK_COMMON:
22621 			convert_ctx_access = bpf_sock_convert_ctx_access;
22622 			break;
22623 		case PTR_TO_TCP_SOCK:
22624 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
22625 			break;
22626 		case PTR_TO_XDP_SOCK:
22627 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
22628 			break;
22629 		case PTR_TO_BTF_ID:
22630 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
22631 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
22632 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
22633 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
22634 		 * any faults for loads into such types. BPF_WRITE is disallowed
22635 		 * for this case.
22636 		 */
22637 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
22638 		case PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED:
22639 			if (type == BPF_READ) {
22640 				if (BPF_MODE(insn->code) == BPF_MEM)
22641 					insn->code = BPF_LDX | BPF_PROBE_MEM |
22642 						     BPF_SIZE((insn)->code);
22643 				else
22644 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
22645 						     BPF_SIZE((insn)->code);
22646 				env->prog->aux->num_exentries++;
22647 			}
22648 			continue;
22649 		case PTR_TO_ARENA:
22650 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
22651 				if (!bpf_jit_supports_insn(insn, true)) {
22652 					verbose(env, "sign extending loads from arena are not supported yet\n");
22653 					return -EOPNOTSUPP;
22654 				}
22655 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32SX | BPF_SIZE(insn->code);
22656 			} else {
22657 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
22658 			}
22659 			env->prog->aux->num_exentries++;
22660 			continue;
22661 		default:
22662 			continue;
22663 		}
22664 
22665 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
22666 		size = BPF_LDST_BYTES(insn);
22667 		mode = BPF_MODE(insn->code);
22668 
22669 		/* If the read access is a narrower load of the field,
22670 		 * convert to a 4/8-byte load, to minimum program type specific
22671 		 * convert_ctx_access changes. If conversion is successful,
22672 		 * we will apply proper mask to the result.
22673 		 */
22674 		is_narrower_load = size < ctx_field_size;
22675 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
22676 		off = insn->off;
22677 		if (is_narrower_load) {
22678 			u8 size_code;
22679 
22680 			if (type == BPF_WRITE) {
22681 				verifier_bug(env, "narrow ctx access misconfigured");
22682 				return -EFAULT;
22683 			}
22684 
22685 			size_code = BPF_H;
22686 			if (ctx_field_size == 4)
22687 				size_code = BPF_W;
22688 			else if (ctx_field_size == 8)
22689 				size_code = BPF_DW;
22690 
22691 			insn->off = off & ~(size_default - 1);
22692 			insn->code = BPF_LDX | BPF_MEM | size_code;
22693 		}
22694 
22695 		target_size = 0;
22696 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
22697 					 &target_size);
22698 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
22699 		    (ctx_field_size && !target_size)) {
22700 			verifier_bug(env, "error during ctx access conversion (%d)", cnt);
22701 			return -EFAULT;
22702 		}
22703 
22704 		if (is_narrower_load && size < target_size) {
22705 			u8 shift = bpf_ctx_narrow_access_offset(
22706 				off, size, size_default) * 8;
22707 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
22708 				verifier_bug(env, "narrow ctx load misconfigured");
22709 				return -EFAULT;
22710 			}
22711 			if (ctx_field_size <= 4) {
22712 				if (shift)
22713 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
22714 									insn->dst_reg,
22715 									shift);
22716 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
22717 								(1 << size * 8) - 1);
22718 			} else {
22719 				if (shift)
22720 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
22721 									insn->dst_reg,
22722 									shift);
22723 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
22724 								(1ULL << size * 8) - 1);
22725 			}
22726 		}
22727 		if (mode == BPF_MEMSX)
22728 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
22729 						       insn->dst_reg, insn->dst_reg,
22730 						       size * 8, 0);
22731 
22732 patch_insn_buf:
22733 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22734 		if (!new_prog)
22735 			return -ENOMEM;
22736 
22737 		delta += cnt - 1;
22738 
22739 		/* keep walking new program and skip insns we just inserted */
22740 		env->prog = new_prog;
22741 		insn      = new_prog->insnsi + i + delta;
22742 	}
22743 
22744 	return 0;
22745 }
22746 
22747 static int jit_subprogs(struct bpf_verifier_env *env)
22748 {
22749 	struct bpf_prog *prog = env->prog, **func, *tmp;
22750 	int i, j, subprog_start, subprog_end = 0, len, subprog;
22751 	struct bpf_map *map_ptr;
22752 	struct bpf_insn *insn;
22753 	void *old_bpf_func;
22754 	int err, num_exentries;
22755 	int old_len, subprog_start_adjustment = 0;
22756 
22757 	if (env->subprog_cnt <= 1)
22758 		return 0;
22759 
22760 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22761 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
22762 			continue;
22763 
22764 		/* Upon error here we cannot fall back to interpreter but
22765 		 * need a hard reject of the program. Thus -EFAULT is
22766 		 * propagated in any case.
22767 		 */
22768 		subprog = find_subprog(env, i + insn->imm + 1);
22769 		if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d",
22770 				    i + insn->imm + 1))
22771 			return -EFAULT;
22772 		/* temporarily remember subprog id inside insn instead of
22773 		 * aux_data, since next loop will split up all insns into funcs
22774 		 */
22775 		insn->off = subprog;
22776 		/* remember original imm in case JIT fails and fallback
22777 		 * to interpreter will be needed
22778 		 */
22779 		env->insn_aux_data[i].call_imm = insn->imm;
22780 		/* point imm to __bpf_call_base+1 from JITs point of view */
22781 		insn->imm = 1;
22782 		if (bpf_pseudo_func(insn)) {
22783 #if defined(MODULES_VADDR)
22784 			u64 addr = MODULES_VADDR;
22785 #else
22786 			u64 addr = VMALLOC_START;
22787 #endif
22788 			/* jit (e.g. x86_64) may emit fewer instructions
22789 			 * if it learns a u32 imm is the same as a u64 imm.
22790 			 * Set close enough to possible prog address.
22791 			 */
22792 			insn[0].imm = (u32)addr;
22793 			insn[1].imm = addr >> 32;
22794 		}
22795 	}
22796 
22797 	err = bpf_prog_alloc_jited_linfo(prog);
22798 	if (err)
22799 		goto out_undo_insn;
22800 
22801 	err = -ENOMEM;
22802 	func = kzalloc_objs(prog, env->subprog_cnt);
22803 	if (!func)
22804 		goto out_undo_insn;
22805 
22806 	for (i = 0; i < env->subprog_cnt; i++) {
22807 		subprog_start = subprog_end;
22808 		subprog_end = env->subprog_info[i + 1].start;
22809 
22810 		len = subprog_end - subprog_start;
22811 		/* bpf_prog_run() doesn't call subprogs directly,
22812 		 * hence main prog stats include the runtime of subprogs.
22813 		 * subprogs don't have IDs and not reachable via prog_get_next_id
22814 		 * func[i]->stats will never be accessed and stays NULL
22815 		 */
22816 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
22817 		if (!func[i])
22818 			goto out_free;
22819 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
22820 		       len * sizeof(struct bpf_insn));
22821 		func[i]->type = prog->type;
22822 		func[i]->len = len;
22823 		if (bpf_prog_calc_tag(func[i]))
22824 			goto out_free;
22825 		func[i]->is_func = 1;
22826 		func[i]->sleepable = prog->sleepable;
22827 		func[i]->aux->func_idx = i;
22828 		/* Below members will be freed only at prog->aux */
22829 		func[i]->aux->btf = prog->aux->btf;
22830 		func[i]->aux->subprog_start = subprog_start + subprog_start_adjustment;
22831 		func[i]->aux->func_info = prog->aux->func_info;
22832 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
22833 		func[i]->aux->poke_tab = prog->aux->poke_tab;
22834 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
22835 		func[i]->aux->main_prog_aux = prog->aux;
22836 
22837 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
22838 			struct bpf_jit_poke_descriptor *poke;
22839 
22840 			poke = &prog->aux->poke_tab[j];
22841 			if (poke->insn_idx < subprog_end &&
22842 			    poke->insn_idx >= subprog_start)
22843 				poke->aux = func[i]->aux;
22844 		}
22845 
22846 		func[i]->aux->name[0] = 'F';
22847 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
22848 		if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
22849 			func[i]->aux->jits_use_priv_stack = true;
22850 
22851 		func[i]->jit_requested = 1;
22852 		func[i]->blinding_requested = prog->blinding_requested;
22853 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
22854 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
22855 		func[i]->aux->linfo = prog->aux->linfo;
22856 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
22857 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
22858 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
22859 		func[i]->aux->arena = prog->aux->arena;
22860 		func[i]->aux->used_maps = env->used_maps;
22861 		func[i]->aux->used_map_cnt = env->used_map_cnt;
22862 		num_exentries = 0;
22863 		insn = func[i]->insnsi;
22864 		for (j = 0; j < func[i]->len; j++, insn++) {
22865 			if (BPF_CLASS(insn->code) == BPF_LDX &&
22866 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22867 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
22868 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32SX ||
22869 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
22870 				num_exentries++;
22871 			if ((BPF_CLASS(insn->code) == BPF_STX ||
22872 			     BPF_CLASS(insn->code) == BPF_ST) &&
22873 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
22874 				num_exentries++;
22875 			if (BPF_CLASS(insn->code) == BPF_STX &&
22876 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
22877 				num_exentries++;
22878 		}
22879 		func[i]->aux->num_exentries = num_exentries;
22880 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
22881 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
22882 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
22883 		func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
22884 		if (!i)
22885 			func[i]->aux->exception_boundary = env->seen_exception;
22886 
22887 		/*
22888 		 * To properly pass the absolute subprog start to jit
22889 		 * all instruction adjustments should be accumulated
22890 		 */
22891 		old_len = func[i]->len;
22892 		func[i] = bpf_int_jit_compile(func[i]);
22893 		subprog_start_adjustment += func[i]->len - old_len;
22894 
22895 		if (!func[i]->jited) {
22896 			err = -ENOTSUPP;
22897 			goto out_free;
22898 		}
22899 		cond_resched();
22900 	}
22901 
22902 	/* at this point all bpf functions were successfully JITed
22903 	 * now populate all bpf_calls with correct addresses and
22904 	 * run last pass of JIT
22905 	 */
22906 	for (i = 0; i < env->subprog_cnt; i++) {
22907 		insn = func[i]->insnsi;
22908 		for (j = 0; j < func[i]->len; j++, insn++) {
22909 			if (bpf_pseudo_func(insn)) {
22910 				subprog = insn->off;
22911 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
22912 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
22913 				continue;
22914 			}
22915 			if (!bpf_pseudo_call(insn))
22916 				continue;
22917 			subprog = insn->off;
22918 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
22919 		}
22920 
22921 		/* we use the aux data to keep a list of the start addresses
22922 		 * of the JITed images for each function in the program
22923 		 *
22924 		 * for some architectures, such as powerpc64, the imm field
22925 		 * might not be large enough to hold the offset of the start
22926 		 * address of the callee's JITed image from __bpf_call_base
22927 		 *
22928 		 * in such cases, we can lookup the start address of a callee
22929 		 * by using its subprog id, available from the off field of
22930 		 * the call instruction, as an index for this list
22931 		 */
22932 		func[i]->aux->func = func;
22933 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
22934 		func[i]->aux->real_func_cnt = env->subprog_cnt;
22935 	}
22936 	for (i = 0; i < env->subprog_cnt; i++) {
22937 		old_bpf_func = func[i]->bpf_func;
22938 		tmp = bpf_int_jit_compile(func[i]);
22939 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
22940 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
22941 			err = -ENOTSUPP;
22942 			goto out_free;
22943 		}
22944 		cond_resched();
22945 	}
22946 
22947 	/*
22948 	 * Cleanup func[i]->aux fields which aren't required
22949 	 * or can become invalid in future
22950 	 */
22951 	for (i = 0; i < env->subprog_cnt; i++) {
22952 		func[i]->aux->used_maps = NULL;
22953 		func[i]->aux->used_map_cnt = 0;
22954 	}
22955 
22956 	/* finally lock prog and jit images for all functions and
22957 	 * populate kallsysm. Begin at the first subprogram, since
22958 	 * bpf_prog_load will add the kallsyms for the main program.
22959 	 */
22960 	for (i = 1; i < env->subprog_cnt; i++) {
22961 		err = bpf_prog_lock_ro(func[i]);
22962 		if (err)
22963 			goto out_free;
22964 	}
22965 
22966 	for (i = 1; i < env->subprog_cnt; i++)
22967 		bpf_prog_kallsyms_add(func[i]);
22968 
22969 	/* Last step: make now unused interpreter insns from main
22970 	 * prog consistent for later dump requests, so they can
22971 	 * later look the same as if they were interpreted only.
22972 	 */
22973 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22974 		if (bpf_pseudo_func(insn)) {
22975 			insn[0].imm = env->insn_aux_data[i].call_imm;
22976 			insn[1].imm = insn->off;
22977 			insn->off = 0;
22978 			continue;
22979 		}
22980 		if (!bpf_pseudo_call(insn))
22981 			continue;
22982 		insn->off = env->insn_aux_data[i].call_imm;
22983 		subprog = find_subprog(env, i + insn->off + 1);
22984 		insn->imm = subprog;
22985 	}
22986 
22987 	prog->jited = 1;
22988 	prog->bpf_func = func[0]->bpf_func;
22989 	prog->jited_len = func[0]->jited_len;
22990 	prog->aux->extable = func[0]->aux->extable;
22991 	prog->aux->num_exentries = func[0]->aux->num_exentries;
22992 	prog->aux->func = func;
22993 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
22994 	prog->aux->real_func_cnt = env->subprog_cnt;
22995 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
22996 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
22997 	bpf_prog_jit_attempt_done(prog);
22998 	return 0;
22999 out_free:
23000 	/* We failed JIT'ing, so at this point we need to unregister poke
23001 	 * descriptors from subprogs, so that kernel is not attempting to
23002 	 * patch it anymore as we're freeing the subprog JIT memory.
23003 	 */
23004 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
23005 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
23006 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
23007 	}
23008 	/* At this point we're guaranteed that poke descriptors are not
23009 	 * live anymore. We can just unlink its descriptor table as it's
23010 	 * released with the main prog.
23011 	 */
23012 	for (i = 0; i < env->subprog_cnt; i++) {
23013 		if (!func[i])
23014 			continue;
23015 		func[i]->aux->poke_tab = NULL;
23016 		bpf_jit_free(func[i]);
23017 	}
23018 	kfree(func);
23019 out_undo_insn:
23020 	/* cleanup main prog to be interpreted */
23021 	prog->jit_requested = 0;
23022 	prog->blinding_requested = 0;
23023 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
23024 		if (!bpf_pseudo_call(insn))
23025 			continue;
23026 		insn->off = 0;
23027 		insn->imm = env->insn_aux_data[i].call_imm;
23028 	}
23029 	bpf_prog_jit_attempt_done(prog);
23030 	return err;
23031 }
23032 
23033 static int fixup_call_args(struct bpf_verifier_env *env)
23034 {
23035 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
23036 	struct bpf_prog *prog = env->prog;
23037 	struct bpf_insn *insn = prog->insnsi;
23038 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
23039 	int i, depth;
23040 #endif
23041 	int err = 0;
23042 
23043 	if (env->prog->jit_requested &&
23044 	    !bpf_prog_is_offloaded(env->prog->aux)) {
23045 		err = jit_subprogs(env);
23046 		if (err == 0)
23047 			return 0;
23048 		if (err == -EFAULT)
23049 			return err;
23050 	}
23051 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
23052 	if (has_kfunc_call) {
23053 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
23054 		return -EINVAL;
23055 	}
23056 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
23057 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
23058 		 * have to be rejected, since interpreter doesn't support them yet.
23059 		 */
23060 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
23061 		return -EINVAL;
23062 	}
23063 	for (i = 0; i < prog->len; i++, insn++) {
23064 		if (bpf_pseudo_func(insn)) {
23065 			/* When JIT fails the progs with callback calls
23066 			 * have to be rejected, since interpreter doesn't support them yet.
23067 			 */
23068 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
23069 			return -EINVAL;
23070 		}
23071 
23072 		if (!bpf_pseudo_call(insn))
23073 			continue;
23074 		depth = get_callee_stack_depth(env, insn, i);
23075 		if (depth < 0)
23076 			return depth;
23077 		bpf_patch_call_args(insn, depth);
23078 	}
23079 	err = 0;
23080 #endif
23081 	return err;
23082 }
23083 
23084 /* replace a generic kfunc with a specialized version if necessary */
23085 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)
23086 {
23087 	struct bpf_prog *prog = env->prog;
23088 	bool seen_direct_write;
23089 	void *xdp_kfunc;
23090 	bool is_rdonly;
23091 	u32 func_id = desc->func_id;
23092 	u16 offset = desc->offset;
23093 	unsigned long addr = desc->addr;
23094 
23095 	if (offset) /* return if module BTF is used */
23096 		return 0;
23097 
23098 	if (bpf_dev_bound_kfunc_id(func_id)) {
23099 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
23100 		if (xdp_kfunc)
23101 			addr = (unsigned long)xdp_kfunc;
23102 		/* fallback to default kfunc when not supported by netdev */
23103 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
23104 		seen_direct_write = env->seen_direct_write;
23105 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
23106 
23107 		if (is_rdonly)
23108 			addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
23109 
23110 		/* restore env->seen_direct_write to its original value, since
23111 		 * may_access_direct_pkt_data mutates it
23112 		 */
23113 		env->seen_direct_write = seen_direct_write;
23114 	} else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {
23115 		if (bpf_lsm_has_d_inode_locked(prog))
23116 			addr = (unsigned long)bpf_set_dentry_xattr_locked;
23117 	} else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
23118 		if (bpf_lsm_has_d_inode_locked(prog))
23119 			addr = (unsigned long)bpf_remove_dentry_xattr_locked;
23120 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
23121 		if (!env->insn_aux_data[insn_idx].non_sleepable)
23122 			addr = (unsigned long)bpf_dynptr_from_file_sleepable;
23123 	} else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) {
23124 		if (env->insn_aux_data[insn_idx].non_sleepable)
23125 			addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable;
23126 	} else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) {
23127 		if (env->insn_aux_data[insn_idx].non_sleepable)
23128 			addr = (unsigned long)bpf_arena_free_pages_non_sleepable;
23129 	}
23130 	desc->addr = addr;
23131 	return 0;
23132 }
23133 
23134 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
23135 					    u16 struct_meta_reg,
23136 					    u16 node_offset_reg,
23137 					    struct bpf_insn *insn,
23138 					    struct bpf_insn *insn_buf,
23139 					    int *cnt)
23140 {
23141 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
23142 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
23143 
23144 	insn_buf[0] = addr[0];
23145 	insn_buf[1] = addr[1];
23146 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
23147 	insn_buf[3] = *insn;
23148 	*cnt = 4;
23149 }
23150 
23151 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
23152 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
23153 {
23154 	struct bpf_kfunc_desc *desc;
23155 	int err;
23156 
23157 	if (!insn->imm) {
23158 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
23159 		return -EINVAL;
23160 	}
23161 
23162 	*cnt = 0;
23163 
23164 	/* insn->imm has the btf func_id. Replace it with an offset relative to
23165 	 * __bpf_call_base, unless the JIT needs to call functions that are
23166 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
23167 	 */
23168 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
23169 	if (!desc) {
23170 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
23171 			     insn->imm);
23172 		return -EFAULT;
23173 	}
23174 
23175 	err = specialize_kfunc(env, desc, insn_idx);
23176 	if (err)
23177 		return err;
23178 
23179 	if (!bpf_jit_supports_far_kfunc_call())
23180 		insn->imm = BPF_CALL_IMM(desc->addr);
23181 
23182 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
23183 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
23184 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
23185 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
23186 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
23187 
23188 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
23189 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
23190 				     insn_idx);
23191 			return -EFAULT;
23192 		}
23193 
23194 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
23195 		insn_buf[1] = addr[0];
23196 		insn_buf[2] = addr[1];
23197 		insn_buf[3] = *insn;
23198 		*cnt = 4;
23199 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
23200 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
23201 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
23202 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
23203 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
23204 
23205 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
23206 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
23207 				     insn_idx);
23208 			return -EFAULT;
23209 		}
23210 
23211 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
23212 		    !kptr_struct_meta) {
23213 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
23214 				     insn_idx);
23215 			return -EFAULT;
23216 		}
23217 
23218 		insn_buf[0] = addr[0];
23219 		insn_buf[1] = addr[1];
23220 		insn_buf[2] = *insn;
23221 		*cnt = 3;
23222 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
23223 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
23224 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
23225 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
23226 		int struct_meta_reg = BPF_REG_3;
23227 		int node_offset_reg = BPF_REG_4;
23228 
23229 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
23230 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
23231 			struct_meta_reg = BPF_REG_4;
23232 			node_offset_reg = BPF_REG_5;
23233 		}
23234 
23235 		if (!kptr_struct_meta) {
23236 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
23237 				     insn_idx);
23238 			return -EFAULT;
23239 		}
23240 
23241 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
23242 						node_offset_reg, insn, insn_buf, cnt);
23243 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
23244 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
23245 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
23246 		*cnt = 1;
23247 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] &&
23248 		   env->prog->expected_attach_type == BPF_TRACE_FSESSION) {
23249 		/*
23250 		 * inline the bpf_session_is_return() for fsession:
23251 		 *   bool bpf_session_is_return(void *ctx)
23252 		 *   {
23253 		 *       return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1;
23254 		 *   }
23255 		 */
23256 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23257 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT);
23258 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1);
23259 		*cnt = 3;
23260 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] &&
23261 		   env->prog->expected_attach_type == BPF_TRACE_FSESSION) {
23262 		/*
23263 		 * inline bpf_session_cookie() for fsession:
23264 		 *   __u64 *bpf_session_cookie(void *ctx)
23265 		 *   {
23266 		 *       u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF;
23267 		 *       return &((u64 *)ctx)[-off];
23268 		 *   }
23269 		 */
23270 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23271 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT);
23272 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
23273 		insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
23274 		insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1);
23275 		insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0);
23276 		*cnt = 6;
23277 	}
23278 
23279 	if (env->insn_aux_data[insn_idx].arg_prog) {
23280 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
23281 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
23282 		int idx = *cnt;
23283 
23284 		insn_buf[idx++] = ld_addrs[0];
23285 		insn_buf[idx++] = ld_addrs[1];
23286 		insn_buf[idx++] = *insn;
23287 		*cnt = idx;
23288 	}
23289 	return 0;
23290 }
23291 
23292 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
23293 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
23294 {
23295 	struct bpf_subprog_info *info = env->subprog_info;
23296 	int cnt = env->subprog_cnt;
23297 	struct bpf_prog *prog;
23298 
23299 	/* We only reserve one slot for hidden subprogs in subprog_info. */
23300 	if (env->hidden_subprog_cnt) {
23301 		verifier_bug(env, "only one hidden subprog supported");
23302 		return -EFAULT;
23303 	}
23304 	/* We're not patching any existing instruction, just appending the new
23305 	 * ones for the hidden subprog. Hence all of the adjustment operations
23306 	 * in bpf_patch_insn_data are no-ops.
23307 	 */
23308 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
23309 	if (!prog)
23310 		return -ENOMEM;
23311 	env->prog = prog;
23312 	info[cnt + 1].start = info[cnt].start;
23313 	info[cnt].start = prog->len - len + 1;
23314 	env->subprog_cnt++;
23315 	env->hidden_subprog_cnt++;
23316 	return 0;
23317 }
23318 
23319 /* Do various post-verification rewrites in a single program pass.
23320  * These rewrites simplify JIT and interpreter implementations.
23321  */
23322 static int do_misc_fixups(struct bpf_verifier_env *env)
23323 {
23324 	struct bpf_prog *prog = env->prog;
23325 	enum bpf_attach_type eatype = prog->expected_attach_type;
23326 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
23327 	struct bpf_insn *insn = prog->insnsi;
23328 	const struct bpf_func_proto *fn;
23329 	const int insn_cnt = prog->len;
23330 	const struct bpf_map_ops *ops;
23331 	struct bpf_insn_aux_data *aux;
23332 	struct bpf_insn *insn_buf = env->insn_buf;
23333 	struct bpf_prog *new_prog;
23334 	struct bpf_map *map_ptr;
23335 	int i, ret, cnt, delta = 0, cur_subprog = 0;
23336 	struct bpf_subprog_info *subprogs = env->subprog_info;
23337 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
23338 	u16 stack_depth_extra = 0;
23339 
23340 	if (env->seen_exception && !env->exception_callback_subprog) {
23341 		struct bpf_insn *patch = insn_buf;
23342 
23343 		*patch++ = env->prog->insnsi[insn_cnt - 1];
23344 		*patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
23345 		*patch++ = BPF_EXIT_INSN();
23346 		ret = add_hidden_subprog(env, insn_buf, patch - insn_buf);
23347 		if (ret < 0)
23348 			return ret;
23349 		prog = env->prog;
23350 		insn = prog->insnsi;
23351 
23352 		env->exception_callback_subprog = env->subprog_cnt - 1;
23353 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
23354 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
23355 	}
23356 
23357 	for (i = 0; i < insn_cnt;) {
23358 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
23359 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
23360 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
23361 				/* convert to 32-bit mov that clears upper 32-bit */
23362 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
23363 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
23364 				insn->off = 0;
23365 				insn->imm = 0;
23366 			} /* cast from as(0) to as(1) should be handled by JIT */
23367 			goto next_insn;
23368 		}
23369 
23370 		if (env->insn_aux_data[i + delta].needs_zext)
23371 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
23372 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
23373 
23374 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
23375 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
23376 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
23377 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
23378 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
23379 		    insn->off == 1 && insn->imm == -1) {
23380 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
23381 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
23382 			struct bpf_insn *patch = insn_buf;
23383 
23384 			if (isdiv)
23385 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
23386 							BPF_NEG | BPF_K, insn->dst_reg,
23387 							0, 0, 0);
23388 			else
23389 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
23390 
23391 			cnt = patch - insn_buf;
23392 
23393 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23394 			if (!new_prog)
23395 				return -ENOMEM;
23396 
23397 			delta    += cnt - 1;
23398 			env->prog = prog = new_prog;
23399 			insn      = new_prog->insnsi + i + delta;
23400 			goto next_insn;
23401 		}
23402 
23403 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
23404 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
23405 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
23406 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
23407 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
23408 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
23409 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
23410 			bool is_sdiv = isdiv && insn->off == 1;
23411 			bool is_smod = !isdiv && insn->off == 1;
23412 			struct bpf_insn *patch = insn_buf;
23413 
23414 			if (is_sdiv) {
23415 				/* [R,W]x sdiv 0 -> 0
23416 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
23417 				 * INT_MIN sdiv -1 -> INT_MIN
23418 				 */
23419 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
23420 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
23421 							BPF_ADD | BPF_K, BPF_REG_AX,
23422 							0, 0, 1);
23423 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
23424 							BPF_JGT | BPF_K, BPF_REG_AX,
23425 							0, 4, 1);
23426 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
23427 							BPF_JEQ | BPF_K, BPF_REG_AX,
23428 							0, 1, 0);
23429 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
23430 							BPF_MOV | BPF_K, insn->dst_reg,
23431 							0, 0, 0);
23432 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
23433 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
23434 							BPF_NEG | BPF_K, insn->dst_reg,
23435 							0, 0, 0);
23436 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
23437 				*patch++ = *insn;
23438 				cnt = patch - insn_buf;
23439 			} else if (is_smod) {
23440 				/* [R,W]x mod 0 -> [R,W]x */
23441 				/* [R,W]x mod -1 -> 0 */
23442 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
23443 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
23444 							BPF_ADD | BPF_K, BPF_REG_AX,
23445 							0, 0, 1);
23446 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
23447 							BPF_JGT | BPF_K, BPF_REG_AX,
23448 							0, 3, 1);
23449 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
23450 							BPF_JEQ | BPF_K, BPF_REG_AX,
23451 							0, 3 + (is64 ? 0 : 1), 1);
23452 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
23453 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
23454 				*patch++ = *insn;
23455 
23456 				if (!is64) {
23457 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
23458 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
23459 				}
23460 				cnt = patch - insn_buf;
23461 			} else if (isdiv) {
23462 				/* [R,W]x div 0 -> 0 */
23463 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
23464 							BPF_JNE | BPF_K, insn->src_reg,
23465 							0, 2, 0);
23466 				*patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg);
23467 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
23468 				*patch++ = *insn;
23469 				cnt = patch - insn_buf;
23470 			} else {
23471 				/* [R,W]x mod 0 -> [R,W]x */
23472 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
23473 							BPF_JEQ | BPF_K, insn->src_reg,
23474 							0, 1 + (is64 ? 0 : 1), 0);
23475 				*patch++ = *insn;
23476 
23477 				if (!is64) {
23478 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
23479 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
23480 				}
23481 				cnt = patch - insn_buf;
23482 			}
23483 
23484 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23485 			if (!new_prog)
23486 				return -ENOMEM;
23487 
23488 			delta    += cnt - 1;
23489 			env->prog = prog = new_prog;
23490 			insn      = new_prog->insnsi + i + delta;
23491 			goto next_insn;
23492 		}
23493 
23494 		/* Make it impossible to de-reference a userspace address */
23495 		if (BPF_CLASS(insn->code) == BPF_LDX &&
23496 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
23497 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
23498 			struct bpf_insn *patch = insn_buf;
23499 			u64 uaddress_limit = bpf_arch_uaddress_limit();
23500 
23501 			if (!uaddress_limit)
23502 				goto next_insn;
23503 
23504 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
23505 			if (insn->off)
23506 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
23507 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
23508 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
23509 			*patch++ = *insn;
23510 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
23511 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
23512 
23513 			cnt = patch - insn_buf;
23514 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23515 			if (!new_prog)
23516 				return -ENOMEM;
23517 
23518 			delta    += cnt - 1;
23519 			env->prog = prog = new_prog;
23520 			insn      = new_prog->insnsi + i + delta;
23521 			goto next_insn;
23522 		}
23523 
23524 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
23525 		if (BPF_CLASS(insn->code) == BPF_LD &&
23526 		    (BPF_MODE(insn->code) == BPF_ABS ||
23527 		     BPF_MODE(insn->code) == BPF_IND)) {
23528 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
23529 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
23530 				verifier_bug(env, "%d insns generated for ld_abs", cnt);
23531 				return -EFAULT;
23532 			}
23533 
23534 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23535 			if (!new_prog)
23536 				return -ENOMEM;
23537 
23538 			delta    += cnt - 1;
23539 			env->prog = prog = new_prog;
23540 			insn      = new_prog->insnsi + i + delta;
23541 			goto next_insn;
23542 		}
23543 
23544 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
23545 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
23546 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
23547 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
23548 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
23549 			struct bpf_insn *patch = insn_buf;
23550 			bool issrc, isneg, isimm;
23551 			u32 off_reg;
23552 
23553 			aux = &env->insn_aux_data[i + delta];
23554 			if (!aux->alu_state ||
23555 			    aux->alu_state == BPF_ALU_NON_POINTER)
23556 				goto next_insn;
23557 
23558 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
23559 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
23560 				BPF_ALU_SANITIZE_SRC;
23561 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
23562 
23563 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
23564 			if (isimm) {
23565 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
23566 			} else {
23567 				if (isneg)
23568 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
23569 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
23570 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
23571 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
23572 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
23573 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
23574 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
23575 			}
23576 			if (!issrc)
23577 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
23578 			insn->src_reg = BPF_REG_AX;
23579 			if (isneg)
23580 				insn->code = insn->code == code_add ?
23581 					     code_sub : code_add;
23582 			*patch++ = *insn;
23583 			if (issrc && isneg && !isimm)
23584 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
23585 			cnt = patch - insn_buf;
23586 
23587 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23588 			if (!new_prog)
23589 				return -ENOMEM;
23590 
23591 			delta    += cnt - 1;
23592 			env->prog = prog = new_prog;
23593 			insn      = new_prog->insnsi + i + delta;
23594 			goto next_insn;
23595 		}
23596 
23597 		if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) {
23598 			int stack_off_cnt = -stack_depth - 16;
23599 
23600 			/*
23601 			 * Two 8 byte slots, depth-16 stores the count, and
23602 			 * depth-8 stores the start timestamp of the loop.
23603 			 *
23604 			 * The starting value of count is BPF_MAX_TIMED_LOOPS
23605 			 * (0xffff).  Every iteration loads it and subs it by 1,
23606 			 * until the value becomes 0 in AX (thus, 1 in stack),
23607 			 * after which we call arch_bpf_timed_may_goto, which
23608 			 * either sets AX to 0xffff to keep looping, or to 0
23609 			 * upon timeout. AX is then stored into the stack. In
23610 			 * the next iteration, we either see 0 and break out, or
23611 			 * continue iterating until the next time value is 0
23612 			 * after subtraction, rinse and repeat.
23613 			 */
23614 			stack_depth_extra = 16;
23615 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt);
23616 			if (insn->off >= 0)
23617 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5);
23618 			else
23619 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
23620 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
23621 			insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
23622 			/*
23623 			 * AX is used as an argument to pass in stack_off_cnt
23624 			 * (to add to r10/fp), and also as the return value of
23625 			 * the call to arch_bpf_timed_may_goto.
23626 			 */
23627 			insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt);
23628 			insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
23629 			insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt);
23630 			cnt = 7;
23631 
23632 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23633 			if (!new_prog)
23634 				return -ENOMEM;
23635 
23636 			delta += cnt - 1;
23637 			env->prog = prog = new_prog;
23638 			insn = new_prog->insnsi + i + delta;
23639 			goto next_insn;
23640 		} else if (is_may_goto_insn(insn)) {
23641 			int stack_off = -stack_depth - 8;
23642 
23643 			stack_depth_extra = 8;
23644 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
23645 			if (insn->off >= 0)
23646 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
23647 			else
23648 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
23649 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
23650 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
23651 			cnt = 4;
23652 
23653 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23654 			if (!new_prog)
23655 				return -ENOMEM;
23656 
23657 			delta += cnt - 1;
23658 			env->prog = prog = new_prog;
23659 			insn = new_prog->insnsi + i + delta;
23660 			goto next_insn;
23661 		}
23662 
23663 		if (insn->code != (BPF_JMP | BPF_CALL))
23664 			goto next_insn;
23665 		if (insn->src_reg == BPF_PSEUDO_CALL)
23666 			goto next_insn;
23667 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
23668 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
23669 			if (ret)
23670 				return ret;
23671 			if (cnt == 0)
23672 				goto next_insn;
23673 
23674 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23675 			if (!new_prog)
23676 				return -ENOMEM;
23677 
23678 			delta	 += cnt - 1;
23679 			env->prog = prog = new_prog;
23680 			insn	  = new_prog->insnsi + i + delta;
23681 			goto next_insn;
23682 		}
23683 
23684 		/* Skip inlining the helper call if the JIT does it. */
23685 		if (bpf_jit_inlines_helper_call(insn->imm))
23686 			goto next_insn;
23687 
23688 		if (insn->imm == BPF_FUNC_get_route_realm)
23689 			prog->dst_needed = 1;
23690 		if (insn->imm == BPF_FUNC_get_prandom_u32)
23691 			bpf_user_rnd_init_once();
23692 		if (insn->imm == BPF_FUNC_override_return)
23693 			prog->kprobe_override = 1;
23694 		if (insn->imm == BPF_FUNC_tail_call) {
23695 			/* If we tail call into other programs, we
23696 			 * cannot make any assumptions since they can
23697 			 * be replaced dynamically during runtime in
23698 			 * the program array.
23699 			 */
23700 			prog->cb_access = 1;
23701 			if (!allow_tail_call_in_subprogs(env))
23702 				prog->aux->stack_depth = MAX_BPF_STACK;
23703 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
23704 
23705 			/* mark bpf_tail_call as different opcode to avoid
23706 			 * conditional branch in the interpreter for every normal
23707 			 * call and to prevent accidental JITing by JIT compiler
23708 			 * that doesn't support bpf_tail_call yet
23709 			 */
23710 			insn->imm = 0;
23711 			insn->code = BPF_JMP | BPF_TAIL_CALL;
23712 
23713 			aux = &env->insn_aux_data[i + delta];
23714 			if (env->bpf_capable && !prog->blinding_requested &&
23715 			    prog->jit_requested &&
23716 			    !bpf_map_key_poisoned(aux) &&
23717 			    !bpf_map_ptr_poisoned(aux) &&
23718 			    !bpf_map_ptr_unpriv(aux)) {
23719 				struct bpf_jit_poke_descriptor desc = {
23720 					.reason = BPF_POKE_REASON_TAIL_CALL,
23721 					.tail_call.map = aux->map_ptr_state.map_ptr,
23722 					.tail_call.key = bpf_map_key_immediate(aux),
23723 					.insn_idx = i + delta,
23724 				};
23725 
23726 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
23727 				if (ret < 0) {
23728 					verbose(env, "adding tail call poke descriptor failed\n");
23729 					return ret;
23730 				}
23731 
23732 				insn->imm = ret + 1;
23733 				goto next_insn;
23734 			}
23735 
23736 			if (!bpf_map_ptr_unpriv(aux))
23737 				goto next_insn;
23738 
23739 			/* instead of changing every JIT dealing with tail_call
23740 			 * emit two extra insns:
23741 			 * if (index >= max_entries) goto out;
23742 			 * index &= array->index_mask;
23743 			 * to avoid out-of-bounds cpu speculation
23744 			 */
23745 			if (bpf_map_ptr_poisoned(aux)) {
23746 				verbose(env, "tail_call abusing map_ptr\n");
23747 				return -EINVAL;
23748 			}
23749 
23750 			map_ptr = aux->map_ptr_state.map_ptr;
23751 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
23752 						  map_ptr->max_entries, 2);
23753 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
23754 						    container_of(map_ptr,
23755 								 struct bpf_array,
23756 								 map)->index_mask);
23757 			insn_buf[2] = *insn;
23758 			cnt = 3;
23759 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23760 			if (!new_prog)
23761 				return -ENOMEM;
23762 
23763 			delta    += cnt - 1;
23764 			env->prog = prog = new_prog;
23765 			insn      = new_prog->insnsi + i + delta;
23766 			goto next_insn;
23767 		}
23768 
23769 		if (insn->imm == BPF_FUNC_timer_set_callback) {
23770 			/* The verifier will process callback_fn as many times as necessary
23771 			 * with different maps and the register states prepared by
23772 			 * set_timer_callback_state will be accurate.
23773 			 *
23774 			 * The following use case is valid:
23775 			 *   map1 is shared by prog1, prog2, prog3.
23776 			 *   prog1 calls bpf_timer_init for some map1 elements
23777 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
23778 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
23779 			 *   prog3 calls bpf_timer_start for some map1 elements.
23780 			 *     Those that were not both bpf_timer_init-ed and
23781 			 *     bpf_timer_set_callback-ed will return -EINVAL.
23782 			 */
23783 			struct bpf_insn ld_addrs[2] = {
23784 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
23785 			};
23786 
23787 			insn_buf[0] = ld_addrs[0];
23788 			insn_buf[1] = ld_addrs[1];
23789 			insn_buf[2] = *insn;
23790 			cnt = 3;
23791 
23792 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23793 			if (!new_prog)
23794 				return -ENOMEM;
23795 
23796 			delta    += cnt - 1;
23797 			env->prog = prog = new_prog;
23798 			insn      = new_prog->insnsi + i + delta;
23799 			goto patch_call_imm;
23800 		}
23801 
23802 		if (is_storage_get_function(insn->imm)) {
23803 			if (env->insn_aux_data[i + delta].non_sleepable)
23804 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
23805 			else
23806 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
23807 			insn_buf[1] = *insn;
23808 			cnt = 2;
23809 
23810 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23811 			if (!new_prog)
23812 				return -ENOMEM;
23813 
23814 			delta += cnt - 1;
23815 			env->prog = prog = new_prog;
23816 			insn = new_prog->insnsi + i + delta;
23817 			goto patch_call_imm;
23818 		}
23819 
23820 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
23821 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
23822 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
23823 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
23824 			 */
23825 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
23826 			insn_buf[1] = *insn;
23827 			cnt = 2;
23828 
23829 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23830 			if (!new_prog)
23831 				return -ENOMEM;
23832 
23833 			delta += cnt - 1;
23834 			env->prog = prog = new_prog;
23835 			insn = new_prog->insnsi + i + delta;
23836 			goto patch_call_imm;
23837 		}
23838 
23839 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
23840 		 * and other inlining handlers are currently limited to 64 bit
23841 		 * only.
23842 		 */
23843 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
23844 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
23845 		     insn->imm == BPF_FUNC_map_update_elem ||
23846 		     insn->imm == BPF_FUNC_map_delete_elem ||
23847 		     insn->imm == BPF_FUNC_map_push_elem   ||
23848 		     insn->imm == BPF_FUNC_map_pop_elem    ||
23849 		     insn->imm == BPF_FUNC_map_peek_elem   ||
23850 		     insn->imm == BPF_FUNC_redirect_map    ||
23851 		     insn->imm == BPF_FUNC_for_each_map_elem ||
23852 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
23853 			aux = &env->insn_aux_data[i + delta];
23854 			if (bpf_map_ptr_poisoned(aux))
23855 				goto patch_call_imm;
23856 
23857 			map_ptr = aux->map_ptr_state.map_ptr;
23858 			ops = map_ptr->ops;
23859 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
23860 			    ops->map_gen_lookup) {
23861 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
23862 				if (cnt == -EOPNOTSUPP)
23863 					goto patch_map_ops_generic;
23864 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
23865 					verifier_bug(env, "%d insns generated for map lookup", cnt);
23866 					return -EFAULT;
23867 				}
23868 
23869 				new_prog = bpf_patch_insn_data(env, i + delta,
23870 							       insn_buf, cnt);
23871 				if (!new_prog)
23872 					return -ENOMEM;
23873 
23874 				delta    += cnt - 1;
23875 				env->prog = prog = new_prog;
23876 				insn      = new_prog->insnsi + i + delta;
23877 				goto next_insn;
23878 			}
23879 
23880 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
23881 				     (void *(*)(struct bpf_map *map, void *key))NULL));
23882 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
23883 				     (long (*)(struct bpf_map *map, void *key))NULL));
23884 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
23885 				     (long (*)(struct bpf_map *map, void *key, void *value,
23886 					      u64 flags))NULL));
23887 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
23888 				     (long (*)(struct bpf_map *map, void *value,
23889 					      u64 flags))NULL));
23890 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
23891 				     (long (*)(struct bpf_map *map, void *value))NULL));
23892 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
23893 				     (long (*)(struct bpf_map *map, void *value))NULL));
23894 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
23895 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
23896 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
23897 				     (long (*)(struct bpf_map *map,
23898 					      bpf_callback_t callback_fn,
23899 					      void *callback_ctx,
23900 					      u64 flags))NULL));
23901 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
23902 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
23903 
23904 patch_map_ops_generic:
23905 			switch (insn->imm) {
23906 			case BPF_FUNC_map_lookup_elem:
23907 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
23908 				goto next_insn;
23909 			case BPF_FUNC_map_update_elem:
23910 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
23911 				goto next_insn;
23912 			case BPF_FUNC_map_delete_elem:
23913 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
23914 				goto next_insn;
23915 			case BPF_FUNC_map_push_elem:
23916 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
23917 				goto next_insn;
23918 			case BPF_FUNC_map_pop_elem:
23919 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
23920 				goto next_insn;
23921 			case BPF_FUNC_map_peek_elem:
23922 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
23923 				goto next_insn;
23924 			case BPF_FUNC_redirect_map:
23925 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
23926 				goto next_insn;
23927 			case BPF_FUNC_for_each_map_elem:
23928 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
23929 				goto next_insn;
23930 			case BPF_FUNC_map_lookup_percpu_elem:
23931 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
23932 				goto next_insn;
23933 			}
23934 
23935 			goto patch_call_imm;
23936 		}
23937 
23938 		/* Implement bpf_jiffies64 inline. */
23939 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
23940 		    insn->imm == BPF_FUNC_jiffies64) {
23941 			struct bpf_insn ld_jiffies_addr[2] = {
23942 				BPF_LD_IMM64(BPF_REG_0,
23943 					     (unsigned long)&jiffies),
23944 			};
23945 
23946 			insn_buf[0] = ld_jiffies_addr[0];
23947 			insn_buf[1] = ld_jiffies_addr[1];
23948 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
23949 						  BPF_REG_0, 0);
23950 			cnt = 3;
23951 
23952 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
23953 						       cnt);
23954 			if (!new_prog)
23955 				return -ENOMEM;
23956 
23957 			delta    += cnt - 1;
23958 			env->prog = prog = new_prog;
23959 			insn      = new_prog->insnsi + i + delta;
23960 			goto next_insn;
23961 		}
23962 
23963 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
23964 		/* Implement bpf_get_smp_processor_id() inline. */
23965 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
23966 		    verifier_inlines_helper_call(env, insn->imm)) {
23967 			/* BPF_FUNC_get_smp_processor_id inlining is an
23968 			 * optimization, so if cpu_number is ever
23969 			 * changed in some incompatible and hard to support
23970 			 * way, it's fine to back out this inlining logic
23971 			 */
23972 #ifdef CONFIG_SMP
23973 			insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number);
23974 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
23975 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
23976 			cnt = 3;
23977 #else
23978 			insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
23979 			cnt = 1;
23980 #endif
23981 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23982 			if (!new_prog)
23983 				return -ENOMEM;
23984 
23985 			delta    += cnt - 1;
23986 			env->prog = prog = new_prog;
23987 			insn      = new_prog->insnsi + i + delta;
23988 			goto next_insn;
23989 		}
23990 
23991 		/* Implement bpf_get_current_task() and bpf_get_current_task_btf() inline. */
23992 		if ((insn->imm == BPF_FUNC_get_current_task || insn->imm == BPF_FUNC_get_current_task_btf) &&
23993 		    verifier_inlines_helper_call(env, insn->imm)) {
23994 			insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&current_task);
23995 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
23996 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_0, 0);
23997 			cnt = 3;
23998 
23999 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
24000 			if (!new_prog)
24001 				return -ENOMEM;
24002 
24003 			delta    += cnt - 1;
24004 			env->prog = prog = new_prog;
24005 			insn      = new_prog->insnsi + i + delta;
24006 			goto next_insn;
24007 		}
24008 #endif
24009 		/* Implement bpf_get_func_arg inline. */
24010 		if (prog_type == BPF_PROG_TYPE_TRACING &&
24011 		    insn->imm == BPF_FUNC_get_func_arg) {
24012 			if (eatype == BPF_TRACE_RAW_TP) {
24013 				int nr_args = btf_type_vlen(prog->aux->attach_func_proto);
24014 
24015 				/* skip 'void *__data' in btf_trace_##name() and save to reg0 */
24016 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, nr_args - 1);
24017 				cnt = 1;
24018 			} else {
24019 				/* Load nr_args from ctx - 8 */
24020 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
24021 				insn_buf[1] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
24022 				cnt = 2;
24023 			}
24024 			insn_buf[cnt++] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
24025 			insn_buf[cnt++] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
24026 			insn_buf[cnt++] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
24027 			insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
24028 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
24029 			insn_buf[cnt++] = BPF_MOV64_IMM(BPF_REG_0, 0);
24030 			insn_buf[cnt++] = BPF_JMP_A(1);
24031 			insn_buf[cnt++] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
24032 
24033 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
24034 			if (!new_prog)
24035 				return -ENOMEM;
24036 
24037 			delta    += cnt - 1;
24038 			env->prog = prog = new_prog;
24039 			insn      = new_prog->insnsi + i + delta;
24040 			goto next_insn;
24041 		}
24042 
24043 		/* Implement bpf_get_func_ret inline. */
24044 		if (prog_type == BPF_PROG_TYPE_TRACING &&
24045 		    insn->imm == BPF_FUNC_get_func_ret) {
24046 			if (eatype == BPF_TRACE_FEXIT ||
24047 			    eatype == BPF_TRACE_FSESSION ||
24048 			    eatype == BPF_MODIFY_RETURN) {
24049 				/* Load nr_args from ctx - 8 */
24050 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
24051 				insn_buf[1] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
24052 				insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
24053 				insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
24054 				insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
24055 				insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
24056 				insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
24057 				cnt = 7;
24058 			} else {
24059 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
24060 				cnt = 1;
24061 			}
24062 
24063 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
24064 			if (!new_prog)
24065 				return -ENOMEM;
24066 
24067 			delta    += cnt - 1;
24068 			env->prog = prog = new_prog;
24069 			insn      = new_prog->insnsi + i + delta;
24070 			goto next_insn;
24071 		}
24072 
24073 		/* Implement get_func_arg_cnt inline. */
24074 		if (prog_type == BPF_PROG_TYPE_TRACING &&
24075 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
24076 			if (eatype == BPF_TRACE_RAW_TP) {
24077 				int nr_args = btf_type_vlen(prog->aux->attach_func_proto);
24078 
24079 				/* skip 'void *__data' in btf_trace_##name() and save to reg0 */
24080 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, nr_args - 1);
24081 				cnt = 1;
24082 			} else {
24083 				/* Load nr_args from ctx - 8 */
24084 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
24085 				insn_buf[1] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
24086 				cnt = 2;
24087 			}
24088 
24089 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
24090 			if (!new_prog)
24091 				return -ENOMEM;
24092 
24093 			delta    += cnt - 1;
24094 			env->prog = prog = new_prog;
24095 			insn      = new_prog->insnsi + i + delta;
24096 			goto next_insn;
24097 		}
24098 
24099 		/* Implement bpf_get_func_ip inline. */
24100 		if (prog_type == BPF_PROG_TYPE_TRACING &&
24101 		    insn->imm == BPF_FUNC_get_func_ip) {
24102 			/* Load IP address from ctx - 16 */
24103 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
24104 
24105 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
24106 			if (!new_prog)
24107 				return -ENOMEM;
24108 
24109 			env->prog = prog = new_prog;
24110 			insn      = new_prog->insnsi + i + delta;
24111 			goto next_insn;
24112 		}
24113 
24114 		/* Implement bpf_get_branch_snapshot inline. */
24115 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
24116 		    prog->jit_requested && BITS_PER_LONG == 64 &&
24117 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
24118 			/* We are dealing with the following func protos:
24119 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
24120 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
24121 			 */
24122 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
24123 
24124 			/* struct perf_branch_entry is part of UAPI and is
24125 			 * used as an array element, so extremely unlikely to
24126 			 * ever grow or shrink
24127 			 */
24128 			BUILD_BUG_ON(br_entry_size != 24);
24129 
24130 			/* if (unlikely(flags)) return -EINVAL */
24131 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
24132 
24133 			/* Transform size (bytes) into number of entries (cnt = size / 24).
24134 			 * But to avoid expensive division instruction, we implement
24135 			 * divide-by-3 through multiplication, followed by further
24136 			 * division by 8 through 3-bit right shift.
24137 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
24138 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
24139 			 *
24140 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
24141 			 */
24142 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
24143 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
24144 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
24145 
24146 			/* call perf_snapshot_branch_stack implementation */
24147 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
24148 			/* if (entry_cnt == 0) return -ENOENT */
24149 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
24150 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
24151 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
24152 			insn_buf[7] = BPF_JMP_A(3);
24153 			/* return -EINVAL; */
24154 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
24155 			insn_buf[9] = BPF_JMP_A(1);
24156 			/* return -ENOENT; */
24157 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
24158 			cnt = 11;
24159 
24160 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
24161 			if (!new_prog)
24162 				return -ENOMEM;
24163 
24164 			delta    += cnt - 1;
24165 			env->prog = prog = new_prog;
24166 			insn      = new_prog->insnsi + i + delta;
24167 			goto next_insn;
24168 		}
24169 
24170 		/* Implement bpf_kptr_xchg inline */
24171 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
24172 		    insn->imm == BPF_FUNC_kptr_xchg &&
24173 		    bpf_jit_supports_ptr_xchg()) {
24174 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
24175 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
24176 			cnt = 2;
24177 
24178 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
24179 			if (!new_prog)
24180 				return -ENOMEM;
24181 
24182 			delta    += cnt - 1;
24183 			env->prog = prog = new_prog;
24184 			insn      = new_prog->insnsi + i + delta;
24185 			goto next_insn;
24186 		}
24187 patch_call_imm:
24188 		fn = env->ops->get_func_proto(insn->imm, env->prog);
24189 		/* all functions that have prototype and verifier allowed
24190 		 * programs to call them, must be real in-kernel functions
24191 		 */
24192 		if (!fn->func) {
24193 			verifier_bug(env,
24194 				     "not inlined functions %s#%d is missing func",
24195 				     func_id_name(insn->imm), insn->imm);
24196 			return -EFAULT;
24197 		}
24198 		insn->imm = fn->func - __bpf_call_base;
24199 next_insn:
24200 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
24201 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
24202 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
24203 
24204 			stack_depth = subprogs[cur_subprog].stack_depth;
24205 			if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) {
24206 				verbose(env, "stack size %d(extra %d) is too large\n",
24207 					stack_depth, stack_depth_extra);
24208 				return -EINVAL;
24209 			}
24210 			cur_subprog++;
24211 			stack_depth = subprogs[cur_subprog].stack_depth;
24212 			stack_depth_extra = 0;
24213 		}
24214 		i++;
24215 		insn++;
24216 	}
24217 
24218 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
24219 	for (i = 0; i < env->subprog_cnt; i++) {
24220 		int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1;
24221 		int subprog_start = subprogs[i].start;
24222 		int stack_slots = subprogs[i].stack_extra / 8;
24223 		int slots = delta, cnt = 0;
24224 
24225 		if (!stack_slots)
24226 			continue;
24227 		/* We need two slots in case timed may_goto is supported. */
24228 		if (stack_slots > slots) {
24229 			verifier_bug(env, "stack_slots supports may_goto only");
24230 			return -EFAULT;
24231 		}
24232 
24233 		stack_depth = subprogs[i].stack_depth;
24234 		if (bpf_jit_supports_timed_may_goto()) {
24235 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
24236 						     BPF_MAX_TIMED_LOOPS);
24237 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0);
24238 		} else {
24239 			/* Add ST insn to subprog prologue to init extra stack */
24240 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
24241 						     BPF_MAX_LOOPS);
24242 		}
24243 		/* Copy first actual insn to preserve it */
24244 		insn_buf[cnt++] = env->prog->insnsi[subprog_start];
24245 
24246 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt);
24247 		if (!new_prog)
24248 			return -ENOMEM;
24249 		env->prog = prog = new_prog;
24250 		/*
24251 		 * If may_goto is a first insn of a prog there could be a jmp
24252 		 * insn that points to it, hence adjust all such jmps to point
24253 		 * to insn after BPF_ST that inits may_goto count.
24254 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
24255 		 */
24256 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta));
24257 	}
24258 
24259 	/* Since poke tab is now finalized, publish aux to tracker. */
24260 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
24261 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
24262 		if (!map_ptr->ops->map_poke_track ||
24263 		    !map_ptr->ops->map_poke_untrack ||
24264 		    !map_ptr->ops->map_poke_run) {
24265 			verifier_bug(env, "poke tab is misconfigured");
24266 			return -EFAULT;
24267 		}
24268 
24269 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
24270 		if (ret < 0) {
24271 			verbose(env, "tracking tail call prog failed\n");
24272 			return ret;
24273 		}
24274 	}
24275 
24276 	ret = sort_kfunc_descs_by_imm_off(env);
24277 	if (ret)
24278 		return ret;
24279 
24280 	return 0;
24281 }
24282 
24283 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
24284 					int position,
24285 					s32 stack_base,
24286 					u32 callback_subprogno,
24287 					u32 *total_cnt)
24288 {
24289 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
24290 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
24291 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
24292 	int reg_loop_max = BPF_REG_6;
24293 	int reg_loop_cnt = BPF_REG_7;
24294 	int reg_loop_ctx = BPF_REG_8;
24295 
24296 	struct bpf_insn *insn_buf = env->insn_buf;
24297 	struct bpf_prog *new_prog;
24298 	u32 callback_start;
24299 	u32 call_insn_offset;
24300 	s32 callback_offset;
24301 	u32 cnt = 0;
24302 
24303 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
24304 	 * be careful to modify this code in sync.
24305 	 */
24306 
24307 	/* Return error and jump to the end of the patch if
24308 	 * expected number of iterations is too big.
24309 	 */
24310 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
24311 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
24312 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
24313 	/* spill R6, R7, R8 to use these as loop vars */
24314 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
24315 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
24316 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
24317 	/* initialize loop vars */
24318 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
24319 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
24320 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
24321 	/* loop header,
24322 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
24323 	 */
24324 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
24325 	/* callback call,
24326 	 * correct callback offset would be set after patching
24327 	 */
24328 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
24329 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
24330 	insn_buf[cnt++] = BPF_CALL_REL(0);
24331 	/* increment loop counter */
24332 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
24333 	/* jump to loop header if callback returned 0 */
24334 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
24335 	/* return value of bpf_loop,
24336 	 * set R0 to the number of iterations
24337 	 */
24338 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
24339 	/* restore original values of R6, R7, R8 */
24340 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
24341 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
24342 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
24343 
24344 	*total_cnt = cnt;
24345 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
24346 	if (!new_prog)
24347 		return new_prog;
24348 
24349 	/* callback start is known only after patching */
24350 	callback_start = env->subprog_info[callback_subprogno].start;
24351 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
24352 	call_insn_offset = position + 12;
24353 	callback_offset = callback_start - call_insn_offset - 1;
24354 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
24355 
24356 	return new_prog;
24357 }
24358 
24359 static bool is_bpf_loop_call(struct bpf_insn *insn)
24360 {
24361 	return insn->code == (BPF_JMP | BPF_CALL) &&
24362 		insn->src_reg == 0 &&
24363 		insn->imm == BPF_FUNC_loop;
24364 }
24365 
24366 /* For all sub-programs in the program (including main) check
24367  * insn_aux_data to see if there are bpf_loop calls that require
24368  * inlining. If such calls are found the calls are replaced with a
24369  * sequence of instructions produced by `inline_bpf_loop` function and
24370  * subprog stack_depth is increased by the size of 3 registers.
24371  * This stack space is used to spill values of the R6, R7, R8.  These
24372  * registers are used to store the loop bound, counter and context
24373  * variables.
24374  */
24375 static int optimize_bpf_loop(struct bpf_verifier_env *env)
24376 {
24377 	struct bpf_subprog_info *subprogs = env->subprog_info;
24378 	int i, cur_subprog = 0, cnt, delta = 0;
24379 	struct bpf_insn *insn = env->prog->insnsi;
24380 	int insn_cnt = env->prog->len;
24381 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
24382 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
24383 	u16 stack_depth_extra = 0;
24384 
24385 	for (i = 0; i < insn_cnt; i++, insn++) {
24386 		struct bpf_loop_inline_state *inline_state =
24387 			&env->insn_aux_data[i + delta].loop_inline_state;
24388 
24389 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
24390 			struct bpf_prog *new_prog;
24391 
24392 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
24393 			new_prog = inline_bpf_loop(env,
24394 						   i + delta,
24395 						   -(stack_depth + stack_depth_extra),
24396 						   inline_state->callback_subprogno,
24397 						   &cnt);
24398 			if (!new_prog)
24399 				return -ENOMEM;
24400 
24401 			delta     += cnt - 1;
24402 			env->prog  = new_prog;
24403 			insn       = new_prog->insnsi + i + delta;
24404 		}
24405 
24406 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
24407 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
24408 			cur_subprog++;
24409 			stack_depth = subprogs[cur_subprog].stack_depth;
24410 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
24411 			stack_depth_extra = 0;
24412 		}
24413 	}
24414 
24415 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
24416 
24417 	return 0;
24418 }
24419 
24420 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
24421  * adjust subprograms stack depth when possible.
24422  */
24423 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
24424 {
24425 	struct bpf_subprog_info *subprog = env->subprog_info;
24426 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
24427 	struct bpf_insn *insn = env->prog->insnsi;
24428 	int insn_cnt = env->prog->len;
24429 	u32 spills_num;
24430 	bool modified = false;
24431 	int i, j;
24432 
24433 	for (i = 0; i < insn_cnt; i++, insn++) {
24434 		if (aux[i].fastcall_spills_num > 0) {
24435 			spills_num = aux[i].fastcall_spills_num;
24436 			/* NOPs would be removed by opt_remove_nops() */
24437 			for (j = 1; j <= spills_num; ++j) {
24438 				*(insn - j) = NOP;
24439 				*(insn + j) = NOP;
24440 			}
24441 			modified = true;
24442 		}
24443 		if ((subprog + 1)->start == i + 1) {
24444 			if (modified && !subprog->keep_fastcall_stack)
24445 				subprog->stack_depth = -subprog->fastcall_stack_off;
24446 			subprog++;
24447 			modified = false;
24448 		}
24449 	}
24450 
24451 	return 0;
24452 }
24453 
24454 static void free_states(struct bpf_verifier_env *env)
24455 {
24456 	struct bpf_verifier_state_list *sl;
24457 	struct list_head *head, *pos, *tmp;
24458 	struct bpf_scc_info *info;
24459 	int i, j;
24460 
24461 	free_verifier_state(env->cur_state, true);
24462 	env->cur_state = NULL;
24463 	while (!pop_stack(env, NULL, NULL, false));
24464 
24465 	list_for_each_safe(pos, tmp, &env->free_list) {
24466 		sl = container_of(pos, struct bpf_verifier_state_list, node);
24467 		free_verifier_state(&sl->state, false);
24468 		kfree(sl);
24469 	}
24470 	INIT_LIST_HEAD(&env->free_list);
24471 
24472 	for (i = 0; i < env->scc_cnt; ++i) {
24473 		info = env->scc_info[i];
24474 		if (!info)
24475 			continue;
24476 		for (j = 0; j < info->num_visits; j++)
24477 			free_backedges(&info->visits[j]);
24478 		kvfree(info);
24479 		env->scc_info[i] = NULL;
24480 	}
24481 
24482 	if (!env->explored_states)
24483 		return;
24484 
24485 	for (i = 0; i < state_htab_size(env); i++) {
24486 		head = &env->explored_states[i];
24487 
24488 		list_for_each_safe(pos, tmp, head) {
24489 			sl = container_of(pos, struct bpf_verifier_state_list, node);
24490 			free_verifier_state(&sl->state, false);
24491 			kfree(sl);
24492 		}
24493 		INIT_LIST_HEAD(&env->explored_states[i]);
24494 	}
24495 }
24496 
24497 static int do_check_common(struct bpf_verifier_env *env, int subprog)
24498 {
24499 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
24500 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
24501 	struct bpf_prog_aux *aux = env->prog->aux;
24502 	struct bpf_verifier_state *state;
24503 	struct bpf_reg_state *regs;
24504 	int ret, i;
24505 
24506 	env->prev_linfo = NULL;
24507 	env->pass_cnt++;
24508 
24509 	state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT);
24510 	if (!state)
24511 		return -ENOMEM;
24512 	state->curframe = 0;
24513 	state->speculative = false;
24514 	state->branches = 1;
24515 	state->in_sleepable = env->prog->sleepable;
24516 	state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT);
24517 	if (!state->frame[0]) {
24518 		kfree(state);
24519 		return -ENOMEM;
24520 	}
24521 	env->cur_state = state;
24522 	init_func_state(env, state->frame[0],
24523 			BPF_MAIN_FUNC /* callsite */,
24524 			0 /* frameno */,
24525 			subprog);
24526 	state->first_insn_idx = env->subprog_info[subprog].start;
24527 	state->last_insn_idx = -1;
24528 
24529 	regs = state->frame[state->curframe]->regs;
24530 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
24531 		const char *sub_name = subprog_name(env, subprog);
24532 		struct bpf_subprog_arg_info *arg;
24533 		struct bpf_reg_state *reg;
24534 
24535 		if (env->log.level & BPF_LOG_LEVEL)
24536 			verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
24537 		ret = btf_prepare_func_args(env, subprog);
24538 		if (ret)
24539 			goto out;
24540 
24541 		if (subprog_is_exc_cb(env, subprog)) {
24542 			state->frame[0]->in_exception_callback_fn = true;
24543 			/* We have already ensured that the callback returns an integer, just
24544 			 * like all global subprogs. We need to determine it only has a single
24545 			 * scalar argument.
24546 			 */
24547 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
24548 				verbose(env, "exception cb only supports single integer argument\n");
24549 				ret = -EINVAL;
24550 				goto out;
24551 			}
24552 		}
24553 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
24554 			arg = &sub->args[i - BPF_REG_1];
24555 			reg = &regs[i];
24556 
24557 			if (arg->arg_type == ARG_PTR_TO_CTX) {
24558 				reg->type = PTR_TO_CTX;
24559 				mark_reg_known_zero(env, regs, i);
24560 			} else if (arg->arg_type == ARG_ANYTHING) {
24561 				reg->type = SCALAR_VALUE;
24562 				mark_reg_unknown(env, regs, i);
24563 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
24564 				/* assume unspecial LOCAL dynptr type */
24565 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
24566 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
24567 				reg->type = PTR_TO_MEM;
24568 				reg->type |= arg->arg_type &
24569 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
24570 				mark_reg_known_zero(env, regs, i);
24571 				reg->mem_size = arg->mem_size;
24572 				if (arg->arg_type & PTR_MAYBE_NULL)
24573 					reg->id = ++env->id_gen;
24574 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
24575 				reg->type = PTR_TO_BTF_ID;
24576 				if (arg->arg_type & PTR_MAYBE_NULL)
24577 					reg->type |= PTR_MAYBE_NULL;
24578 				if (arg->arg_type & PTR_UNTRUSTED)
24579 					reg->type |= PTR_UNTRUSTED;
24580 				if (arg->arg_type & PTR_TRUSTED)
24581 					reg->type |= PTR_TRUSTED;
24582 				mark_reg_known_zero(env, regs, i);
24583 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
24584 				reg->btf_id = arg->btf_id;
24585 				reg->id = ++env->id_gen;
24586 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
24587 				/* caller can pass either PTR_TO_ARENA or SCALAR */
24588 				mark_reg_unknown(env, regs, i);
24589 			} else {
24590 				verifier_bug(env, "unhandled arg#%d type %d",
24591 					     i - BPF_REG_1, arg->arg_type);
24592 				ret = -EFAULT;
24593 				goto out;
24594 			}
24595 		}
24596 	} else {
24597 		/* if main BPF program has associated BTF info, validate that
24598 		 * it's matching expected signature, and otherwise mark BTF
24599 		 * info for main program as unreliable
24600 		 */
24601 		if (env->prog->aux->func_info_aux) {
24602 			ret = btf_prepare_func_args(env, 0);
24603 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
24604 				env->prog->aux->func_info_aux[0].unreliable = true;
24605 		}
24606 
24607 		/* 1st arg to a function */
24608 		regs[BPF_REG_1].type = PTR_TO_CTX;
24609 		mark_reg_known_zero(env, regs, BPF_REG_1);
24610 	}
24611 
24612 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
24613 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
24614 		for (i = 0; i < aux->ctx_arg_info_size; i++)
24615 			aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ?
24616 							  acquire_reference(env, 0) : 0;
24617 	}
24618 
24619 	ret = do_check(env);
24620 out:
24621 	if (!ret && pop_log)
24622 		bpf_vlog_reset(&env->log, 0);
24623 	free_states(env);
24624 	return ret;
24625 }
24626 
24627 /* Lazily verify all global functions based on their BTF, if they are called
24628  * from main BPF program or any of subprograms transitively.
24629  * BPF global subprogs called from dead code are not validated.
24630  * All callable global functions must pass verification.
24631  * Otherwise the whole program is rejected.
24632  * Consider:
24633  * int bar(int);
24634  * int foo(int f)
24635  * {
24636  *    return bar(f);
24637  * }
24638  * int bar(int b)
24639  * {
24640  *    ...
24641  * }
24642  * foo() will be verified first for R1=any_scalar_value. During verification it
24643  * will be assumed that bar() already verified successfully and call to bar()
24644  * from foo() will be checked for type match only. Later bar() will be verified
24645  * independently to check that it's safe for R1=any_scalar_value.
24646  */
24647 static int do_check_subprogs(struct bpf_verifier_env *env)
24648 {
24649 	struct bpf_prog_aux *aux = env->prog->aux;
24650 	struct bpf_func_info_aux *sub_aux;
24651 	int i, ret, new_cnt;
24652 
24653 	if (!aux->func_info)
24654 		return 0;
24655 
24656 	/* exception callback is presumed to be always called */
24657 	if (env->exception_callback_subprog)
24658 		subprog_aux(env, env->exception_callback_subprog)->called = true;
24659 
24660 again:
24661 	new_cnt = 0;
24662 	for (i = 1; i < env->subprog_cnt; i++) {
24663 		if (!subprog_is_global(env, i))
24664 			continue;
24665 
24666 		sub_aux = subprog_aux(env, i);
24667 		if (!sub_aux->called || sub_aux->verified)
24668 			continue;
24669 
24670 		env->insn_idx = env->subprog_info[i].start;
24671 		WARN_ON_ONCE(env->insn_idx == 0);
24672 		ret = do_check_common(env, i);
24673 		if (ret) {
24674 			return ret;
24675 		} else if (env->log.level & BPF_LOG_LEVEL) {
24676 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
24677 				i, subprog_name(env, i));
24678 		}
24679 
24680 		/* We verified new global subprog, it might have called some
24681 		 * more global subprogs that we haven't verified yet, so we
24682 		 * need to do another pass over subprogs to verify those.
24683 		 */
24684 		sub_aux->verified = true;
24685 		new_cnt++;
24686 	}
24687 
24688 	/* We can't loop forever as we verify at least one global subprog on
24689 	 * each pass.
24690 	 */
24691 	if (new_cnt)
24692 		goto again;
24693 
24694 	return 0;
24695 }
24696 
24697 static int do_check_main(struct bpf_verifier_env *env)
24698 {
24699 	int ret;
24700 
24701 	env->insn_idx = 0;
24702 	ret = do_check_common(env, 0);
24703 	if (!ret)
24704 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
24705 	return ret;
24706 }
24707 
24708 
24709 static void print_verification_stats(struct bpf_verifier_env *env)
24710 {
24711 	int i;
24712 
24713 	if (env->log.level & BPF_LOG_STATS) {
24714 		verbose(env, "verification time %lld usec\n",
24715 			div_u64(env->verification_time, 1000));
24716 		verbose(env, "stack depth ");
24717 		for (i = 0; i < env->subprog_cnt; i++) {
24718 			u32 depth = env->subprog_info[i].stack_depth;
24719 
24720 			verbose(env, "%d", depth);
24721 			if (i + 1 < env->subprog_cnt)
24722 				verbose(env, "+");
24723 		}
24724 		verbose(env, "\n");
24725 	}
24726 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
24727 		"total_states %d peak_states %d mark_read %d\n",
24728 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
24729 		env->max_states_per_insn, env->total_states,
24730 		env->peak_states, env->longest_mark_read_walk);
24731 }
24732 
24733 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
24734 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
24735 {
24736 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
24737 	prog->aux->ctx_arg_info_size = cnt;
24738 
24739 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
24740 }
24741 
24742 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
24743 {
24744 	const struct btf_type *t, *func_proto;
24745 	const struct bpf_struct_ops_desc *st_ops_desc;
24746 	const struct bpf_struct_ops *st_ops;
24747 	const struct btf_member *member;
24748 	struct bpf_prog *prog = env->prog;
24749 	bool has_refcounted_arg = false;
24750 	u32 btf_id, member_idx, member_off;
24751 	struct btf *btf;
24752 	const char *mname;
24753 	int i, err;
24754 
24755 	if (!prog->gpl_compatible) {
24756 		verbose(env, "struct ops programs must have a GPL compatible license\n");
24757 		return -EINVAL;
24758 	}
24759 
24760 	if (!prog->aux->attach_btf_id)
24761 		return -ENOTSUPP;
24762 
24763 	btf = prog->aux->attach_btf;
24764 	if (btf_is_module(btf)) {
24765 		/* Make sure st_ops is valid through the lifetime of env */
24766 		env->attach_btf_mod = btf_try_get_module(btf);
24767 		if (!env->attach_btf_mod) {
24768 			verbose(env, "struct_ops module %s is not found\n",
24769 				btf_get_name(btf));
24770 			return -ENOTSUPP;
24771 		}
24772 	}
24773 
24774 	btf_id = prog->aux->attach_btf_id;
24775 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
24776 	if (!st_ops_desc) {
24777 		verbose(env, "attach_btf_id %u is not a supported struct\n",
24778 			btf_id);
24779 		return -ENOTSUPP;
24780 	}
24781 	st_ops = st_ops_desc->st_ops;
24782 
24783 	t = st_ops_desc->type;
24784 	member_idx = prog->expected_attach_type;
24785 	if (member_idx >= btf_type_vlen(t)) {
24786 		verbose(env, "attach to invalid member idx %u of struct %s\n",
24787 			member_idx, st_ops->name);
24788 		return -EINVAL;
24789 	}
24790 
24791 	member = &btf_type_member(t)[member_idx];
24792 	mname = btf_name_by_offset(btf, member->name_off);
24793 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
24794 					       NULL);
24795 	if (!func_proto) {
24796 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
24797 			mname, member_idx, st_ops->name);
24798 		return -EINVAL;
24799 	}
24800 
24801 	member_off = __btf_member_bit_offset(t, member) / 8;
24802 	err = bpf_struct_ops_supported(st_ops, member_off);
24803 	if (err) {
24804 		verbose(env, "attach to unsupported member %s of struct %s\n",
24805 			mname, st_ops->name);
24806 		return err;
24807 	}
24808 
24809 	if (st_ops->check_member) {
24810 		err = st_ops->check_member(t, member, prog);
24811 
24812 		if (err) {
24813 			verbose(env, "attach to unsupported member %s of struct %s\n",
24814 				mname, st_ops->name);
24815 			return err;
24816 		}
24817 	}
24818 
24819 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
24820 		verbose(env, "Private stack not supported by jit\n");
24821 		return -EACCES;
24822 	}
24823 
24824 	for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) {
24825 		if (st_ops_desc->arg_info[member_idx].info->refcounted) {
24826 			has_refcounted_arg = true;
24827 			break;
24828 		}
24829 	}
24830 
24831 	/* Tail call is not allowed for programs with refcounted arguments since we
24832 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
24833 	 */
24834 	for (i = 0; i < env->subprog_cnt; i++) {
24835 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
24836 			verbose(env, "program with __ref argument cannot tail call\n");
24837 			return -EINVAL;
24838 		}
24839 	}
24840 
24841 	prog->aux->st_ops = st_ops;
24842 	prog->aux->attach_st_ops_member_off = member_off;
24843 
24844 	prog->aux->attach_func_proto = func_proto;
24845 	prog->aux->attach_func_name = mname;
24846 	env->ops = st_ops->verifier_ops;
24847 
24848 	return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info,
24849 					  st_ops_desc->arg_info[member_idx].cnt);
24850 }
24851 #define SECURITY_PREFIX "security_"
24852 
24853 static int check_attach_modify_return(unsigned long addr, const char *func_name)
24854 {
24855 	if (within_error_injection_list(addr) ||
24856 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
24857 		return 0;
24858 
24859 	return -EINVAL;
24860 }
24861 
24862 /* list of non-sleepable functions that are otherwise on
24863  * ALLOW_ERROR_INJECTION list
24864  */
24865 BTF_SET_START(btf_non_sleepable_error_inject)
24866 /* Three functions below can be called from sleepable and non-sleepable context.
24867  * Assume non-sleepable from bpf safety point of view.
24868  */
24869 BTF_ID(func, __filemap_add_folio)
24870 #ifdef CONFIG_FAIL_PAGE_ALLOC
24871 BTF_ID(func, should_fail_alloc_page)
24872 #endif
24873 #ifdef CONFIG_FAILSLAB
24874 BTF_ID(func, should_failslab)
24875 #endif
24876 BTF_SET_END(btf_non_sleepable_error_inject)
24877 
24878 static int check_non_sleepable_error_inject(u32 btf_id)
24879 {
24880 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
24881 }
24882 
24883 int bpf_check_attach_target(struct bpf_verifier_log *log,
24884 			    const struct bpf_prog *prog,
24885 			    const struct bpf_prog *tgt_prog,
24886 			    u32 btf_id,
24887 			    struct bpf_attach_target_info *tgt_info)
24888 {
24889 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
24890 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
24891 	char trace_symbol[KSYM_SYMBOL_LEN];
24892 	const char prefix[] = "btf_trace_";
24893 	struct bpf_raw_event_map *btp;
24894 	int ret = 0, subprog = -1, i;
24895 	const struct btf_type *t;
24896 	bool conservative = true;
24897 	const char *tname, *fname;
24898 	struct btf *btf;
24899 	long addr = 0;
24900 	struct module *mod = NULL;
24901 
24902 	if (!btf_id) {
24903 		bpf_log(log, "Tracing programs must provide btf_id\n");
24904 		return -EINVAL;
24905 	}
24906 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
24907 	if (!btf) {
24908 		bpf_log(log,
24909 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
24910 		return -EINVAL;
24911 	}
24912 	t = btf_type_by_id(btf, btf_id);
24913 	if (!t) {
24914 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
24915 		return -EINVAL;
24916 	}
24917 	tname = btf_name_by_offset(btf, t->name_off);
24918 	if (!tname) {
24919 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
24920 		return -EINVAL;
24921 	}
24922 	if (tgt_prog) {
24923 		struct bpf_prog_aux *aux = tgt_prog->aux;
24924 		bool tgt_changes_pkt_data;
24925 		bool tgt_might_sleep;
24926 
24927 		if (bpf_prog_is_dev_bound(prog->aux) &&
24928 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
24929 			bpf_log(log, "Target program bound device mismatch");
24930 			return -EINVAL;
24931 		}
24932 
24933 		for (i = 0; i < aux->func_info_cnt; i++)
24934 			if (aux->func_info[i].type_id == btf_id) {
24935 				subprog = i;
24936 				break;
24937 			}
24938 		if (subprog == -1) {
24939 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
24940 			return -EINVAL;
24941 		}
24942 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
24943 			bpf_log(log,
24944 				"%s programs cannot attach to exception callback\n",
24945 				prog_extension ? "Extension" : "FENTRY/FEXIT");
24946 			return -EINVAL;
24947 		}
24948 		conservative = aux->func_info_aux[subprog].unreliable;
24949 		if (prog_extension) {
24950 			if (conservative) {
24951 				bpf_log(log,
24952 					"Cannot replace static functions\n");
24953 				return -EINVAL;
24954 			}
24955 			if (!prog->jit_requested) {
24956 				bpf_log(log,
24957 					"Extension programs should be JITed\n");
24958 				return -EINVAL;
24959 			}
24960 			tgt_changes_pkt_data = aux->func
24961 					       ? aux->func[subprog]->aux->changes_pkt_data
24962 					       : aux->changes_pkt_data;
24963 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
24964 				bpf_log(log,
24965 					"Extension program changes packet data, while original does not\n");
24966 				return -EINVAL;
24967 			}
24968 
24969 			tgt_might_sleep = aux->func
24970 					  ? aux->func[subprog]->aux->might_sleep
24971 					  : aux->might_sleep;
24972 			if (prog->aux->might_sleep && !tgt_might_sleep) {
24973 				bpf_log(log,
24974 					"Extension program may sleep, while original does not\n");
24975 				return -EINVAL;
24976 			}
24977 		}
24978 		if (!tgt_prog->jited) {
24979 			bpf_log(log, "Can attach to only JITed progs\n");
24980 			return -EINVAL;
24981 		}
24982 		if (prog_tracing) {
24983 			if (aux->attach_tracing_prog) {
24984 				/*
24985 				 * Target program is an fentry/fexit which is already attached
24986 				 * to another tracing program. More levels of nesting
24987 				 * attachment are not allowed.
24988 				 */
24989 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
24990 				return -EINVAL;
24991 			}
24992 		} else if (tgt_prog->type == prog->type) {
24993 			/*
24994 			 * To avoid potential call chain cycles, prevent attaching of a
24995 			 * program extension to another extension. It's ok to attach
24996 			 * fentry/fexit to extension program.
24997 			 */
24998 			bpf_log(log, "Cannot recursively attach\n");
24999 			return -EINVAL;
25000 		}
25001 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
25002 		    prog_extension &&
25003 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
25004 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT ||
25005 		     tgt_prog->expected_attach_type == BPF_TRACE_FSESSION)) {
25006 			/* Program extensions can extend all program types
25007 			 * except fentry/fexit. The reason is the following.
25008 			 * The fentry/fexit programs are used for performance
25009 			 * analysis, stats and can be attached to any program
25010 			 * type. When extension program is replacing XDP function
25011 			 * it is necessary to allow performance analysis of all
25012 			 * functions. Both original XDP program and its program
25013 			 * extension. Hence attaching fentry/fexit to
25014 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
25015 			 * fentry/fexit was allowed it would be possible to create
25016 			 * long call chain fentry->extension->fentry->extension
25017 			 * beyond reasonable stack size. Hence extending fentry
25018 			 * is not allowed.
25019 			 */
25020 			bpf_log(log, "Cannot extend fentry/fexit/fsession\n");
25021 			return -EINVAL;
25022 		}
25023 	} else {
25024 		if (prog_extension) {
25025 			bpf_log(log, "Cannot replace kernel functions\n");
25026 			return -EINVAL;
25027 		}
25028 	}
25029 
25030 	switch (prog->expected_attach_type) {
25031 	case BPF_TRACE_RAW_TP:
25032 		if (tgt_prog) {
25033 			bpf_log(log,
25034 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
25035 			return -EINVAL;
25036 		}
25037 		if (!btf_type_is_typedef(t)) {
25038 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
25039 				btf_id);
25040 			return -EINVAL;
25041 		}
25042 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
25043 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
25044 				btf_id, tname);
25045 			return -EINVAL;
25046 		}
25047 		tname += sizeof(prefix) - 1;
25048 
25049 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
25050 		 * names. Thus using bpf_raw_event_map to get argument names.
25051 		 */
25052 		btp = bpf_get_raw_tracepoint(tname);
25053 		if (!btp)
25054 			return -EINVAL;
25055 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
25056 					trace_symbol);
25057 		bpf_put_raw_tracepoint(btp);
25058 
25059 		if (fname)
25060 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
25061 
25062 		if (!fname || ret < 0) {
25063 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
25064 				prefix, tname);
25065 			t = btf_type_by_id(btf, t->type);
25066 			if (!btf_type_is_ptr(t))
25067 				/* should never happen in valid vmlinux build */
25068 				return -EINVAL;
25069 		} else {
25070 			t = btf_type_by_id(btf, ret);
25071 			if (!btf_type_is_func(t))
25072 				/* should never happen in valid vmlinux build */
25073 				return -EINVAL;
25074 		}
25075 
25076 		t = btf_type_by_id(btf, t->type);
25077 		if (!btf_type_is_func_proto(t))
25078 			/* should never happen in valid vmlinux build */
25079 			return -EINVAL;
25080 
25081 		break;
25082 	case BPF_TRACE_ITER:
25083 		if (!btf_type_is_func(t)) {
25084 			bpf_log(log, "attach_btf_id %u is not a function\n",
25085 				btf_id);
25086 			return -EINVAL;
25087 		}
25088 		t = btf_type_by_id(btf, t->type);
25089 		if (!btf_type_is_func_proto(t))
25090 			return -EINVAL;
25091 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
25092 		if (ret)
25093 			return ret;
25094 		break;
25095 	default:
25096 		if (!prog_extension)
25097 			return -EINVAL;
25098 		fallthrough;
25099 	case BPF_MODIFY_RETURN:
25100 	case BPF_LSM_MAC:
25101 	case BPF_LSM_CGROUP:
25102 	case BPF_TRACE_FENTRY:
25103 	case BPF_TRACE_FEXIT:
25104 	case BPF_TRACE_FSESSION:
25105 		if (prog->expected_attach_type == BPF_TRACE_FSESSION &&
25106 		    !bpf_jit_supports_fsession()) {
25107 			bpf_log(log, "JIT does not support fsession\n");
25108 			return -EOPNOTSUPP;
25109 		}
25110 		if (!btf_type_is_func(t)) {
25111 			bpf_log(log, "attach_btf_id %u is not a function\n",
25112 				btf_id);
25113 			return -EINVAL;
25114 		}
25115 		if (prog_extension &&
25116 		    btf_check_type_match(log, prog, btf, t))
25117 			return -EINVAL;
25118 		t = btf_type_by_id(btf, t->type);
25119 		if (!btf_type_is_func_proto(t))
25120 			return -EINVAL;
25121 
25122 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
25123 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
25124 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
25125 			return -EINVAL;
25126 
25127 		if (tgt_prog && conservative)
25128 			t = NULL;
25129 
25130 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
25131 		if (ret < 0)
25132 			return ret;
25133 
25134 		if (tgt_prog) {
25135 			if (subprog == 0)
25136 				addr = (long) tgt_prog->bpf_func;
25137 			else
25138 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
25139 		} else {
25140 			if (btf_is_module(btf)) {
25141 				mod = btf_try_get_module(btf);
25142 				if (mod)
25143 					addr = find_kallsyms_symbol_value(mod, tname);
25144 				else
25145 					addr = 0;
25146 			} else {
25147 				addr = kallsyms_lookup_name(tname);
25148 			}
25149 			if (!addr) {
25150 				module_put(mod);
25151 				bpf_log(log,
25152 					"The address of function %s cannot be found\n",
25153 					tname);
25154 				return -ENOENT;
25155 			}
25156 		}
25157 
25158 		if (prog->sleepable) {
25159 			ret = -EINVAL;
25160 			switch (prog->type) {
25161 			case BPF_PROG_TYPE_TRACING:
25162 
25163 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
25164 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
25165 				 */
25166 				if (!check_non_sleepable_error_inject(btf_id) &&
25167 				    within_error_injection_list(addr))
25168 					ret = 0;
25169 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
25170 				 * in the fmodret id set with the KF_SLEEPABLE flag.
25171 				 */
25172 				else {
25173 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
25174 										prog);
25175 
25176 					if (flags && (*flags & KF_SLEEPABLE))
25177 						ret = 0;
25178 				}
25179 				break;
25180 			case BPF_PROG_TYPE_LSM:
25181 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
25182 				 * Only some of them are sleepable.
25183 				 */
25184 				if (bpf_lsm_is_sleepable_hook(btf_id))
25185 					ret = 0;
25186 				break;
25187 			default:
25188 				break;
25189 			}
25190 			if (ret) {
25191 				module_put(mod);
25192 				bpf_log(log, "%s is not sleepable\n", tname);
25193 				return ret;
25194 			}
25195 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
25196 			if (tgt_prog) {
25197 				module_put(mod);
25198 				bpf_log(log, "can't modify return codes of BPF programs\n");
25199 				return -EINVAL;
25200 			}
25201 			ret = -EINVAL;
25202 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
25203 			    !check_attach_modify_return(addr, tname))
25204 				ret = 0;
25205 			if (ret) {
25206 				module_put(mod);
25207 				bpf_log(log, "%s() is not modifiable\n", tname);
25208 				return ret;
25209 			}
25210 		}
25211 
25212 		break;
25213 	}
25214 	tgt_info->tgt_addr = addr;
25215 	tgt_info->tgt_name = tname;
25216 	tgt_info->tgt_type = t;
25217 	tgt_info->tgt_mod = mod;
25218 	return 0;
25219 }
25220 
25221 BTF_SET_START(btf_id_deny)
25222 BTF_ID_UNUSED
25223 #ifdef CONFIG_SMP
25224 BTF_ID(func, ___migrate_enable)
25225 BTF_ID(func, migrate_disable)
25226 BTF_ID(func, migrate_enable)
25227 #endif
25228 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
25229 BTF_ID(func, rcu_read_unlock_strict)
25230 #endif
25231 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
25232 BTF_ID(func, preempt_count_add)
25233 BTF_ID(func, preempt_count_sub)
25234 #endif
25235 #ifdef CONFIG_PREEMPT_RCU
25236 BTF_ID(func, __rcu_read_lock)
25237 BTF_ID(func, __rcu_read_unlock)
25238 #endif
25239 BTF_SET_END(btf_id_deny)
25240 
25241 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
25242  * Currently, we must manually list all __noreturn functions here. Once a more
25243  * robust solution is implemented, this workaround can be removed.
25244  */
25245 BTF_SET_START(noreturn_deny)
25246 #ifdef CONFIG_IA32_EMULATION
25247 BTF_ID(func, __ia32_sys_exit)
25248 BTF_ID(func, __ia32_sys_exit_group)
25249 #endif
25250 #ifdef CONFIG_KUNIT
25251 BTF_ID(func, __kunit_abort)
25252 BTF_ID(func, kunit_try_catch_throw)
25253 #endif
25254 #ifdef CONFIG_MODULES
25255 BTF_ID(func, __module_put_and_kthread_exit)
25256 #endif
25257 #ifdef CONFIG_X86_64
25258 BTF_ID(func, __x64_sys_exit)
25259 BTF_ID(func, __x64_sys_exit_group)
25260 #endif
25261 BTF_ID(func, do_exit)
25262 BTF_ID(func, do_group_exit)
25263 BTF_ID(func, kthread_complete_and_exit)
25264 BTF_ID(func, kthread_exit)
25265 BTF_ID(func, make_task_dead)
25266 BTF_SET_END(noreturn_deny)
25267 
25268 static bool can_be_sleepable(struct bpf_prog *prog)
25269 {
25270 	if (prog->type == BPF_PROG_TYPE_TRACING) {
25271 		switch (prog->expected_attach_type) {
25272 		case BPF_TRACE_FENTRY:
25273 		case BPF_TRACE_FEXIT:
25274 		case BPF_MODIFY_RETURN:
25275 		case BPF_TRACE_ITER:
25276 		case BPF_TRACE_FSESSION:
25277 			return true;
25278 		default:
25279 			return false;
25280 		}
25281 	}
25282 	return prog->type == BPF_PROG_TYPE_LSM ||
25283 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
25284 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
25285 }
25286 
25287 static int check_attach_btf_id(struct bpf_verifier_env *env)
25288 {
25289 	struct bpf_prog *prog = env->prog;
25290 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
25291 	struct bpf_attach_target_info tgt_info = {};
25292 	u32 btf_id = prog->aux->attach_btf_id;
25293 	struct bpf_trampoline *tr;
25294 	int ret;
25295 	u64 key;
25296 
25297 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
25298 		if (prog->sleepable)
25299 			/* attach_btf_id checked to be zero already */
25300 			return 0;
25301 		verbose(env, "Syscall programs can only be sleepable\n");
25302 		return -EINVAL;
25303 	}
25304 
25305 	if (prog->sleepable && !can_be_sleepable(prog)) {
25306 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
25307 		return -EINVAL;
25308 	}
25309 
25310 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
25311 		return check_struct_ops_btf_id(env);
25312 
25313 	if (prog->type != BPF_PROG_TYPE_TRACING &&
25314 	    prog->type != BPF_PROG_TYPE_LSM &&
25315 	    prog->type != BPF_PROG_TYPE_EXT)
25316 		return 0;
25317 
25318 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
25319 	if (ret)
25320 		return ret;
25321 
25322 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
25323 		/* to make freplace equivalent to their targets, they need to
25324 		 * inherit env->ops and expected_attach_type for the rest of the
25325 		 * verification
25326 		 */
25327 		env->ops = bpf_verifier_ops[tgt_prog->type];
25328 		prog->expected_attach_type = tgt_prog->expected_attach_type;
25329 	}
25330 
25331 	/* store info about the attachment target that will be used later */
25332 	prog->aux->attach_func_proto = tgt_info.tgt_type;
25333 	prog->aux->attach_func_name = tgt_info.tgt_name;
25334 	prog->aux->mod = tgt_info.tgt_mod;
25335 
25336 	if (tgt_prog) {
25337 		prog->aux->saved_dst_prog_type = tgt_prog->type;
25338 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
25339 	}
25340 
25341 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
25342 		prog->aux->attach_btf_trace = true;
25343 		return 0;
25344 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
25345 		return bpf_iter_prog_supported(prog);
25346 	}
25347 
25348 	if (prog->type == BPF_PROG_TYPE_LSM) {
25349 		ret = bpf_lsm_verify_prog(&env->log, prog);
25350 		if (ret < 0)
25351 			return ret;
25352 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
25353 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
25354 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
25355 			tgt_info.tgt_name);
25356 		return -EINVAL;
25357 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
25358 		   prog->expected_attach_type == BPF_TRACE_FSESSION ||
25359 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
25360 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
25361 		verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n",
25362 			tgt_info.tgt_name);
25363 		return -EINVAL;
25364 	}
25365 
25366 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
25367 	tr = bpf_trampoline_get(key, &tgt_info);
25368 	if (!tr)
25369 		return -ENOMEM;
25370 
25371 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
25372 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
25373 
25374 	prog->aux->dst_trampoline = tr;
25375 	return 0;
25376 }
25377 
25378 struct btf *bpf_get_btf_vmlinux(void)
25379 {
25380 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
25381 		mutex_lock(&bpf_verifier_lock);
25382 		if (!btf_vmlinux)
25383 			btf_vmlinux = btf_parse_vmlinux();
25384 		mutex_unlock(&bpf_verifier_lock);
25385 	}
25386 	return btf_vmlinux;
25387 }
25388 
25389 /*
25390  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
25391  * this case expect that every file descriptor in the array is either a map or
25392  * a BTF. Everything else is considered to be trash.
25393  */
25394 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
25395 {
25396 	struct bpf_map *map;
25397 	struct btf *btf;
25398 	CLASS(fd, f)(fd);
25399 	int err;
25400 
25401 	map = __bpf_map_get(f);
25402 	if (!IS_ERR(map)) {
25403 		err = __add_used_map(env, map);
25404 		if (err < 0)
25405 			return err;
25406 		return 0;
25407 	}
25408 
25409 	btf = __btf_get_by_fd(f);
25410 	if (!IS_ERR(btf)) {
25411 		btf_get(btf);
25412 		return __add_used_btf(env, btf);
25413 	}
25414 
25415 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
25416 	return PTR_ERR(map);
25417 }
25418 
25419 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
25420 {
25421 	size_t size = sizeof(int);
25422 	int ret;
25423 	int fd;
25424 	u32 i;
25425 
25426 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
25427 
25428 	/*
25429 	 * The only difference between old (no fd_array_cnt is given) and new
25430 	 * APIs is that in the latter case the fd_array is expected to be
25431 	 * continuous and is scanned for map fds right away
25432 	 */
25433 	if (!attr->fd_array_cnt)
25434 		return 0;
25435 
25436 	/* Check for integer overflow */
25437 	if (attr->fd_array_cnt >= (U32_MAX / size)) {
25438 		verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
25439 		return -EINVAL;
25440 	}
25441 
25442 	for (i = 0; i < attr->fd_array_cnt; i++) {
25443 		if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
25444 			return -EFAULT;
25445 
25446 		ret = add_fd_from_fd_array(env, fd);
25447 		if (ret)
25448 			return ret;
25449 	}
25450 
25451 	return 0;
25452 }
25453 
25454 /* Each field is a register bitmask */
25455 struct insn_live_regs {
25456 	u16 use;	/* registers read by instruction */
25457 	u16 def;	/* registers written by instruction */
25458 	u16 in;		/* registers that may be alive before instruction */
25459 	u16 out;	/* registers that may be alive after instruction */
25460 };
25461 
25462 /* Bitmask with 1s for all caller saved registers */
25463 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
25464 
25465 /* Compute info->{use,def} fields for the instruction */
25466 static void compute_insn_live_regs(struct bpf_verifier_env *env,
25467 				   struct bpf_insn *insn,
25468 				   struct insn_live_regs *info)
25469 {
25470 	struct call_summary cs;
25471 	u8 class = BPF_CLASS(insn->code);
25472 	u8 code = BPF_OP(insn->code);
25473 	u8 mode = BPF_MODE(insn->code);
25474 	u16 src = BIT(insn->src_reg);
25475 	u16 dst = BIT(insn->dst_reg);
25476 	u16 r0  = BIT(0);
25477 	u16 def = 0;
25478 	u16 use = 0xffff;
25479 
25480 	switch (class) {
25481 	case BPF_LD:
25482 		switch (mode) {
25483 		case BPF_IMM:
25484 			if (BPF_SIZE(insn->code) == BPF_DW) {
25485 				def = dst;
25486 				use = 0;
25487 			}
25488 			break;
25489 		case BPF_LD | BPF_ABS:
25490 		case BPF_LD | BPF_IND:
25491 			/* stick with defaults */
25492 			break;
25493 		}
25494 		break;
25495 	case BPF_LDX:
25496 		switch (mode) {
25497 		case BPF_MEM:
25498 		case BPF_MEMSX:
25499 			def = dst;
25500 			use = src;
25501 			break;
25502 		}
25503 		break;
25504 	case BPF_ST:
25505 		switch (mode) {
25506 		case BPF_MEM:
25507 			def = 0;
25508 			use = dst;
25509 			break;
25510 		}
25511 		break;
25512 	case BPF_STX:
25513 		switch (mode) {
25514 		case BPF_MEM:
25515 			def = 0;
25516 			use = dst | src;
25517 			break;
25518 		case BPF_ATOMIC:
25519 			switch (insn->imm) {
25520 			case BPF_CMPXCHG:
25521 				use = r0 | dst | src;
25522 				def = r0;
25523 				break;
25524 			case BPF_LOAD_ACQ:
25525 				def = dst;
25526 				use = src;
25527 				break;
25528 			case BPF_STORE_REL:
25529 				def = 0;
25530 				use = dst | src;
25531 				break;
25532 			default:
25533 				use = dst | src;
25534 				if (insn->imm & BPF_FETCH)
25535 					def = src;
25536 				else
25537 					def = 0;
25538 			}
25539 			break;
25540 		}
25541 		break;
25542 	case BPF_ALU:
25543 	case BPF_ALU64:
25544 		switch (code) {
25545 		case BPF_END:
25546 			use = dst;
25547 			def = dst;
25548 			break;
25549 		case BPF_MOV:
25550 			def = dst;
25551 			if (BPF_SRC(insn->code) == BPF_K)
25552 				use = 0;
25553 			else
25554 				use = src;
25555 			break;
25556 		default:
25557 			def = dst;
25558 			if (BPF_SRC(insn->code) == BPF_K)
25559 				use = dst;
25560 			else
25561 				use = dst | src;
25562 		}
25563 		break;
25564 	case BPF_JMP:
25565 	case BPF_JMP32:
25566 		switch (code) {
25567 		case BPF_JA:
25568 			def = 0;
25569 			if (BPF_SRC(insn->code) == BPF_X)
25570 				use = dst;
25571 			else
25572 				use = 0;
25573 			break;
25574 		case BPF_JCOND:
25575 			def = 0;
25576 			use = 0;
25577 			break;
25578 		case BPF_EXIT:
25579 			def = 0;
25580 			use = r0;
25581 			break;
25582 		case BPF_CALL:
25583 			def = ALL_CALLER_SAVED_REGS;
25584 			use = def & ~BIT(BPF_REG_0);
25585 			if (get_call_summary(env, insn, &cs))
25586 				use = GENMASK(cs.num_params, 1);
25587 			break;
25588 		default:
25589 			def = 0;
25590 			if (BPF_SRC(insn->code) == BPF_K)
25591 				use = dst;
25592 			else
25593 				use = dst | src;
25594 		}
25595 		break;
25596 	}
25597 
25598 	info->def = def;
25599 	info->use = use;
25600 }
25601 
25602 /* Compute may-live registers after each instruction in the program.
25603  * The register is live after the instruction I if it is read by some
25604  * instruction S following I during program execution and is not
25605  * overwritten between I and S.
25606  *
25607  * Store result in env->insn_aux_data[i].live_regs.
25608  */
25609 static int compute_live_registers(struct bpf_verifier_env *env)
25610 {
25611 	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
25612 	struct bpf_insn *insns = env->prog->insnsi;
25613 	struct insn_live_regs *state;
25614 	int insn_cnt = env->prog->len;
25615 	int err = 0, i, j;
25616 	bool changed;
25617 
25618 	/* Use the following algorithm:
25619 	 * - define the following:
25620 	 *   - I.use : a set of all registers read by instruction I;
25621 	 *   - I.def : a set of all registers written by instruction I;
25622 	 *   - I.in  : a set of all registers that may be alive before I execution;
25623 	 *   - I.out : a set of all registers that may be alive after I execution;
25624 	 *   - insn_successors(I): a set of instructions S that might immediately
25625 	 *                         follow I for some program execution;
25626 	 * - associate separate empty sets 'I.in' and 'I.out' with each instruction;
25627 	 * - visit each instruction in a postorder and update
25628 	 *   state[i].in, state[i].out as follows:
25629 	 *
25630 	 *       state[i].out = U [state[s].in for S in insn_successors(i)]
25631 	 *       state[i].in  = (state[i].out / state[i].def) U state[i].use
25632 	 *
25633 	 *   (where U stands for set union, / stands for set difference)
25634 	 * - repeat the computation while {in,out} fields changes for
25635 	 *   any instruction.
25636 	 */
25637 	state = kvzalloc_objs(*state, insn_cnt, GFP_KERNEL_ACCOUNT);
25638 	if (!state) {
25639 		err = -ENOMEM;
25640 		goto out;
25641 	}
25642 
25643 	for (i = 0; i < insn_cnt; ++i)
25644 		compute_insn_live_regs(env, &insns[i], &state[i]);
25645 
25646 	changed = true;
25647 	while (changed) {
25648 		changed = false;
25649 		for (i = 0; i < env->cfg.cur_postorder; ++i) {
25650 			int insn_idx = env->cfg.insn_postorder[i];
25651 			struct insn_live_regs *live = &state[insn_idx];
25652 			struct bpf_iarray *succ;
25653 			u16 new_out = 0;
25654 			u16 new_in = 0;
25655 
25656 			succ = bpf_insn_successors(env, insn_idx);
25657 			for (int s = 0; s < succ->cnt; ++s)
25658 				new_out |= state[succ->items[s]].in;
25659 			new_in = (new_out & ~live->def) | live->use;
25660 			if (new_out != live->out || new_in != live->in) {
25661 				live->in = new_in;
25662 				live->out = new_out;
25663 				changed = true;
25664 			}
25665 		}
25666 	}
25667 
25668 	for (i = 0; i < insn_cnt; ++i)
25669 		insn_aux[i].live_regs_before = state[i].in;
25670 
25671 	if (env->log.level & BPF_LOG_LEVEL2) {
25672 		verbose(env, "Live regs before insn:\n");
25673 		for (i = 0; i < insn_cnt; ++i) {
25674 			if (env->insn_aux_data[i].scc)
25675 				verbose(env, "%3d ", env->insn_aux_data[i].scc);
25676 			else
25677 				verbose(env, "    ");
25678 			verbose(env, "%3d: ", i);
25679 			for (j = BPF_REG_0; j < BPF_REG_10; ++j)
25680 				if (insn_aux[i].live_regs_before & BIT(j))
25681 					verbose(env, "%d", j);
25682 				else
25683 					verbose(env, ".");
25684 			verbose(env, " ");
25685 			verbose_insn(env, &insns[i]);
25686 			if (bpf_is_ldimm64(&insns[i]))
25687 				i++;
25688 		}
25689 	}
25690 
25691 out:
25692 	kvfree(state);
25693 	return err;
25694 }
25695 
25696 /*
25697  * Compute strongly connected components (SCCs) on the CFG.
25698  * Assign an SCC number to each instruction, recorded in env->insn_aux[*].scc.
25699  * If instruction is a sole member of its SCC and there are no self edges,
25700  * assign it SCC number of zero.
25701  * Uses a non-recursive adaptation of Tarjan's algorithm for SCC computation.
25702  */
25703 static int compute_scc(struct bpf_verifier_env *env)
25704 {
25705 	const u32 NOT_ON_STACK = U32_MAX;
25706 
25707 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
25708 	const u32 insn_cnt = env->prog->len;
25709 	int stack_sz, dfs_sz, err = 0;
25710 	u32 *stack, *pre, *low, *dfs;
25711 	u32 i, j, t, w;
25712 	u32 next_preorder_num;
25713 	u32 next_scc_id;
25714 	bool assign_scc;
25715 	struct bpf_iarray *succ;
25716 
25717 	next_preorder_num = 1;
25718 	next_scc_id = 1;
25719 	/*
25720 	 * - 'stack' accumulates vertices in DFS order, see invariant comment below;
25721 	 * - 'pre[t] == p' => preorder number of vertex 't' is 'p';
25722 	 * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n';
25723 	 * - 'dfs' DFS traversal stack, used to emulate explicit recursion.
25724 	 */
25725 	stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
25726 	pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
25727 	low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
25728 	dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT);
25729 	if (!stack || !pre || !low || !dfs) {
25730 		err = -ENOMEM;
25731 		goto exit;
25732 	}
25733 	/*
25734 	 * References:
25735 	 * [1] R. Tarjan "Depth-First Search and Linear Graph Algorithms"
25736 	 * [2] D. J. Pearce "A Space-Efficient Algorithm for Finding Strongly Connected Components"
25737 	 *
25738 	 * The algorithm maintains the following invariant:
25739 	 * - suppose there is a path 'u' ~> 'v', such that 'pre[v] < pre[u]';
25740 	 * - then, vertex 'u' remains on stack while vertex 'v' is on stack.
25741 	 *
25742 	 * Consequently:
25743 	 * - If 'low[v] < pre[v]', there is a path from 'v' to some vertex 'u',
25744 	 *   such that 'pre[u] == low[v]'; vertex 'u' is currently on the stack,
25745 	 *   and thus there is an SCC (loop) containing both 'u' and 'v'.
25746 	 * - If 'low[v] == pre[v]', loops containing 'v' have been explored,
25747 	 *   and 'v' can be considered the root of some SCC.
25748 	 *
25749 	 * Here is a pseudo-code for an explicitly recursive version of the algorithm:
25750 	 *
25751 	 *    NOT_ON_STACK = insn_cnt + 1
25752 	 *    pre = [0] * insn_cnt
25753 	 *    low = [0] * insn_cnt
25754 	 *    scc = [0] * insn_cnt
25755 	 *    stack = []
25756 	 *
25757 	 *    next_preorder_num = 1
25758 	 *    next_scc_id = 1
25759 	 *
25760 	 *    def recur(w):
25761 	 *        nonlocal next_preorder_num
25762 	 *        nonlocal next_scc_id
25763 	 *
25764 	 *        pre[w] = next_preorder_num
25765 	 *        low[w] = next_preorder_num
25766 	 *        next_preorder_num += 1
25767 	 *        stack.append(w)
25768 	 *        for s in successors(w):
25769 	 *            # Note: for classic algorithm the block below should look as:
25770 	 *            #
25771 	 *            # if pre[s] == 0:
25772 	 *            #     recur(s)
25773 	 *            #	    low[w] = min(low[w], low[s])
25774 	 *            # elif low[s] != NOT_ON_STACK:
25775 	 *            #     low[w] = min(low[w], pre[s])
25776 	 *            #
25777 	 *            # But replacing both 'min' instructions with 'low[w] = min(low[w], low[s])'
25778 	 *            # does not break the invariant and makes itartive version of the algorithm
25779 	 *            # simpler. See 'Algorithm #3' from [2].
25780 	 *
25781 	 *            # 's' not yet visited
25782 	 *            if pre[s] == 0:
25783 	 *                recur(s)
25784 	 *            # if 's' is on stack, pick lowest reachable preorder number from it;
25785 	 *            # if 's' is not on stack 'low[s] == NOT_ON_STACK > low[w]',
25786 	 *            # so 'min' would be a noop.
25787 	 *            low[w] = min(low[w], low[s])
25788 	 *
25789 	 *        if low[w] == pre[w]:
25790 	 *            # 'w' is the root of an SCC, pop all vertices
25791 	 *            # below 'w' on stack and assign same SCC to them.
25792 	 *            while True:
25793 	 *                t = stack.pop()
25794 	 *                low[t] = NOT_ON_STACK
25795 	 *                scc[t] = next_scc_id
25796 	 *                if t == w:
25797 	 *                    break
25798 	 *            next_scc_id += 1
25799 	 *
25800 	 *    for i in range(0, insn_cnt):
25801 	 *        if pre[i] == 0:
25802 	 *            recur(i)
25803 	 *
25804 	 * Below implementation replaces explicit recursion with array 'dfs'.
25805 	 */
25806 	for (i = 0; i < insn_cnt; i++) {
25807 		if (pre[i])
25808 			continue;
25809 		stack_sz = 0;
25810 		dfs_sz = 1;
25811 		dfs[0] = i;
25812 dfs_continue:
25813 		while (dfs_sz) {
25814 			w = dfs[dfs_sz - 1];
25815 			if (pre[w] == 0) {
25816 				low[w] = next_preorder_num;
25817 				pre[w] = next_preorder_num;
25818 				next_preorder_num++;
25819 				stack[stack_sz++] = w;
25820 			}
25821 			/* Visit 'w' successors */
25822 			succ = bpf_insn_successors(env, w);
25823 			for (j = 0; j < succ->cnt; ++j) {
25824 				if (pre[succ->items[j]]) {
25825 					low[w] = min(low[w], low[succ->items[j]]);
25826 				} else {
25827 					dfs[dfs_sz++] = succ->items[j];
25828 					goto dfs_continue;
25829 				}
25830 			}
25831 			/*
25832 			 * Preserve the invariant: if some vertex above in the stack
25833 			 * is reachable from 'w', keep 'w' on the stack.
25834 			 */
25835 			if (low[w] < pre[w]) {
25836 				dfs_sz--;
25837 				goto dfs_continue;
25838 			}
25839 			/*
25840 			 * Assign SCC number only if component has two or more elements,
25841 			 * or if component has a self reference, or if instruction is a
25842 			 * callback calling function (implicit loop).
25843 			 */
25844 			assign_scc = stack[stack_sz - 1] != w;	/* two or more elements? */
25845 			for (j = 0; j < succ->cnt; ++j) {	/* self reference? */
25846 				if (succ->items[j] == w) {
25847 					assign_scc = true;
25848 					break;
25849 				}
25850 			}
25851 			if (bpf_calls_callback(env, w)) /* implicit loop? */
25852 				assign_scc = true;
25853 			/* Pop component elements from stack */
25854 			do {
25855 				t = stack[--stack_sz];
25856 				low[t] = NOT_ON_STACK;
25857 				if (assign_scc)
25858 					aux[t].scc = next_scc_id;
25859 			} while (t != w);
25860 			if (assign_scc)
25861 				next_scc_id++;
25862 			dfs_sz--;
25863 		}
25864 	}
25865 	env->scc_info = kvzalloc_objs(*env->scc_info, next_scc_id,
25866 				      GFP_KERNEL_ACCOUNT);
25867 	if (!env->scc_info) {
25868 		err = -ENOMEM;
25869 		goto exit;
25870 	}
25871 	env->scc_cnt = next_scc_id;
25872 exit:
25873 	kvfree(stack);
25874 	kvfree(pre);
25875 	kvfree(low);
25876 	kvfree(dfs);
25877 	return err;
25878 }
25879 
25880 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
25881 {
25882 	u64 start_time = ktime_get_ns();
25883 	struct bpf_verifier_env *env;
25884 	int i, len, ret = -EINVAL, err;
25885 	u32 log_true_size;
25886 	bool is_priv;
25887 
25888 	BTF_TYPE_EMIT(enum bpf_features);
25889 
25890 	/* no program is valid */
25891 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
25892 		return -EINVAL;
25893 
25894 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
25895 	 * allocate/free it every time bpf_check() is called
25896 	 */
25897 	env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT);
25898 	if (!env)
25899 		return -ENOMEM;
25900 
25901 	env->bt.env = env;
25902 
25903 	len = (*prog)->len;
25904 	env->insn_aux_data =
25905 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
25906 	ret = -ENOMEM;
25907 	if (!env->insn_aux_data)
25908 		goto err_free_env;
25909 	for (i = 0; i < len; i++)
25910 		env->insn_aux_data[i].orig_idx = i;
25911 	env->succ = iarray_realloc(NULL, 2);
25912 	if (!env->succ)
25913 		goto err_free_env;
25914 	env->prog = *prog;
25915 	env->ops = bpf_verifier_ops[env->prog->type];
25916 
25917 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
25918 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
25919 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
25920 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
25921 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
25922 
25923 	bpf_get_btf_vmlinux();
25924 
25925 	/* grab the mutex to protect few globals used by verifier */
25926 	if (!is_priv)
25927 		mutex_lock(&bpf_verifier_lock);
25928 
25929 	/* user could have requested verbose verifier output
25930 	 * and supplied buffer to store the verification trace
25931 	 */
25932 	ret = bpf_vlog_init(&env->log, attr->log_level,
25933 			    (char __user *) (unsigned long) attr->log_buf,
25934 			    attr->log_size);
25935 	if (ret)
25936 		goto err_unlock;
25937 
25938 	ret = process_fd_array(env, attr, uattr);
25939 	if (ret)
25940 		goto skip_full_check;
25941 
25942 	mark_verifier_state_clean(env);
25943 
25944 	if (IS_ERR(btf_vmlinux)) {
25945 		/* Either gcc or pahole or kernel are broken. */
25946 		verbose(env, "in-kernel BTF is malformed\n");
25947 		ret = PTR_ERR(btf_vmlinux);
25948 		goto skip_full_check;
25949 	}
25950 
25951 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
25952 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
25953 		env->strict_alignment = true;
25954 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
25955 		env->strict_alignment = false;
25956 
25957 	if (is_priv)
25958 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
25959 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
25960 
25961 	env->explored_states = kvzalloc_objs(struct list_head,
25962 					     state_htab_size(env),
25963 					     GFP_KERNEL_ACCOUNT);
25964 	ret = -ENOMEM;
25965 	if (!env->explored_states)
25966 		goto skip_full_check;
25967 
25968 	for (i = 0; i < state_htab_size(env); i++)
25969 		INIT_LIST_HEAD(&env->explored_states[i]);
25970 	INIT_LIST_HEAD(&env->free_list);
25971 
25972 	ret = check_btf_info_early(env, attr, uattr);
25973 	if (ret < 0)
25974 		goto skip_full_check;
25975 
25976 	ret = add_subprog_and_kfunc(env);
25977 	if (ret < 0)
25978 		goto skip_full_check;
25979 
25980 	ret = check_subprogs(env);
25981 	if (ret < 0)
25982 		goto skip_full_check;
25983 
25984 	ret = check_btf_info(env, attr, uattr);
25985 	if (ret < 0)
25986 		goto skip_full_check;
25987 
25988 	ret = resolve_pseudo_ldimm64(env);
25989 	if (ret < 0)
25990 		goto skip_full_check;
25991 
25992 	if (bpf_prog_is_offloaded(env->prog->aux)) {
25993 		ret = bpf_prog_offload_verifier_prep(env->prog);
25994 		if (ret)
25995 			goto skip_full_check;
25996 	}
25997 
25998 	ret = check_cfg(env);
25999 	if (ret < 0)
26000 		goto skip_full_check;
26001 
26002 	ret = compute_postorder(env);
26003 	if (ret < 0)
26004 		goto skip_full_check;
26005 
26006 	ret = bpf_stack_liveness_init(env);
26007 	if (ret)
26008 		goto skip_full_check;
26009 
26010 	ret = check_attach_btf_id(env);
26011 	if (ret)
26012 		goto skip_full_check;
26013 
26014 	ret = compute_scc(env);
26015 	if (ret < 0)
26016 		goto skip_full_check;
26017 
26018 	ret = compute_live_registers(env);
26019 	if (ret < 0)
26020 		goto skip_full_check;
26021 
26022 	ret = mark_fastcall_patterns(env);
26023 	if (ret < 0)
26024 		goto skip_full_check;
26025 
26026 	ret = do_check_main(env);
26027 	ret = ret ?: do_check_subprogs(env);
26028 
26029 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
26030 		ret = bpf_prog_offload_finalize(env);
26031 
26032 skip_full_check:
26033 	kvfree(env->explored_states);
26034 
26035 	/* might decrease stack depth, keep it before passes that
26036 	 * allocate additional slots.
26037 	 */
26038 	if (ret == 0)
26039 		ret = remove_fastcall_spills_fills(env);
26040 
26041 	if (ret == 0)
26042 		ret = check_max_stack_depth(env);
26043 
26044 	/* instruction rewrites happen after this point */
26045 	if (ret == 0)
26046 		ret = optimize_bpf_loop(env);
26047 
26048 	if (is_priv) {
26049 		if (ret == 0)
26050 			opt_hard_wire_dead_code_branches(env);
26051 		if (ret == 0)
26052 			ret = opt_remove_dead_code(env);
26053 		if (ret == 0)
26054 			ret = opt_remove_nops(env);
26055 	} else {
26056 		if (ret == 0)
26057 			sanitize_dead_code(env);
26058 	}
26059 
26060 	if (ret == 0)
26061 		/* program is valid, convert *(u32*)(ctx + off) accesses */
26062 		ret = convert_ctx_accesses(env);
26063 
26064 	if (ret == 0)
26065 		ret = do_misc_fixups(env);
26066 
26067 	/* do 32-bit optimization after insn patching has done so those patched
26068 	 * insns could be handled correctly.
26069 	 */
26070 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
26071 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
26072 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
26073 								     : false;
26074 	}
26075 
26076 	if (ret == 0)
26077 		ret = fixup_call_args(env);
26078 
26079 	env->verification_time = ktime_get_ns() - start_time;
26080 	print_verification_stats(env);
26081 	env->prog->aux->verified_insns = env->insn_processed;
26082 
26083 	/* preserve original error even if log finalization is successful */
26084 	err = bpf_vlog_finalize(&env->log, &log_true_size);
26085 	if (err)
26086 		ret = err;
26087 
26088 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
26089 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
26090 				  &log_true_size, sizeof(log_true_size))) {
26091 		ret = -EFAULT;
26092 		goto err_release_maps;
26093 	}
26094 
26095 	if (ret)
26096 		goto err_release_maps;
26097 
26098 	if (env->used_map_cnt) {
26099 		/* if program passed verifier, update used_maps in bpf_prog_info */
26100 		env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0],
26101 							 env->used_map_cnt,
26102 							 GFP_KERNEL_ACCOUNT);
26103 
26104 		if (!env->prog->aux->used_maps) {
26105 			ret = -ENOMEM;
26106 			goto err_release_maps;
26107 		}
26108 
26109 		memcpy(env->prog->aux->used_maps, env->used_maps,
26110 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
26111 		env->prog->aux->used_map_cnt = env->used_map_cnt;
26112 	}
26113 	if (env->used_btf_cnt) {
26114 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
26115 		env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0],
26116 							 env->used_btf_cnt,
26117 							 GFP_KERNEL_ACCOUNT);
26118 		if (!env->prog->aux->used_btfs) {
26119 			ret = -ENOMEM;
26120 			goto err_release_maps;
26121 		}
26122 
26123 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
26124 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
26125 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
26126 	}
26127 	if (env->used_map_cnt || env->used_btf_cnt) {
26128 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
26129 		 * bpf_ld_imm64 instructions
26130 		 */
26131 		convert_pseudo_ld_imm64(env);
26132 	}
26133 
26134 	adjust_btf_func(env);
26135 
26136 err_release_maps:
26137 	if (ret)
26138 		release_insn_arrays(env);
26139 	if (!env->prog->aux->used_maps)
26140 		/* if we didn't copy map pointers into bpf_prog_info, release
26141 		 * them now. Otherwise free_used_maps() will release them.
26142 		 */
26143 		release_maps(env);
26144 	if (!env->prog->aux->used_btfs)
26145 		release_btfs(env);
26146 
26147 	/* extension progs temporarily inherit the attach_type of their targets
26148 	   for verification purposes, so set it back to zero before returning
26149 	 */
26150 	if (env->prog->type == BPF_PROG_TYPE_EXT)
26151 		env->prog->expected_attach_type = 0;
26152 
26153 	*prog = env->prog;
26154 
26155 	module_put(env->attach_btf_mod);
26156 err_unlock:
26157 	if (!is_priv)
26158 		mutex_unlock(&bpf_verifier_lock);
26159 	clear_insn_aux_data(env, 0, env->prog->len);
26160 	vfree(env->insn_aux_data);
26161 err_free_env:
26162 	bpf_stack_liveness_free(env);
26163 	kvfree(env->cfg.insn_postorder);
26164 	kvfree(env->scc_info);
26165 	kvfree(env->succ);
26166 	kvfree(env->gotox_tmp_buf);
26167 	kvfree(env);
26168 	return ret;
26169 }
26170