xref: /linux/kernel/bpf/verifier.c (revision a7ddedc84c59a645ef970b992f7cda5bffc70cc0)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <linux/bpf_mem_alloc.h>
30 #include <net/xdp.h>
31 #include <linux/trace_events.h>
32 #include <linux/kallsyms.h>
33 
34 #include "disasm.h"
35 
36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
38 	[_id] = & _name ## _verifier_ops,
39 #define BPF_MAP_TYPE(_id, _ops)
40 #define BPF_LINK_TYPE(_id, _name)
41 #include <linux/bpf_types.h>
42 #undef BPF_PROG_TYPE
43 #undef BPF_MAP_TYPE
44 #undef BPF_LINK_TYPE
45 };
46 
47 enum bpf_features {
48 	BPF_FEAT_RDONLY_CAST_TO_VOID = 0,
49 	BPF_FEAT_STREAMS	     = 1,
50 	__MAX_BPF_FEAT,
51 };
52 
53 struct bpf_mem_alloc bpf_global_percpu_ma;
54 static bool bpf_global_percpu_ma_set;
55 
56 /* bpf_check() is a static code analyzer that walks eBPF program
57  * instruction by instruction and updates register/stack state.
58  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
59  *
60  * The first pass is depth-first-search to check that the program is a DAG.
61  * It rejects the following programs:
62  * - larger than BPF_MAXINSNS insns
63  * - if loop is present (detected via back-edge)
64  * - unreachable insns exist (shouldn't be a forest. program = one function)
65  * - out of bounds or malformed jumps
66  * The second pass is all possible path descent from the 1st insn.
67  * Since it's analyzing all paths through the program, the length of the
68  * analysis is limited to 64k insn, which may be hit even if total number of
69  * insn is less then 4K, but there are too many branches that change stack/regs.
70  * Number of 'branches to be analyzed' is limited to 1k
71  *
72  * On entry to each instruction, each register has a type, and the instruction
73  * changes the types of the registers depending on instruction semantics.
74  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
75  * copied to R1.
76  *
77  * All registers are 64-bit.
78  * R0 - return register
79  * R1-R5 argument passing registers
80  * R6-R9 callee saved registers
81  * R10 - frame pointer read-only
82  *
83  * At the start of BPF program the register R1 contains a pointer to bpf_context
84  * and has type PTR_TO_CTX.
85  *
86  * Verifier tracks arithmetic operations on pointers in case:
87  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
88  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
89  * 1st insn copies R10 (which has FRAME_PTR) type into R1
90  * and 2nd arithmetic instruction is pattern matched to recognize
91  * that it wants to construct a pointer to some element within stack.
92  * So after 2nd insn, the register R1 has type PTR_TO_STACK
93  * (and -20 constant is saved for further stack bounds checking).
94  * Meaning that this reg is a pointer to stack plus known immediate constant.
95  *
96  * Most of the time the registers have SCALAR_VALUE type, which
97  * means the register has some value, but it's not a valid pointer.
98  * (like pointer plus pointer becomes SCALAR_VALUE type)
99  *
100  * When verifier sees load or store instructions the type of base register
101  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
102  * four pointer types recognized by check_mem_access() function.
103  *
104  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
105  * and the range of [ptr, ptr + map's value_size) is accessible.
106  *
107  * registers used to pass values to function calls are checked against
108  * function argument constraints.
109  *
110  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
111  * It means that the register type passed to this function must be
112  * PTR_TO_STACK and it will be used inside the function as
113  * 'pointer to map element key'
114  *
115  * For example the argument constraints for bpf_map_lookup_elem():
116  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
117  *   .arg1_type = ARG_CONST_MAP_PTR,
118  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
119  *
120  * ret_type says that this function returns 'pointer to map elem value or null'
121  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
122  * 2nd argument should be a pointer to stack, which will be used inside
123  * the helper function as a pointer to map element key.
124  *
125  * On the kernel side the helper function looks like:
126  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
127  * {
128  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
129  *    void *key = (void *) (unsigned long) r2;
130  *    void *value;
131  *
132  *    here kernel can access 'key' and 'map' pointers safely, knowing that
133  *    [key, key + map->key_size) bytes are valid and were initialized on
134  *    the stack of eBPF program.
135  * }
136  *
137  * Corresponding eBPF program may look like:
138  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
139  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
140  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
141  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
142  * here verifier looks at prototype of map_lookup_elem() and sees:
143  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
144  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
145  *
146  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
147  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
148  * and were initialized prior to this call.
149  * If it's ok, then verifier allows this BPF_CALL insn and looks at
150  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
151  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
152  * returns either pointer to map value or NULL.
153  *
154  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
155  * insn, the register holding that pointer in the true branch changes state to
156  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
157  * branch. See check_cond_jmp_op().
158  *
159  * After the call R0 is set to return type of the function and registers R1-R5
160  * are set to NOT_INIT to indicate that they are no longer readable.
161  *
162  * The following reference types represent a potential reference to a kernel
163  * resource which, after first being allocated, must be checked and freed by
164  * the BPF program:
165  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
166  *
167  * When the verifier sees a helper call return a reference type, it allocates a
168  * pointer id for the reference and stores it in the current function state.
169  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
170  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
171  * passes through a NULL-check conditional. For the branch wherein the state is
172  * changed to CONST_IMM, the verifier releases the reference.
173  *
174  * For each helper function that allocates a reference, such as
175  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
176  * bpf_sk_release(). When a reference type passes into the release function,
177  * the verifier also releases the reference. If any unchecked or unreleased
178  * reference remains at the end of the program, the verifier rejects it.
179  */
180 
181 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
182 struct bpf_verifier_stack_elem {
183 	/* verifier state is 'st'
184 	 * before processing instruction 'insn_idx'
185 	 * and after processing instruction 'prev_insn_idx'
186 	 */
187 	struct bpf_verifier_state st;
188 	int insn_idx;
189 	int prev_insn_idx;
190 	struct bpf_verifier_stack_elem *next;
191 	/* length of verifier log at the time this state was pushed on stack */
192 	u32 log_pos;
193 };
194 
195 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
196 #define BPF_COMPLEXITY_LIMIT_STATES	64
197 
198 #define BPF_MAP_KEY_POISON	(1ULL << 63)
199 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
200 
201 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
202 
203 #define BPF_PRIV_STACK_MIN_SIZE		64
204 
205 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx);
206 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id);
207 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
208 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
209 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
210 static int ref_set_non_owning(struct bpf_verifier_env *env,
211 			      struct bpf_reg_state *reg);
212 static void specialize_kfunc(struct bpf_verifier_env *env,
213 			     u32 func_id, u16 offset, unsigned long *addr);
214 static bool is_trusted_reg(const struct bpf_reg_state *reg);
215 
216 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
217 {
218 	return aux->map_ptr_state.poison;
219 }
220 
221 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
222 {
223 	return aux->map_ptr_state.unpriv;
224 }
225 
226 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
227 			      struct bpf_map *map,
228 			      bool unpriv, bool poison)
229 {
230 	unpriv |= bpf_map_ptr_unpriv(aux);
231 	aux->map_ptr_state.unpriv = unpriv;
232 	aux->map_ptr_state.poison = poison;
233 	aux->map_ptr_state.map_ptr = map;
234 }
235 
236 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
237 {
238 	return aux->map_key_state & BPF_MAP_KEY_POISON;
239 }
240 
241 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
242 {
243 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
244 }
245 
246 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
247 {
248 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
249 }
250 
251 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
252 {
253 	bool poisoned = bpf_map_key_poisoned(aux);
254 
255 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
256 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
257 }
258 
259 static bool bpf_helper_call(const struct bpf_insn *insn)
260 {
261 	return insn->code == (BPF_JMP | BPF_CALL) &&
262 	       insn->src_reg == 0;
263 }
264 
265 static bool bpf_pseudo_call(const struct bpf_insn *insn)
266 {
267 	return insn->code == (BPF_JMP | BPF_CALL) &&
268 	       insn->src_reg == BPF_PSEUDO_CALL;
269 }
270 
271 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
272 {
273 	return insn->code == (BPF_JMP | BPF_CALL) &&
274 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
275 }
276 
277 struct bpf_call_arg_meta {
278 	struct bpf_map *map_ptr;
279 	bool raw_mode;
280 	bool pkt_access;
281 	u8 release_regno;
282 	int regno;
283 	int access_size;
284 	int mem_size;
285 	u64 msize_max_value;
286 	int ref_obj_id;
287 	int dynptr_id;
288 	int map_uid;
289 	int func_id;
290 	struct btf *btf;
291 	u32 btf_id;
292 	struct btf *ret_btf;
293 	u32 ret_btf_id;
294 	u32 subprogno;
295 	struct btf_field *kptr_field;
296 	s64 const_map_key;
297 };
298 
299 struct bpf_kfunc_call_arg_meta {
300 	/* In parameters */
301 	struct btf *btf;
302 	u32 func_id;
303 	u32 kfunc_flags;
304 	const struct btf_type *func_proto;
305 	const char *func_name;
306 	/* Out parameters */
307 	u32 ref_obj_id;
308 	u8 release_regno;
309 	bool r0_rdonly;
310 	u32 ret_btf_id;
311 	u64 r0_size;
312 	u32 subprogno;
313 	struct {
314 		u64 value;
315 		bool found;
316 	} arg_constant;
317 
318 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
319 	 * generally to pass info about user-defined local kptr types to later
320 	 * verification logic
321 	 *   bpf_obj_drop/bpf_percpu_obj_drop
322 	 *     Record the local kptr type to be drop'd
323 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
324 	 *     Record the local kptr type to be refcount_incr'd and use
325 	 *     arg_owning_ref to determine whether refcount_acquire should be
326 	 *     fallible
327 	 */
328 	struct btf *arg_btf;
329 	u32 arg_btf_id;
330 	bool arg_owning_ref;
331 	bool arg_prog;
332 
333 	struct {
334 		struct btf_field *field;
335 	} arg_list_head;
336 	struct {
337 		struct btf_field *field;
338 	} arg_rbtree_root;
339 	struct {
340 		enum bpf_dynptr_type type;
341 		u32 id;
342 		u32 ref_obj_id;
343 	} initialized_dynptr;
344 	struct {
345 		u8 spi;
346 		u8 frameno;
347 	} iter;
348 	struct {
349 		struct bpf_map *ptr;
350 		int uid;
351 	} map;
352 	u64 mem_size;
353 };
354 
355 struct btf *btf_vmlinux;
356 
357 static const char *btf_type_name(const struct btf *btf, u32 id)
358 {
359 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
360 }
361 
362 static DEFINE_MUTEX(bpf_verifier_lock);
363 static DEFINE_MUTEX(bpf_percpu_ma_lock);
364 
365 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
366 {
367 	struct bpf_verifier_env *env = private_data;
368 	va_list args;
369 
370 	if (!bpf_verifier_log_needed(&env->log))
371 		return;
372 
373 	va_start(args, fmt);
374 	bpf_verifier_vlog(&env->log, fmt, args);
375 	va_end(args);
376 }
377 
378 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
379 				   struct bpf_reg_state *reg,
380 				   struct bpf_retval_range range, const char *ctx,
381 				   const char *reg_name)
382 {
383 	bool unknown = true;
384 
385 	verbose(env, "%s the register %s has", ctx, reg_name);
386 	if (reg->smin_value > S64_MIN) {
387 		verbose(env, " smin=%lld", reg->smin_value);
388 		unknown = false;
389 	}
390 	if (reg->smax_value < S64_MAX) {
391 		verbose(env, " smax=%lld", reg->smax_value);
392 		unknown = false;
393 	}
394 	if (unknown)
395 		verbose(env, " unknown scalar value");
396 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
397 }
398 
399 static bool reg_not_null(const struct bpf_reg_state *reg)
400 {
401 	enum bpf_reg_type type;
402 
403 	type = reg->type;
404 	if (type_may_be_null(type))
405 		return false;
406 
407 	type = base_type(type);
408 	return type == PTR_TO_SOCKET ||
409 		type == PTR_TO_TCP_SOCK ||
410 		type == PTR_TO_MAP_VALUE ||
411 		type == PTR_TO_MAP_KEY ||
412 		type == PTR_TO_SOCK_COMMON ||
413 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
414 		(type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) ||
415 		type == CONST_PTR_TO_MAP;
416 }
417 
418 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
419 {
420 	struct btf_record *rec = NULL;
421 	struct btf_struct_meta *meta;
422 
423 	if (reg->type == PTR_TO_MAP_VALUE) {
424 		rec = reg->map_ptr->record;
425 	} else if (type_is_ptr_alloc_obj(reg->type)) {
426 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
427 		if (meta)
428 			rec = meta->record;
429 	}
430 	return rec;
431 }
432 
433 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
434 {
435 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
436 
437 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
438 }
439 
440 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
441 {
442 	struct bpf_func_info *info;
443 
444 	if (!env->prog->aux->func_info)
445 		return "";
446 
447 	info = &env->prog->aux->func_info[subprog];
448 	return btf_type_name(env->prog->aux->btf, info->type_id);
449 }
450 
451 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
452 {
453 	struct bpf_subprog_info *info = subprog_info(env, subprog);
454 
455 	info->is_cb = true;
456 	info->is_async_cb = true;
457 	info->is_exception_cb = true;
458 }
459 
460 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
461 {
462 	return subprog_info(env, subprog)->is_exception_cb;
463 }
464 
465 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
466 {
467 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
468 }
469 
470 static bool type_is_rdonly_mem(u32 type)
471 {
472 	return type & MEM_RDONLY;
473 }
474 
475 static bool is_acquire_function(enum bpf_func_id func_id,
476 				const struct bpf_map *map)
477 {
478 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
479 
480 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
481 	    func_id == BPF_FUNC_sk_lookup_udp ||
482 	    func_id == BPF_FUNC_skc_lookup_tcp ||
483 	    func_id == BPF_FUNC_ringbuf_reserve ||
484 	    func_id == BPF_FUNC_kptr_xchg)
485 		return true;
486 
487 	if (func_id == BPF_FUNC_map_lookup_elem &&
488 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
489 	     map_type == BPF_MAP_TYPE_SOCKHASH))
490 		return true;
491 
492 	return false;
493 }
494 
495 static bool is_ptr_cast_function(enum bpf_func_id func_id)
496 {
497 	return func_id == BPF_FUNC_tcp_sock ||
498 		func_id == BPF_FUNC_sk_fullsock ||
499 		func_id == BPF_FUNC_skc_to_tcp_sock ||
500 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
501 		func_id == BPF_FUNC_skc_to_udp6_sock ||
502 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
503 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
504 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
505 }
506 
507 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
508 {
509 	return func_id == BPF_FUNC_dynptr_data;
510 }
511 
512 static bool is_sync_callback_calling_kfunc(u32 btf_id);
513 static bool is_async_callback_calling_kfunc(u32 btf_id);
514 static bool is_callback_calling_kfunc(u32 btf_id);
515 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
516 
517 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
518 
519 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
520 {
521 	return func_id == BPF_FUNC_for_each_map_elem ||
522 	       func_id == BPF_FUNC_find_vma ||
523 	       func_id == BPF_FUNC_loop ||
524 	       func_id == BPF_FUNC_user_ringbuf_drain;
525 }
526 
527 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
528 {
529 	return func_id == BPF_FUNC_timer_set_callback;
530 }
531 
532 static bool is_callback_calling_function(enum bpf_func_id func_id)
533 {
534 	return is_sync_callback_calling_function(func_id) ||
535 	       is_async_callback_calling_function(func_id);
536 }
537 
538 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
539 {
540 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
541 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
542 }
543 
544 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
545 {
546 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
547 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
548 }
549 
550 static bool is_may_goto_insn(struct bpf_insn *insn)
551 {
552 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
553 }
554 
555 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
556 {
557 	return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
558 }
559 
560 static bool is_storage_get_function(enum bpf_func_id func_id)
561 {
562 	return func_id == BPF_FUNC_sk_storage_get ||
563 	       func_id == BPF_FUNC_inode_storage_get ||
564 	       func_id == BPF_FUNC_task_storage_get ||
565 	       func_id == BPF_FUNC_cgrp_storage_get;
566 }
567 
568 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
569 					const struct bpf_map *map)
570 {
571 	int ref_obj_uses = 0;
572 
573 	if (is_ptr_cast_function(func_id))
574 		ref_obj_uses++;
575 	if (is_acquire_function(func_id, map))
576 		ref_obj_uses++;
577 	if (is_dynptr_ref_function(func_id))
578 		ref_obj_uses++;
579 
580 	return ref_obj_uses > 1;
581 }
582 
583 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
584 {
585 	return BPF_CLASS(insn->code) == BPF_STX &&
586 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
587 	       insn->imm == BPF_CMPXCHG;
588 }
589 
590 static bool is_atomic_load_insn(const struct bpf_insn *insn)
591 {
592 	return BPF_CLASS(insn->code) == BPF_STX &&
593 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
594 	       insn->imm == BPF_LOAD_ACQ;
595 }
596 
597 static int __get_spi(s32 off)
598 {
599 	return (-off - 1) / BPF_REG_SIZE;
600 }
601 
602 static struct bpf_func_state *func(struct bpf_verifier_env *env,
603 				   const struct bpf_reg_state *reg)
604 {
605 	struct bpf_verifier_state *cur = env->cur_state;
606 
607 	return cur->frame[reg->frameno];
608 }
609 
610 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
611 {
612        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
613 
614        /* We need to check that slots between [spi - nr_slots + 1, spi] are
615 	* within [0, allocated_stack).
616 	*
617 	* Please note that the spi grows downwards. For example, a dynptr
618 	* takes the size of two stack slots; the first slot will be at
619 	* spi and the second slot will be at spi - 1.
620 	*/
621        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
622 }
623 
624 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
625 			          const char *obj_kind, int nr_slots)
626 {
627 	int off, spi;
628 
629 	if (!tnum_is_const(reg->var_off)) {
630 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
631 		return -EINVAL;
632 	}
633 
634 	off = reg->off + reg->var_off.value;
635 	if (off % BPF_REG_SIZE) {
636 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
637 		return -EINVAL;
638 	}
639 
640 	spi = __get_spi(off);
641 	if (spi + 1 < nr_slots) {
642 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
643 		return -EINVAL;
644 	}
645 
646 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
647 		return -ERANGE;
648 	return spi;
649 }
650 
651 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
652 {
653 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
654 }
655 
656 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
657 {
658 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
659 }
660 
661 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
662 {
663 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
664 }
665 
666 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
667 {
668 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
669 	case DYNPTR_TYPE_LOCAL:
670 		return BPF_DYNPTR_TYPE_LOCAL;
671 	case DYNPTR_TYPE_RINGBUF:
672 		return BPF_DYNPTR_TYPE_RINGBUF;
673 	case DYNPTR_TYPE_SKB:
674 		return BPF_DYNPTR_TYPE_SKB;
675 	case DYNPTR_TYPE_XDP:
676 		return BPF_DYNPTR_TYPE_XDP;
677 	case DYNPTR_TYPE_SKB_META:
678 		return BPF_DYNPTR_TYPE_SKB_META;
679 	default:
680 		return BPF_DYNPTR_TYPE_INVALID;
681 	}
682 }
683 
684 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
685 {
686 	switch (type) {
687 	case BPF_DYNPTR_TYPE_LOCAL:
688 		return DYNPTR_TYPE_LOCAL;
689 	case BPF_DYNPTR_TYPE_RINGBUF:
690 		return DYNPTR_TYPE_RINGBUF;
691 	case BPF_DYNPTR_TYPE_SKB:
692 		return DYNPTR_TYPE_SKB;
693 	case BPF_DYNPTR_TYPE_XDP:
694 		return DYNPTR_TYPE_XDP;
695 	case BPF_DYNPTR_TYPE_SKB_META:
696 		return DYNPTR_TYPE_SKB_META;
697 	default:
698 		return 0;
699 	}
700 }
701 
702 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
703 {
704 	return type == BPF_DYNPTR_TYPE_RINGBUF;
705 }
706 
707 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
708 			      enum bpf_dynptr_type type,
709 			      bool first_slot, int dynptr_id);
710 
711 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
712 				struct bpf_reg_state *reg);
713 
714 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
715 				   struct bpf_reg_state *sreg1,
716 				   struct bpf_reg_state *sreg2,
717 				   enum bpf_dynptr_type type)
718 {
719 	int id = ++env->id_gen;
720 
721 	__mark_dynptr_reg(sreg1, type, true, id);
722 	__mark_dynptr_reg(sreg2, type, false, id);
723 }
724 
725 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
726 			       struct bpf_reg_state *reg,
727 			       enum bpf_dynptr_type type)
728 {
729 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
730 }
731 
732 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
733 				        struct bpf_func_state *state, int spi);
734 
735 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
736 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
737 {
738 	struct bpf_func_state *state = func(env, reg);
739 	enum bpf_dynptr_type type;
740 	int spi, i, err;
741 
742 	spi = dynptr_get_spi(env, reg);
743 	if (spi < 0)
744 		return spi;
745 
746 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
747 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
748 	 * to ensure that for the following example:
749 	 *	[d1][d1][d2][d2]
750 	 * spi    3   2   1   0
751 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
752 	 * case they do belong to same dynptr, second call won't see slot_type
753 	 * as STACK_DYNPTR and will simply skip destruction.
754 	 */
755 	err = destroy_if_dynptr_stack_slot(env, state, spi);
756 	if (err)
757 		return err;
758 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
759 	if (err)
760 		return err;
761 
762 	for (i = 0; i < BPF_REG_SIZE; i++) {
763 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
764 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
765 	}
766 
767 	type = arg_to_dynptr_type(arg_type);
768 	if (type == BPF_DYNPTR_TYPE_INVALID)
769 		return -EINVAL;
770 
771 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
772 			       &state->stack[spi - 1].spilled_ptr, type);
773 
774 	if (dynptr_type_refcounted(type)) {
775 		/* The id is used to track proper releasing */
776 		int id;
777 
778 		if (clone_ref_obj_id)
779 			id = clone_ref_obj_id;
780 		else
781 			id = acquire_reference(env, insn_idx);
782 
783 		if (id < 0)
784 			return id;
785 
786 		state->stack[spi].spilled_ptr.ref_obj_id = id;
787 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
788 	}
789 
790 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
791 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
792 
793 	return 0;
794 }
795 
796 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
797 {
798 	int i;
799 
800 	for (i = 0; i < BPF_REG_SIZE; i++) {
801 		state->stack[spi].slot_type[i] = STACK_INVALID;
802 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
803 	}
804 
805 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
806 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
807 
808 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
809 	 *
810 	 * While we don't allow reading STACK_INVALID, it is still possible to
811 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
812 	 * helpers or insns can do partial read of that part without failing,
813 	 * but check_stack_range_initialized, check_stack_read_var_off, and
814 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
815 	 * the slot conservatively. Hence we need to prevent those liveness
816 	 * marking walks.
817 	 *
818 	 * This was not a problem before because STACK_INVALID is only set by
819 	 * default (where the default reg state has its reg->parent as NULL), or
820 	 * in clean_live_states after REG_LIVE_DONE (at which point
821 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
822 	 * verifier state exploration (like we did above). Hence, for our case
823 	 * parentage chain will still be live (i.e. reg->parent may be
824 	 * non-NULL), while earlier reg->parent was NULL, so we need
825 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
826 	 * done later on reads or by mark_dynptr_read as well to unnecessary
827 	 * mark registers in verifier state.
828 	 */
829 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
830 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
831 }
832 
833 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
834 {
835 	struct bpf_func_state *state = func(env, reg);
836 	int spi, ref_obj_id, i;
837 
838 	spi = dynptr_get_spi(env, reg);
839 	if (spi < 0)
840 		return spi;
841 
842 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
843 		invalidate_dynptr(env, state, spi);
844 		return 0;
845 	}
846 
847 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
848 
849 	/* If the dynptr has a ref_obj_id, then we need to invalidate
850 	 * two things:
851 	 *
852 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
853 	 * 2) Any slices derived from this dynptr.
854 	 */
855 
856 	/* Invalidate any slices associated with this dynptr */
857 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
858 
859 	/* Invalidate any dynptr clones */
860 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
861 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
862 			continue;
863 
864 		/* it should always be the case that if the ref obj id
865 		 * matches then the stack slot also belongs to a
866 		 * dynptr
867 		 */
868 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
869 			verifier_bug(env, "misconfigured ref_obj_id");
870 			return -EFAULT;
871 		}
872 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
873 			invalidate_dynptr(env, state, i);
874 	}
875 
876 	return 0;
877 }
878 
879 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
880 			       struct bpf_reg_state *reg);
881 
882 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
883 {
884 	if (!env->allow_ptr_leaks)
885 		__mark_reg_not_init(env, reg);
886 	else
887 		__mark_reg_unknown(env, reg);
888 }
889 
890 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
891 				        struct bpf_func_state *state, int spi)
892 {
893 	struct bpf_func_state *fstate;
894 	struct bpf_reg_state *dreg;
895 	int i, dynptr_id;
896 
897 	/* We always ensure that STACK_DYNPTR is never set partially,
898 	 * hence just checking for slot_type[0] is enough. This is
899 	 * different for STACK_SPILL, where it may be only set for
900 	 * 1 byte, so code has to use is_spilled_reg.
901 	 */
902 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
903 		return 0;
904 
905 	/* Reposition spi to first slot */
906 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
907 		spi = spi + 1;
908 
909 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
910 		verbose(env, "cannot overwrite referenced dynptr\n");
911 		return -EINVAL;
912 	}
913 
914 	mark_stack_slot_scratched(env, spi);
915 	mark_stack_slot_scratched(env, spi - 1);
916 
917 	/* Writing partially to one dynptr stack slot destroys both. */
918 	for (i = 0; i < BPF_REG_SIZE; i++) {
919 		state->stack[spi].slot_type[i] = STACK_INVALID;
920 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
921 	}
922 
923 	dynptr_id = state->stack[spi].spilled_ptr.id;
924 	/* Invalidate any slices associated with this dynptr */
925 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
926 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
927 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
928 			continue;
929 		if (dreg->dynptr_id == dynptr_id)
930 			mark_reg_invalid(env, dreg);
931 	}));
932 
933 	/* Do not release reference state, we are destroying dynptr on stack,
934 	 * not using some helper to release it. Just reset register.
935 	 */
936 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
937 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
938 
939 	/* Same reason as unmark_stack_slots_dynptr above */
940 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
941 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
942 
943 	return 0;
944 }
945 
946 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
947 {
948 	int spi;
949 
950 	if (reg->type == CONST_PTR_TO_DYNPTR)
951 		return false;
952 
953 	spi = dynptr_get_spi(env, reg);
954 
955 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
956 	 * error because this just means the stack state hasn't been updated yet.
957 	 * We will do check_mem_access to check and update stack bounds later.
958 	 */
959 	if (spi < 0 && spi != -ERANGE)
960 		return false;
961 
962 	/* We don't need to check if the stack slots are marked by previous
963 	 * dynptr initializations because we allow overwriting existing unreferenced
964 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
965 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
966 	 * touching are completely destructed before we reinitialize them for a new
967 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
968 	 * instead of delaying it until the end where the user will get "Unreleased
969 	 * reference" error.
970 	 */
971 	return true;
972 }
973 
974 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
975 {
976 	struct bpf_func_state *state = func(env, reg);
977 	int i, spi;
978 
979 	/* This already represents first slot of initialized bpf_dynptr.
980 	 *
981 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
982 	 * check_func_arg_reg_off's logic, so we don't need to check its
983 	 * offset and alignment.
984 	 */
985 	if (reg->type == CONST_PTR_TO_DYNPTR)
986 		return true;
987 
988 	spi = dynptr_get_spi(env, reg);
989 	if (spi < 0)
990 		return false;
991 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
992 		return false;
993 
994 	for (i = 0; i < BPF_REG_SIZE; i++) {
995 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
996 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
997 			return false;
998 	}
999 
1000 	return true;
1001 }
1002 
1003 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1004 				    enum bpf_arg_type arg_type)
1005 {
1006 	struct bpf_func_state *state = func(env, reg);
1007 	enum bpf_dynptr_type dynptr_type;
1008 	int spi;
1009 
1010 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1011 	if (arg_type == ARG_PTR_TO_DYNPTR)
1012 		return true;
1013 
1014 	dynptr_type = arg_to_dynptr_type(arg_type);
1015 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1016 		return reg->dynptr.type == dynptr_type;
1017 	} else {
1018 		spi = dynptr_get_spi(env, reg);
1019 		if (spi < 0)
1020 			return false;
1021 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1022 	}
1023 }
1024 
1025 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1026 
1027 static bool in_rcu_cs(struct bpf_verifier_env *env);
1028 
1029 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1030 
1031 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1032 				 struct bpf_kfunc_call_arg_meta *meta,
1033 				 struct bpf_reg_state *reg, int insn_idx,
1034 				 struct btf *btf, u32 btf_id, int nr_slots)
1035 {
1036 	struct bpf_func_state *state = func(env, reg);
1037 	int spi, i, j, id;
1038 
1039 	spi = iter_get_spi(env, reg, nr_slots);
1040 	if (spi < 0)
1041 		return spi;
1042 
1043 	id = acquire_reference(env, insn_idx);
1044 	if (id < 0)
1045 		return id;
1046 
1047 	for (i = 0; i < nr_slots; i++) {
1048 		struct bpf_stack_state *slot = &state->stack[spi - i];
1049 		struct bpf_reg_state *st = &slot->spilled_ptr;
1050 
1051 		__mark_reg_known_zero(st);
1052 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1053 		if (is_kfunc_rcu_protected(meta)) {
1054 			if (in_rcu_cs(env))
1055 				st->type |= MEM_RCU;
1056 			else
1057 				st->type |= PTR_UNTRUSTED;
1058 		}
1059 		st->live |= REG_LIVE_WRITTEN;
1060 		st->ref_obj_id = i == 0 ? id : 0;
1061 		st->iter.btf = btf;
1062 		st->iter.btf_id = btf_id;
1063 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1064 		st->iter.depth = 0;
1065 
1066 		for (j = 0; j < BPF_REG_SIZE; j++)
1067 			slot->slot_type[j] = STACK_ITER;
1068 
1069 		mark_stack_slot_scratched(env, spi - i);
1070 	}
1071 
1072 	return 0;
1073 }
1074 
1075 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1076 				   struct bpf_reg_state *reg, int nr_slots)
1077 {
1078 	struct bpf_func_state *state = func(env, reg);
1079 	int spi, i, j;
1080 
1081 	spi = iter_get_spi(env, reg, nr_slots);
1082 	if (spi < 0)
1083 		return spi;
1084 
1085 	for (i = 0; i < nr_slots; i++) {
1086 		struct bpf_stack_state *slot = &state->stack[spi - i];
1087 		struct bpf_reg_state *st = &slot->spilled_ptr;
1088 
1089 		if (i == 0)
1090 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1091 
1092 		__mark_reg_not_init(env, st);
1093 
1094 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1095 		st->live |= REG_LIVE_WRITTEN;
1096 
1097 		for (j = 0; j < BPF_REG_SIZE; j++)
1098 			slot->slot_type[j] = STACK_INVALID;
1099 
1100 		mark_stack_slot_scratched(env, spi - i);
1101 	}
1102 
1103 	return 0;
1104 }
1105 
1106 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1107 				     struct bpf_reg_state *reg, int nr_slots)
1108 {
1109 	struct bpf_func_state *state = func(env, reg);
1110 	int spi, i, j;
1111 
1112 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1113 	 * will do check_mem_access to check and update stack bounds later, so
1114 	 * return true for that case.
1115 	 */
1116 	spi = iter_get_spi(env, reg, nr_slots);
1117 	if (spi == -ERANGE)
1118 		return true;
1119 	if (spi < 0)
1120 		return false;
1121 
1122 	for (i = 0; i < nr_slots; i++) {
1123 		struct bpf_stack_state *slot = &state->stack[spi - i];
1124 
1125 		for (j = 0; j < BPF_REG_SIZE; j++)
1126 			if (slot->slot_type[j] == STACK_ITER)
1127 				return false;
1128 	}
1129 
1130 	return true;
1131 }
1132 
1133 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1134 				   struct btf *btf, u32 btf_id, int nr_slots)
1135 {
1136 	struct bpf_func_state *state = func(env, reg);
1137 	int spi, i, j;
1138 
1139 	spi = iter_get_spi(env, reg, nr_slots);
1140 	if (spi < 0)
1141 		return -EINVAL;
1142 
1143 	for (i = 0; i < nr_slots; i++) {
1144 		struct bpf_stack_state *slot = &state->stack[spi - i];
1145 		struct bpf_reg_state *st = &slot->spilled_ptr;
1146 
1147 		if (st->type & PTR_UNTRUSTED)
1148 			return -EPROTO;
1149 		/* only main (first) slot has ref_obj_id set */
1150 		if (i == 0 && !st->ref_obj_id)
1151 			return -EINVAL;
1152 		if (i != 0 && st->ref_obj_id)
1153 			return -EINVAL;
1154 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1155 			return -EINVAL;
1156 
1157 		for (j = 0; j < BPF_REG_SIZE; j++)
1158 			if (slot->slot_type[j] != STACK_ITER)
1159 				return -EINVAL;
1160 	}
1161 
1162 	return 0;
1163 }
1164 
1165 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1166 static int release_irq_state(struct bpf_verifier_state *state, int id);
1167 
1168 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1169 				     struct bpf_kfunc_call_arg_meta *meta,
1170 				     struct bpf_reg_state *reg, int insn_idx,
1171 				     int kfunc_class)
1172 {
1173 	struct bpf_func_state *state = func(env, reg);
1174 	struct bpf_stack_state *slot;
1175 	struct bpf_reg_state *st;
1176 	int spi, i, id;
1177 
1178 	spi = irq_flag_get_spi(env, reg);
1179 	if (spi < 0)
1180 		return spi;
1181 
1182 	id = acquire_irq_state(env, insn_idx);
1183 	if (id < 0)
1184 		return id;
1185 
1186 	slot = &state->stack[spi];
1187 	st = &slot->spilled_ptr;
1188 
1189 	__mark_reg_known_zero(st);
1190 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1191 	st->live |= REG_LIVE_WRITTEN;
1192 	st->ref_obj_id = id;
1193 	st->irq.kfunc_class = kfunc_class;
1194 
1195 	for (i = 0; i < BPF_REG_SIZE; i++)
1196 		slot->slot_type[i] = STACK_IRQ_FLAG;
1197 
1198 	mark_stack_slot_scratched(env, spi);
1199 	return 0;
1200 }
1201 
1202 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1203 				      int kfunc_class)
1204 {
1205 	struct bpf_func_state *state = func(env, reg);
1206 	struct bpf_stack_state *slot;
1207 	struct bpf_reg_state *st;
1208 	int spi, i, err;
1209 
1210 	spi = irq_flag_get_spi(env, reg);
1211 	if (spi < 0)
1212 		return spi;
1213 
1214 	slot = &state->stack[spi];
1215 	st = &slot->spilled_ptr;
1216 
1217 	if (st->irq.kfunc_class != kfunc_class) {
1218 		const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1219 		const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1220 
1221 		verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1222 			flag_kfunc, used_kfunc);
1223 		return -EINVAL;
1224 	}
1225 
1226 	err = release_irq_state(env->cur_state, st->ref_obj_id);
1227 	WARN_ON_ONCE(err && err != -EACCES);
1228 	if (err) {
1229 		int insn_idx = 0;
1230 
1231 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1232 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1233 				insn_idx = env->cur_state->refs[i].insn_idx;
1234 				break;
1235 			}
1236 		}
1237 
1238 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1239 			env->cur_state->active_irq_id, insn_idx);
1240 		return err;
1241 	}
1242 
1243 	__mark_reg_not_init(env, st);
1244 
1245 	/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1246 	st->live |= REG_LIVE_WRITTEN;
1247 
1248 	for (i = 0; i < BPF_REG_SIZE; i++)
1249 		slot->slot_type[i] = STACK_INVALID;
1250 
1251 	mark_stack_slot_scratched(env, spi);
1252 	return 0;
1253 }
1254 
1255 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1256 {
1257 	struct bpf_func_state *state = func(env, reg);
1258 	struct bpf_stack_state *slot;
1259 	int spi, i;
1260 
1261 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1262 	 * will do check_mem_access to check and update stack bounds later, so
1263 	 * return true for that case.
1264 	 */
1265 	spi = irq_flag_get_spi(env, reg);
1266 	if (spi == -ERANGE)
1267 		return true;
1268 	if (spi < 0)
1269 		return false;
1270 
1271 	slot = &state->stack[spi];
1272 
1273 	for (i = 0; i < BPF_REG_SIZE; i++)
1274 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1275 			return false;
1276 	return true;
1277 }
1278 
1279 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1280 {
1281 	struct bpf_func_state *state = func(env, reg);
1282 	struct bpf_stack_state *slot;
1283 	struct bpf_reg_state *st;
1284 	int spi, i;
1285 
1286 	spi = irq_flag_get_spi(env, reg);
1287 	if (spi < 0)
1288 		return -EINVAL;
1289 
1290 	slot = &state->stack[spi];
1291 	st = &slot->spilled_ptr;
1292 
1293 	if (!st->ref_obj_id)
1294 		return -EINVAL;
1295 
1296 	for (i = 0; i < BPF_REG_SIZE; i++)
1297 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1298 			return -EINVAL;
1299 	return 0;
1300 }
1301 
1302 /* Check if given stack slot is "special":
1303  *   - spilled register state (STACK_SPILL);
1304  *   - dynptr state (STACK_DYNPTR);
1305  *   - iter state (STACK_ITER).
1306  *   - irq flag state (STACK_IRQ_FLAG)
1307  */
1308 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1309 {
1310 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1311 
1312 	switch (type) {
1313 	case STACK_SPILL:
1314 	case STACK_DYNPTR:
1315 	case STACK_ITER:
1316 	case STACK_IRQ_FLAG:
1317 		return true;
1318 	case STACK_INVALID:
1319 	case STACK_MISC:
1320 	case STACK_ZERO:
1321 		return false;
1322 	default:
1323 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1324 		return true;
1325 	}
1326 }
1327 
1328 /* The reg state of a pointer or a bounded scalar was saved when
1329  * it was spilled to the stack.
1330  */
1331 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1332 {
1333 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1334 }
1335 
1336 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1337 {
1338 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1339 	       stack->spilled_ptr.type == SCALAR_VALUE;
1340 }
1341 
1342 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1343 {
1344 	return stack->slot_type[0] == STACK_SPILL &&
1345 	       stack->spilled_ptr.type == SCALAR_VALUE;
1346 }
1347 
1348 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1349  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1350  * more precise STACK_ZERO.
1351  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1352  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1353  * unnecessary as both are considered equivalent when loading data and pruning,
1354  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1355  * slots.
1356  */
1357 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1358 {
1359 	if (*stype == STACK_ZERO)
1360 		return;
1361 	if (*stype == STACK_INVALID)
1362 		return;
1363 	*stype = STACK_MISC;
1364 }
1365 
1366 static void scrub_spilled_slot(u8 *stype)
1367 {
1368 	if (*stype != STACK_INVALID)
1369 		*stype = STACK_MISC;
1370 }
1371 
1372 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1373  * small to hold src. This is different from krealloc since we don't want to preserve
1374  * the contents of dst.
1375  *
1376  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1377  * not be allocated.
1378  */
1379 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1380 {
1381 	size_t alloc_bytes;
1382 	void *orig = dst;
1383 	size_t bytes;
1384 
1385 	if (ZERO_OR_NULL_PTR(src))
1386 		goto out;
1387 
1388 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1389 		return NULL;
1390 
1391 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1392 	dst = krealloc(orig, alloc_bytes, flags);
1393 	if (!dst) {
1394 		kfree(orig);
1395 		return NULL;
1396 	}
1397 
1398 	memcpy(dst, src, bytes);
1399 out:
1400 	return dst ? dst : ZERO_SIZE_PTR;
1401 }
1402 
1403 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1404  * small to hold new_n items. new items are zeroed out if the array grows.
1405  *
1406  * Contrary to krealloc_array, does not free arr if new_n is zero.
1407  */
1408 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1409 {
1410 	size_t alloc_size;
1411 	void *new_arr;
1412 
1413 	if (!new_n || old_n == new_n)
1414 		goto out;
1415 
1416 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1417 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1418 	if (!new_arr) {
1419 		kfree(arr);
1420 		return NULL;
1421 	}
1422 	arr = new_arr;
1423 
1424 	if (new_n > old_n)
1425 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1426 
1427 out:
1428 	return arr ? arr : ZERO_SIZE_PTR;
1429 }
1430 
1431 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1432 {
1433 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1434 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1435 	if (!dst->refs)
1436 		return -ENOMEM;
1437 
1438 	dst->acquired_refs = src->acquired_refs;
1439 	dst->active_locks = src->active_locks;
1440 	dst->active_preempt_locks = src->active_preempt_locks;
1441 	dst->active_rcu_lock = src->active_rcu_lock;
1442 	dst->active_irq_id = src->active_irq_id;
1443 	dst->active_lock_id = src->active_lock_id;
1444 	dst->active_lock_ptr = src->active_lock_ptr;
1445 	return 0;
1446 }
1447 
1448 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1449 {
1450 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1451 
1452 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1453 				GFP_KERNEL_ACCOUNT);
1454 	if (!dst->stack)
1455 		return -ENOMEM;
1456 
1457 	dst->allocated_stack = src->allocated_stack;
1458 	return 0;
1459 }
1460 
1461 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1462 {
1463 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1464 				    sizeof(struct bpf_reference_state));
1465 	if (!state->refs)
1466 		return -ENOMEM;
1467 
1468 	state->acquired_refs = n;
1469 	return 0;
1470 }
1471 
1472 /* Possibly update state->allocated_stack to be at least size bytes. Also
1473  * possibly update the function's high-water mark in its bpf_subprog_info.
1474  */
1475 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1476 {
1477 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1478 
1479 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1480 	size = round_up(size, BPF_REG_SIZE);
1481 	n = size / BPF_REG_SIZE;
1482 
1483 	if (old_n >= n)
1484 		return 0;
1485 
1486 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1487 	if (!state->stack)
1488 		return -ENOMEM;
1489 
1490 	state->allocated_stack = size;
1491 
1492 	/* update known max for given subprogram */
1493 	if (env->subprog_info[state->subprogno].stack_depth < size)
1494 		env->subprog_info[state->subprogno].stack_depth = size;
1495 
1496 	return 0;
1497 }
1498 
1499 /* Acquire a pointer id from the env and update the state->refs to include
1500  * this new pointer reference.
1501  * On success, returns a valid pointer id to associate with the register
1502  * On failure, returns a negative errno.
1503  */
1504 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1505 {
1506 	struct bpf_verifier_state *state = env->cur_state;
1507 	int new_ofs = state->acquired_refs;
1508 	int err;
1509 
1510 	err = resize_reference_state(state, state->acquired_refs + 1);
1511 	if (err)
1512 		return NULL;
1513 	state->refs[new_ofs].insn_idx = insn_idx;
1514 
1515 	return &state->refs[new_ofs];
1516 }
1517 
1518 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx)
1519 {
1520 	struct bpf_reference_state *s;
1521 
1522 	s = acquire_reference_state(env, insn_idx);
1523 	if (!s)
1524 		return -ENOMEM;
1525 	s->type = REF_TYPE_PTR;
1526 	s->id = ++env->id_gen;
1527 	return s->id;
1528 }
1529 
1530 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1531 			      int id, void *ptr)
1532 {
1533 	struct bpf_verifier_state *state = env->cur_state;
1534 	struct bpf_reference_state *s;
1535 
1536 	s = acquire_reference_state(env, insn_idx);
1537 	if (!s)
1538 		return -ENOMEM;
1539 	s->type = type;
1540 	s->id = id;
1541 	s->ptr = ptr;
1542 
1543 	state->active_locks++;
1544 	state->active_lock_id = id;
1545 	state->active_lock_ptr = ptr;
1546 	return 0;
1547 }
1548 
1549 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1550 {
1551 	struct bpf_verifier_state *state = env->cur_state;
1552 	struct bpf_reference_state *s;
1553 
1554 	s = acquire_reference_state(env, insn_idx);
1555 	if (!s)
1556 		return -ENOMEM;
1557 	s->type = REF_TYPE_IRQ;
1558 	s->id = ++env->id_gen;
1559 
1560 	state->active_irq_id = s->id;
1561 	return s->id;
1562 }
1563 
1564 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1565 {
1566 	int last_idx;
1567 	size_t rem;
1568 
1569 	/* IRQ state requires the relative ordering of elements remaining the
1570 	 * same, since it relies on the refs array to behave as a stack, so that
1571 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1572 	 * the array instead of swapping the final element into the deleted idx.
1573 	 */
1574 	last_idx = state->acquired_refs - 1;
1575 	rem = state->acquired_refs - idx - 1;
1576 	if (last_idx && idx != last_idx)
1577 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1578 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1579 	state->acquired_refs--;
1580 	return;
1581 }
1582 
1583 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id)
1584 {
1585 	int i;
1586 
1587 	for (i = 0; i < state->acquired_refs; i++)
1588 		if (state->refs[i].id == ptr_id)
1589 			return true;
1590 
1591 	return false;
1592 }
1593 
1594 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
1595 {
1596 	void *prev_ptr = NULL;
1597 	u32 prev_id = 0;
1598 	int i;
1599 
1600 	for (i = 0; i < state->acquired_refs; i++) {
1601 		if (state->refs[i].type == type && state->refs[i].id == id &&
1602 		    state->refs[i].ptr == ptr) {
1603 			release_reference_state(state, i);
1604 			state->active_locks--;
1605 			/* Reassign active lock (id, ptr). */
1606 			state->active_lock_id = prev_id;
1607 			state->active_lock_ptr = prev_ptr;
1608 			return 0;
1609 		}
1610 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1611 			prev_id = state->refs[i].id;
1612 			prev_ptr = state->refs[i].ptr;
1613 		}
1614 	}
1615 	return -EINVAL;
1616 }
1617 
1618 static int release_irq_state(struct bpf_verifier_state *state, int id)
1619 {
1620 	u32 prev_id = 0;
1621 	int i;
1622 
1623 	if (id != state->active_irq_id)
1624 		return -EACCES;
1625 
1626 	for (i = 0; i < state->acquired_refs; i++) {
1627 		if (state->refs[i].type != REF_TYPE_IRQ)
1628 			continue;
1629 		if (state->refs[i].id == id) {
1630 			release_reference_state(state, i);
1631 			state->active_irq_id = prev_id;
1632 			return 0;
1633 		} else {
1634 			prev_id = state->refs[i].id;
1635 		}
1636 	}
1637 	return -EINVAL;
1638 }
1639 
1640 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1641 						   int id, void *ptr)
1642 {
1643 	int i;
1644 
1645 	for (i = 0; i < state->acquired_refs; i++) {
1646 		struct bpf_reference_state *s = &state->refs[i];
1647 
1648 		if (!(s->type & type))
1649 			continue;
1650 
1651 		if (s->id == id && s->ptr == ptr)
1652 			return s;
1653 	}
1654 	return NULL;
1655 }
1656 
1657 static void update_peak_states(struct bpf_verifier_env *env)
1658 {
1659 	u32 cur_states;
1660 
1661 	cur_states = env->explored_states_size + env->free_list_size + env->num_backedges;
1662 	env->peak_states = max(env->peak_states, cur_states);
1663 }
1664 
1665 static void free_func_state(struct bpf_func_state *state)
1666 {
1667 	if (!state)
1668 		return;
1669 	kfree(state->stack);
1670 	kfree(state);
1671 }
1672 
1673 static void clear_jmp_history(struct bpf_verifier_state *state)
1674 {
1675 	kfree(state->jmp_history);
1676 	state->jmp_history = NULL;
1677 	state->jmp_history_cnt = 0;
1678 }
1679 
1680 static void free_verifier_state(struct bpf_verifier_state *state,
1681 				bool free_self)
1682 {
1683 	int i;
1684 
1685 	for (i = 0; i <= state->curframe; i++) {
1686 		free_func_state(state->frame[i]);
1687 		state->frame[i] = NULL;
1688 	}
1689 	kfree(state->refs);
1690 	clear_jmp_history(state);
1691 	if (free_self)
1692 		kfree(state);
1693 }
1694 
1695 /* struct bpf_verifier_state->parent refers to states
1696  * that are in either of env->{expored_states,free_list}.
1697  * In both cases the state is contained in struct bpf_verifier_state_list.
1698  */
1699 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st)
1700 {
1701 	if (st->parent)
1702 		return container_of(st->parent, struct bpf_verifier_state_list, state);
1703 	return NULL;
1704 }
1705 
1706 static bool incomplete_read_marks(struct bpf_verifier_env *env,
1707 				  struct bpf_verifier_state *st);
1708 
1709 /* A state can be freed if it is no longer referenced:
1710  * - is in the env->free_list;
1711  * - has no children states;
1712  */
1713 static void maybe_free_verifier_state(struct bpf_verifier_env *env,
1714 				      struct bpf_verifier_state_list *sl)
1715 {
1716 	if (!sl->in_free_list
1717 	    || sl->state.branches != 0
1718 	    || incomplete_read_marks(env, &sl->state))
1719 		return;
1720 	list_del(&sl->node);
1721 	free_verifier_state(&sl->state, false);
1722 	kfree(sl);
1723 	env->free_list_size--;
1724 }
1725 
1726 /* copy verifier state from src to dst growing dst stack space
1727  * when necessary to accommodate larger src stack
1728  */
1729 static int copy_func_state(struct bpf_func_state *dst,
1730 			   const struct bpf_func_state *src)
1731 {
1732 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1733 	return copy_stack_state(dst, src);
1734 }
1735 
1736 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1737 			       const struct bpf_verifier_state *src)
1738 {
1739 	struct bpf_func_state *dst;
1740 	int i, err;
1741 
1742 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1743 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1744 					  GFP_KERNEL_ACCOUNT);
1745 	if (!dst_state->jmp_history)
1746 		return -ENOMEM;
1747 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1748 
1749 	/* if dst has more stack frames then src frame, free them, this is also
1750 	 * necessary in case of exceptional exits using bpf_throw.
1751 	 */
1752 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1753 		free_func_state(dst_state->frame[i]);
1754 		dst_state->frame[i] = NULL;
1755 	}
1756 	err = copy_reference_state(dst_state, src);
1757 	if (err)
1758 		return err;
1759 	dst_state->speculative = src->speculative;
1760 	dst_state->in_sleepable = src->in_sleepable;
1761 	dst_state->curframe = src->curframe;
1762 	dst_state->branches = src->branches;
1763 	dst_state->parent = src->parent;
1764 	dst_state->first_insn_idx = src->first_insn_idx;
1765 	dst_state->last_insn_idx = src->last_insn_idx;
1766 	dst_state->dfs_depth = src->dfs_depth;
1767 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1768 	dst_state->may_goto_depth = src->may_goto_depth;
1769 	dst_state->equal_state = src->equal_state;
1770 	for (i = 0; i <= src->curframe; i++) {
1771 		dst = dst_state->frame[i];
1772 		if (!dst) {
1773 			dst = kzalloc(sizeof(*dst), GFP_KERNEL_ACCOUNT);
1774 			if (!dst)
1775 				return -ENOMEM;
1776 			dst_state->frame[i] = dst;
1777 		}
1778 		err = copy_func_state(dst, src->frame[i]);
1779 		if (err)
1780 			return err;
1781 	}
1782 	return 0;
1783 }
1784 
1785 static u32 state_htab_size(struct bpf_verifier_env *env)
1786 {
1787 	return env->prog->len;
1788 }
1789 
1790 static struct list_head *explored_state(struct bpf_verifier_env *env, int idx)
1791 {
1792 	struct bpf_verifier_state *cur = env->cur_state;
1793 	struct bpf_func_state *state = cur->frame[cur->curframe];
1794 
1795 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1796 }
1797 
1798 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1799 {
1800 	int fr;
1801 
1802 	if (a->curframe != b->curframe)
1803 		return false;
1804 
1805 	for (fr = a->curframe; fr >= 0; fr--)
1806 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1807 			return false;
1808 
1809 	return true;
1810 }
1811 
1812 /* Return IP for a given frame in a call stack */
1813 static u32 frame_insn_idx(struct bpf_verifier_state *st, u32 frame)
1814 {
1815 	return frame == st->curframe
1816 	       ? st->insn_idx
1817 	       : st->frame[frame + 1]->callsite;
1818 }
1819 
1820 /* For state @st look for a topmost frame with frame_insn_idx() in some SCC,
1821  * if such frame exists form a corresponding @callchain as an array of
1822  * call sites leading to this frame and SCC id.
1823  * E.g.:
1824  *
1825  *    void foo()  { A: loop {... SCC#1 ...}; }
1826  *    void bar()  { B: loop { C: foo(); ... SCC#2 ... }
1827  *                  D: loop { E: foo(); ... SCC#3 ... } }
1828  *    void main() { F: bar(); }
1829  *
1830  * @callchain at (A) would be either (F,SCC#2) or (F,SCC#3) depending
1831  * on @st frame call sites being (F,C,A) or (F,E,A).
1832  */
1833 static bool compute_scc_callchain(struct bpf_verifier_env *env,
1834 				  struct bpf_verifier_state *st,
1835 				  struct bpf_scc_callchain *callchain)
1836 {
1837 	u32 i, scc, insn_idx;
1838 
1839 	memset(callchain, 0, sizeof(*callchain));
1840 	for (i = 0; i <= st->curframe; i++) {
1841 		insn_idx = frame_insn_idx(st, i);
1842 		scc = env->insn_aux_data[insn_idx].scc;
1843 		if (scc) {
1844 			callchain->scc = scc;
1845 			break;
1846 		} else if (i < st->curframe) {
1847 			callchain->callsites[i] = insn_idx;
1848 		} else {
1849 			return false;
1850 		}
1851 	}
1852 	return true;
1853 }
1854 
1855 /* Check if bpf_scc_visit instance for @callchain exists. */
1856 static struct bpf_scc_visit *scc_visit_lookup(struct bpf_verifier_env *env,
1857 					      struct bpf_scc_callchain *callchain)
1858 {
1859 	struct bpf_scc_info *info = env->scc_info[callchain->scc];
1860 	struct bpf_scc_visit *visits = info->visits;
1861 	u32 i;
1862 
1863 	if (!info)
1864 		return NULL;
1865 	for (i = 0; i < info->num_visits; i++)
1866 		if (memcmp(callchain, &visits[i].callchain, sizeof(*callchain)) == 0)
1867 			return &visits[i];
1868 	return NULL;
1869 }
1870 
1871 /* Allocate a new bpf_scc_visit instance corresponding to @callchain.
1872  * Allocated instances are alive for a duration of the do_check_common()
1873  * call and are freed by free_states().
1874  */
1875 static struct bpf_scc_visit *scc_visit_alloc(struct bpf_verifier_env *env,
1876 					     struct bpf_scc_callchain *callchain)
1877 {
1878 	struct bpf_scc_visit *visit;
1879 	struct bpf_scc_info *info;
1880 	u32 scc, num_visits;
1881 	u64 new_sz;
1882 
1883 	scc = callchain->scc;
1884 	info = env->scc_info[scc];
1885 	num_visits = info ? info->num_visits : 0;
1886 	new_sz = sizeof(*info) + sizeof(struct bpf_scc_visit) * (num_visits + 1);
1887 	info = kvrealloc(env->scc_info[scc], new_sz, GFP_KERNEL_ACCOUNT);
1888 	if (!info)
1889 		return NULL;
1890 	env->scc_info[scc] = info;
1891 	info->num_visits = num_visits + 1;
1892 	visit = &info->visits[num_visits];
1893 	memset(visit, 0, sizeof(*visit));
1894 	memcpy(&visit->callchain, callchain, sizeof(*callchain));
1895 	return visit;
1896 }
1897 
1898 /* Form a string '(callsite#1,callsite#2,...,scc)' in env->tmp_str_buf */
1899 static char *format_callchain(struct bpf_verifier_env *env, struct bpf_scc_callchain *callchain)
1900 {
1901 	char *buf = env->tmp_str_buf;
1902 	int i, delta = 0;
1903 
1904 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "(");
1905 	for (i = 0; i < ARRAY_SIZE(callchain->callsites); i++) {
1906 		if (!callchain->callsites[i])
1907 			break;
1908 		delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u,",
1909 				  callchain->callsites[i]);
1910 	}
1911 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u)", callchain->scc);
1912 	return env->tmp_str_buf;
1913 }
1914 
1915 /* If callchain for @st exists (@st is in some SCC), ensure that
1916  * bpf_scc_visit instance for this callchain exists.
1917  * If instance does not exist or is empty, assign visit->entry_state to @st.
1918  */
1919 static int maybe_enter_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1920 {
1921 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1922 	struct bpf_scc_visit *visit;
1923 
1924 	if (!compute_scc_callchain(env, st, callchain))
1925 		return 0;
1926 	visit = scc_visit_lookup(env, callchain);
1927 	visit = visit ?: scc_visit_alloc(env, callchain);
1928 	if (!visit)
1929 		return -ENOMEM;
1930 	if (!visit->entry_state) {
1931 		visit->entry_state = st;
1932 		if (env->log.level & BPF_LOG_LEVEL2)
1933 			verbose(env, "SCC enter %s\n", format_callchain(env, callchain));
1934 	}
1935 	return 0;
1936 }
1937 
1938 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit);
1939 
1940 /* If callchain for @st exists (@st is in some SCC), make it empty:
1941  * - set visit->entry_state to NULL;
1942  * - flush accumulated backedges.
1943  */
1944 static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1945 {
1946 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1947 	struct bpf_scc_visit *visit;
1948 
1949 	if (!compute_scc_callchain(env, st, callchain))
1950 		return 0;
1951 	visit = scc_visit_lookup(env, callchain);
1952 	if (!visit) {
1953 		verifier_bug(env, "scc exit: no visit info for call chain %s",
1954 			     format_callchain(env, callchain));
1955 		return -EFAULT;
1956 	}
1957 	if (visit->entry_state != st)
1958 		return 0;
1959 	if (env->log.level & BPF_LOG_LEVEL2)
1960 		verbose(env, "SCC exit %s\n", format_callchain(env, callchain));
1961 	visit->entry_state = NULL;
1962 	env->num_backedges -= visit->num_backedges;
1963 	visit->num_backedges = 0;
1964 	update_peak_states(env);
1965 	return propagate_backedges(env, visit);
1966 }
1967 
1968 /* Lookup an bpf_scc_visit instance corresponding to @st callchain
1969  * and add @backedge to visit->backedges. @st callchain must exist.
1970  */
1971 static int add_scc_backedge(struct bpf_verifier_env *env,
1972 			    struct bpf_verifier_state *st,
1973 			    struct bpf_scc_backedge *backedge)
1974 {
1975 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1976 	struct bpf_scc_visit *visit;
1977 
1978 	if (!compute_scc_callchain(env, st, callchain)) {
1979 		verifier_bug(env, "add backedge: no SCC in verification path, insn_idx %d",
1980 			     st->insn_idx);
1981 		return -EFAULT;
1982 	}
1983 	visit = scc_visit_lookup(env, callchain);
1984 	if (!visit) {
1985 		verifier_bug(env, "add backedge: no visit info for call chain %s",
1986 			     format_callchain(env, callchain));
1987 		return -EFAULT;
1988 	}
1989 	if (env->log.level & BPF_LOG_LEVEL2)
1990 		verbose(env, "SCC backedge %s\n", format_callchain(env, callchain));
1991 	backedge->next = visit->backedges;
1992 	visit->backedges = backedge;
1993 	visit->num_backedges++;
1994 	env->num_backedges++;
1995 	update_peak_states(env);
1996 	return 0;
1997 }
1998 
1999 /* bpf_reg_state->live marks for registers in a state @st are incomplete,
2000  * if state @st is in some SCC and not all execution paths starting at this
2001  * SCC are fully explored.
2002  */
2003 static bool incomplete_read_marks(struct bpf_verifier_env *env,
2004 				  struct bpf_verifier_state *st)
2005 {
2006 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
2007 	struct bpf_scc_visit *visit;
2008 
2009 	if (!compute_scc_callchain(env, st, callchain))
2010 		return false;
2011 	visit = scc_visit_lookup(env, callchain);
2012 	if (!visit)
2013 		return false;
2014 	return !!visit->backedges;
2015 }
2016 
2017 static void free_backedges(struct bpf_scc_visit *visit)
2018 {
2019 	struct bpf_scc_backedge *backedge, *next;
2020 
2021 	for (backedge = visit->backedges; backedge; backedge = next) {
2022 		free_verifier_state(&backedge->state, false);
2023 		next = backedge->next;
2024 		kvfree(backedge);
2025 	}
2026 	visit->backedges = NULL;
2027 }
2028 
2029 static int update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2030 {
2031 	struct bpf_verifier_state_list *sl = NULL, *parent_sl;
2032 	struct bpf_verifier_state *parent;
2033 	int err;
2034 
2035 	while (st) {
2036 		u32 br = --st->branches;
2037 
2038 		/* verifier_bug_if(br > 1, ...) technically makes sense here,
2039 		 * but see comment in push_stack(), hence:
2040 		 */
2041 		verifier_bug_if((int)br < 0, env, "%s:branches_to_explore=%d", __func__, br);
2042 		if (br)
2043 			break;
2044 		err = maybe_exit_scc(env, st);
2045 		if (err)
2046 			return err;
2047 		parent = st->parent;
2048 		parent_sl = state_parent_as_list(st);
2049 		if (sl)
2050 			maybe_free_verifier_state(env, sl);
2051 		st = parent;
2052 		sl = parent_sl;
2053 	}
2054 	return 0;
2055 }
2056 
2057 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2058 		     int *insn_idx, bool pop_log)
2059 {
2060 	struct bpf_verifier_state *cur = env->cur_state;
2061 	struct bpf_verifier_stack_elem *elem, *head = env->head;
2062 	int err;
2063 
2064 	if (env->head == NULL)
2065 		return -ENOENT;
2066 
2067 	if (cur) {
2068 		err = copy_verifier_state(cur, &head->st);
2069 		if (err)
2070 			return err;
2071 	}
2072 	if (pop_log)
2073 		bpf_vlog_reset(&env->log, head->log_pos);
2074 	if (insn_idx)
2075 		*insn_idx = head->insn_idx;
2076 	if (prev_insn_idx)
2077 		*prev_insn_idx = head->prev_insn_idx;
2078 	elem = head->next;
2079 	free_verifier_state(&head->st, false);
2080 	kfree(head);
2081 	env->head = elem;
2082 	env->stack_size--;
2083 	return 0;
2084 }
2085 
2086 static bool error_recoverable_with_nospec(int err)
2087 {
2088 	/* Should only return true for non-fatal errors that are allowed to
2089 	 * occur during speculative verification. For these we can insert a
2090 	 * nospec and the program might still be accepted. Do not include
2091 	 * something like ENOMEM because it is likely to re-occur for the next
2092 	 * architectural path once it has been recovered-from in all speculative
2093 	 * paths.
2094 	 */
2095 	return err == -EPERM || err == -EACCES || err == -EINVAL;
2096 }
2097 
2098 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2099 					     int insn_idx, int prev_insn_idx,
2100 					     bool speculative)
2101 {
2102 	struct bpf_verifier_state *cur = env->cur_state;
2103 	struct bpf_verifier_stack_elem *elem;
2104 	int err;
2105 
2106 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2107 	if (!elem)
2108 		return NULL;
2109 
2110 	elem->insn_idx = insn_idx;
2111 	elem->prev_insn_idx = prev_insn_idx;
2112 	elem->next = env->head;
2113 	elem->log_pos = env->log.end_pos;
2114 	env->head = elem;
2115 	env->stack_size++;
2116 	err = copy_verifier_state(&elem->st, cur);
2117 	if (err)
2118 		return NULL;
2119 	elem->st.speculative |= speculative;
2120 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2121 		verbose(env, "The sequence of %d jumps is too complex.\n",
2122 			env->stack_size);
2123 		return NULL;
2124 	}
2125 	if (elem->st.parent) {
2126 		++elem->st.parent->branches;
2127 		/* WARN_ON(branches > 2) technically makes sense here,
2128 		 * but
2129 		 * 1. speculative states will bump 'branches' for non-branch
2130 		 * instructions
2131 		 * 2. is_state_visited() heuristics may decide not to create
2132 		 * a new state for a sequence of branches and all such current
2133 		 * and cloned states will be pointing to a single parent state
2134 		 * which might have large 'branches' count.
2135 		 */
2136 	}
2137 	return &elem->st;
2138 }
2139 
2140 #define CALLER_SAVED_REGS 6
2141 static const int caller_saved[CALLER_SAVED_REGS] = {
2142 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2143 };
2144 
2145 /* This helper doesn't clear reg->id */
2146 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2147 {
2148 	reg->var_off = tnum_const(imm);
2149 	reg->smin_value = (s64)imm;
2150 	reg->smax_value = (s64)imm;
2151 	reg->umin_value = imm;
2152 	reg->umax_value = imm;
2153 
2154 	reg->s32_min_value = (s32)imm;
2155 	reg->s32_max_value = (s32)imm;
2156 	reg->u32_min_value = (u32)imm;
2157 	reg->u32_max_value = (u32)imm;
2158 }
2159 
2160 /* Mark the unknown part of a register (variable offset or scalar value) as
2161  * known to have the value @imm.
2162  */
2163 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2164 {
2165 	/* Clear off and union(map_ptr, range) */
2166 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2167 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2168 	reg->id = 0;
2169 	reg->ref_obj_id = 0;
2170 	___mark_reg_known(reg, imm);
2171 }
2172 
2173 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2174 {
2175 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2176 	reg->s32_min_value = (s32)imm;
2177 	reg->s32_max_value = (s32)imm;
2178 	reg->u32_min_value = (u32)imm;
2179 	reg->u32_max_value = (u32)imm;
2180 }
2181 
2182 /* Mark the 'variable offset' part of a register as zero.  This should be
2183  * used only on registers holding a pointer type.
2184  */
2185 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2186 {
2187 	__mark_reg_known(reg, 0);
2188 }
2189 
2190 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2191 {
2192 	__mark_reg_known(reg, 0);
2193 	reg->type = SCALAR_VALUE;
2194 	/* all scalars are assumed imprecise initially (unless unprivileged,
2195 	 * in which case everything is forced to be precise)
2196 	 */
2197 	reg->precise = !env->bpf_capable;
2198 }
2199 
2200 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2201 				struct bpf_reg_state *regs, u32 regno)
2202 {
2203 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2204 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2205 		/* Something bad happened, let's kill all regs */
2206 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2207 			__mark_reg_not_init(env, regs + regno);
2208 		return;
2209 	}
2210 	__mark_reg_known_zero(regs + regno);
2211 }
2212 
2213 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2214 			      bool first_slot, int dynptr_id)
2215 {
2216 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2217 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2218 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2219 	 */
2220 	__mark_reg_known_zero(reg);
2221 	reg->type = CONST_PTR_TO_DYNPTR;
2222 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2223 	reg->id = dynptr_id;
2224 	reg->dynptr.type = type;
2225 	reg->dynptr.first_slot = first_slot;
2226 }
2227 
2228 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2229 {
2230 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2231 		const struct bpf_map *map = reg->map_ptr;
2232 
2233 		if (map->inner_map_meta) {
2234 			reg->type = CONST_PTR_TO_MAP;
2235 			reg->map_ptr = map->inner_map_meta;
2236 			/* transfer reg's id which is unique for every map_lookup_elem
2237 			 * as UID of the inner map.
2238 			 */
2239 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2240 				reg->map_uid = reg->id;
2241 			if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE))
2242 				reg->map_uid = reg->id;
2243 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2244 			reg->type = PTR_TO_XDP_SOCK;
2245 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2246 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2247 			reg->type = PTR_TO_SOCKET;
2248 		} else {
2249 			reg->type = PTR_TO_MAP_VALUE;
2250 		}
2251 		return;
2252 	}
2253 
2254 	reg->type &= ~PTR_MAYBE_NULL;
2255 }
2256 
2257 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2258 				struct btf_field_graph_root *ds_head)
2259 {
2260 	__mark_reg_known_zero(&regs[regno]);
2261 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2262 	regs[regno].btf = ds_head->btf;
2263 	regs[regno].btf_id = ds_head->value_btf_id;
2264 	regs[regno].off = ds_head->node_offset;
2265 }
2266 
2267 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2268 {
2269 	return type_is_pkt_pointer(reg->type);
2270 }
2271 
2272 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2273 {
2274 	return reg_is_pkt_pointer(reg) ||
2275 	       reg->type == PTR_TO_PACKET_END;
2276 }
2277 
2278 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2279 {
2280 	return base_type(reg->type) == PTR_TO_MEM &&
2281 	       (reg->type &
2282 		(DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META));
2283 }
2284 
2285 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2286 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2287 				    enum bpf_reg_type which)
2288 {
2289 	/* The register can already have a range from prior markings.
2290 	 * This is fine as long as it hasn't been advanced from its
2291 	 * origin.
2292 	 */
2293 	return reg->type == which &&
2294 	       reg->id == 0 &&
2295 	       reg->off == 0 &&
2296 	       tnum_equals_const(reg->var_off, 0);
2297 }
2298 
2299 /* Reset the min/max bounds of a register */
2300 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2301 {
2302 	reg->smin_value = S64_MIN;
2303 	reg->smax_value = S64_MAX;
2304 	reg->umin_value = 0;
2305 	reg->umax_value = U64_MAX;
2306 
2307 	reg->s32_min_value = S32_MIN;
2308 	reg->s32_max_value = S32_MAX;
2309 	reg->u32_min_value = 0;
2310 	reg->u32_max_value = U32_MAX;
2311 }
2312 
2313 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2314 {
2315 	reg->smin_value = S64_MIN;
2316 	reg->smax_value = S64_MAX;
2317 	reg->umin_value = 0;
2318 	reg->umax_value = U64_MAX;
2319 }
2320 
2321 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2322 {
2323 	reg->s32_min_value = S32_MIN;
2324 	reg->s32_max_value = S32_MAX;
2325 	reg->u32_min_value = 0;
2326 	reg->u32_max_value = U32_MAX;
2327 }
2328 
2329 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2330 {
2331 	struct tnum var32_off = tnum_subreg(reg->var_off);
2332 
2333 	/* min signed is max(sign bit) | min(other bits) */
2334 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2335 			var32_off.value | (var32_off.mask & S32_MIN));
2336 	/* max signed is min(sign bit) | max(other bits) */
2337 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2338 			var32_off.value | (var32_off.mask & S32_MAX));
2339 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2340 	reg->u32_max_value = min(reg->u32_max_value,
2341 				 (u32)(var32_off.value | var32_off.mask));
2342 }
2343 
2344 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2345 {
2346 	/* min signed is max(sign bit) | min(other bits) */
2347 	reg->smin_value = max_t(s64, reg->smin_value,
2348 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2349 	/* max signed is min(sign bit) | max(other bits) */
2350 	reg->smax_value = min_t(s64, reg->smax_value,
2351 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2352 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2353 	reg->umax_value = min(reg->umax_value,
2354 			      reg->var_off.value | reg->var_off.mask);
2355 }
2356 
2357 static void __update_reg_bounds(struct bpf_reg_state *reg)
2358 {
2359 	__update_reg32_bounds(reg);
2360 	__update_reg64_bounds(reg);
2361 }
2362 
2363 /* Uses signed min/max values to inform unsigned, and vice-versa */
2364 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2365 {
2366 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
2367 	 * bits to improve our u32/s32 boundaries.
2368 	 *
2369 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
2370 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
2371 	 * [10, 20] range. But this property holds for any 64-bit range as
2372 	 * long as upper 32 bits in that entire range of values stay the same.
2373 	 *
2374 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
2375 	 * in decimal) has the same upper 32 bits throughout all the values in
2376 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
2377 	 * range.
2378 	 *
2379 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
2380 	 * following the rules outlined below about u64/s64 correspondence
2381 	 * (which equally applies to u32 vs s32 correspondence). In general it
2382 	 * depends on actual hexadecimal values of 32-bit range. They can form
2383 	 * only valid u32, or only valid s32 ranges in some cases.
2384 	 *
2385 	 * So we use all these insights to derive bounds for subregisters here.
2386 	 */
2387 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
2388 		/* u64 to u32 casting preserves validity of low 32 bits as
2389 		 * a range, if upper 32 bits are the same
2390 		 */
2391 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2392 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2393 
2394 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2395 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2396 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2397 		}
2398 	}
2399 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2400 		/* low 32 bits should form a proper u32 range */
2401 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2402 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2403 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2404 		}
2405 		/* low 32 bits should form a proper s32 range */
2406 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2407 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2408 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2409 		}
2410 	}
2411 	/* Special case where upper bits form a small sequence of two
2412 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2413 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2414 	 * going from negative numbers to positive numbers. E.g., let's say we
2415 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2416 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2417 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2418 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2419 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2420 	 * upper 32 bits. As a random example, s64 range
2421 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2422 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2423 	 */
2424 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2425 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2426 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2427 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2428 	}
2429 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2430 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2431 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2432 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2433 	}
2434 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2435 	 * try to learn from that
2436 	 */
2437 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2438 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2439 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2440 	}
2441 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2442 	 * are the same, so combine.  This works even in the negative case, e.g.
2443 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2444 	 */
2445 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2446 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2447 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2448 	}
2449 }
2450 
2451 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2452 {
2453 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2454 	 * try to learn from that. Let's do a bit of ASCII art to see when
2455 	 * this is happening. Let's take u64 range first:
2456 	 *
2457 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2458 	 * |-------------------------------|--------------------------------|
2459 	 *
2460 	 * Valid u64 range is formed when umin and umax are anywhere in the
2461 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2462 	 * straightforward. Let's see how s64 range maps onto the same range
2463 	 * of values, annotated below the line for comparison:
2464 	 *
2465 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2466 	 * |-------------------------------|--------------------------------|
2467 	 * 0                        S64_MAX S64_MIN                        -1
2468 	 *
2469 	 * So s64 values basically start in the middle and they are logically
2470 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2471 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2472 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2473 	 * more visually as mapped to sign-agnostic range of hex values.
2474 	 *
2475 	 *  u64 start                                               u64 end
2476 	 *  _______________________________________________________________
2477 	 * /                                                               \
2478 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2479 	 * |-------------------------------|--------------------------------|
2480 	 * 0                        S64_MAX S64_MIN                        -1
2481 	 *                                / \
2482 	 * >------------------------------   ------------------------------->
2483 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2484 	 *
2485 	 * What this means is that, in general, we can't always derive
2486 	 * something new about u64 from any random s64 range, and vice versa.
2487 	 *
2488 	 * But we can do that in two particular cases. One is when entire
2489 	 * u64/s64 range is *entirely* contained within left half of the above
2490 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2491 	 *
2492 	 * |-------------------------------|--------------------------------|
2493 	 *     ^                   ^            ^                 ^
2494 	 *     A                   B            C                 D
2495 	 *
2496 	 * [A, B] and [C, D] are contained entirely in their respective halves
2497 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2498 	 * will be non-negative both as u64 and s64 (and in fact it will be
2499 	 * identical ranges no matter the signedness). [C, D] treated as s64
2500 	 * will be a range of negative values, while in u64 it will be
2501 	 * non-negative range of values larger than 0x8000000000000000.
2502 	 *
2503 	 * Now, any other range here can't be represented in both u64 and s64
2504 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2505 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2506 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2507 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2508 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2509 	 * ranges as u64. Currently reg_state can't represent two segments per
2510 	 * numeric domain, so in such situations we can only derive maximal
2511 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2512 	 *
2513 	 * So we use these facts to derive umin/umax from smin/smax and vice
2514 	 * versa only if they stay within the same "half". This is equivalent
2515 	 * to checking sign bit: lower half will have sign bit as zero, upper
2516 	 * half have sign bit 1. Below in code we simplify this by just
2517 	 * casting umin/umax as smin/smax and checking if they form valid
2518 	 * range, and vice versa. Those are equivalent checks.
2519 	 */
2520 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2521 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2522 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2523 	}
2524 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2525 	 * are the same, so combine.  This works even in the negative case, e.g.
2526 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2527 	 */
2528 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2529 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2530 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2531 	} else {
2532 		/* If the s64 range crosses the sign boundary, then it's split
2533 		 * between the beginning and end of the U64 domain. In that
2534 		 * case, we can derive new bounds if the u64 range overlaps
2535 		 * with only one end of the s64 range.
2536 		 *
2537 		 * In the following example, the u64 range overlaps only with
2538 		 * positive portion of the s64 range.
2539 		 *
2540 		 * 0                                                   U64_MAX
2541 		 * |  [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]              |
2542 		 * |----------------------------|----------------------------|
2543 		 * |xxxxx s64 range xxxxxxxxx]                       [xxxxxxx|
2544 		 * 0                     S64_MAX S64_MIN                    -1
2545 		 *
2546 		 * We can thus derive the following new s64 and u64 ranges.
2547 		 *
2548 		 * 0                                                   U64_MAX
2549 		 * |  [xxxxxx u64 range xxxxx]                               |
2550 		 * |----------------------------|----------------------------|
2551 		 * |  [xxxxxx s64 range xxxxx]                               |
2552 		 * 0                     S64_MAX S64_MIN                    -1
2553 		 *
2554 		 * If they overlap in two places, we can't derive anything
2555 		 * because reg_state can't represent two ranges per numeric
2556 		 * domain.
2557 		 *
2558 		 * 0                                                   U64_MAX
2559 		 * |  [xxxxxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxxxxx]        |
2560 		 * |----------------------------|----------------------------|
2561 		 * |xxxxx s64 range xxxxxxxxx]                    [xxxxxxxxxx|
2562 		 * 0                     S64_MAX S64_MIN                    -1
2563 		 *
2564 		 * The first condition below corresponds to the first diagram
2565 		 * above.
2566 		 */
2567 		if (reg->umax_value < (u64)reg->smin_value) {
2568 			reg->smin_value = (s64)reg->umin_value;
2569 			reg->umax_value = min_t(u64, reg->umax_value, reg->smax_value);
2570 		} else if ((u64)reg->smax_value < reg->umin_value) {
2571 			/* This second condition considers the case where the u64 range
2572 			 * overlaps with the negative portion of the s64 range:
2573 			 *
2574 			 * 0                                                   U64_MAX
2575 			 * |              [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]  |
2576 			 * |----------------------------|----------------------------|
2577 			 * |xxxxxxxxx]                       [xxxxxxxxxxxx s64 range |
2578 			 * 0                     S64_MAX S64_MIN                    -1
2579 			 */
2580 			reg->smax_value = (s64)reg->umax_value;
2581 			reg->umin_value = max_t(u64, reg->umin_value, reg->smin_value);
2582 		}
2583 	}
2584 }
2585 
2586 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2587 {
2588 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2589 	 * values on both sides of 64-bit range in hope to have tighter range.
2590 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2591 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2592 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2593 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2594 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2595 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2596 	 * We just need to make sure that derived bounds we are intersecting
2597 	 * with are well-formed ranges in respective s64 or u64 domain, just
2598 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2599 	 */
2600 	__u64 new_umin, new_umax;
2601 	__s64 new_smin, new_smax;
2602 
2603 	/* u32 -> u64 tightening, it's always well-formed */
2604 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2605 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2606 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2607 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2608 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2609 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2610 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2611 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2612 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2613 
2614 	/* Here we would like to handle a special case after sign extending load,
2615 	 * when upper bits for a 64-bit range are all 1s or all 0s.
2616 	 *
2617 	 * Upper bits are all 1s when register is in a range:
2618 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2619 	 * Upper bits are all 0s when register is in a range:
2620 	 *   [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2621 	 * Together this forms are continuous range:
2622 	 *   [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2623 	 *
2624 	 * Now, suppose that register range is in fact tighter:
2625 	 *   [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2626 	 * Also suppose that it's 32-bit range is positive,
2627 	 * meaning that lower 32-bits of the full 64-bit register
2628 	 * are in the range:
2629 	 *   [0x0000_0000, 0x7fff_ffff] (W)
2630 	 *
2631 	 * If this happens, then any value in a range:
2632 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2633 	 * is smaller than a lowest bound of the range (R):
2634 	 *   0xffff_ffff_8000_0000
2635 	 * which means that upper bits of the full 64-bit register
2636 	 * can't be all 1s, when lower bits are in range (W).
2637 	 *
2638 	 * Note that:
2639 	 *  - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2640 	 *  - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2641 	 * These relations are used in the conditions below.
2642 	 */
2643 	if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2644 		reg->smin_value = reg->s32_min_value;
2645 		reg->smax_value = reg->s32_max_value;
2646 		reg->umin_value = reg->s32_min_value;
2647 		reg->umax_value = reg->s32_max_value;
2648 		reg->var_off = tnum_intersect(reg->var_off,
2649 					      tnum_range(reg->smin_value, reg->smax_value));
2650 	}
2651 }
2652 
2653 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2654 {
2655 	__reg32_deduce_bounds(reg);
2656 	__reg64_deduce_bounds(reg);
2657 	__reg_deduce_mixed_bounds(reg);
2658 }
2659 
2660 /* Attempts to improve var_off based on unsigned min/max information */
2661 static void __reg_bound_offset(struct bpf_reg_state *reg)
2662 {
2663 	struct tnum var64_off = tnum_intersect(reg->var_off,
2664 					       tnum_range(reg->umin_value,
2665 							  reg->umax_value));
2666 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2667 					       tnum_range(reg->u32_min_value,
2668 							  reg->u32_max_value));
2669 
2670 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2671 }
2672 
2673 static void reg_bounds_sync(struct bpf_reg_state *reg)
2674 {
2675 	/* We might have learned new bounds from the var_off. */
2676 	__update_reg_bounds(reg);
2677 	/* We might have learned something about the sign bit. */
2678 	__reg_deduce_bounds(reg);
2679 	__reg_deduce_bounds(reg);
2680 	__reg_deduce_bounds(reg);
2681 	/* We might have learned some bits from the bounds. */
2682 	__reg_bound_offset(reg);
2683 	/* Intersecting with the old var_off might have improved our bounds
2684 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2685 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2686 	 */
2687 	__update_reg_bounds(reg);
2688 }
2689 
2690 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2691 				   struct bpf_reg_state *reg, const char *ctx)
2692 {
2693 	const char *msg;
2694 
2695 	if (reg->umin_value > reg->umax_value ||
2696 	    reg->smin_value > reg->smax_value ||
2697 	    reg->u32_min_value > reg->u32_max_value ||
2698 	    reg->s32_min_value > reg->s32_max_value) {
2699 		    msg = "range bounds violation";
2700 		    goto out;
2701 	}
2702 
2703 	if (tnum_is_const(reg->var_off)) {
2704 		u64 uval = reg->var_off.value;
2705 		s64 sval = (s64)uval;
2706 
2707 		if (reg->umin_value != uval || reg->umax_value != uval ||
2708 		    reg->smin_value != sval || reg->smax_value != sval) {
2709 			msg = "const tnum out of sync with range bounds";
2710 			goto out;
2711 		}
2712 	}
2713 
2714 	if (tnum_subreg_is_const(reg->var_off)) {
2715 		u32 uval32 = tnum_subreg(reg->var_off).value;
2716 		s32 sval32 = (s32)uval32;
2717 
2718 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2719 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2720 			msg = "const subreg tnum out of sync with range bounds";
2721 			goto out;
2722 		}
2723 	}
2724 
2725 	return 0;
2726 out:
2727 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2728 		     "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)",
2729 		     ctx, msg, reg->umin_value, reg->umax_value,
2730 		     reg->smin_value, reg->smax_value,
2731 		     reg->u32_min_value, reg->u32_max_value,
2732 		     reg->s32_min_value, reg->s32_max_value,
2733 		     reg->var_off.value, reg->var_off.mask);
2734 	if (env->test_reg_invariants)
2735 		return -EFAULT;
2736 	__mark_reg_unbounded(reg);
2737 	return 0;
2738 }
2739 
2740 static bool __reg32_bound_s64(s32 a)
2741 {
2742 	return a >= 0 && a <= S32_MAX;
2743 }
2744 
2745 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2746 {
2747 	reg->umin_value = reg->u32_min_value;
2748 	reg->umax_value = reg->u32_max_value;
2749 
2750 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2751 	 * be positive otherwise set to worse case bounds and refine later
2752 	 * from tnum.
2753 	 */
2754 	if (__reg32_bound_s64(reg->s32_min_value) &&
2755 	    __reg32_bound_s64(reg->s32_max_value)) {
2756 		reg->smin_value = reg->s32_min_value;
2757 		reg->smax_value = reg->s32_max_value;
2758 	} else {
2759 		reg->smin_value = 0;
2760 		reg->smax_value = U32_MAX;
2761 	}
2762 }
2763 
2764 /* Mark a register as having a completely unknown (scalar) value. */
2765 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2766 {
2767 	/*
2768 	 * Clear type, off, and union(map_ptr, range) and
2769 	 * padding between 'type' and union
2770 	 */
2771 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2772 	reg->type = SCALAR_VALUE;
2773 	reg->id = 0;
2774 	reg->ref_obj_id = 0;
2775 	reg->var_off = tnum_unknown;
2776 	reg->frameno = 0;
2777 	reg->precise = false;
2778 	__mark_reg_unbounded(reg);
2779 }
2780 
2781 /* Mark a register as having a completely unknown (scalar) value,
2782  * initialize .precise as true when not bpf capable.
2783  */
2784 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2785 			       struct bpf_reg_state *reg)
2786 {
2787 	__mark_reg_unknown_imprecise(reg);
2788 	reg->precise = !env->bpf_capable;
2789 }
2790 
2791 static void mark_reg_unknown(struct bpf_verifier_env *env,
2792 			     struct bpf_reg_state *regs, u32 regno)
2793 {
2794 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2795 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2796 		/* Something bad happened, let's kill all regs except FP */
2797 		for (regno = 0; regno < BPF_REG_FP; regno++)
2798 			__mark_reg_not_init(env, regs + regno);
2799 		return;
2800 	}
2801 	__mark_reg_unknown(env, regs + regno);
2802 }
2803 
2804 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2805 				struct bpf_reg_state *regs,
2806 				u32 regno,
2807 				s32 s32_min,
2808 				s32 s32_max)
2809 {
2810 	struct bpf_reg_state *reg = regs + regno;
2811 
2812 	reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2813 	reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2814 
2815 	reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2816 	reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2817 
2818 	reg_bounds_sync(reg);
2819 
2820 	return reg_bounds_sanity_check(env, reg, "s32_range");
2821 }
2822 
2823 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2824 				struct bpf_reg_state *reg)
2825 {
2826 	__mark_reg_unknown(env, reg);
2827 	reg->type = NOT_INIT;
2828 }
2829 
2830 static void mark_reg_not_init(struct bpf_verifier_env *env,
2831 			      struct bpf_reg_state *regs, u32 regno)
2832 {
2833 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2834 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2835 		/* Something bad happened, let's kill all regs except FP */
2836 		for (regno = 0; regno < BPF_REG_FP; regno++)
2837 			__mark_reg_not_init(env, regs + regno);
2838 		return;
2839 	}
2840 	__mark_reg_not_init(env, regs + regno);
2841 }
2842 
2843 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2844 			   struct bpf_reg_state *regs, u32 regno,
2845 			   enum bpf_reg_type reg_type,
2846 			   struct btf *btf, u32 btf_id,
2847 			   enum bpf_type_flag flag)
2848 {
2849 	switch (reg_type) {
2850 	case SCALAR_VALUE:
2851 		mark_reg_unknown(env, regs, regno);
2852 		return 0;
2853 	case PTR_TO_BTF_ID:
2854 		mark_reg_known_zero(env, regs, regno);
2855 		regs[regno].type = PTR_TO_BTF_ID | flag;
2856 		regs[regno].btf = btf;
2857 		regs[regno].btf_id = btf_id;
2858 		if (type_may_be_null(flag))
2859 			regs[regno].id = ++env->id_gen;
2860 		return 0;
2861 	case PTR_TO_MEM:
2862 		mark_reg_known_zero(env, regs, regno);
2863 		regs[regno].type = PTR_TO_MEM | flag;
2864 		regs[regno].mem_size = 0;
2865 		return 0;
2866 	default:
2867 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2868 		return -EFAULT;
2869 	}
2870 }
2871 
2872 #define DEF_NOT_SUBREG	(0)
2873 static void init_reg_state(struct bpf_verifier_env *env,
2874 			   struct bpf_func_state *state)
2875 {
2876 	struct bpf_reg_state *regs = state->regs;
2877 	int i;
2878 
2879 	for (i = 0; i < MAX_BPF_REG; i++) {
2880 		mark_reg_not_init(env, regs, i);
2881 		regs[i].live = REG_LIVE_NONE;
2882 		regs[i].parent = NULL;
2883 		regs[i].subreg_def = DEF_NOT_SUBREG;
2884 	}
2885 
2886 	/* frame pointer */
2887 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2888 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2889 	regs[BPF_REG_FP].frameno = state->frameno;
2890 }
2891 
2892 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2893 {
2894 	return (struct bpf_retval_range){ minval, maxval };
2895 }
2896 
2897 #define BPF_MAIN_FUNC (-1)
2898 static void init_func_state(struct bpf_verifier_env *env,
2899 			    struct bpf_func_state *state,
2900 			    int callsite, int frameno, int subprogno)
2901 {
2902 	state->callsite = callsite;
2903 	state->frameno = frameno;
2904 	state->subprogno = subprogno;
2905 	state->callback_ret_range = retval_range(0, 0);
2906 	init_reg_state(env, state);
2907 	mark_verifier_state_scratched(env);
2908 }
2909 
2910 /* Similar to push_stack(), but for async callbacks */
2911 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2912 						int insn_idx, int prev_insn_idx,
2913 						int subprog, bool is_sleepable)
2914 {
2915 	struct bpf_verifier_stack_elem *elem;
2916 	struct bpf_func_state *frame;
2917 
2918 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2919 	if (!elem)
2920 		return NULL;
2921 
2922 	elem->insn_idx = insn_idx;
2923 	elem->prev_insn_idx = prev_insn_idx;
2924 	elem->next = env->head;
2925 	elem->log_pos = env->log.end_pos;
2926 	env->head = elem;
2927 	env->stack_size++;
2928 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2929 		verbose(env,
2930 			"The sequence of %d jumps is too complex for async cb.\n",
2931 			env->stack_size);
2932 		return NULL;
2933 	}
2934 	/* Unlike push_stack() do not copy_verifier_state().
2935 	 * The caller state doesn't matter.
2936 	 * This is async callback. It starts in a fresh stack.
2937 	 * Initialize it similar to do_check_common().
2938 	 */
2939 	elem->st.branches = 1;
2940 	elem->st.in_sleepable = is_sleepable;
2941 	frame = kzalloc(sizeof(*frame), GFP_KERNEL_ACCOUNT);
2942 	if (!frame)
2943 		return NULL;
2944 	init_func_state(env, frame,
2945 			BPF_MAIN_FUNC /* callsite */,
2946 			0 /* frameno within this callchain */,
2947 			subprog /* subprog number within this prog */);
2948 	elem->st.frame[0] = frame;
2949 	return &elem->st;
2950 }
2951 
2952 
2953 enum reg_arg_type {
2954 	SRC_OP,		/* register is used as source operand */
2955 	DST_OP,		/* register is used as destination operand */
2956 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2957 };
2958 
2959 static int cmp_subprogs(const void *a, const void *b)
2960 {
2961 	return ((struct bpf_subprog_info *)a)->start -
2962 	       ((struct bpf_subprog_info *)b)->start;
2963 }
2964 
2965 /* Find subprogram that contains instruction at 'off' */
2966 static struct bpf_subprog_info *find_containing_subprog(struct bpf_verifier_env *env, int off)
2967 {
2968 	struct bpf_subprog_info *vals = env->subprog_info;
2969 	int l, r, m;
2970 
2971 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2972 		return NULL;
2973 
2974 	l = 0;
2975 	r = env->subprog_cnt - 1;
2976 	while (l < r) {
2977 		m = l + (r - l + 1) / 2;
2978 		if (vals[m].start <= off)
2979 			l = m;
2980 		else
2981 			r = m - 1;
2982 	}
2983 	return &vals[l];
2984 }
2985 
2986 /* Find subprogram that starts exactly at 'off' */
2987 static int find_subprog(struct bpf_verifier_env *env, int off)
2988 {
2989 	struct bpf_subprog_info *p;
2990 
2991 	p = find_containing_subprog(env, off);
2992 	if (!p || p->start != off)
2993 		return -ENOENT;
2994 	return p - env->subprog_info;
2995 }
2996 
2997 static int add_subprog(struct bpf_verifier_env *env, int off)
2998 {
2999 	int insn_cnt = env->prog->len;
3000 	int ret;
3001 
3002 	if (off >= insn_cnt || off < 0) {
3003 		verbose(env, "call to invalid destination\n");
3004 		return -EINVAL;
3005 	}
3006 	ret = find_subprog(env, off);
3007 	if (ret >= 0)
3008 		return ret;
3009 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
3010 		verbose(env, "too many subprograms\n");
3011 		return -E2BIG;
3012 	}
3013 	/* determine subprog starts. The end is one before the next starts */
3014 	env->subprog_info[env->subprog_cnt++].start = off;
3015 	sort(env->subprog_info, env->subprog_cnt,
3016 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
3017 	return env->subprog_cnt - 1;
3018 }
3019 
3020 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
3021 {
3022 	struct bpf_prog_aux *aux = env->prog->aux;
3023 	struct btf *btf = aux->btf;
3024 	const struct btf_type *t;
3025 	u32 main_btf_id, id;
3026 	const char *name;
3027 	int ret, i;
3028 
3029 	/* Non-zero func_info_cnt implies valid btf */
3030 	if (!aux->func_info_cnt)
3031 		return 0;
3032 	main_btf_id = aux->func_info[0].type_id;
3033 
3034 	t = btf_type_by_id(btf, main_btf_id);
3035 	if (!t) {
3036 		verbose(env, "invalid btf id for main subprog in func_info\n");
3037 		return -EINVAL;
3038 	}
3039 
3040 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
3041 	if (IS_ERR(name)) {
3042 		ret = PTR_ERR(name);
3043 		/* If there is no tag present, there is no exception callback */
3044 		if (ret == -ENOENT)
3045 			ret = 0;
3046 		else if (ret == -EEXIST)
3047 			verbose(env, "multiple exception callback tags for main subprog\n");
3048 		return ret;
3049 	}
3050 
3051 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
3052 	if (ret < 0) {
3053 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
3054 		return ret;
3055 	}
3056 	id = ret;
3057 	t = btf_type_by_id(btf, id);
3058 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3059 		verbose(env, "exception callback '%s' must have global linkage\n", name);
3060 		return -EINVAL;
3061 	}
3062 	ret = 0;
3063 	for (i = 0; i < aux->func_info_cnt; i++) {
3064 		if (aux->func_info[i].type_id != id)
3065 			continue;
3066 		ret = aux->func_info[i].insn_off;
3067 		/* Further func_info and subprog checks will also happen
3068 		 * later, so assume this is the right insn_off for now.
3069 		 */
3070 		if (!ret) {
3071 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
3072 			ret = -EINVAL;
3073 		}
3074 	}
3075 	if (!ret) {
3076 		verbose(env, "exception callback type id not found in func_info\n");
3077 		ret = -EINVAL;
3078 	}
3079 	return ret;
3080 }
3081 
3082 #define MAX_KFUNC_DESCS 256
3083 #define MAX_KFUNC_BTFS	256
3084 
3085 struct bpf_kfunc_desc {
3086 	struct btf_func_model func_model;
3087 	u32 func_id;
3088 	s32 imm;
3089 	u16 offset;
3090 	unsigned long addr;
3091 };
3092 
3093 struct bpf_kfunc_btf {
3094 	struct btf *btf;
3095 	struct module *module;
3096 	u16 offset;
3097 };
3098 
3099 struct bpf_kfunc_desc_tab {
3100 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
3101 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
3102 	 * available, therefore at the end of verification do_misc_fixups()
3103 	 * sorts this by imm and offset.
3104 	 */
3105 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
3106 	u32 nr_descs;
3107 };
3108 
3109 struct bpf_kfunc_btf_tab {
3110 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
3111 	u32 nr_descs;
3112 };
3113 
3114 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
3115 {
3116 	const struct bpf_kfunc_desc *d0 = a;
3117 	const struct bpf_kfunc_desc *d1 = b;
3118 
3119 	/* func_id is not greater than BTF_MAX_TYPE */
3120 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
3121 }
3122 
3123 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
3124 {
3125 	const struct bpf_kfunc_btf *d0 = a;
3126 	const struct bpf_kfunc_btf *d1 = b;
3127 
3128 	return d0->offset - d1->offset;
3129 }
3130 
3131 static const struct bpf_kfunc_desc *
3132 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
3133 {
3134 	struct bpf_kfunc_desc desc = {
3135 		.func_id = func_id,
3136 		.offset = offset,
3137 	};
3138 	struct bpf_kfunc_desc_tab *tab;
3139 
3140 	tab = prog->aux->kfunc_tab;
3141 	return bsearch(&desc, tab->descs, tab->nr_descs,
3142 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
3143 }
3144 
3145 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3146 		       u16 btf_fd_idx, u8 **func_addr)
3147 {
3148 	const struct bpf_kfunc_desc *desc;
3149 
3150 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
3151 	if (!desc)
3152 		return -EFAULT;
3153 
3154 	*func_addr = (u8 *)desc->addr;
3155 	return 0;
3156 }
3157 
3158 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
3159 					 s16 offset)
3160 {
3161 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
3162 	struct bpf_kfunc_btf_tab *tab;
3163 	struct bpf_kfunc_btf *b;
3164 	struct module *mod;
3165 	struct btf *btf;
3166 	int btf_fd;
3167 
3168 	tab = env->prog->aux->kfunc_btf_tab;
3169 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
3170 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
3171 	if (!b) {
3172 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
3173 			verbose(env, "too many different module BTFs\n");
3174 			return ERR_PTR(-E2BIG);
3175 		}
3176 
3177 		if (bpfptr_is_null(env->fd_array)) {
3178 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
3179 			return ERR_PTR(-EPROTO);
3180 		}
3181 
3182 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
3183 					    offset * sizeof(btf_fd),
3184 					    sizeof(btf_fd)))
3185 			return ERR_PTR(-EFAULT);
3186 
3187 		btf = btf_get_by_fd(btf_fd);
3188 		if (IS_ERR(btf)) {
3189 			verbose(env, "invalid module BTF fd specified\n");
3190 			return btf;
3191 		}
3192 
3193 		if (!btf_is_module(btf)) {
3194 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
3195 			btf_put(btf);
3196 			return ERR_PTR(-EINVAL);
3197 		}
3198 
3199 		mod = btf_try_get_module(btf);
3200 		if (!mod) {
3201 			btf_put(btf);
3202 			return ERR_PTR(-ENXIO);
3203 		}
3204 
3205 		b = &tab->descs[tab->nr_descs++];
3206 		b->btf = btf;
3207 		b->module = mod;
3208 		b->offset = offset;
3209 
3210 		/* sort() reorders entries by value, so b may no longer point
3211 		 * to the right entry after this
3212 		 */
3213 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3214 		     kfunc_btf_cmp_by_off, NULL);
3215 	} else {
3216 		btf = b->btf;
3217 	}
3218 
3219 	return btf;
3220 }
3221 
3222 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
3223 {
3224 	if (!tab)
3225 		return;
3226 
3227 	while (tab->nr_descs--) {
3228 		module_put(tab->descs[tab->nr_descs].module);
3229 		btf_put(tab->descs[tab->nr_descs].btf);
3230 	}
3231 	kfree(tab);
3232 }
3233 
3234 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
3235 {
3236 	if (offset) {
3237 		if (offset < 0) {
3238 			/* In the future, this can be allowed to increase limit
3239 			 * of fd index into fd_array, interpreted as u16.
3240 			 */
3241 			verbose(env, "negative offset disallowed for kernel module function call\n");
3242 			return ERR_PTR(-EINVAL);
3243 		}
3244 
3245 		return __find_kfunc_desc_btf(env, offset);
3246 	}
3247 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
3248 }
3249 
3250 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
3251 {
3252 	const struct btf_type *func, *func_proto;
3253 	struct bpf_kfunc_btf_tab *btf_tab;
3254 	struct bpf_kfunc_desc_tab *tab;
3255 	struct bpf_prog_aux *prog_aux;
3256 	struct bpf_kfunc_desc *desc;
3257 	const char *func_name;
3258 	struct btf *desc_btf;
3259 	unsigned long call_imm;
3260 	unsigned long addr;
3261 	int err;
3262 
3263 	prog_aux = env->prog->aux;
3264 	tab = prog_aux->kfunc_tab;
3265 	btf_tab = prog_aux->kfunc_btf_tab;
3266 	if (!tab) {
3267 		if (!btf_vmlinux) {
3268 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3269 			return -ENOTSUPP;
3270 		}
3271 
3272 		if (!env->prog->jit_requested) {
3273 			verbose(env, "JIT is required for calling kernel function\n");
3274 			return -ENOTSUPP;
3275 		}
3276 
3277 		if (!bpf_jit_supports_kfunc_call()) {
3278 			verbose(env, "JIT does not support calling kernel function\n");
3279 			return -ENOTSUPP;
3280 		}
3281 
3282 		if (!env->prog->gpl_compatible) {
3283 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3284 			return -EINVAL;
3285 		}
3286 
3287 		tab = kzalloc(sizeof(*tab), GFP_KERNEL_ACCOUNT);
3288 		if (!tab)
3289 			return -ENOMEM;
3290 		prog_aux->kfunc_tab = tab;
3291 	}
3292 
3293 	/* func_id == 0 is always invalid, but instead of returning an error, be
3294 	 * conservative and wait until the code elimination pass before returning
3295 	 * error, so that invalid calls that get pruned out can be in BPF programs
3296 	 * loaded from userspace.  It is also required that offset be untouched
3297 	 * for such calls.
3298 	 */
3299 	if (!func_id && !offset)
3300 		return 0;
3301 
3302 	if (!btf_tab && offset) {
3303 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL_ACCOUNT);
3304 		if (!btf_tab)
3305 			return -ENOMEM;
3306 		prog_aux->kfunc_btf_tab = btf_tab;
3307 	}
3308 
3309 	desc_btf = find_kfunc_desc_btf(env, offset);
3310 	if (IS_ERR(desc_btf)) {
3311 		verbose(env, "failed to find BTF for kernel function\n");
3312 		return PTR_ERR(desc_btf);
3313 	}
3314 
3315 	if (find_kfunc_desc(env->prog, func_id, offset))
3316 		return 0;
3317 
3318 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
3319 		verbose(env, "too many different kernel function calls\n");
3320 		return -E2BIG;
3321 	}
3322 
3323 	func = btf_type_by_id(desc_btf, func_id);
3324 	if (!func || !btf_type_is_func(func)) {
3325 		verbose(env, "kernel btf_id %u is not a function\n",
3326 			func_id);
3327 		return -EINVAL;
3328 	}
3329 	func_proto = btf_type_by_id(desc_btf, func->type);
3330 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3331 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
3332 			func_id);
3333 		return -EINVAL;
3334 	}
3335 
3336 	func_name = btf_name_by_offset(desc_btf, func->name_off);
3337 	addr = kallsyms_lookup_name(func_name);
3338 	if (!addr) {
3339 		verbose(env, "cannot find address for kernel function %s\n",
3340 			func_name);
3341 		return -EINVAL;
3342 	}
3343 	specialize_kfunc(env, func_id, offset, &addr);
3344 
3345 	if (bpf_jit_supports_far_kfunc_call()) {
3346 		call_imm = func_id;
3347 	} else {
3348 		call_imm = BPF_CALL_IMM(addr);
3349 		/* Check whether the relative offset overflows desc->imm */
3350 		if ((unsigned long)(s32)call_imm != call_imm) {
3351 			verbose(env, "address of kernel function %s is out of range\n",
3352 				func_name);
3353 			return -EINVAL;
3354 		}
3355 	}
3356 
3357 	if (bpf_dev_bound_kfunc_id(func_id)) {
3358 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3359 		if (err)
3360 			return err;
3361 	}
3362 
3363 	desc = &tab->descs[tab->nr_descs++];
3364 	desc->func_id = func_id;
3365 	desc->imm = call_imm;
3366 	desc->offset = offset;
3367 	desc->addr = addr;
3368 	err = btf_distill_func_proto(&env->log, desc_btf,
3369 				     func_proto, func_name,
3370 				     &desc->func_model);
3371 	if (!err)
3372 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3373 		     kfunc_desc_cmp_by_id_off, NULL);
3374 	return err;
3375 }
3376 
3377 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3378 {
3379 	const struct bpf_kfunc_desc *d0 = a;
3380 	const struct bpf_kfunc_desc *d1 = b;
3381 
3382 	if (d0->imm != d1->imm)
3383 		return d0->imm < d1->imm ? -1 : 1;
3384 	if (d0->offset != d1->offset)
3385 		return d0->offset < d1->offset ? -1 : 1;
3386 	return 0;
3387 }
3388 
3389 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
3390 {
3391 	struct bpf_kfunc_desc_tab *tab;
3392 
3393 	tab = prog->aux->kfunc_tab;
3394 	if (!tab)
3395 		return;
3396 
3397 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3398 	     kfunc_desc_cmp_by_imm_off, NULL);
3399 }
3400 
3401 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3402 {
3403 	return !!prog->aux->kfunc_tab;
3404 }
3405 
3406 const struct btf_func_model *
3407 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3408 			 const struct bpf_insn *insn)
3409 {
3410 	const struct bpf_kfunc_desc desc = {
3411 		.imm = insn->imm,
3412 		.offset = insn->off,
3413 	};
3414 	const struct bpf_kfunc_desc *res;
3415 	struct bpf_kfunc_desc_tab *tab;
3416 
3417 	tab = prog->aux->kfunc_tab;
3418 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3419 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3420 
3421 	return res ? &res->func_model : NULL;
3422 }
3423 
3424 static int add_kfunc_in_insns(struct bpf_verifier_env *env,
3425 			      struct bpf_insn *insn, int cnt)
3426 {
3427 	int i, ret;
3428 
3429 	for (i = 0; i < cnt; i++, insn++) {
3430 		if (bpf_pseudo_kfunc_call(insn)) {
3431 			ret = add_kfunc_call(env, insn->imm, insn->off);
3432 			if (ret < 0)
3433 				return ret;
3434 		}
3435 	}
3436 	return 0;
3437 }
3438 
3439 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3440 {
3441 	struct bpf_subprog_info *subprog = env->subprog_info;
3442 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3443 	struct bpf_insn *insn = env->prog->insnsi;
3444 
3445 	/* Add entry function. */
3446 	ret = add_subprog(env, 0);
3447 	if (ret)
3448 		return ret;
3449 
3450 	for (i = 0; i < insn_cnt; i++, insn++) {
3451 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3452 		    !bpf_pseudo_kfunc_call(insn))
3453 			continue;
3454 
3455 		if (!env->bpf_capable) {
3456 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3457 			return -EPERM;
3458 		}
3459 
3460 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3461 			ret = add_subprog(env, i + insn->imm + 1);
3462 		else
3463 			ret = add_kfunc_call(env, insn->imm, insn->off);
3464 
3465 		if (ret < 0)
3466 			return ret;
3467 	}
3468 
3469 	ret = bpf_find_exception_callback_insn_off(env);
3470 	if (ret < 0)
3471 		return ret;
3472 	ex_cb_insn = ret;
3473 
3474 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3475 	 * marked using BTF decl tag to serve as the exception callback.
3476 	 */
3477 	if (ex_cb_insn) {
3478 		ret = add_subprog(env, ex_cb_insn);
3479 		if (ret < 0)
3480 			return ret;
3481 		for (i = 1; i < env->subprog_cnt; i++) {
3482 			if (env->subprog_info[i].start != ex_cb_insn)
3483 				continue;
3484 			env->exception_callback_subprog = i;
3485 			mark_subprog_exc_cb(env, i);
3486 			break;
3487 		}
3488 	}
3489 
3490 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3491 	 * logic. 'subprog_cnt' should not be increased.
3492 	 */
3493 	subprog[env->subprog_cnt].start = insn_cnt;
3494 
3495 	if (env->log.level & BPF_LOG_LEVEL2)
3496 		for (i = 0; i < env->subprog_cnt; i++)
3497 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3498 
3499 	return 0;
3500 }
3501 
3502 static int jmp_offset(struct bpf_insn *insn)
3503 {
3504 	u8 code = insn->code;
3505 
3506 	if (code == (BPF_JMP32 | BPF_JA))
3507 		return insn->imm;
3508 	return insn->off;
3509 }
3510 
3511 static int check_subprogs(struct bpf_verifier_env *env)
3512 {
3513 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3514 	struct bpf_subprog_info *subprog = env->subprog_info;
3515 	struct bpf_insn *insn = env->prog->insnsi;
3516 	int insn_cnt = env->prog->len;
3517 
3518 	/* now check that all jumps are within the same subprog */
3519 	subprog_start = subprog[cur_subprog].start;
3520 	subprog_end = subprog[cur_subprog + 1].start;
3521 	for (i = 0; i < insn_cnt; i++) {
3522 		u8 code = insn[i].code;
3523 
3524 		if (code == (BPF_JMP | BPF_CALL) &&
3525 		    insn[i].src_reg == 0 &&
3526 		    insn[i].imm == BPF_FUNC_tail_call) {
3527 			subprog[cur_subprog].has_tail_call = true;
3528 			subprog[cur_subprog].tail_call_reachable = true;
3529 		}
3530 		if (BPF_CLASS(code) == BPF_LD &&
3531 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3532 			subprog[cur_subprog].has_ld_abs = true;
3533 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3534 			goto next;
3535 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3536 			goto next;
3537 		off = i + jmp_offset(&insn[i]) + 1;
3538 		if (off < subprog_start || off >= subprog_end) {
3539 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3540 			return -EINVAL;
3541 		}
3542 next:
3543 		if (i == subprog_end - 1) {
3544 			/* to avoid fall-through from one subprog into another
3545 			 * the last insn of the subprog should be either exit
3546 			 * or unconditional jump back or bpf_throw call
3547 			 */
3548 			if (code != (BPF_JMP | BPF_EXIT) &&
3549 			    code != (BPF_JMP32 | BPF_JA) &&
3550 			    code != (BPF_JMP | BPF_JA)) {
3551 				verbose(env, "last insn is not an exit or jmp\n");
3552 				return -EINVAL;
3553 			}
3554 			subprog_start = subprog_end;
3555 			cur_subprog++;
3556 			if (cur_subprog < env->subprog_cnt)
3557 				subprog_end = subprog[cur_subprog + 1].start;
3558 		}
3559 	}
3560 	return 0;
3561 }
3562 
3563 /* Parentage chain of this register (or stack slot) should take care of all
3564  * issues like callee-saved registers, stack slot allocation time, etc.
3565  */
3566 static int mark_reg_read(struct bpf_verifier_env *env,
3567 			 const struct bpf_reg_state *state,
3568 			 struct bpf_reg_state *parent, u8 flag)
3569 {
3570 	bool writes = parent == state->parent; /* Observe write marks */
3571 	int cnt = 0;
3572 
3573 	while (parent) {
3574 		/* if read wasn't screened by an earlier write ... */
3575 		if (writes && state->live & REG_LIVE_WRITTEN)
3576 			break;
3577 		if (verifier_bug_if(parent->live & REG_LIVE_DONE, env,
3578 				    "type %s var_off %lld off %d",
3579 				    reg_type_str(env, parent->type),
3580 				    parent->var_off.value, parent->off))
3581 			return -EFAULT;
3582 		/* The first condition is more likely to be true than the
3583 		 * second, checked it first.
3584 		 */
3585 		if ((parent->live & REG_LIVE_READ) == flag ||
3586 		    parent->live & REG_LIVE_READ64)
3587 			/* The parentage chain never changes and
3588 			 * this parent was already marked as LIVE_READ.
3589 			 * There is no need to keep walking the chain again and
3590 			 * keep re-marking all parents as LIVE_READ.
3591 			 * This case happens when the same register is read
3592 			 * multiple times without writes into it in-between.
3593 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3594 			 * then no need to set the weak REG_LIVE_READ32.
3595 			 */
3596 			break;
3597 		/* ... then we depend on parent's value */
3598 		parent->live |= flag;
3599 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3600 		if (flag == REG_LIVE_READ64)
3601 			parent->live &= ~REG_LIVE_READ32;
3602 		state = parent;
3603 		parent = state->parent;
3604 		writes = true;
3605 		cnt++;
3606 	}
3607 
3608 	if (env->longest_mark_read_walk < cnt)
3609 		env->longest_mark_read_walk = cnt;
3610 	return 0;
3611 }
3612 
3613 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3614 				    int spi, int nr_slots)
3615 {
3616 	struct bpf_func_state *state = func(env, reg);
3617 	int err, i;
3618 
3619 	for (i = 0; i < nr_slots; i++) {
3620 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3621 
3622 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3623 		if (err)
3624 			return err;
3625 
3626 		mark_stack_slot_scratched(env, spi - i);
3627 	}
3628 	return 0;
3629 }
3630 
3631 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3632 {
3633 	int spi;
3634 
3635 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3636 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3637 	 * check_kfunc_call.
3638 	 */
3639 	if (reg->type == CONST_PTR_TO_DYNPTR)
3640 		return 0;
3641 	spi = dynptr_get_spi(env, reg);
3642 	if (spi < 0)
3643 		return spi;
3644 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3645 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3646 	 * read.
3647 	 */
3648 	return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS);
3649 }
3650 
3651 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3652 			  int spi, int nr_slots)
3653 {
3654 	return mark_stack_slot_obj_read(env, reg, spi, nr_slots);
3655 }
3656 
3657 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3658 {
3659 	int spi;
3660 
3661 	spi = irq_flag_get_spi(env, reg);
3662 	if (spi < 0)
3663 		return spi;
3664 	return mark_stack_slot_obj_read(env, reg, spi, 1);
3665 }
3666 
3667 /* This function is supposed to be used by the following 32-bit optimization
3668  * code only. It returns TRUE if the source or destination register operates
3669  * on 64-bit, otherwise return FALSE.
3670  */
3671 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3672 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3673 {
3674 	u8 code, class, op;
3675 
3676 	code = insn->code;
3677 	class = BPF_CLASS(code);
3678 	op = BPF_OP(code);
3679 	if (class == BPF_JMP) {
3680 		/* BPF_EXIT for "main" will reach here. Return TRUE
3681 		 * conservatively.
3682 		 */
3683 		if (op == BPF_EXIT)
3684 			return true;
3685 		if (op == BPF_CALL) {
3686 			/* BPF to BPF call will reach here because of marking
3687 			 * caller saved clobber with DST_OP_NO_MARK for which we
3688 			 * don't care the register def because they are anyway
3689 			 * marked as NOT_INIT already.
3690 			 */
3691 			if (insn->src_reg == BPF_PSEUDO_CALL)
3692 				return false;
3693 			/* Helper call will reach here because of arg type
3694 			 * check, conservatively return TRUE.
3695 			 */
3696 			if (t == SRC_OP)
3697 				return true;
3698 
3699 			return false;
3700 		}
3701 	}
3702 
3703 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3704 		return false;
3705 
3706 	if (class == BPF_ALU64 || class == BPF_JMP ||
3707 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3708 		return true;
3709 
3710 	if (class == BPF_ALU || class == BPF_JMP32)
3711 		return false;
3712 
3713 	if (class == BPF_LDX) {
3714 		if (t != SRC_OP)
3715 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3716 		/* LDX source must be ptr. */
3717 		return true;
3718 	}
3719 
3720 	if (class == BPF_STX) {
3721 		/* BPF_STX (including atomic variants) has one or more source
3722 		 * operands, one of which is a ptr. Check whether the caller is
3723 		 * asking about it.
3724 		 */
3725 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3726 			return true;
3727 		return BPF_SIZE(code) == BPF_DW;
3728 	}
3729 
3730 	if (class == BPF_LD) {
3731 		u8 mode = BPF_MODE(code);
3732 
3733 		/* LD_IMM64 */
3734 		if (mode == BPF_IMM)
3735 			return true;
3736 
3737 		/* Both LD_IND and LD_ABS return 32-bit data. */
3738 		if (t != SRC_OP)
3739 			return  false;
3740 
3741 		/* Implicit ctx ptr. */
3742 		if (regno == BPF_REG_6)
3743 			return true;
3744 
3745 		/* Explicit source could be any width. */
3746 		return true;
3747 	}
3748 
3749 	if (class == BPF_ST)
3750 		/* The only source register for BPF_ST is a ptr. */
3751 		return true;
3752 
3753 	/* Conservatively return true at default. */
3754 	return true;
3755 }
3756 
3757 /* Return the regno defined by the insn, or -1. */
3758 static int insn_def_regno(const struct bpf_insn *insn)
3759 {
3760 	switch (BPF_CLASS(insn->code)) {
3761 	case BPF_JMP:
3762 	case BPF_JMP32:
3763 	case BPF_ST:
3764 		return -1;
3765 	case BPF_STX:
3766 		if (BPF_MODE(insn->code) == BPF_ATOMIC ||
3767 		    BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) {
3768 			if (insn->imm == BPF_CMPXCHG)
3769 				return BPF_REG_0;
3770 			else if (insn->imm == BPF_LOAD_ACQ)
3771 				return insn->dst_reg;
3772 			else if (insn->imm & BPF_FETCH)
3773 				return insn->src_reg;
3774 		}
3775 		return -1;
3776 	default:
3777 		return insn->dst_reg;
3778 	}
3779 }
3780 
3781 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3782 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3783 {
3784 	int dst_reg = insn_def_regno(insn);
3785 
3786 	if (dst_reg == -1)
3787 		return false;
3788 
3789 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3790 }
3791 
3792 static void mark_insn_zext(struct bpf_verifier_env *env,
3793 			   struct bpf_reg_state *reg)
3794 {
3795 	s32 def_idx = reg->subreg_def;
3796 
3797 	if (def_idx == DEF_NOT_SUBREG)
3798 		return;
3799 
3800 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3801 	/* The dst will be zero extended, so won't be sub-register anymore. */
3802 	reg->subreg_def = DEF_NOT_SUBREG;
3803 }
3804 
3805 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3806 			   enum reg_arg_type t)
3807 {
3808 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3809 	struct bpf_reg_state *reg;
3810 	bool rw64;
3811 
3812 	if (regno >= MAX_BPF_REG) {
3813 		verbose(env, "R%d is invalid\n", regno);
3814 		return -EINVAL;
3815 	}
3816 
3817 	mark_reg_scratched(env, regno);
3818 
3819 	reg = &regs[regno];
3820 	rw64 = is_reg64(env, insn, regno, reg, t);
3821 	if (t == SRC_OP) {
3822 		/* check whether register used as source operand can be read */
3823 		if (reg->type == NOT_INIT) {
3824 			verbose(env, "R%d !read_ok\n", regno);
3825 			return -EACCES;
3826 		}
3827 		/* We don't need to worry about FP liveness because it's read-only */
3828 		if (regno == BPF_REG_FP)
3829 			return 0;
3830 
3831 		if (rw64)
3832 			mark_insn_zext(env, reg);
3833 
3834 		return mark_reg_read(env, reg, reg->parent,
3835 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3836 	} else {
3837 		/* check whether register used as dest operand can be written to */
3838 		if (regno == BPF_REG_FP) {
3839 			verbose(env, "frame pointer is read only\n");
3840 			return -EACCES;
3841 		}
3842 		reg->live |= REG_LIVE_WRITTEN;
3843 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3844 		if (t == DST_OP)
3845 			mark_reg_unknown(env, regs, regno);
3846 	}
3847 	return 0;
3848 }
3849 
3850 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3851 			 enum reg_arg_type t)
3852 {
3853 	struct bpf_verifier_state *vstate = env->cur_state;
3854 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3855 
3856 	return __check_reg_arg(env, state->regs, regno, t);
3857 }
3858 
3859 static int insn_stack_access_flags(int frameno, int spi)
3860 {
3861 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3862 }
3863 
3864 static int insn_stack_access_spi(int insn_flags)
3865 {
3866 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3867 }
3868 
3869 static int insn_stack_access_frameno(int insn_flags)
3870 {
3871 	return insn_flags & INSN_F_FRAMENO_MASK;
3872 }
3873 
3874 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3875 {
3876 	env->insn_aux_data[idx].jmp_point = true;
3877 }
3878 
3879 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3880 {
3881 	return env->insn_aux_data[insn_idx].jmp_point;
3882 }
3883 
3884 #define LR_FRAMENO_BITS	3
3885 #define LR_SPI_BITS	6
3886 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3887 #define LR_SIZE_BITS	4
3888 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3889 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3890 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3891 #define LR_SPI_OFF	LR_FRAMENO_BITS
3892 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3893 #define LINKED_REGS_MAX	6
3894 
3895 struct linked_reg {
3896 	u8 frameno;
3897 	union {
3898 		u8 spi;
3899 		u8 regno;
3900 	};
3901 	bool is_reg;
3902 };
3903 
3904 struct linked_regs {
3905 	int cnt;
3906 	struct linked_reg entries[LINKED_REGS_MAX];
3907 };
3908 
3909 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3910 {
3911 	if (s->cnt < LINKED_REGS_MAX)
3912 		return &s->entries[s->cnt++];
3913 
3914 	return NULL;
3915 }
3916 
3917 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3918  * number of elements currently in stack.
3919  * Pack one history entry for linked registers as 10 bits in the following format:
3920  * - 3-bits frameno
3921  * - 6-bits spi_or_reg
3922  * - 1-bit  is_reg
3923  */
3924 static u64 linked_regs_pack(struct linked_regs *s)
3925 {
3926 	u64 val = 0;
3927 	int i;
3928 
3929 	for (i = 0; i < s->cnt; ++i) {
3930 		struct linked_reg *e = &s->entries[i];
3931 		u64 tmp = 0;
3932 
3933 		tmp |= e->frameno;
3934 		tmp |= e->spi << LR_SPI_OFF;
3935 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3936 
3937 		val <<= LR_ENTRY_BITS;
3938 		val |= tmp;
3939 	}
3940 	val <<= LR_SIZE_BITS;
3941 	val |= s->cnt;
3942 	return val;
3943 }
3944 
3945 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3946 {
3947 	int i;
3948 
3949 	s->cnt = val & LR_SIZE_MASK;
3950 	val >>= LR_SIZE_BITS;
3951 
3952 	for (i = 0; i < s->cnt; ++i) {
3953 		struct linked_reg *e = &s->entries[i];
3954 
3955 		e->frameno =  val & LR_FRAMENO_MASK;
3956 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3957 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3958 		val >>= LR_ENTRY_BITS;
3959 	}
3960 }
3961 
3962 /* for any branch, call, exit record the history of jmps in the given state */
3963 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3964 			    int insn_flags, u64 linked_regs)
3965 {
3966 	u32 cnt = cur->jmp_history_cnt;
3967 	struct bpf_jmp_history_entry *p;
3968 	size_t alloc_size;
3969 
3970 	/* combine instruction flags if we already recorded this instruction */
3971 	if (env->cur_hist_ent) {
3972 		/* atomic instructions push insn_flags twice, for READ and
3973 		 * WRITE sides, but they should agree on stack slot
3974 		 */
3975 		verifier_bug_if((env->cur_hist_ent->flags & insn_flags) &&
3976 				(env->cur_hist_ent->flags & insn_flags) != insn_flags,
3977 				env, "insn history: insn_idx %d cur flags %x new flags %x",
3978 				env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3979 		env->cur_hist_ent->flags |= insn_flags;
3980 		verifier_bug_if(env->cur_hist_ent->linked_regs != 0, env,
3981 				"insn history: insn_idx %d linked_regs: %#llx",
3982 				env->insn_idx, env->cur_hist_ent->linked_regs);
3983 		env->cur_hist_ent->linked_regs = linked_regs;
3984 		return 0;
3985 	}
3986 
3987 	cnt++;
3988 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3989 	p = krealloc(cur->jmp_history, alloc_size, GFP_KERNEL_ACCOUNT);
3990 	if (!p)
3991 		return -ENOMEM;
3992 	cur->jmp_history = p;
3993 
3994 	p = &cur->jmp_history[cnt - 1];
3995 	p->idx = env->insn_idx;
3996 	p->prev_idx = env->prev_insn_idx;
3997 	p->flags = insn_flags;
3998 	p->linked_regs = linked_regs;
3999 	cur->jmp_history_cnt = cnt;
4000 	env->cur_hist_ent = p;
4001 
4002 	return 0;
4003 }
4004 
4005 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
4006 						        u32 hist_end, int insn_idx)
4007 {
4008 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
4009 		return &st->jmp_history[hist_end - 1];
4010 	return NULL;
4011 }
4012 
4013 /* Backtrack one insn at a time. If idx is not at the top of recorded
4014  * history then previous instruction came from straight line execution.
4015  * Return -ENOENT if we exhausted all instructions within given state.
4016  *
4017  * It's legal to have a bit of a looping with the same starting and ending
4018  * insn index within the same state, e.g.: 3->4->5->3, so just because current
4019  * instruction index is the same as state's first_idx doesn't mean we are
4020  * done. If there is still some jump history left, we should keep going. We
4021  * need to take into account that we might have a jump history between given
4022  * state's parent and itself, due to checkpointing. In this case, we'll have
4023  * history entry recording a jump from last instruction of parent state and
4024  * first instruction of given state.
4025  */
4026 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
4027 			     u32 *history)
4028 {
4029 	u32 cnt = *history;
4030 
4031 	if (i == st->first_insn_idx) {
4032 		if (cnt == 0)
4033 			return -ENOENT;
4034 		if (cnt == 1 && st->jmp_history[0].idx == i)
4035 			return -ENOENT;
4036 	}
4037 
4038 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
4039 		i = st->jmp_history[cnt - 1].prev_idx;
4040 		(*history)--;
4041 	} else {
4042 		i--;
4043 	}
4044 	return i;
4045 }
4046 
4047 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
4048 {
4049 	const struct btf_type *func;
4050 	struct btf *desc_btf;
4051 
4052 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
4053 		return NULL;
4054 
4055 	desc_btf = find_kfunc_desc_btf(data, insn->off);
4056 	if (IS_ERR(desc_btf))
4057 		return "<error>";
4058 
4059 	func = btf_type_by_id(desc_btf, insn->imm);
4060 	return btf_name_by_offset(desc_btf, func->name_off);
4061 }
4062 
4063 static void verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
4064 {
4065 	const struct bpf_insn_cbs cbs = {
4066 		.cb_call	= disasm_kfunc_name,
4067 		.cb_print	= verbose,
4068 		.private_data	= env,
4069 	};
4070 
4071 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
4072 }
4073 
4074 static inline void bt_init(struct backtrack_state *bt, u32 frame)
4075 {
4076 	bt->frame = frame;
4077 }
4078 
4079 static inline void bt_reset(struct backtrack_state *bt)
4080 {
4081 	struct bpf_verifier_env *env = bt->env;
4082 
4083 	memset(bt, 0, sizeof(*bt));
4084 	bt->env = env;
4085 }
4086 
4087 static inline u32 bt_empty(struct backtrack_state *bt)
4088 {
4089 	u64 mask = 0;
4090 	int i;
4091 
4092 	for (i = 0; i <= bt->frame; i++)
4093 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
4094 
4095 	return mask == 0;
4096 }
4097 
4098 static inline int bt_subprog_enter(struct backtrack_state *bt)
4099 {
4100 	if (bt->frame == MAX_CALL_FRAMES - 1) {
4101 		verifier_bug(bt->env, "subprog enter from frame %d", bt->frame);
4102 		return -EFAULT;
4103 	}
4104 	bt->frame++;
4105 	return 0;
4106 }
4107 
4108 static inline int bt_subprog_exit(struct backtrack_state *bt)
4109 {
4110 	if (bt->frame == 0) {
4111 		verifier_bug(bt->env, "subprog exit from frame 0");
4112 		return -EFAULT;
4113 	}
4114 	bt->frame--;
4115 	return 0;
4116 }
4117 
4118 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4119 {
4120 	bt->reg_masks[frame] |= 1 << reg;
4121 }
4122 
4123 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4124 {
4125 	bt->reg_masks[frame] &= ~(1 << reg);
4126 }
4127 
4128 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
4129 {
4130 	bt_set_frame_reg(bt, bt->frame, reg);
4131 }
4132 
4133 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
4134 {
4135 	bt_clear_frame_reg(bt, bt->frame, reg);
4136 }
4137 
4138 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4139 {
4140 	bt->stack_masks[frame] |= 1ull << slot;
4141 }
4142 
4143 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4144 {
4145 	bt->stack_masks[frame] &= ~(1ull << slot);
4146 }
4147 
4148 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
4149 {
4150 	return bt->reg_masks[frame];
4151 }
4152 
4153 static inline u32 bt_reg_mask(struct backtrack_state *bt)
4154 {
4155 	return bt->reg_masks[bt->frame];
4156 }
4157 
4158 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
4159 {
4160 	return bt->stack_masks[frame];
4161 }
4162 
4163 static inline u64 bt_stack_mask(struct backtrack_state *bt)
4164 {
4165 	return bt->stack_masks[bt->frame];
4166 }
4167 
4168 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
4169 {
4170 	return bt->reg_masks[bt->frame] & (1 << reg);
4171 }
4172 
4173 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
4174 {
4175 	return bt->reg_masks[frame] & (1 << reg);
4176 }
4177 
4178 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
4179 {
4180 	return bt->stack_masks[frame] & (1ull << slot);
4181 }
4182 
4183 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
4184 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
4185 {
4186 	DECLARE_BITMAP(mask, 64);
4187 	bool first = true;
4188 	int i, n;
4189 
4190 	buf[0] = '\0';
4191 
4192 	bitmap_from_u64(mask, reg_mask);
4193 	for_each_set_bit(i, mask, 32) {
4194 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
4195 		first = false;
4196 		buf += n;
4197 		buf_sz -= n;
4198 		if (buf_sz < 0)
4199 			break;
4200 	}
4201 }
4202 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
4203 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
4204 {
4205 	DECLARE_BITMAP(mask, 64);
4206 	bool first = true;
4207 	int i, n;
4208 
4209 	buf[0] = '\0';
4210 
4211 	bitmap_from_u64(mask, stack_mask);
4212 	for_each_set_bit(i, mask, 64) {
4213 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
4214 		first = false;
4215 		buf += n;
4216 		buf_sz -= n;
4217 		if (buf_sz < 0)
4218 			break;
4219 	}
4220 }
4221 
4222 /* If any register R in hist->linked_regs is marked as precise in bt,
4223  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
4224  */
4225 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
4226 {
4227 	struct linked_regs linked_regs;
4228 	bool some_precise = false;
4229 	int i;
4230 
4231 	if (!hist || hist->linked_regs == 0)
4232 		return;
4233 
4234 	linked_regs_unpack(hist->linked_regs, &linked_regs);
4235 	for (i = 0; i < linked_regs.cnt; ++i) {
4236 		struct linked_reg *e = &linked_regs.entries[i];
4237 
4238 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
4239 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
4240 			some_precise = true;
4241 			break;
4242 		}
4243 	}
4244 
4245 	if (!some_precise)
4246 		return;
4247 
4248 	for (i = 0; i < linked_regs.cnt; ++i) {
4249 		struct linked_reg *e = &linked_regs.entries[i];
4250 
4251 		if (e->is_reg)
4252 			bt_set_frame_reg(bt, e->frameno, e->regno);
4253 		else
4254 			bt_set_frame_slot(bt, e->frameno, e->spi);
4255 	}
4256 }
4257 
4258 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
4259 
4260 /* For given verifier state backtrack_insn() is called from the last insn to
4261  * the first insn. Its purpose is to compute a bitmask of registers and
4262  * stack slots that needs precision in the parent verifier state.
4263  *
4264  * @idx is an index of the instruction we are currently processing;
4265  * @subseq_idx is an index of the subsequent instruction that:
4266  *   - *would be* executed next, if jump history is viewed in forward order;
4267  *   - *was* processed previously during backtracking.
4268  */
4269 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
4270 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
4271 {
4272 	struct bpf_insn *insn = env->prog->insnsi + idx;
4273 	u8 class = BPF_CLASS(insn->code);
4274 	u8 opcode = BPF_OP(insn->code);
4275 	u8 mode = BPF_MODE(insn->code);
4276 	u32 dreg = insn->dst_reg;
4277 	u32 sreg = insn->src_reg;
4278 	u32 spi, i, fr;
4279 
4280 	if (insn->code == 0)
4281 		return 0;
4282 	if (env->log.level & BPF_LOG_LEVEL2) {
4283 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
4284 		verbose(env, "mark_precise: frame%d: regs=%s ",
4285 			bt->frame, env->tmp_str_buf);
4286 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
4287 		verbose(env, "stack=%s before ", env->tmp_str_buf);
4288 		verbose(env, "%d: ", idx);
4289 		verbose_insn(env, insn);
4290 	}
4291 
4292 	/* If there is a history record that some registers gained range at this insn,
4293 	 * propagate precision marks to those registers, so that bt_is_reg_set()
4294 	 * accounts for these registers.
4295 	 */
4296 	bt_sync_linked_regs(bt, hist);
4297 
4298 	if (class == BPF_ALU || class == BPF_ALU64) {
4299 		if (!bt_is_reg_set(bt, dreg))
4300 			return 0;
4301 		if (opcode == BPF_END || opcode == BPF_NEG) {
4302 			/* sreg is reserved and unused
4303 			 * dreg still need precision before this insn
4304 			 */
4305 			return 0;
4306 		} else if (opcode == BPF_MOV) {
4307 			if (BPF_SRC(insn->code) == BPF_X) {
4308 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
4309 				 * dreg needs precision after this insn
4310 				 * sreg needs precision before this insn
4311 				 */
4312 				bt_clear_reg(bt, dreg);
4313 				if (sreg != BPF_REG_FP)
4314 					bt_set_reg(bt, sreg);
4315 			} else {
4316 				/* dreg = K
4317 				 * dreg needs precision after this insn.
4318 				 * Corresponding register is already marked
4319 				 * as precise=true in this verifier state.
4320 				 * No further markings in parent are necessary
4321 				 */
4322 				bt_clear_reg(bt, dreg);
4323 			}
4324 		} else {
4325 			if (BPF_SRC(insn->code) == BPF_X) {
4326 				/* dreg += sreg
4327 				 * both dreg and sreg need precision
4328 				 * before this insn
4329 				 */
4330 				if (sreg != BPF_REG_FP)
4331 					bt_set_reg(bt, sreg);
4332 			} /* else dreg += K
4333 			   * dreg still needs precision before this insn
4334 			   */
4335 		}
4336 	} else if (class == BPF_LDX || is_atomic_load_insn(insn)) {
4337 		if (!bt_is_reg_set(bt, dreg))
4338 			return 0;
4339 		bt_clear_reg(bt, dreg);
4340 
4341 		/* scalars can only be spilled into stack w/o losing precision.
4342 		 * Load from any other memory can be zero extended.
4343 		 * The desire to keep that precision is already indicated
4344 		 * by 'precise' mark in corresponding register of this state.
4345 		 * No further tracking necessary.
4346 		 */
4347 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4348 			return 0;
4349 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
4350 		 * that [fp - off] slot contains scalar that needs to be
4351 		 * tracked with precision
4352 		 */
4353 		spi = insn_stack_access_spi(hist->flags);
4354 		fr = insn_stack_access_frameno(hist->flags);
4355 		bt_set_frame_slot(bt, fr, spi);
4356 	} else if (class == BPF_STX || class == BPF_ST) {
4357 		if (bt_is_reg_set(bt, dreg))
4358 			/* stx & st shouldn't be using _scalar_ dst_reg
4359 			 * to access memory. It means backtracking
4360 			 * encountered a case of pointer subtraction.
4361 			 */
4362 			return -ENOTSUPP;
4363 		/* scalars can only be spilled into stack */
4364 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4365 			return 0;
4366 		spi = insn_stack_access_spi(hist->flags);
4367 		fr = insn_stack_access_frameno(hist->flags);
4368 		if (!bt_is_frame_slot_set(bt, fr, spi))
4369 			return 0;
4370 		bt_clear_frame_slot(bt, fr, spi);
4371 		if (class == BPF_STX)
4372 			bt_set_reg(bt, sreg);
4373 	} else if (class == BPF_JMP || class == BPF_JMP32) {
4374 		if (bpf_pseudo_call(insn)) {
4375 			int subprog_insn_idx, subprog;
4376 
4377 			subprog_insn_idx = idx + insn->imm + 1;
4378 			subprog = find_subprog(env, subprog_insn_idx);
4379 			if (subprog < 0)
4380 				return -EFAULT;
4381 
4382 			if (subprog_is_global(env, subprog)) {
4383 				/* check that jump history doesn't have any
4384 				 * extra instructions from subprog; the next
4385 				 * instruction after call to global subprog
4386 				 * should be literally next instruction in
4387 				 * caller program
4388 				 */
4389 				verifier_bug_if(idx + 1 != subseq_idx, env,
4390 						"extra insn from subprog");
4391 				/* r1-r5 are invalidated after subprog call,
4392 				 * so for global func call it shouldn't be set
4393 				 * anymore
4394 				 */
4395 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4396 					verifier_bug(env, "global subprog unexpected regs %x",
4397 						     bt_reg_mask(bt));
4398 					return -EFAULT;
4399 				}
4400 				/* global subprog always sets R0 */
4401 				bt_clear_reg(bt, BPF_REG_0);
4402 				return 0;
4403 			} else {
4404 				/* static subprog call instruction, which
4405 				 * means that we are exiting current subprog,
4406 				 * so only r1-r5 could be still requested as
4407 				 * precise, r0 and r6-r10 or any stack slot in
4408 				 * the current frame should be zero by now
4409 				 */
4410 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4411 					verifier_bug(env, "static subprog unexpected regs %x",
4412 						     bt_reg_mask(bt));
4413 					return -EFAULT;
4414 				}
4415 				/* we are now tracking register spills correctly,
4416 				 * so any instance of leftover slots is a bug
4417 				 */
4418 				if (bt_stack_mask(bt) != 0) {
4419 					verifier_bug(env,
4420 						     "static subprog leftover stack slots %llx",
4421 						     bt_stack_mask(bt));
4422 					return -EFAULT;
4423 				}
4424 				/* propagate r1-r5 to the caller */
4425 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
4426 					if (bt_is_reg_set(bt, i)) {
4427 						bt_clear_reg(bt, i);
4428 						bt_set_frame_reg(bt, bt->frame - 1, i);
4429 					}
4430 				}
4431 				if (bt_subprog_exit(bt))
4432 					return -EFAULT;
4433 				return 0;
4434 			}
4435 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
4436 			/* exit from callback subprog to callback-calling helper or
4437 			 * kfunc call. Use idx/subseq_idx check to discern it from
4438 			 * straight line code backtracking.
4439 			 * Unlike the subprog call handling above, we shouldn't
4440 			 * propagate precision of r1-r5 (if any requested), as they are
4441 			 * not actually arguments passed directly to callback subprogs
4442 			 */
4443 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4444 				verifier_bug(env, "callback unexpected regs %x",
4445 					     bt_reg_mask(bt));
4446 				return -EFAULT;
4447 			}
4448 			if (bt_stack_mask(bt) != 0) {
4449 				verifier_bug(env, "callback leftover stack slots %llx",
4450 					     bt_stack_mask(bt));
4451 				return -EFAULT;
4452 			}
4453 			/* clear r1-r5 in callback subprog's mask */
4454 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4455 				bt_clear_reg(bt, i);
4456 			if (bt_subprog_exit(bt))
4457 				return -EFAULT;
4458 			return 0;
4459 		} else if (opcode == BPF_CALL) {
4460 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
4461 			 * catch this error later. Make backtracking conservative
4462 			 * with ENOTSUPP.
4463 			 */
4464 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
4465 				return -ENOTSUPP;
4466 			/* regular helper call sets R0 */
4467 			bt_clear_reg(bt, BPF_REG_0);
4468 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4469 				/* if backtracking was looking for registers R1-R5
4470 				 * they should have been found already.
4471 				 */
4472 				verifier_bug(env, "backtracking call unexpected regs %x",
4473 					     bt_reg_mask(bt));
4474 				return -EFAULT;
4475 			}
4476 		} else if (opcode == BPF_EXIT) {
4477 			bool r0_precise;
4478 
4479 			/* Backtracking to a nested function call, 'idx' is a part of
4480 			 * the inner frame 'subseq_idx' is a part of the outer frame.
4481 			 * In case of a regular function call, instructions giving
4482 			 * precision to registers R1-R5 should have been found already.
4483 			 * In case of a callback, it is ok to have R1-R5 marked for
4484 			 * backtracking, as these registers are set by the function
4485 			 * invoking callback.
4486 			 */
4487 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
4488 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4489 					bt_clear_reg(bt, i);
4490 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4491 				verifier_bug(env, "backtracking exit unexpected regs %x",
4492 					     bt_reg_mask(bt));
4493 				return -EFAULT;
4494 			}
4495 
4496 			/* BPF_EXIT in subprog or callback always returns
4497 			 * right after the call instruction, so by checking
4498 			 * whether the instruction at subseq_idx-1 is subprog
4499 			 * call or not we can distinguish actual exit from
4500 			 * *subprog* from exit from *callback*. In the former
4501 			 * case, we need to propagate r0 precision, if
4502 			 * necessary. In the former we never do that.
4503 			 */
4504 			r0_precise = subseq_idx - 1 >= 0 &&
4505 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4506 				     bt_is_reg_set(bt, BPF_REG_0);
4507 
4508 			bt_clear_reg(bt, BPF_REG_0);
4509 			if (bt_subprog_enter(bt))
4510 				return -EFAULT;
4511 
4512 			if (r0_precise)
4513 				bt_set_reg(bt, BPF_REG_0);
4514 			/* r6-r9 and stack slots will stay set in caller frame
4515 			 * bitmasks until we return back from callee(s)
4516 			 */
4517 			return 0;
4518 		} else if (BPF_SRC(insn->code) == BPF_X) {
4519 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4520 				return 0;
4521 			/* dreg <cond> sreg
4522 			 * Both dreg and sreg need precision before
4523 			 * this insn. If only sreg was marked precise
4524 			 * before it would be equally necessary to
4525 			 * propagate it to dreg.
4526 			 */
4527 			if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK))
4528 				bt_set_reg(bt, sreg);
4529 			if (!hist || !(hist->flags & INSN_F_DST_REG_STACK))
4530 				bt_set_reg(bt, dreg);
4531 		} else if (BPF_SRC(insn->code) == BPF_K) {
4532 			 /* dreg <cond> K
4533 			  * Only dreg still needs precision before
4534 			  * this insn, so for the K-based conditional
4535 			  * there is nothing new to be marked.
4536 			  */
4537 		}
4538 	} else if (class == BPF_LD) {
4539 		if (!bt_is_reg_set(bt, dreg))
4540 			return 0;
4541 		bt_clear_reg(bt, dreg);
4542 		/* It's ld_imm64 or ld_abs or ld_ind.
4543 		 * For ld_imm64 no further tracking of precision
4544 		 * into parent is necessary
4545 		 */
4546 		if (mode == BPF_IND || mode == BPF_ABS)
4547 			/* to be analyzed */
4548 			return -ENOTSUPP;
4549 	}
4550 	/* Propagate precision marks to linked registers, to account for
4551 	 * registers marked as precise in this function.
4552 	 */
4553 	bt_sync_linked_regs(bt, hist);
4554 	return 0;
4555 }
4556 
4557 /* the scalar precision tracking algorithm:
4558  * . at the start all registers have precise=false.
4559  * . scalar ranges are tracked as normal through alu and jmp insns.
4560  * . once precise value of the scalar register is used in:
4561  *   .  ptr + scalar alu
4562  *   . if (scalar cond K|scalar)
4563  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
4564  *   backtrack through the verifier states and mark all registers and
4565  *   stack slots with spilled constants that these scalar registers
4566  *   should be precise.
4567  * . during state pruning two registers (or spilled stack slots)
4568  *   are equivalent if both are not precise.
4569  *
4570  * Note the verifier cannot simply walk register parentage chain,
4571  * since many different registers and stack slots could have been
4572  * used to compute single precise scalar.
4573  *
4574  * The approach of starting with precise=true for all registers and then
4575  * backtrack to mark a register as not precise when the verifier detects
4576  * that program doesn't care about specific value (e.g., when helper
4577  * takes register as ARG_ANYTHING parameter) is not safe.
4578  *
4579  * It's ok to walk single parentage chain of the verifier states.
4580  * It's possible that this backtracking will go all the way till 1st insn.
4581  * All other branches will be explored for needing precision later.
4582  *
4583  * The backtracking needs to deal with cases like:
4584  *   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)
4585  * r9 -= r8
4586  * r5 = r9
4587  * if r5 > 0x79f goto pc+7
4588  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4589  * r5 += 1
4590  * ...
4591  * call bpf_perf_event_output#25
4592  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4593  *
4594  * and this case:
4595  * r6 = 1
4596  * call foo // uses callee's r6 inside to compute r0
4597  * r0 += r6
4598  * if r0 == 0 goto
4599  *
4600  * to track above reg_mask/stack_mask needs to be independent for each frame.
4601  *
4602  * Also if parent's curframe > frame where backtracking started,
4603  * the verifier need to mark registers in both frames, otherwise callees
4604  * may incorrectly prune callers. This is similar to
4605  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4606  *
4607  * For now backtracking falls back into conservative marking.
4608  */
4609 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4610 				     struct bpf_verifier_state *st)
4611 {
4612 	struct bpf_func_state *func;
4613 	struct bpf_reg_state *reg;
4614 	int i, j;
4615 
4616 	if (env->log.level & BPF_LOG_LEVEL2) {
4617 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4618 			st->curframe);
4619 	}
4620 
4621 	/* big hammer: mark all scalars precise in this path.
4622 	 * pop_stack may still get !precise scalars.
4623 	 * We also skip current state and go straight to first parent state,
4624 	 * because precision markings in current non-checkpointed state are
4625 	 * not needed. See why in the comment in __mark_chain_precision below.
4626 	 */
4627 	for (st = st->parent; st; st = st->parent) {
4628 		for (i = 0; i <= st->curframe; i++) {
4629 			func = st->frame[i];
4630 			for (j = 0; j < BPF_REG_FP; j++) {
4631 				reg = &func->regs[j];
4632 				if (reg->type != SCALAR_VALUE || reg->precise)
4633 					continue;
4634 				reg->precise = true;
4635 				if (env->log.level & BPF_LOG_LEVEL2) {
4636 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4637 						i, j);
4638 				}
4639 			}
4640 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4641 				if (!is_spilled_reg(&func->stack[j]))
4642 					continue;
4643 				reg = &func->stack[j].spilled_ptr;
4644 				if (reg->type != SCALAR_VALUE || reg->precise)
4645 					continue;
4646 				reg->precise = true;
4647 				if (env->log.level & BPF_LOG_LEVEL2) {
4648 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4649 						i, -(j + 1) * 8);
4650 				}
4651 			}
4652 		}
4653 	}
4654 }
4655 
4656 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4657 {
4658 	struct bpf_func_state *func;
4659 	struct bpf_reg_state *reg;
4660 	int i, j;
4661 
4662 	for (i = 0; i <= st->curframe; i++) {
4663 		func = st->frame[i];
4664 		for (j = 0; j < BPF_REG_FP; j++) {
4665 			reg = &func->regs[j];
4666 			if (reg->type != SCALAR_VALUE)
4667 				continue;
4668 			reg->precise = false;
4669 		}
4670 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4671 			if (!is_spilled_reg(&func->stack[j]))
4672 				continue;
4673 			reg = &func->stack[j].spilled_ptr;
4674 			if (reg->type != SCALAR_VALUE)
4675 				continue;
4676 			reg->precise = false;
4677 		}
4678 	}
4679 }
4680 
4681 /*
4682  * __mark_chain_precision() backtracks BPF program instruction sequence and
4683  * chain of verifier states making sure that register *regno* (if regno >= 0)
4684  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4685  * SCALARS, as well as any other registers and slots that contribute to
4686  * a tracked state of given registers/stack slots, depending on specific BPF
4687  * assembly instructions (see backtrack_insns() for exact instruction handling
4688  * logic). This backtracking relies on recorded jmp_history and is able to
4689  * traverse entire chain of parent states. This process ends only when all the
4690  * necessary registers/slots and their transitive dependencies are marked as
4691  * precise.
4692  *
4693  * One important and subtle aspect is that precise marks *do not matter* in
4694  * the currently verified state (current state). It is important to understand
4695  * why this is the case.
4696  *
4697  * First, note that current state is the state that is not yet "checkpointed",
4698  * i.e., it is not yet put into env->explored_states, and it has no children
4699  * states as well. It's ephemeral, and can end up either a) being discarded if
4700  * compatible explored state is found at some point or BPF_EXIT instruction is
4701  * reached or b) checkpointed and put into env->explored_states, branching out
4702  * into one or more children states.
4703  *
4704  * In the former case, precise markings in current state are completely
4705  * ignored by state comparison code (see regsafe() for details). Only
4706  * checkpointed ("old") state precise markings are important, and if old
4707  * state's register/slot is precise, regsafe() assumes current state's
4708  * register/slot as precise and checks value ranges exactly and precisely. If
4709  * states turn out to be compatible, current state's necessary precise
4710  * markings and any required parent states' precise markings are enforced
4711  * after the fact with propagate_precision() logic, after the fact. But it's
4712  * important to realize that in this case, even after marking current state
4713  * registers/slots as precise, we immediately discard current state. So what
4714  * actually matters is any of the precise markings propagated into current
4715  * state's parent states, which are always checkpointed (due to b) case above).
4716  * As such, for scenario a) it doesn't matter if current state has precise
4717  * markings set or not.
4718  *
4719  * Now, for the scenario b), checkpointing and forking into child(ren)
4720  * state(s). Note that before current state gets to checkpointing step, any
4721  * processed instruction always assumes precise SCALAR register/slot
4722  * knowledge: if precise value or range is useful to prune jump branch, BPF
4723  * verifier takes this opportunity enthusiastically. Similarly, when
4724  * register's value is used to calculate offset or memory address, exact
4725  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4726  * what we mentioned above about state comparison ignoring precise markings
4727  * during state comparison, BPF verifier ignores and also assumes precise
4728  * markings *at will* during instruction verification process. But as verifier
4729  * assumes precision, it also propagates any precision dependencies across
4730  * parent states, which are not yet finalized, so can be further restricted
4731  * based on new knowledge gained from restrictions enforced by their children
4732  * states. This is so that once those parent states are finalized, i.e., when
4733  * they have no more active children state, state comparison logic in
4734  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4735  * required for correctness.
4736  *
4737  * To build a bit more intuition, note also that once a state is checkpointed,
4738  * the path we took to get to that state is not important. This is crucial
4739  * property for state pruning. When state is checkpointed and finalized at
4740  * some instruction index, it can be correctly and safely used to "short
4741  * circuit" any *compatible* state that reaches exactly the same instruction
4742  * index. I.e., if we jumped to that instruction from a completely different
4743  * code path than original finalized state was derived from, it doesn't
4744  * matter, current state can be discarded because from that instruction
4745  * forward having a compatible state will ensure we will safely reach the
4746  * exit. States describe preconditions for further exploration, but completely
4747  * forget the history of how we got here.
4748  *
4749  * This also means that even if we needed precise SCALAR range to get to
4750  * finalized state, but from that point forward *that same* SCALAR register is
4751  * never used in a precise context (i.e., it's precise value is not needed for
4752  * correctness), it's correct and safe to mark such register as "imprecise"
4753  * (i.e., precise marking set to false). This is what we rely on when we do
4754  * not set precise marking in current state. If no child state requires
4755  * precision for any given SCALAR register, it's safe to dictate that it can
4756  * be imprecise. If any child state does require this register to be precise,
4757  * we'll mark it precise later retroactively during precise markings
4758  * propagation from child state to parent states.
4759  *
4760  * Skipping precise marking setting in current state is a mild version of
4761  * relying on the above observation. But we can utilize this property even
4762  * more aggressively by proactively forgetting any precise marking in the
4763  * current state (which we inherited from the parent state), right before we
4764  * checkpoint it and branch off into new child state. This is done by
4765  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4766  * finalized states which help in short circuiting more future states.
4767  */
4768 static int __mark_chain_precision(struct bpf_verifier_env *env,
4769 				  struct bpf_verifier_state *starting_state,
4770 				  int regno,
4771 				  bool *changed)
4772 {
4773 	struct bpf_verifier_state *st = starting_state;
4774 	struct backtrack_state *bt = &env->bt;
4775 	int first_idx = st->first_insn_idx;
4776 	int last_idx = starting_state->insn_idx;
4777 	int subseq_idx = -1;
4778 	struct bpf_func_state *func;
4779 	bool tmp, skip_first = true;
4780 	struct bpf_reg_state *reg;
4781 	int i, fr, err;
4782 
4783 	if (!env->bpf_capable)
4784 		return 0;
4785 
4786 	changed = changed ?: &tmp;
4787 	/* set frame number from which we are starting to backtrack */
4788 	bt_init(bt, starting_state->curframe);
4789 
4790 	/* Do sanity checks against current state of register and/or stack
4791 	 * slot, but don't set precise flag in current state, as precision
4792 	 * tracking in the current state is unnecessary.
4793 	 */
4794 	func = st->frame[bt->frame];
4795 	if (regno >= 0) {
4796 		reg = &func->regs[regno];
4797 		if (reg->type != SCALAR_VALUE) {
4798 			verifier_bug(env, "backtracking misuse");
4799 			return -EFAULT;
4800 		}
4801 		bt_set_reg(bt, regno);
4802 	}
4803 
4804 	if (bt_empty(bt))
4805 		return 0;
4806 
4807 	for (;;) {
4808 		DECLARE_BITMAP(mask, 64);
4809 		u32 history = st->jmp_history_cnt;
4810 		struct bpf_jmp_history_entry *hist;
4811 
4812 		if (env->log.level & BPF_LOG_LEVEL2) {
4813 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4814 				bt->frame, last_idx, first_idx, subseq_idx);
4815 		}
4816 
4817 		if (last_idx < 0) {
4818 			/* we are at the entry into subprog, which
4819 			 * is expected for global funcs, but only if
4820 			 * requested precise registers are R1-R5
4821 			 * (which are global func's input arguments)
4822 			 */
4823 			if (st->curframe == 0 &&
4824 			    st->frame[0]->subprogno > 0 &&
4825 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4826 			    bt_stack_mask(bt) == 0 &&
4827 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4828 				bitmap_from_u64(mask, bt_reg_mask(bt));
4829 				for_each_set_bit(i, mask, 32) {
4830 					reg = &st->frame[0]->regs[i];
4831 					bt_clear_reg(bt, i);
4832 					if (reg->type == SCALAR_VALUE) {
4833 						reg->precise = true;
4834 						*changed = true;
4835 					}
4836 				}
4837 				return 0;
4838 			}
4839 
4840 			verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %llx",
4841 				     st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4842 			return -EFAULT;
4843 		}
4844 
4845 		for (i = last_idx;;) {
4846 			if (skip_first) {
4847 				err = 0;
4848 				skip_first = false;
4849 			} else {
4850 				hist = get_jmp_hist_entry(st, history, i);
4851 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4852 			}
4853 			if (err == -ENOTSUPP) {
4854 				mark_all_scalars_precise(env, starting_state);
4855 				bt_reset(bt);
4856 				return 0;
4857 			} else if (err) {
4858 				return err;
4859 			}
4860 			if (bt_empty(bt))
4861 				/* Found assignment(s) into tracked register in this state.
4862 				 * Since this state is already marked, just return.
4863 				 * Nothing to be tracked further in the parent state.
4864 				 */
4865 				return 0;
4866 			subseq_idx = i;
4867 			i = get_prev_insn_idx(st, i, &history);
4868 			if (i == -ENOENT)
4869 				break;
4870 			if (i >= env->prog->len) {
4871 				/* This can happen if backtracking reached insn 0
4872 				 * and there are still reg_mask or stack_mask
4873 				 * to backtrack.
4874 				 * It means the backtracking missed the spot where
4875 				 * particular register was initialized with a constant.
4876 				 */
4877 				verifier_bug(env, "backtracking idx %d", i);
4878 				return -EFAULT;
4879 			}
4880 		}
4881 		st = st->parent;
4882 		if (!st)
4883 			break;
4884 
4885 		for (fr = bt->frame; fr >= 0; fr--) {
4886 			func = st->frame[fr];
4887 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4888 			for_each_set_bit(i, mask, 32) {
4889 				reg = &func->regs[i];
4890 				if (reg->type != SCALAR_VALUE) {
4891 					bt_clear_frame_reg(bt, fr, i);
4892 					continue;
4893 				}
4894 				if (reg->precise) {
4895 					bt_clear_frame_reg(bt, fr, i);
4896 				} else {
4897 					reg->precise = true;
4898 					*changed = true;
4899 				}
4900 			}
4901 
4902 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4903 			for_each_set_bit(i, mask, 64) {
4904 				if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE,
4905 						    env, "stack slot %d, total slots %d",
4906 						    i, func->allocated_stack / BPF_REG_SIZE))
4907 					return -EFAULT;
4908 
4909 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4910 					bt_clear_frame_slot(bt, fr, i);
4911 					continue;
4912 				}
4913 				reg = &func->stack[i].spilled_ptr;
4914 				if (reg->precise) {
4915 					bt_clear_frame_slot(bt, fr, i);
4916 				} else {
4917 					reg->precise = true;
4918 					*changed = true;
4919 				}
4920 			}
4921 			if (env->log.level & BPF_LOG_LEVEL2) {
4922 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4923 					     bt_frame_reg_mask(bt, fr));
4924 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4925 					fr, env->tmp_str_buf);
4926 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4927 					       bt_frame_stack_mask(bt, fr));
4928 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4929 				print_verifier_state(env, st, fr, true);
4930 			}
4931 		}
4932 
4933 		if (bt_empty(bt))
4934 			return 0;
4935 
4936 		subseq_idx = first_idx;
4937 		last_idx = st->last_insn_idx;
4938 		first_idx = st->first_insn_idx;
4939 	}
4940 
4941 	/* if we still have requested precise regs or slots, we missed
4942 	 * something (e.g., stack access through non-r10 register), so
4943 	 * fallback to marking all precise
4944 	 */
4945 	if (!bt_empty(bt)) {
4946 		mark_all_scalars_precise(env, starting_state);
4947 		bt_reset(bt);
4948 	}
4949 
4950 	return 0;
4951 }
4952 
4953 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4954 {
4955 	return __mark_chain_precision(env, env->cur_state, regno, NULL);
4956 }
4957 
4958 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4959  * desired reg and stack masks across all relevant frames
4960  */
4961 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
4962 				      struct bpf_verifier_state *starting_state)
4963 {
4964 	return __mark_chain_precision(env, starting_state, -1, NULL);
4965 }
4966 
4967 static bool is_spillable_regtype(enum bpf_reg_type type)
4968 {
4969 	switch (base_type(type)) {
4970 	case PTR_TO_MAP_VALUE:
4971 	case PTR_TO_STACK:
4972 	case PTR_TO_CTX:
4973 	case PTR_TO_PACKET:
4974 	case PTR_TO_PACKET_META:
4975 	case PTR_TO_PACKET_END:
4976 	case PTR_TO_FLOW_KEYS:
4977 	case CONST_PTR_TO_MAP:
4978 	case PTR_TO_SOCKET:
4979 	case PTR_TO_SOCK_COMMON:
4980 	case PTR_TO_TCP_SOCK:
4981 	case PTR_TO_XDP_SOCK:
4982 	case PTR_TO_BTF_ID:
4983 	case PTR_TO_BUF:
4984 	case PTR_TO_MEM:
4985 	case PTR_TO_FUNC:
4986 	case PTR_TO_MAP_KEY:
4987 	case PTR_TO_ARENA:
4988 		return true;
4989 	default:
4990 		return false;
4991 	}
4992 }
4993 
4994 /* Does this register contain a constant zero? */
4995 static bool register_is_null(struct bpf_reg_state *reg)
4996 {
4997 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4998 }
4999 
5000 /* check if register is a constant scalar value */
5001 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
5002 {
5003 	return reg->type == SCALAR_VALUE &&
5004 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
5005 }
5006 
5007 /* assuming is_reg_const() is true, return constant value of a register */
5008 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
5009 {
5010 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
5011 }
5012 
5013 static bool __is_pointer_value(bool allow_ptr_leaks,
5014 			       const struct bpf_reg_state *reg)
5015 {
5016 	if (allow_ptr_leaks)
5017 		return false;
5018 
5019 	return reg->type != SCALAR_VALUE;
5020 }
5021 
5022 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
5023 					struct bpf_reg_state *src_reg)
5024 {
5025 	if (src_reg->type != SCALAR_VALUE)
5026 		return;
5027 
5028 	if (src_reg->id & BPF_ADD_CONST) {
5029 		/*
5030 		 * The verifier is processing rX = rY insn and
5031 		 * rY->id has special linked register already.
5032 		 * Cleared it, since multiple rX += const are not supported.
5033 		 */
5034 		src_reg->id = 0;
5035 		src_reg->off = 0;
5036 	}
5037 
5038 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
5039 		/* Ensure that src_reg has a valid ID that will be copied to
5040 		 * dst_reg and then will be used by sync_linked_regs() to
5041 		 * propagate min/max range.
5042 		 */
5043 		src_reg->id = ++env->id_gen;
5044 }
5045 
5046 /* Copy src state preserving dst->parent and dst->live fields */
5047 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
5048 {
5049 	struct bpf_reg_state *parent = dst->parent;
5050 	enum bpf_reg_liveness live = dst->live;
5051 
5052 	*dst = *src;
5053 	dst->parent = parent;
5054 	dst->live = live;
5055 }
5056 
5057 static void save_register_state(struct bpf_verifier_env *env,
5058 				struct bpf_func_state *state,
5059 				int spi, struct bpf_reg_state *reg,
5060 				int size)
5061 {
5062 	int i;
5063 
5064 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
5065 	if (size == BPF_REG_SIZE)
5066 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
5067 
5068 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
5069 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
5070 
5071 	/* size < 8 bytes spill */
5072 	for (; i; i--)
5073 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
5074 }
5075 
5076 static bool is_bpf_st_mem(struct bpf_insn *insn)
5077 {
5078 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
5079 }
5080 
5081 static int get_reg_width(struct bpf_reg_state *reg)
5082 {
5083 	return fls64(reg->umax_value);
5084 }
5085 
5086 /* See comment for mark_fastcall_pattern_for_call() */
5087 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
5088 					  struct bpf_func_state *state, int insn_idx, int off)
5089 {
5090 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
5091 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
5092 	int i;
5093 
5094 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
5095 		return;
5096 	/* access to the region [max_stack_depth .. fastcall_stack_off)
5097 	 * from something that is not a part of the fastcall pattern,
5098 	 * disable fastcall rewrites for current subprogram by setting
5099 	 * fastcall_stack_off to a value smaller than any possible offset.
5100 	 */
5101 	subprog->fastcall_stack_off = S16_MIN;
5102 	/* reset fastcall aux flags within subprogram,
5103 	 * happens at most once per subprogram
5104 	 */
5105 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
5106 		aux[i].fastcall_spills_num = 0;
5107 		aux[i].fastcall_pattern = 0;
5108 	}
5109 }
5110 
5111 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
5112  * stack boundary and alignment are checked in check_mem_access()
5113  */
5114 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
5115 				       /* stack frame we're writing to */
5116 				       struct bpf_func_state *state,
5117 				       int off, int size, int value_regno,
5118 				       int insn_idx)
5119 {
5120 	struct bpf_func_state *cur; /* state of the current function */
5121 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
5122 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5123 	struct bpf_reg_state *reg = NULL;
5124 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
5125 
5126 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
5127 	 * so it's aligned access and [off, off + size) are within stack limits
5128 	 */
5129 	if (!env->allow_ptr_leaks &&
5130 	    is_spilled_reg(&state->stack[spi]) &&
5131 	    !is_spilled_scalar_reg(&state->stack[spi]) &&
5132 	    size != BPF_REG_SIZE) {
5133 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
5134 		return -EACCES;
5135 	}
5136 
5137 	cur = env->cur_state->frame[env->cur_state->curframe];
5138 	if (value_regno >= 0)
5139 		reg = &cur->regs[value_regno];
5140 	if (!env->bypass_spec_v4) {
5141 		bool sanitize = reg && is_spillable_regtype(reg->type);
5142 
5143 		for (i = 0; i < size; i++) {
5144 			u8 type = state->stack[spi].slot_type[i];
5145 
5146 			if (type != STACK_MISC && type != STACK_ZERO) {
5147 				sanitize = true;
5148 				break;
5149 			}
5150 		}
5151 
5152 		if (sanitize)
5153 			env->insn_aux_data[insn_idx].nospec_result = true;
5154 	}
5155 
5156 	err = destroy_if_dynptr_stack_slot(env, state, spi);
5157 	if (err)
5158 		return err;
5159 
5160 	check_fastcall_stack_contract(env, state, insn_idx, off);
5161 	mark_stack_slot_scratched(env, spi);
5162 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
5163 		bool reg_value_fits;
5164 
5165 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
5166 		/* Make sure that reg had an ID to build a relation on spill. */
5167 		if (reg_value_fits)
5168 			assign_scalar_id_before_mov(env, reg);
5169 		save_register_state(env, state, spi, reg, size);
5170 		/* Break the relation on a narrowing spill. */
5171 		if (!reg_value_fits)
5172 			state->stack[spi].spilled_ptr.id = 0;
5173 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
5174 		   env->bpf_capable) {
5175 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
5176 
5177 		memset(tmp_reg, 0, sizeof(*tmp_reg));
5178 		__mark_reg_known(tmp_reg, insn->imm);
5179 		tmp_reg->type = SCALAR_VALUE;
5180 		save_register_state(env, state, spi, tmp_reg, size);
5181 	} else if (reg && is_spillable_regtype(reg->type)) {
5182 		/* register containing pointer is being spilled into stack */
5183 		if (size != BPF_REG_SIZE) {
5184 			verbose_linfo(env, insn_idx, "; ");
5185 			verbose(env, "invalid size of register spill\n");
5186 			return -EACCES;
5187 		}
5188 		if (state != cur && reg->type == PTR_TO_STACK) {
5189 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
5190 			return -EINVAL;
5191 		}
5192 		save_register_state(env, state, spi, reg, size);
5193 	} else {
5194 		u8 type = STACK_MISC;
5195 
5196 		/* regular write of data into stack destroys any spilled ptr */
5197 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5198 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
5199 		if (is_stack_slot_special(&state->stack[spi]))
5200 			for (i = 0; i < BPF_REG_SIZE; i++)
5201 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
5202 
5203 		/* only mark the slot as written if all 8 bytes were written
5204 		 * otherwise read propagation may incorrectly stop too soon
5205 		 * when stack slots are partially written.
5206 		 * This heuristic means that read propagation will be
5207 		 * conservative, since it will add reg_live_read marks
5208 		 * to stack slots all the way to first state when programs
5209 		 * writes+reads less than 8 bytes
5210 		 */
5211 		if (size == BPF_REG_SIZE)
5212 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
5213 
5214 		/* when we zero initialize stack slots mark them as such */
5215 		if ((reg && register_is_null(reg)) ||
5216 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
5217 			/* STACK_ZERO case happened because register spill
5218 			 * wasn't properly aligned at the stack slot boundary,
5219 			 * so it's not a register spill anymore; force
5220 			 * originating register to be precise to make
5221 			 * STACK_ZERO correct for subsequent states
5222 			 */
5223 			err = mark_chain_precision(env, value_regno);
5224 			if (err)
5225 				return err;
5226 			type = STACK_ZERO;
5227 		}
5228 
5229 		/* Mark slots affected by this stack write. */
5230 		for (i = 0; i < size; i++)
5231 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
5232 		insn_flags = 0; /* not a register spill */
5233 	}
5234 
5235 	if (insn_flags)
5236 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5237 	return 0;
5238 }
5239 
5240 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
5241  * known to contain a variable offset.
5242  * This function checks whether the write is permitted and conservatively
5243  * tracks the effects of the write, considering that each stack slot in the
5244  * dynamic range is potentially written to.
5245  *
5246  * 'off' includes 'regno->off'.
5247  * 'value_regno' can be -1, meaning that an unknown value is being written to
5248  * the stack.
5249  *
5250  * Spilled pointers in range are not marked as written because we don't know
5251  * what's going to be actually written. This means that read propagation for
5252  * future reads cannot be terminated by this write.
5253  *
5254  * For privileged programs, uninitialized stack slots are considered
5255  * initialized by this write (even though we don't know exactly what offsets
5256  * are going to be written to). The idea is that we don't want the verifier to
5257  * reject future reads that access slots written to through variable offsets.
5258  */
5259 static int check_stack_write_var_off(struct bpf_verifier_env *env,
5260 				     /* func where register points to */
5261 				     struct bpf_func_state *state,
5262 				     int ptr_regno, int off, int size,
5263 				     int value_regno, int insn_idx)
5264 {
5265 	struct bpf_func_state *cur; /* state of the current function */
5266 	int min_off, max_off;
5267 	int i, err;
5268 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
5269 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5270 	bool writing_zero = false;
5271 	/* set if the fact that we're writing a zero is used to let any
5272 	 * stack slots remain STACK_ZERO
5273 	 */
5274 	bool zero_used = false;
5275 
5276 	cur = env->cur_state->frame[env->cur_state->curframe];
5277 	ptr_reg = &cur->regs[ptr_regno];
5278 	min_off = ptr_reg->smin_value + off;
5279 	max_off = ptr_reg->smax_value + off + size;
5280 	if (value_regno >= 0)
5281 		value_reg = &cur->regs[value_regno];
5282 	if ((value_reg && register_is_null(value_reg)) ||
5283 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
5284 		writing_zero = true;
5285 
5286 	for (i = min_off; i < max_off; i++) {
5287 		int spi;
5288 
5289 		spi = __get_spi(i);
5290 		err = destroy_if_dynptr_stack_slot(env, state, spi);
5291 		if (err)
5292 			return err;
5293 	}
5294 
5295 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
5296 	/* Variable offset writes destroy any spilled pointers in range. */
5297 	for (i = min_off; i < max_off; i++) {
5298 		u8 new_type, *stype;
5299 		int slot, spi;
5300 
5301 		slot = -i - 1;
5302 		spi = slot / BPF_REG_SIZE;
5303 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5304 		mark_stack_slot_scratched(env, spi);
5305 
5306 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
5307 			/* Reject the write if range we may write to has not
5308 			 * been initialized beforehand. If we didn't reject
5309 			 * here, the ptr status would be erased below (even
5310 			 * though not all slots are actually overwritten),
5311 			 * possibly opening the door to leaks.
5312 			 *
5313 			 * We do however catch STACK_INVALID case below, and
5314 			 * only allow reading possibly uninitialized memory
5315 			 * later for CAP_PERFMON, as the write may not happen to
5316 			 * that slot.
5317 			 */
5318 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
5319 				insn_idx, i);
5320 			return -EINVAL;
5321 		}
5322 
5323 		/* If writing_zero and the spi slot contains a spill of value 0,
5324 		 * maintain the spill type.
5325 		 */
5326 		if (writing_zero && *stype == STACK_SPILL &&
5327 		    is_spilled_scalar_reg(&state->stack[spi])) {
5328 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
5329 
5330 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
5331 				zero_used = true;
5332 				continue;
5333 			}
5334 		}
5335 
5336 		/* Erase all other spilled pointers. */
5337 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5338 
5339 		/* Update the slot type. */
5340 		new_type = STACK_MISC;
5341 		if (writing_zero && *stype == STACK_ZERO) {
5342 			new_type = STACK_ZERO;
5343 			zero_used = true;
5344 		}
5345 		/* If the slot is STACK_INVALID, we check whether it's OK to
5346 		 * pretend that it will be initialized by this write. The slot
5347 		 * might not actually be written to, and so if we mark it as
5348 		 * initialized future reads might leak uninitialized memory.
5349 		 * For privileged programs, we will accept such reads to slots
5350 		 * that may or may not be written because, if we're reject
5351 		 * them, the error would be too confusing.
5352 		 */
5353 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
5354 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
5355 					insn_idx, i);
5356 			return -EINVAL;
5357 		}
5358 		*stype = new_type;
5359 	}
5360 	if (zero_used) {
5361 		/* backtracking doesn't work for STACK_ZERO yet. */
5362 		err = mark_chain_precision(env, value_regno);
5363 		if (err)
5364 			return err;
5365 	}
5366 	return 0;
5367 }
5368 
5369 /* When register 'dst_regno' is assigned some values from stack[min_off,
5370  * max_off), we set the register's type according to the types of the
5371  * respective stack slots. If all the stack values are known to be zeros, then
5372  * so is the destination reg. Otherwise, the register is considered to be
5373  * SCALAR. This function does not deal with register filling; the caller must
5374  * ensure that all spilled registers in the stack range have been marked as
5375  * read.
5376  */
5377 static void mark_reg_stack_read(struct bpf_verifier_env *env,
5378 				/* func where src register points to */
5379 				struct bpf_func_state *ptr_state,
5380 				int min_off, int max_off, int dst_regno)
5381 {
5382 	struct bpf_verifier_state *vstate = env->cur_state;
5383 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5384 	int i, slot, spi;
5385 	u8 *stype;
5386 	int zeros = 0;
5387 
5388 	for (i = min_off; i < max_off; i++) {
5389 		slot = -i - 1;
5390 		spi = slot / BPF_REG_SIZE;
5391 		mark_stack_slot_scratched(env, spi);
5392 		stype = ptr_state->stack[spi].slot_type;
5393 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
5394 			break;
5395 		zeros++;
5396 	}
5397 	if (zeros == max_off - min_off) {
5398 		/* Any access_size read into register is zero extended,
5399 		 * so the whole register == const_zero.
5400 		 */
5401 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
5402 	} else {
5403 		/* have read misc data from the stack */
5404 		mark_reg_unknown(env, state->regs, dst_regno);
5405 	}
5406 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5407 }
5408 
5409 /* Read the stack at 'off' and put the results into the register indicated by
5410  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
5411  * spilled reg.
5412  *
5413  * 'dst_regno' can be -1, meaning that the read value is not going to a
5414  * register.
5415  *
5416  * The access is assumed to be within the current stack bounds.
5417  */
5418 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
5419 				      /* func where src register points to */
5420 				      struct bpf_func_state *reg_state,
5421 				      int off, int size, int dst_regno)
5422 {
5423 	struct bpf_verifier_state *vstate = env->cur_state;
5424 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5425 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
5426 	struct bpf_reg_state *reg;
5427 	u8 *stype, type;
5428 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
5429 
5430 	stype = reg_state->stack[spi].slot_type;
5431 	reg = &reg_state->stack[spi].spilled_ptr;
5432 
5433 	mark_stack_slot_scratched(env, spi);
5434 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
5435 
5436 	if (is_spilled_reg(&reg_state->stack[spi])) {
5437 		u8 spill_size = 1;
5438 
5439 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
5440 			spill_size++;
5441 
5442 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
5443 			if (reg->type != SCALAR_VALUE) {
5444 				verbose_linfo(env, env->insn_idx, "; ");
5445 				verbose(env, "invalid size of register fill\n");
5446 				return -EACCES;
5447 			}
5448 
5449 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5450 			if (dst_regno < 0)
5451 				return 0;
5452 
5453 			if (size <= spill_size &&
5454 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
5455 				/* The earlier check_reg_arg() has decided the
5456 				 * subreg_def for this insn.  Save it first.
5457 				 */
5458 				s32 subreg_def = state->regs[dst_regno].subreg_def;
5459 
5460 				copy_register_state(&state->regs[dst_regno], reg);
5461 				state->regs[dst_regno].subreg_def = subreg_def;
5462 
5463 				/* Break the relation on a narrowing fill.
5464 				 * coerce_reg_to_size will adjust the boundaries.
5465 				 */
5466 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
5467 					state->regs[dst_regno].id = 0;
5468 			} else {
5469 				int spill_cnt = 0, zero_cnt = 0;
5470 
5471 				for (i = 0; i < size; i++) {
5472 					type = stype[(slot - i) % BPF_REG_SIZE];
5473 					if (type == STACK_SPILL) {
5474 						spill_cnt++;
5475 						continue;
5476 					}
5477 					if (type == STACK_MISC)
5478 						continue;
5479 					if (type == STACK_ZERO) {
5480 						zero_cnt++;
5481 						continue;
5482 					}
5483 					if (type == STACK_INVALID && env->allow_uninit_stack)
5484 						continue;
5485 					verbose(env, "invalid read from stack off %d+%d size %d\n",
5486 						off, i, size);
5487 					return -EACCES;
5488 				}
5489 
5490 				if (spill_cnt == size &&
5491 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
5492 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5493 					/* this IS register fill, so keep insn_flags */
5494 				} else if (zero_cnt == size) {
5495 					/* similarly to mark_reg_stack_read(), preserve zeroes */
5496 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5497 					insn_flags = 0; /* not restoring original register state */
5498 				} else {
5499 					mark_reg_unknown(env, state->regs, dst_regno);
5500 					insn_flags = 0; /* not restoring original register state */
5501 				}
5502 			}
5503 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5504 		} else if (dst_regno >= 0) {
5505 			/* restore register state from stack */
5506 			copy_register_state(&state->regs[dst_regno], reg);
5507 			/* mark reg as written since spilled pointer state likely
5508 			 * has its liveness marks cleared by is_state_visited()
5509 			 * which resets stack/reg liveness for state transitions
5510 			 */
5511 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5512 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5513 			/* If dst_regno==-1, the caller is asking us whether
5514 			 * it is acceptable to use this value as a SCALAR_VALUE
5515 			 * (e.g. for XADD).
5516 			 * We must not allow unprivileged callers to do that
5517 			 * with spilled pointers.
5518 			 */
5519 			verbose(env, "leaking pointer from stack off %d\n",
5520 				off);
5521 			return -EACCES;
5522 		}
5523 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5524 	} else {
5525 		for (i = 0; i < size; i++) {
5526 			type = stype[(slot - i) % BPF_REG_SIZE];
5527 			if (type == STACK_MISC)
5528 				continue;
5529 			if (type == STACK_ZERO)
5530 				continue;
5531 			if (type == STACK_INVALID && env->allow_uninit_stack)
5532 				continue;
5533 			verbose(env, "invalid read from stack off %d+%d size %d\n",
5534 				off, i, size);
5535 			return -EACCES;
5536 		}
5537 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5538 		if (dst_regno >= 0)
5539 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5540 		insn_flags = 0; /* we are not restoring spilled register */
5541 	}
5542 	if (insn_flags)
5543 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5544 	return 0;
5545 }
5546 
5547 enum bpf_access_src {
5548 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5549 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
5550 };
5551 
5552 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5553 					 int regno, int off, int access_size,
5554 					 bool zero_size_allowed,
5555 					 enum bpf_access_type type,
5556 					 struct bpf_call_arg_meta *meta);
5557 
5558 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5559 {
5560 	return cur_regs(env) + regno;
5561 }
5562 
5563 /* Read the stack at 'ptr_regno + off' and put the result into the register
5564  * 'dst_regno'.
5565  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5566  * but not its variable offset.
5567  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5568  *
5569  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5570  * filling registers (i.e. reads of spilled register cannot be detected when
5571  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5572  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5573  * offset; for a fixed offset check_stack_read_fixed_off should be used
5574  * instead.
5575  */
5576 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5577 				    int ptr_regno, int off, int size, int dst_regno)
5578 {
5579 	/* The state of the source register. */
5580 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5581 	struct bpf_func_state *ptr_state = func(env, reg);
5582 	int err;
5583 	int min_off, max_off;
5584 
5585 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5586 	 */
5587 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5588 					    false, BPF_READ, NULL);
5589 	if (err)
5590 		return err;
5591 
5592 	min_off = reg->smin_value + off;
5593 	max_off = reg->smax_value + off;
5594 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5595 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5596 	return 0;
5597 }
5598 
5599 /* check_stack_read dispatches to check_stack_read_fixed_off or
5600  * check_stack_read_var_off.
5601  *
5602  * The caller must ensure that the offset falls within the allocated stack
5603  * bounds.
5604  *
5605  * 'dst_regno' is a register which will receive the value from the stack. It
5606  * can be -1, meaning that the read value is not going to a register.
5607  */
5608 static int check_stack_read(struct bpf_verifier_env *env,
5609 			    int ptr_regno, int off, int size,
5610 			    int dst_regno)
5611 {
5612 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5613 	struct bpf_func_state *state = func(env, reg);
5614 	int err;
5615 	/* Some accesses are only permitted with a static offset. */
5616 	bool var_off = !tnum_is_const(reg->var_off);
5617 
5618 	/* The offset is required to be static when reads don't go to a
5619 	 * register, in order to not leak pointers (see
5620 	 * check_stack_read_fixed_off).
5621 	 */
5622 	if (dst_regno < 0 && var_off) {
5623 		char tn_buf[48];
5624 
5625 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5626 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5627 			tn_buf, off, size);
5628 		return -EACCES;
5629 	}
5630 	/* Variable offset is prohibited for unprivileged mode for simplicity
5631 	 * since it requires corresponding support in Spectre masking for stack
5632 	 * ALU. See also retrieve_ptr_limit(). The check in
5633 	 * check_stack_access_for_ptr_arithmetic() called by
5634 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5635 	 * with variable offsets, therefore no check is required here. Further,
5636 	 * just checking it here would be insufficient as speculative stack
5637 	 * writes could still lead to unsafe speculative behaviour.
5638 	 */
5639 	if (!var_off) {
5640 		off += reg->var_off.value;
5641 		err = check_stack_read_fixed_off(env, state, off, size,
5642 						 dst_regno);
5643 	} else {
5644 		/* Variable offset stack reads need more conservative handling
5645 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5646 		 * branch.
5647 		 */
5648 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5649 					       dst_regno);
5650 	}
5651 	return err;
5652 }
5653 
5654 
5655 /* check_stack_write dispatches to check_stack_write_fixed_off or
5656  * check_stack_write_var_off.
5657  *
5658  * 'ptr_regno' is the register used as a pointer into the stack.
5659  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5660  * 'value_regno' is the register whose value we're writing to the stack. It can
5661  * be -1, meaning that we're not writing from a register.
5662  *
5663  * The caller must ensure that the offset falls within the maximum stack size.
5664  */
5665 static int check_stack_write(struct bpf_verifier_env *env,
5666 			     int ptr_regno, int off, int size,
5667 			     int value_regno, int insn_idx)
5668 {
5669 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5670 	struct bpf_func_state *state = func(env, reg);
5671 	int err;
5672 
5673 	if (tnum_is_const(reg->var_off)) {
5674 		off += reg->var_off.value;
5675 		err = check_stack_write_fixed_off(env, state, off, size,
5676 						  value_regno, insn_idx);
5677 	} else {
5678 		/* Variable offset stack reads need more conservative handling
5679 		 * than fixed offset ones.
5680 		 */
5681 		err = check_stack_write_var_off(env, state,
5682 						ptr_regno, off, size,
5683 						value_regno, insn_idx);
5684 	}
5685 	return err;
5686 }
5687 
5688 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5689 				 int off, int size, enum bpf_access_type type)
5690 {
5691 	struct bpf_reg_state *regs = cur_regs(env);
5692 	struct bpf_map *map = regs[regno].map_ptr;
5693 	u32 cap = bpf_map_flags_to_cap(map);
5694 
5695 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5696 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5697 			map->value_size, off, size);
5698 		return -EACCES;
5699 	}
5700 
5701 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5702 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5703 			map->value_size, off, size);
5704 		return -EACCES;
5705 	}
5706 
5707 	return 0;
5708 }
5709 
5710 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5711 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5712 			      int off, int size, u32 mem_size,
5713 			      bool zero_size_allowed)
5714 {
5715 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5716 	struct bpf_reg_state *reg;
5717 
5718 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5719 		return 0;
5720 
5721 	reg = &cur_regs(env)[regno];
5722 	switch (reg->type) {
5723 	case PTR_TO_MAP_KEY:
5724 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5725 			mem_size, off, size);
5726 		break;
5727 	case PTR_TO_MAP_VALUE:
5728 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5729 			mem_size, off, size);
5730 		break;
5731 	case PTR_TO_PACKET:
5732 	case PTR_TO_PACKET_META:
5733 	case PTR_TO_PACKET_END:
5734 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5735 			off, size, regno, reg->id, off, mem_size);
5736 		break;
5737 	case PTR_TO_MEM:
5738 	default:
5739 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5740 			mem_size, off, size);
5741 	}
5742 
5743 	return -EACCES;
5744 }
5745 
5746 /* check read/write into a memory region with possible variable offset */
5747 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5748 				   int off, int size, u32 mem_size,
5749 				   bool zero_size_allowed)
5750 {
5751 	struct bpf_verifier_state *vstate = env->cur_state;
5752 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5753 	struct bpf_reg_state *reg = &state->regs[regno];
5754 	int err;
5755 
5756 	/* We may have adjusted the register pointing to memory region, so we
5757 	 * need to try adding each of min_value and max_value to off
5758 	 * to make sure our theoretical access will be safe.
5759 	 *
5760 	 * The minimum value is only important with signed
5761 	 * comparisons where we can't assume the floor of a
5762 	 * value is 0.  If we are using signed variables for our
5763 	 * index'es we need to make sure that whatever we use
5764 	 * will have a set floor within our range.
5765 	 */
5766 	if (reg->smin_value < 0 &&
5767 	    (reg->smin_value == S64_MIN ||
5768 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5769 	      reg->smin_value + off < 0)) {
5770 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5771 			regno);
5772 		return -EACCES;
5773 	}
5774 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5775 				 mem_size, zero_size_allowed);
5776 	if (err) {
5777 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5778 			regno);
5779 		return err;
5780 	}
5781 
5782 	/* If we haven't set a max value then we need to bail since we can't be
5783 	 * sure we won't do bad things.
5784 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5785 	 */
5786 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5787 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5788 			regno);
5789 		return -EACCES;
5790 	}
5791 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5792 				 mem_size, zero_size_allowed);
5793 	if (err) {
5794 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5795 			regno);
5796 		return err;
5797 	}
5798 
5799 	return 0;
5800 }
5801 
5802 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5803 			       const struct bpf_reg_state *reg, int regno,
5804 			       bool fixed_off_ok)
5805 {
5806 	/* Access to this pointer-typed register or passing it to a helper
5807 	 * is only allowed in its original, unmodified form.
5808 	 */
5809 
5810 	if (reg->off < 0) {
5811 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5812 			reg_type_str(env, reg->type), regno, reg->off);
5813 		return -EACCES;
5814 	}
5815 
5816 	if (!fixed_off_ok && reg->off) {
5817 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5818 			reg_type_str(env, reg->type), regno, reg->off);
5819 		return -EACCES;
5820 	}
5821 
5822 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5823 		char tn_buf[48];
5824 
5825 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5826 		verbose(env, "variable %s access var_off=%s disallowed\n",
5827 			reg_type_str(env, reg->type), tn_buf);
5828 		return -EACCES;
5829 	}
5830 
5831 	return 0;
5832 }
5833 
5834 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5835 		             const struct bpf_reg_state *reg, int regno)
5836 {
5837 	return __check_ptr_off_reg(env, reg, regno, false);
5838 }
5839 
5840 static int map_kptr_match_type(struct bpf_verifier_env *env,
5841 			       struct btf_field *kptr_field,
5842 			       struct bpf_reg_state *reg, u32 regno)
5843 {
5844 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5845 	int perm_flags;
5846 	const char *reg_name = "";
5847 
5848 	if (btf_is_kernel(reg->btf)) {
5849 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5850 
5851 		/* Only unreferenced case accepts untrusted pointers */
5852 		if (kptr_field->type == BPF_KPTR_UNREF)
5853 			perm_flags |= PTR_UNTRUSTED;
5854 	} else {
5855 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5856 		if (kptr_field->type == BPF_KPTR_PERCPU)
5857 			perm_flags |= MEM_PERCPU;
5858 	}
5859 
5860 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5861 		goto bad_type;
5862 
5863 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5864 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5865 
5866 	/* For ref_ptr case, release function check should ensure we get one
5867 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5868 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5869 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5870 	 * reg->off and reg->ref_obj_id are not needed here.
5871 	 */
5872 	if (__check_ptr_off_reg(env, reg, regno, true))
5873 		return -EACCES;
5874 
5875 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5876 	 * we also need to take into account the reg->off.
5877 	 *
5878 	 * We want to support cases like:
5879 	 *
5880 	 * struct foo {
5881 	 *         struct bar br;
5882 	 *         struct baz bz;
5883 	 * };
5884 	 *
5885 	 * struct foo *v;
5886 	 * v = func();	      // PTR_TO_BTF_ID
5887 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5888 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5889 	 *                    // first member type of struct after comparison fails
5890 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5891 	 *                    // to match type
5892 	 *
5893 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5894 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5895 	 * the struct to match type against first member of struct, i.e. reject
5896 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5897 	 * strict mode to true for type match.
5898 	 */
5899 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5900 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5901 				  kptr_field->type != BPF_KPTR_UNREF))
5902 		goto bad_type;
5903 	return 0;
5904 bad_type:
5905 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5906 		reg_type_str(env, reg->type), reg_name);
5907 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5908 	if (kptr_field->type == BPF_KPTR_UNREF)
5909 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5910 			targ_name);
5911 	else
5912 		verbose(env, "\n");
5913 	return -EINVAL;
5914 }
5915 
5916 static bool in_sleepable(struct bpf_verifier_env *env)
5917 {
5918 	return env->prog->sleepable ||
5919 	       (env->cur_state && env->cur_state->in_sleepable);
5920 }
5921 
5922 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5923  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5924  */
5925 static bool in_rcu_cs(struct bpf_verifier_env *env)
5926 {
5927 	return env->cur_state->active_rcu_lock ||
5928 	       env->cur_state->active_locks ||
5929 	       !in_sleepable(env);
5930 }
5931 
5932 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5933 BTF_SET_START(rcu_protected_types)
5934 #ifdef CONFIG_NET
5935 BTF_ID(struct, prog_test_ref_kfunc)
5936 #endif
5937 #ifdef CONFIG_CGROUPS
5938 BTF_ID(struct, cgroup)
5939 #endif
5940 #ifdef CONFIG_BPF_JIT
5941 BTF_ID(struct, bpf_cpumask)
5942 #endif
5943 BTF_ID(struct, task_struct)
5944 #ifdef CONFIG_CRYPTO
5945 BTF_ID(struct, bpf_crypto_ctx)
5946 #endif
5947 BTF_SET_END(rcu_protected_types)
5948 
5949 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5950 {
5951 	if (!btf_is_kernel(btf))
5952 		return true;
5953 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5954 }
5955 
5956 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5957 {
5958 	struct btf_struct_meta *meta;
5959 
5960 	if (btf_is_kernel(kptr_field->kptr.btf))
5961 		return NULL;
5962 
5963 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5964 				    kptr_field->kptr.btf_id);
5965 
5966 	return meta ? meta->record : NULL;
5967 }
5968 
5969 static bool rcu_safe_kptr(const struct btf_field *field)
5970 {
5971 	const struct btf_field_kptr *kptr = &field->kptr;
5972 
5973 	return field->type == BPF_KPTR_PERCPU ||
5974 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5975 }
5976 
5977 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5978 {
5979 	struct btf_record *rec;
5980 	u32 ret;
5981 
5982 	ret = PTR_MAYBE_NULL;
5983 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5984 		ret |= MEM_RCU;
5985 		if (kptr_field->type == BPF_KPTR_PERCPU)
5986 			ret |= MEM_PERCPU;
5987 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5988 			ret |= MEM_ALLOC;
5989 
5990 		rec = kptr_pointee_btf_record(kptr_field);
5991 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5992 			ret |= NON_OWN_REF;
5993 	} else {
5994 		ret |= PTR_UNTRUSTED;
5995 	}
5996 
5997 	return ret;
5998 }
5999 
6000 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
6001 			    struct btf_field *field)
6002 {
6003 	struct bpf_reg_state *reg;
6004 	const struct btf_type *t;
6005 
6006 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
6007 	mark_reg_known_zero(env, cur_regs(env), regno);
6008 	reg = reg_state(env, regno);
6009 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
6010 	reg->mem_size = t->size;
6011 	reg->id = ++env->id_gen;
6012 
6013 	return 0;
6014 }
6015 
6016 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
6017 				 int value_regno, int insn_idx,
6018 				 struct btf_field *kptr_field)
6019 {
6020 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
6021 	int class = BPF_CLASS(insn->code);
6022 	struct bpf_reg_state *val_reg;
6023 	int ret;
6024 
6025 	/* Things we already checked for in check_map_access and caller:
6026 	 *  - Reject cases where variable offset may touch kptr
6027 	 *  - size of access (must be BPF_DW)
6028 	 *  - tnum_is_const(reg->var_off)
6029 	 *  - kptr_field->offset == off + reg->var_off.value
6030 	 */
6031 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
6032 	if (BPF_MODE(insn->code) != BPF_MEM) {
6033 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
6034 		return -EACCES;
6035 	}
6036 
6037 	/* We only allow loading referenced kptr, since it will be marked as
6038 	 * untrusted, similar to unreferenced kptr.
6039 	 */
6040 	if (class != BPF_LDX &&
6041 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
6042 		verbose(env, "store to referenced kptr disallowed\n");
6043 		return -EACCES;
6044 	}
6045 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
6046 		verbose(env, "store to uptr disallowed\n");
6047 		return -EACCES;
6048 	}
6049 
6050 	if (class == BPF_LDX) {
6051 		if (kptr_field->type == BPF_UPTR)
6052 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
6053 
6054 		/* We can simply mark the value_regno receiving the pointer
6055 		 * value from map as PTR_TO_BTF_ID, with the correct type.
6056 		 */
6057 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
6058 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
6059 				      btf_ld_kptr_type(env, kptr_field));
6060 		if (ret < 0)
6061 			return ret;
6062 	} else if (class == BPF_STX) {
6063 		val_reg = reg_state(env, value_regno);
6064 		if (!register_is_null(val_reg) &&
6065 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
6066 			return -EACCES;
6067 	} else if (class == BPF_ST) {
6068 		if (insn->imm) {
6069 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
6070 				kptr_field->offset);
6071 			return -EACCES;
6072 		}
6073 	} else {
6074 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
6075 		return -EACCES;
6076 	}
6077 	return 0;
6078 }
6079 
6080 /* check read/write into a map element with possible variable offset */
6081 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
6082 			    int off, int size, bool zero_size_allowed,
6083 			    enum bpf_access_src src)
6084 {
6085 	struct bpf_verifier_state *vstate = env->cur_state;
6086 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6087 	struct bpf_reg_state *reg = &state->regs[regno];
6088 	struct bpf_map *map = reg->map_ptr;
6089 	struct btf_record *rec;
6090 	int err, i;
6091 
6092 	err = check_mem_region_access(env, regno, off, size, map->value_size,
6093 				      zero_size_allowed);
6094 	if (err)
6095 		return err;
6096 
6097 	if (IS_ERR_OR_NULL(map->record))
6098 		return 0;
6099 	rec = map->record;
6100 	for (i = 0; i < rec->cnt; i++) {
6101 		struct btf_field *field = &rec->fields[i];
6102 		u32 p = field->offset;
6103 
6104 		/* If any part of a field  can be touched by load/store, reject
6105 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
6106 		 * it is sufficient to check x1 < y2 && y1 < x2.
6107 		 */
6108 		if (reg->smin_value + off < p + field->size &&
6109 		    p < reg->umax_value + off + size) {
6110 			switch (field->type) {
6111 			case BPF_KPTR_UNREF:
6112 			case BPF_KPTR_REF:
6113 			case BPF_KPTR_PERCPU:
6114 			case BPF_UPTR:
6115 				if (src != ACCESS_DIRECT) {
6116 					verbose(env, "%s cannot be accessed indirectly by helper\n",
6117 						btf_field_type_name(field->type));
6118 					return -EACCES;
6119 				}
6120 				if (!tnum_is_const(reg->var_off)) {
6121 					verbose(env, "%s access cannot have variable offset\n",
6122 						btf_field_type_name(field->type));
6123 					return -EACCES;
6124 				}
6125 				if (p != off + reg->var_off.value) {
6126 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
6127 						btf_field_type_name(field->type),
6128 						p, off + reg->var_off.value);
6129 					return -EACCES;
6130 				}
6131 				if (size != bpf_size_to_bytes(BPF_DW)) {
6132 					verbose(env, "%s access size must be BPF_DW\n",
6133 						btf_field_type_name(field->type));
6134 					return -EACCES;
6135 				}
6136 				break;
6137 			default:
6138 				verbose(env, "%s cannot be accessed directly by load/store\n",
6139 					btf_field_type_name(field->type));
6140 				return -EACCES;
6141 			}
6142 		}
6143 	}
6144 	return 0;
6145 }
6146 
6147 #define MAX_PACKET_OFF 0xffff
6148 
6149 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
6150 				       const struct bpf_call_arg_meta *meta,
6151 				       enum bpf_access_type t)
6152 {
6153 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6154 
6155 	switch (prog_type) {
6156 	/* Program types only with direct read access go here! */
6157 	case BPF_PROG_TYPE_LWT_IN:
6158 	case BPF_PROG_TYPE_LWT_OUT:
6159 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
6160 	case BPF_PROG_TYPE_SK_REUSEPORT:
6161 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6162 	case BPF_PROG_TYPE_CGROUP_SKB:
6163 		if (t == BPF_WRITE)
6164 			return false;
6165 		fallthrough;
6166 
6167 	/* Program types with direct read + write access go here! */
6168 	case BPF_PROG_TYPE_SCHED_CLS:
6169 	case BPF_PROG_TYPE_SCHED_ACT:
6170 	case BPF_PROG_TYPE_XDP:
6171 	case BPF_PROG_TYPE_LWT_XMIT:
6172 	case BPF_PROG_TYPE_SK_SKB:
6173 	case BPF_PROG_TYPE_SK_MSG:
6174 		if (meta)
6175 			return meta->pkt_access;
6176 
6177 		env->seen_direct_write = true;
6178 		return true;
6179 
6180 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
6181 		if (t == BPF_WRITE)
6182 			env->seen_direct_write = true;
6183 
6184 		return true;
6185 
6186 	default:
6187 		return false;
6188 	}
6189 }
6190 
6191 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
6192 			       int size, bool zero_size_allowed)
6193 {
6194 	struct bpf_reg_state *regs = cur_regs(env);
6195 	struct bpf_reg_state *reg = &regs[regno];
6196 	int err;
6197 
6198 	/* We may have added a variable offset to the packet pointer; but any
6199 	 * reg->range we have comes after that.  We are only checking the fixed
6200 	 * offset.
6201 	 */
6202 
6203 	/* We don't allow negative numbers, because we aren't tracking enough
6204 	 * detail to prove they're safe.
6205 	 */
6206 	if (reg->smin_value < 0) {
6207 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6208 			regno);
6209 		return -EACCES;
6210 	}
6211 
6212 	err = reg->range < 0 ? -EINVAL :
6213 	      __check_mem_access(env, regno, off, size, reg->range,
6214 				 zero_size_allowed);
6215 	if (err) {
6216 		verbose(env, "R%d offset is outside of the packet\n", regno);
6217 		return err;
6218 	}
6219 
6220 	/* __check_mem_access has made sure "off + size - 1" is within u16.
6221 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
6222 	 * otherwise find_good_pkt_pointers would have refused to set range info
6223 	 * that __check_mem_access would have rejected this pkt access.
6224 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
6225 	 */
6226 	env->prog->aux->max_pkt_offset =
6227 		max_t(u32, env->prog->aux->max_pkt_offset,
6228 		      off + reg->umax_value + size - 1);
6229 
6230 	return err;
6231 }
6232 
6233 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
6234 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
6235 			    enum bpf_access_type t, struct bpf_insn_access_aux *info)
6236 {
6237 	if (env->ops->is_valid_access &&
6238 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
6239 		/* A non zero info.ctx_field_size indicates that this field is a
6240 		 * candidate for later verifier transformation to load the whole
6241 		 * field and then apply a mask when accessed with a narrower
6242 		 * access than actual ctx access size. A zero info.ctx_field_size
6243 		 * will only allow for whole field access and rejects any other
6244 		 * type of narrower access.
6245 		 */
6246 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
6247 			if (info->ref_obj_id &&
6248 			    !find_reference_state(env->cur_state, info->ref_obj_id)) {
6249 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
6250 					off);
6251 				return -EACCES;
6252 			}
6253 		} else {
6254 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
6255 		}
6256 		/* remember the offset of last byte accessed in ctx */
6257 		if (env->prog->aux->max_ctx_offset < off + size)
6258 			env->prog->aux->max_ctx_offset = off + size;
6259 		return 0;
6260 	}
6261 
6262 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
6263 	return -EACCES;
6264 }
6265 
6266 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
6267 				  int size)
6268 {
6269 	if (size < 0 || off < 0 ||
6270 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
6271 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
6272 			off, size);
6273 		return -EACCES;
6274 	}
6275 	return 0;
6276 }
6277 
6278 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
6279 			     u32 regno, int off, int size,
6280 			     enum bpf_access_type t)
6281 {
6282 	struct bpf_reg_state *regs = cur_regs(env);
6283 	struct bpf_reg_state *reg = &regs[regno];
6284 	struct bpf_insn_access_aux info = {};
6285 	bool valid;
6286 
6287 	if (reg->smin_value < 0) {
6288 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6289 			regno);
6290 		return -EACCES;
6291 	}
6292 
6293 	switch (reg->type) {
6294 	case PTR_TO_SOCK_COMMON:
6295 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
6296 		break;
6297 	case PTR_TO_SOCKET:
6298 		valid = bpf_sock_is_valid_access(off, size, t, &info);
6299 		break;
6300 	case PTR_TO_TCP_SOCK:
6301 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
6302 		break;
6303 	case PTR_TO_XDP_SOCK:
6304 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
6305 		break;
6306 	default:
6307 		valid = false;
6308 	}
6309 
6310 
6311 	if (valid) {
6312 		env->insn_aux_data[insn_idx].ctx_field_size =
6313 			info.ctx_field_size;
6314 		return 0;
6315 	}
6316 
6317 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
6318 		regno, reg_type_str(env, reg->type), off, size);
6319 
6320 	return -EACCES;
6321 }
6322 
6323 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
6324 {
6325 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
6326 }
6327 
6328 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
6329 {
6330 	const struct bpf_reg_state *reg = reg_state(env, regno);
6331 
6332 	return reg->type == PTR_TO_CTX;
6333 }
6334 
6335 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
6336 {
6337 	const struct bpf_reg_state *reg = reg_state(env, regno);
6338 
6339 	return type_is_sk_pointer(reg->type);
6340 }
6341 
6342 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
6343 {
6344 	const struct bpf_reg_state *reg = reg_state(env, regno);
6345 
6346 	return type_is_pkt_pointer(reg->type);
6347 }
6348 
6349 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
6350 {
6351 	const struct bpf_reg_state *reg = reg_state(env, regno);
6352 
6353 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
6354 	return reg->type == PTR_TO_FLOW_KEYS;
6355 }
6356 
6357 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
6358 {
6359 	const struct bpf_reg_state *reg = reg_state(env, regno);
6360 
6361 	return reg->type == PTR_TO_ARENA;
6362 }
6363 
6364 /* Return false if @regno contains a pointer whose type isn't supported for
6365  * atomic instruction @insn.
6366  */
6367 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
6368 			       struct bpf_insn *insn)
6369 {
6370 	if (is_ctx_reg(env, regno))
6371 		return false;
6372 	if (is_pkt_reg(env, regno))
6373 		return false;
6374 	if (is_flow_key_reg(env, regno))
6375 		return false;
6376 	if (is_sk_reg(env, regno))
6377 		return false;
6378 	if (is_arena_reg(env, regno))
6379 		return bpf_jit_supports_insn(insn, true);
6380 
6381 	return true;
6382 }
6383 
6384 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
6385 #ifdef CONFIG_NET
6386 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
6387 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6388 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
6389 #endif
6390 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
6391 };
6392 
6393 static bool is_trusted_reg(const struct bpf_reg_state *reg)
6394 {
6395 	/* A referenced register is always trusted. */
6396 	if (reg->ref_obj_id)
6397 		return true;
6398 
6399 	/* Types listed in the reg2btf_ids are always trusted */
6400 	if (reg2btf_ids[base_type(reg->type)] &&
6401 	    !bpf_type_has_unsafe_modifiers(reg->type))
6402 		return true;
6403 
6404 	/* If a register is not referenced, it is trusted if it has the
6405 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
6406 	 * other type modifiers may be safe, but we elect to take an opt-in
6407 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
6408 	 * not.
6409 	 *
6410 	 * Eventually, we should make PTR_TRUSTED the single source of truth
6411 	 * for whether a register is trusted.
6412 	 */
6413 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
6414 	       !bpf_type_has_unsafe_modifiers(reg->type);
6415 }
6416 
6417 static bool is_rcu_reg(const struct bpf_reg_state *reg)
6418 {
6419 	return reg->type & MEM_RCU;
6420 }
6421 
6422 static void clear_trusted_flags(enum bpf_type_flag *flag)
6423 {
6424 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
6425 }
6426 
6427 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
6428 				   const struct bpf_reg_state *reg,
6429 				   int off, int size, bool strict)
6430 {
6431 	struct tnum reg_off;
6432 	int ip_align;
6433 
6434 	/* Byte size accesses are always allowed. */
6435 	if (!strict || size == 1)
6436 		return 0;
6437 
6438 	/* For platforms that do not have a Kconfig enabling
6439 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
6440 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
6441 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
6442 	 * to this code only in strict mode where we want to emulate
6443 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
6444 	 * unconditional IP align value of '2'.
6445 	 */
6446 	ip_align = 2;
6447 
6448 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
6449 	if (!tnum_is_aligned(reg_off, size)) {
6450 		char tn_buf[48];
6451 
6452 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6453 		verbose(env,
6454 			"misaligned packet access off %d+%s+%d+%d size %d\n",
6455 			ip_align, tn_buf, reg->off, off, size);
6456 		return -EACCES;
6457 	}
6458 
6459 	return 0;
6460 }
6461 
6462 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
6463 				       const struct bpf_reg_state *reg,
6464 				       const char *pointer_desc,
6465 				       int off, int size, bool strict)
6466 {
6467 	struct tnum reg_off;
6468 
6469 	/* Byte size accesses are always allowed. */
6470 	if (!strict || size == 1)
6471 		return 0;
6472 
6473 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
6474 	if (!tnum_is_aligned(reg_off, size)) {
6475 		char tn_buf[48];
6476 
6477 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6478 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
6479 			pointer_desc, tn_buf, reg->off, off, size);
6480 		return -EACCES;
6481 	}
6482 
6483 	return 0;
6484 }
6485 
6486 static int check_ptr_alignment(struct bpf_verifier_env *env,
6487 			       const struct bpf_reg_state *reg, int off,
6488 			       int size, bool strict_alignment_once)
6489 {
6490 	bool strict = env->strict_alignment || strict_alignment_once;
6491 	const char *pointer_desc = "";
6492 
6493 	switch (reg->type) {
6494 	case PTR_TO_PACKET:
6495 	case PTR_TO_PACKET_META:
6496 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
6497 		 * right in front, treat it the very same way.
6498 		 */
6499 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
6500 	case PTR_TO_FLOW_KEYS:
6501 		pointer_desc = "flow keys ";
6502 		break;
6503 	case PTR_TO_MAP_KEY:
6504 		pointer_desc = "key ";
6505 		break;
6506 	case PTR_TO_MAP_VALUE:
6507 		pointer_desc = "value ";
6508 		break;
6509 	case PTR_TO_CTX:
6510 		pointer_desc = "context ";
6511 		break;
6512 	case PTR_TO_STACK:
6513 		pointer_desc = "stack ";
6514 		/* The stack spill tracking logic in check_stack_write_fixed_off()
6515 		 * and check_stack_read_fixed_off() relies on stack accesses being
6516 		 * aligned.
6517 		 */
6518 		strict = true;
6519 		break;
6520 	case PTR_TO_SOCKET:
6521 		pointer_desc = "sock ";
6522 		break;
6523 	case PTR_TO_SOCK_COMMON:
6524 		pointer_desc = "sock_common ";
6525 		break;
6526 	case PTR_TO_TCP_SOCK:
6527 		pointer_desc = "tcp_sock ";
6528 		break;
6529 	case PTR_TO_XDP_SOCK:
6530 		pointer_desc = "xdp_sock ";
6531 		break;
6532 	case PTR_TO_ARENA:
6533 		return 0;
6534 	default:
6535 		break;
6536 	}
6537 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
6538 					   strict);
6539 }
6540 
6541 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
6542 {
6543 	if (!bpf_jit_supports_private_stack())
6544 		return NO_PRIV_STACK;
6545 
6546 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
6547 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
6548 	 * explicitly.
6549 	 */
6550 	switch (prog->type) {
6551 	case BPF_PROG_TYPE_KPROBE:
6552 	case BPF_PROG_TYPE_TRACEPOINT:
6553 	case BPF_PROG_TYPE_PERF_EVENT:
6554 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6555 		return PRIV_STACK_ADAPTIVE;
6556 	case BPF_PROG_TYPE_TRACING:
6557 	case BPF_PROG_TYPE_LSM:
6558 	case BPF_PROG_TYPE_STRUCT_OPS:
6559 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
6560 			return PRIV_STACK_ADAPTIVE;
6561 		fallthrough;
6562 	default:
6563 		break;
6564 	}
6565 
6566 	return NO_PRIV_STACK;
6567 }
6568 
6569 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
6570 {
6571 	if (env->prog->jit_requested)
6572 		return round_up(stack_depth, 16);
6573 
6574 	/* round up to 32-bytes, since this is granularity
6575 	 * of interpreter stack size
6576 	 */
6577 	return round_up(max_t(u32, stack_depth, 1), 32);
6578 }
6579 
6580 /* starting from main bpf function walk all instructions of the function
6581  * and recursively walk all callees that given function can call.
6582  * Ignore jump and exit insns.
6583  * Since recursion is prevented by check_cfg() this algorithm
6584  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6585  */
6586 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
6587 					 bool priv_stack_supported)
6588 {
6589 	struct bpf_subprog_info *subprog = env->subprog_info;
6590 	struct bpf_insn *insn = env->prog->insnsi;
6591 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
6592 	bool tail_call_reachable = false;
6593 	int ret_insn[MAX_CALL_FRAMES];
6594 	int ret_prog[MAX_CALL_FRAMES];
6595 	int j;
6596 
6597 	i = subprog[idx].start;
6598 	if (!priv_stack_supported)
6599 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6600 process_func:
6601 	/* protect against potential stack overflow that might happen when
6602 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6603 	 * depth for such case down to 256 so that the worst case scenario
6604 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
6605 	 * 8k).
6606 	 *
6607 	 * To get the idea what might happen, see an example:
6608 	 * func1 -> sub rsp, 128
6609 	 *  subfunc1 -> sub rsp, 256
6610 	 *  tailcall1 -> add rsp, 256
6611 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6612 	 *   subfunc2 -> sub rsp, 64
6613 	 *   subfunc22 -> sub rsp, 128
6614 	 *   tailcall2 -> add rsp, 128
6615 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6616 	 *
6617 	 * tailcall will unwind the current stack frame but it will not get rid
6618 	 * of caller's stack as shown on the example above.
6619 	 */
6620 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
6621 		verbose(env,
6622 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6623 			depth);
6624 		return -EACCES;
6625 	}
6626 
6627 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
6628 	if (priv_stack_supported) {
6629 		/* Request private stack support only if the subprog stack
6630 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
6631 		 * avoid jit penalty if the stack usage is small.
6632 		 */
6633 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
6634 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
6635 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
6636 	}
6637 
6638 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6639 		if (subprog_depth > MAX_BPF_STACK) {
6640 			verbose(env, "stack size of subprog %d is %d. Too large\n",
6641 				idx, subprog_depth);
6642 			return -EACCES;
6643 		}
6644 	} else {
6645 		depth += subprog_depth;
6646 		if (depth > MAX_BPF_STACK) {
6647 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
6648 				frame + 1, depth);
6649 			return -EACCES;
6650 		}
6651 	}
6652 continue_func:
6653 	subprog_end = subprog[idx + 1].start;
6654 	for (; i < subprog_end; i++) {
6655 		int next_insn, sidx;
6656 
6657 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6658 			bool err = false;
6659 
6660 			if (!is_bpf_throw_kfunc(insn + i))
6661 				continue;
6662 			if (subprog[idx].is_cb)
6663 				err = true;
6664 			for (int c = 0; c < frame && !err; c++) {
6665 				if (subprog[ret_prog[c]].is_cb) {
6666 					err = true;
6667 					break;
6668 				}
6669 			}
6670 			if (!err)
6671 				continue;
6672 			verbose(env,
6673 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6674 				i, idx);
6675 			return -EINVAL;
6676 		}
6677 
6678 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6679 			continue;
6680 		/* remember insn and function to return to */
6681 		ret_insn[frame] = i + 1;
6682 		ret_prog[frame] = idx;
6683 
6684 		/* find the callee */
6685 		next_insn = i + insn[i].imm + 1;
6686 		sidx = find_subprog(env, next_insn);
6687 		if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
6688 			return -EFAULT;
6689 		if (subprog[sidx].is_async_cb) {
6690 			if (subprog[sidx].has_tail_call) {
6691 				verifier_bug(env, "subprog has tail_call and async cb");
6692 				return -EFAULT;
6693 			}
6694 			/* async callbacks don't increase bpf prog stack size unless called directly */
6695 			if (!bpf_pseudo_call(insn + i))
6696 				continue;
6697 			if (subprog[sidx].is_exception_cb) {
6698 				verbose(env, "insn %d cannot call exception cb directly", i);
6699 				return -EINVAL;
6700 			}
6701 		}
6702 		i = next_insn;
6703 		idx = sidx;
6704 		if (!priv_stack_supported)
6705 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6706 
6707 		if (subprog[idx].has_tail_call)
6708 			tail_call_reachable = true;
6709 
6710 		frame++;
6711 		if (frame >= MAX_CALL_FRAMES) {
6712 			verbose(env, "the call stack of %d frames is too deep !\n",
6713 				frame);
6714 			return -E2BIG;
6715 		}
6716 		goto process_func;
6717 	}
6718 	/* if tail call got detected across bpf2bpf calls then mark each of the
6719 	 * currently present subprog frames as tail call reachable subprogs;
6720 	 * this info will be utilized by JIT so that we will be preserving the
6721 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6722 	 */
6723 	if (tail_call_reachable)
6724 		for (j = 0; j < frame; j++) {
6725 			if (subprog[ret_prog[j]].is_exception_cb) {
6726 				verbose(env, "cannot tail call within exception cb\n");
6727 				return -EINVAL;
6728 			}
6729 			subprog[ret_prog[j]].tail_call_reachable = true;
6730 		}
6731 	if (subprog[0].tail_call_reachable)
6732 		env->prog->aux->tail_call_reachable = true;
6733 
6734 	/* end of for() loop means the last insn of the 'subprog'
6735 	 * was reached. Doesn't matter whether it was JA or EXIT
6736 	 */
6737 	if (frame == 0)
6738 		return 0;
6739 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6740 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6741 	frame--;
6742 	i = ret_insn[frame];
6743 	idx = ret_prog[frame];
6744 	goto continue_func;
6745 }
6746 
6747 static int check_max_stack_depth(struct bpf_verifier_env *env)
6748 {
6749 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6750 	struct bpf_subprog_info *si = env->subprog_info;
6751 	bool priv_stack_supported;
6752 	int ret;
6753 
6754 	for (int i = 0; i < env->subprog_cnt; i++) {
6755 		if (si[i].has_tail_call) {
6756 			priv_stack_mode = NO_PRIV_STACK;
6757 			break;
6758 		}
6759 	}
6760 
6761 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6762 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6763 
6764 	/* All async_cb subprogs use normal kernel stack. If a particular
6765 	 * subprog appears in both main prog and async_cb subtree, that
6766 	 * subprog will use normal kernel stack to avoid potential nesting.
6767 	 * The reverse subprog traversal ensures when main prog subtree is
6768 	 * checked, the subprogs appearing in async_cb subtrees are already
6769 	 * marked as using normal kernel stack, so stack size checking can
6770 	 * be done properly.
6771 	 */
6772 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6773 		if (!i || si[i].is_async_cb) {
6774 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6775 			ret = check_max_stack_depth_subprog(env, i, priv_stack_supported);
6776 			if (ret < 0)
6777 				return ret;
6778 		}
6779 	}
6780 
6781 	for (int i = 0; i < env->subprog_cnt; i++) {
6782 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6783 			env->prog->aux->jits_use_priv_stack = true;
6784 			break;
6785 		}
6786 	}
6787 
6788 	return 0;
6789 }
6790 
6791 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6792 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6793 				  const struct bpf_insn *insn, int idx)
6794 {
6795 	int start = idx + insn->imm + 1, subprog;
6796 
6797 	subprog = find_subprog(env, start);
6798 	if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start))
6799 		return -EFAULT;
6800 	return env->subprog_info[subprog].stack_depth;
6801 }
6802 #endif
6803 
6804 static int __check_buffer_access(struct bpf_verifier_env *env,
6805 				 const char *buf_info,
6806 				 const struct bpf_reg_state *reg,
6807 				 int regno, int off, int size)
6808 {
6809 	if (off < 0) {
6810 		verbose(env,
6811 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6812 			regno, buf_info, off, size);
6813 		return -EACCES;
6814 	}
6815 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6816 		char tn_buf[48];
6817 
6818 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6819 		verbose(env,
6820 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6821 			regno, off, tn_buf);
6822 		return -EACCES;
6823 	}
6824 
6825 	return 0;
6826 }
6827 
6828 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6829 				  const struct bpf_reg_state *reg,
6830 				  int regno, int off, int size)
6831 {
6832 	int err;
6833 
6834 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6835 	if (err)
6836 		return err;
6837 
6838 	if (off + size > env->prog->aux->max_tp_access)
6839 		env->prog->aux->max_tp_access = off + size;
6840 
6841 	return 0;
6842 }
6843 
6844 static int check_buffer_access(struct bpf_verifier_env *env,
6845 			       const struct bpf_reg_state *reg,
6846 			       int regno, int off, int size,
6847 			       bool zero_size_allowed,
6848 			       u32 *max_access)
6849 {
6850 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6851 	int err;
6852 
6853 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6854 	if (err)
6855 		return err;
6856 
6857 	if (off + size > *max_access)
6858 		*max_access = off + size;
6859 
6860 	return 0;
6861 }
6862 
6863 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6864 static void zext_32_to_64(struct bpf_reg_state *reg)
6865 {
6866 	reg->var_off = tnum_subreg(reg->var_off);
6867 	__reg_assign_32_into_64(reg);
6868 }
6869 
6870 /* truncate register to smaller size (in bytes)
6871  * must be called with size < BPF_REG_SIZE
6872  */
6873 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6874 {
6875 	u64 mask;
6876 
6877 	/* clear high bits in bit representation */
6878 	reg->var_off = tnum_cast(reg->var_off, size);
6879 
6880 	/* fix arithmetic bounds */
6881 	mask = ((u64)1 << (size * 8)) - 1;
6882 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6883 		reg->umin_value &= mask;
6884 		reg->umax_value &= mask;
6885 	} else {
6886 		reg->umin_value = 0;
6887 		reg->umax_value = mask;
6888 	}
6889 	reg->smin_value = reg->umin_value;
6890 	reg->smax_value = reg->umax_value;
6891 
6892 	/* If size is smaller than 32bit register the 32bit register
6893 	 * values are also truncated so we push 64-bit bounds into
6894 	 * 32-bit bounds. Above were truncated < 32-bits already.
6895 	 */
6896 	if (size < 4)
6897 		__mark_reg32_unbounded(reg);
6898 
6899 	reg_bounds_sync(reg);
6900 }
6901 
6902 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6903 {
6904 	if (size == 1) {
6905 		reg->smin_value = reg->s32_min_value = S8_MIN;
6906 		reg->smax_value = reg->s32_max_value = S8_MAX;
6907 	} else if (size == 2) {
6908 		reg->smin_value = reg->s32_min_value = S16_MIN;
6909 		reg->smax_value = reg->s32_max_value = S16_MAX;
6910 	} else {
6911 		/* size == 4 */
6912 		reg->smin_value = reg->s32_min_value = S32_MIN;
6913 		reg->smax_value = reg->s32_max_value = S32_MAX;
6914 	}
6915 	reg->umin_value = reg->u32_min_value = 0;
6916 	reg->umax_value = U64_MAX;
6917 	reg->u32_max_value = U32_MAX;
6918 	reg->var_off = tnum_unknown;
6919 }
6920 
6921 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6922 {
6923 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6924 	u64 top_smax_value, top_smin_value;
6925 	u64 num_bits = size * 8;
6926 
6927 	if (tnum_is_const(reg->var_off)) {
6928 		u64_cval = reg->var_off.value;
6929 		if (size == 1)
6930 			reg->var_off = tnum_const((s8)u64_cval);
6931 		else if (size == 2)
6932 			reg->var_off = tnum_const((s16)u64_cval);
6933 		else
6934 			/* size == 4 */
6935 			reg->var_off = tnum_const((s32)u64_cval);
6936 
6937 		u64_cval = reg->var_off.value;
6938 		reg->smax_value = reg->smin_value = u64_cval;
6939 		reg->umax_value = reg->umin_value = u64_cval;
6940 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6941 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6942 		return;
6943 	}
6944 
6945 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6946 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6947 
6948 	if (top_smax_value != top_smin_value)
6949 		goto out;
6950 
6951 	/* find the s64_min and s64_min after sign extension */
6952 	if (size == 1) {
6953 		init_s64_max = (s8)reg->smax_value;
6954 		init_s64_min = (s8)reg->smin_value;
6955 	} else if (size == 2) {
6956 		init_s64_max = (s16)reg->smax_value;
6957 		init_s64_min = (s16)reg->smin_value;
6958 	} else {
6959 		init_s64_max = (s32)reg->smax_value;
6960 		init_s64_min = (s32)reg->smin_value;
6961 	}
6962 
6963 	s64_max = max(init_s64_max, init_s64_min);
6964 	s64_min = min(init_s64_max, init_s64_min);
6965 
6966 	/* both of s64_max/s64_min positive or negative */
6967 	if ((s64_max >= 0) == (s64_min >= 0)) {
6968 		reg->s32_min_value = reg->smin_value = s64_min;
6969 		reg->s32_max_value = reg->smax_value = s64_max;
6970 		reg->u32_min_value = reg->umin_value = s64_min;
6971 		reg->u32_max_value = reg->umax_value = s64_max;
6972 		reg->var_off = tnum_range(s64_min, s64_max);
6973 		return;
6974 	}
6975 
6976 out:
6977 	set_sext64_default_val(reg, size);
6978 }
6979 
6980 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6981 {
6982 	if (size == 1) {
6983 		reg->s32_min_value = S8_MIN;
6984 		reg->s32_max_value = S8_MAX;
6985 	} else {
6986 		/* size == 2 */
6987 		reg->s32_min_value = S16_MIN;
6988 		reg->s32_max_value = S16_MAX;
6989 	}
6990 	reg->u32_min_value = 0;
6991 	reg->u32_max_value = U32_MAX;
6992 	reg->var_off = tnum_subreg(tnum_unknown);
6993 }
6994 
6995 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6996 {
6997 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6998 	u32 top_smax_value, top_smin_value;
6999 	u32 num_bits = size * 8;
7000 
7001 	if (tnum_is_const(reg->var_off)) {
7002 		u32_val = reg->var_off.value;
7003 		if (size == 1)
7004 			reg->var_off = tnum_const((s8)u32_val);
7005 		else
7006 			reg->var_off = tnum_const((s16)u32_val);
7007 
7008 		u32_val = reg->var_off.value;
7009 		reg->s32_min_value = reg->s32_max_value = u32_val;
7010 		reg->u32_min_value = reg->u32_max_value = u32_val;
7011 		return;
7012 	}
7013 
7014 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
7015 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
7016 
7017 	if (top_smax_value != top_smin_value)
7018 		goto out;
7019 
7020 	/* find the s32_min and s32_min after sign extension */
7021 	if (size == 1) {
7022 		init_s32_max = (s8)reg->s32_max_value;
7023 		init_s32_min = (s8)reg->s32_min_value;
7024 	} else {
7025 		/* size == 2 */
7026 		init_s32_max = (s16)reg->s32_max_value;
7027 		init_s32_min = (s16)reg->s32_min_value;
7028 	}
7029 	s32_max = max(init_s32_max, init_s32_min);
7030 	s32_min = min(init_s32_max, init_s32_min);
7031 
7032 	if ((s32_min >= 0) == (s32_max >= 0)) {
7033 		reg->s32_min_value = s32_min;
7034 		reg->s32_max_value = s32_max;
7035 		reg->u32_min_value = (u32)s32_min;
7036 		reg->u32_max_value = (u32)s32_max;
7037 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
7038 		return;
7039 	}
7040 
7041 out:
7042 	set_sext32_default_val(reg, size);
7043 }
7044 
7045 static bool bpf_map_is_rdonly(const struct bpf_map *map)
7046 {
7047 	/* A map is considered read-only if the following condition are true:
7048 	 *
7049 	 * 1) BPF program side cannot change any of the map content. The
7050 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
7051 	 *    and was set at map creation time.
7052 	 * 2) The map value(s) have been initialized from user space by a
7053 	 *    loader and then "frozen", such that no new map update/delete
7054 	 *    operations from syscall side are possible for the rest of
7055 	 *    the map's lifetime from that point onwards.
7056 	 * 3) Any parallel/pending map update/delete operations from syscall
7057 	 *    side have been completed. Only after that point, it's safe to
7058 	 *    assume that map value(s) are immutable.
7059 	 */
7060 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
7061 	       READ_ONCE(map->frozen) &&
7062 	       !bpf_map_write_active(map);
7063 }
7064 
7065 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
7066 			       bool is_ldsx)
7067 {
7068 	void *ptr;
7069 	u64 addr;
7070 	int err;
7071 
7072 	err = map->ops->map_direct_value_addr(map, &addr, off);
7073 	if (err)
7074 		return err;
7075 	ptr = (void *)(long)addr + off;
7076 
7077 	switch (size) {
7078 	case sizeof(u8):
7079 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
7080 		break;
7081 	case sizeof(u16):
7082 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
7083 		break;
7084 	case sizeof(u32):
7085 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
7086 		break;
7087 	case sizeof(u64):
7088 		*val = *(u64 *)ptr;
7089 		break;
7090 	default:
7091 		return -EINVAL;
7092 	}
7093 	return 0;
7094 }
7095 
7096 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
7097 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
7098 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
7099 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
7100 
7101 /*
7102  * Allow list few fields as RCU trusted or full trusted.
7103  * This logic doesn't allow mix tagging and will be removed once GCC supports
7104  * btf_type_tag.
7105  */
7106 
7107 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
7108 BTF_TYPE_SAFE_RCU(struct task_struct) {
7109 	const cpumask_t *cpus_ptr;
7110 	struct css_set __rcu *cgroups;
7111 	struct task_struct __rcu *real_parent;
7112 	struct task_struct *group_leader;
7113 };
7114 
7115 BTF_TYPE_SAFE_RCU(struct cgroup) {
7116 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
7117 	struct kernfs_node *kn;
7118 };
7119 
7120 BTF_TYPE_SAFE_RCU(struct css_set) {
7121 	struct cgroup *dfl_cgrp;
7122 };
7123 
7124 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
7125 	struct cgroup *cgroup;
7126 };
7127 
7128 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
7129 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
7130 	struct file __rcu *exe_file;
7131 };
7132 
7133 /* skb->sk, req->sk are not RCU protected, but we mark them as such
7134  * because bpf prog accessible sockets are SOCK_RCU_FREE.
7135  */
7136 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
7137 	struct sock *sk;
7138 };
7139 
7140 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
7141 	struct sock *sk;
7142 };
7143 
7144 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
7145 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
7146 	struct seq_file *seq;
7147 };
7148 
7149 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
7150 	struct bpf_iter_meta *meta;
7151 	struct task_struct *task;
7152 };
7153 
7154 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
7155 	struct file *file;
7156 };
7157 
7158 BTF_TYPE_SAFE_TRUSTED(struct file) {
7159 	struct inode *f_inode;
7160 };
7161 
7162 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
7163 	struct inode *d_inode;
7164 };
7165 
7166 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
7167 	struct sock *sk;
7168 };
7169 
7170 static bool type_is_rcu(struct bpf_verifier_env *env,
7171 			struct bpf_reg_state *reg,
7172 			const char *field_name, u32 btf_id)
7173 {
7174 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
7175 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
7176 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
7177 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
7178 
7179 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
7180 }
7181 
7182 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
7183 				struct bpf_reg_state *reg,
7184 				const char *field_name, u32 btf_id)
7185 {
7186 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
7187 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
7188 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
7189 
7190 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
7191 }
7192 
7193 static bool type_is_trusted(struct bpf_verifier_env *env,
7194 			    struct bpf_reg_state *reg,
7195 			    const char *field_name, u32 btf_id)
7196 {
7197 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
7198 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
7199 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
7200 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
7201 
7202 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
7203 }
7204 
7205 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
7206 				    struct bpf_reg_state *reg,
7207 				    const char *field_name, u32 btf_id)
7208 {
7209 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
7210 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
7211 
7212 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
7213 					  "__safe_trusted_or_null");
7214 }
7215 
7216 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
7217 				   struct bpf_reg_state *regs,
7218 				   int regno, int off, int size,
7219 				   enum bpf_access_type atype,
7220 				   int value_regno)
7221 {
7222 	struct bpf_reg_state *reg = regs + regno;
7223 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
7224 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
7225 	const char *field_name = NULL;
7226 	enum bpf_type_flag flag = 0;
7227 	u32 btf_id = 0;
7228 	int ret;
7229 
7230 	if (!env->allow_ptr_leaks) {
7231 		verbose(env,
7232 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7233 			tname);
7234 		return -EPERM;
7235 	}
7236 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
7237 		verbose(env,
7238 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
7239 			tname);
7240 		return -EINVAL;
7241 	}
7242 	if (off < 0) {
7243 		verbose(env,
7244 			"R%d is ptr_%s invalid negative access: off=%d\n",
7245 			regno, tname, off);
7246 		return -EACCES;
7247 	}
7248 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
7249 		char tn_buf[48];
7250 
7251 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7252 		verbose(env,
7253 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
7254 			regno, tname, off, tn_buf);
7255 		return -EACCES;
7256 	}
7257 
7258 	if (reg->type & MEM_USER) {
7259 		verbose(env,
7260 			"R%d is ptr_%s access user memory: off=%d\n",
7261 			regno, tname, off);
7262 		return -EACCES;
7263 	}
7264 
7265 	if (reg->type & MEM_PERCPU) {
7266 		verbose(env,
7267 			"R%d is ptr_%s access percpu memory: off=%d\n",
7268 			regno, tname, off);
7269 		return -EACCES;
7270 	}
7271 
7272 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
7273 		if (!btf_is_kernel(reg->btf)) {
7274 			verifier_bug(env, "reg->btf must be kernel btf");
7275 			return -EFAULT;
7276 		}
7277 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
7278 	} else {
7279 		/* Writes are permitted with default btf_struct_access for
7280 		 * program allocated objects (which always have ref_obj_id > 0),
7281 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
7282 		 */
7283 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
7284 			verbose(env, "only read is supported\n");
7285 			return -EACCES;
7286 		}
7287 
7288 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
7289 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
7290 			verifier_bug(env, "ref_obj_id for allocated object must be non-zero");
7291 			return -EFAULT;
7292 		}
7293 
7294 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
7295 	}
7296 
7297 	if (ret < 0)
7298 		return ret;
7299 
7300 	if (ret != PTR_TO_BTF_ID) {
7301 		/* just mark; */
7302 
7303 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
7304 		/* If this is an untrusted pointer, all pointers formed by walking it
7305 		 * also inherit the untrusted flag.
7306 		 */
7307 		flag = PTR_UNTRUSTED;
7308 
7309 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
7310 		/* By default any pointer obtained from walking a trusted pointer is no
7311 		 * longer trusted, unless the field being accessed has explicitly been
7312 		 * marked as inheriting its parent's state of trust (either full or RCU).
7313 		 * For example:
7314 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
7315 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
7316 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
7317 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
7318 		 *
7319 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
7320 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
7321 		 */
7322 		if (type_is_trusted(env, reg, field_name, btf_id)) {
7323 			flag |= PTR_TRUSTED;
7324 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
7325 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
7326 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
7327 			if (type_is_rcu(env, reg, field_name, btf_id)) {
7328 				/* ignore __rcu tag and mark it MEM_RCU */
7329 				flag |= MEM_RCU;
7330 			} else if (flag & MEM_RCU ||
7331 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
7332 				/* __rcu tagged pointers can be NULL */
7333 				flag |= MEM_RCU | PTR_MAYBE_NULL;
7334 
7335 				/* We always trust them */
7336 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
7337 				    flag & PTR_UNTRUSTED)
7338 					flag &= ~PTR_UNTRUSTED;
7339 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
7340 				/* keep as-is */
7341 			} else {
7342 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
7343 				clear_trusted_flags(&flag);
7344 			}
7345 		} else {
7346 			/*
7347 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
7348 			 * aggressively mark as untrusted otherwise such
7349 			 * pointers will be plain PTR_TO_BTF_ID without flags
7350 			 * and will be allowed to be passed into helpers for
7351 			 * compat reasons.
7352 			 */
7353 			flag = PTR_UNTRUSTED;
7354 		}
7355 	} else {
7356 		/* Old compat. Deprecated */
7357 		clear_trusted_flags(&flag);
7358 	}
7359 
7360 	if (atype == BPF_READ && value_regno >= 0) {
7361 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
7362 		if (ret < 0)
7363 			return ret;
7364 	}
7365 
7366 	return 0;
7367 }
7368 
7369 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
7370 				   struct bpf_reg_state *regs,
7371 				   int regno, int off, int size,
7372 				   enum bpf_access_type atype,
7373 				   int value_regno)
7374 {
7375 	struct bpf_reg_state *reg = regs + regno;
7376 	struct bpf_map *map = reg->map_ptr;
7377 	struct bpf_reg_state map_reg;
7378 	enum bpf_type_flag flag = 0;
7379 	const struct btf_type *t;
7380 	const char *tname;
7381 	u32 btf_id;
7382 	int ret;
7383 
7384 	if (!btf_vmlinux) {
7385 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
7386 		return -ENOTSUPP;
7387 	}
7388 
7389 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
7390 		verbose(env, "map_ptr access not supported for map type %d\n",
7391 			map->map_type);
7392 		return -ENOTSUPP;
7393 	}
7394 
7395 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
7396 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
7397 
7398 	if (!env->allow_ptr_leaks) {
7399 		verbose(env,
7400 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7401 			tname);
7402 		return -EPERM;
7403 	}
7404 
7405 	if (off < 0) {
7406 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
7407 			regno, tname, off);
7408 		return -EACCES;
7409 	}
7410 
7411 	if (atype != BPF_READ) {
7412 		verbose(env, "only read from %s is supported\n", tname);
7413 		return -EACCES;
7414 	}
7415 
7416 	/* Simulate access to a PTR_TO_BTF_ID */
7417 	memset(&map_reg, 0, sizeof(map_reg));
7418 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
7419 			      btf_vmlinux, *map->ops->map_btf_id, 0);
7420 	if (ret < 0)
7421 		return ret;
7422 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
7423 	if (ret < 0)
7424 		return ret;
7425 
7426 	if (value_regno >= 0) {
7427 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
7428 		if (ret < 0)
7429 			return ret;
7430 	}
7431 
7432 	return 0;
7433 }
7434 
7435 /* Check that the stack access at the given offset is within bounds. The
7436  * maximum valid offset is -1.
7437  *
7438  * The minimum valid offset is -MAX_BPF_STACK for writes, and
7439  * -state->allocated_stack for reads.
7440  */
7441 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
7442                                           s64 off,
7443                                           struct bpf_func_state *state,
7444                                           enum bpf_access_type t)
7445 {
7446 	int min_valid_off;
7447 
7448 	if (t == BPF_WRITE || env->allow_uninit_stack)
7449 		min_valid_off = -MAX_BPF_STACK;
7450 	else
7451 		min_valid_off = -state->allocated_stack;
7452 
7453 	if (off < min_valid_off || off > -1)
7454 		return -EACCES;
7455 	return 0;
7456 }
7457 
7458 /* Check that the stack access at 'regno + off' falls within the maximum stack
7459  * bounds.
7460  *
7461  * 'off' includes `regno->offset`, but not its dynamic part (if any).
7462  */
7463 static int check_stack_access_within_bounds(
7464 		struct bpf_verifier_env *env,
7465 		int regno, int off, int access_size,
7466 		enum bpf_access_type type)
7467 {
7468 	struct bpf_reg_state *regs = cur_regs(env);
7469 	struct bpf_reg_state *reg = regs + regno;
7470 	struct bpf_func_state *state = func(env, reg);
7471 	s64 min_off, max_off;
7472 	int err;
7473 	char *err_extra;
7474 
7475 	if (type == BPF_READ)
7476 		err_extra = " read from";
7477 	else
7478 		err_extra = " write to";
7479 
7480 	if (tnum_is_const(reg->var_off)) {
7481 		min_off = (s64)reg->var_off.value + off;
7482 		max_off = min_off + access_size;
7483 	} else {
7484 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
7485 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
7486 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
7487 				err_extra, regno);
7488 			return -EACCES;
7489 		}
7490 		min_off = reg->smin_value + off;
7491 		max_off = reg->smax_value + off + access_size;
7492 	}
7493 
7494 	err = check_stack_slot_within_bounds(env, min_off, state, type);
7495 	if (!err && max_off > 0)
7496 		err = -EINVAL; /* out of stack access into non-negative offsets */
7497 	if (!err && access_size < 0)
7498 		/* access_size should not be negative (or overflow an int); others checks
7499 		 * along the way should have prevented such an access.
7500 		 */
7501 		err = -EFAULT; /* invalid negative access size; integer overflow? */
7502 
7503 	if (err) {
7504 		if (tnum_is_const(reg->var_off)) {
7505 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
7506 				err_extra, regno, off, access_size);
7507 		} else {
7508 			char tn_buf[48];
7509 
7510 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7511 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
7512 				err_extra, regno, tn_buf, off, access_size);
7513 		}
7514 		return err;
7515 	}
7516 
7517 	/* Note that there is no stack access with offset zero, so the needed stack
7518 	 * size is -min_off, not -min_off+1.
7519 	 */
7520 	return grow_stack_state(env, state, -min_off /* size */);
7521 }
7522 
7523 static bool get_func_retval_range(struct bpf_prog *prog,
7524 				  struct bpf_retval_range *range)
7525 {
7526 	if (prog->type == BPF_PROG_TYPE_LSM &&
7527 		prog->expected_attach_type == BPF_LSM_MAC &&
7528 		!bpf_lsm_get_retval_range(prog, range)) {
7529 		return true;
7530 	}
7531 	return false;
7532 }
7533 
7534 /* check whether memory at (regno + off) is accessible for t = (read | write)
7535  * if t==write, value_regno is a register which value is stored into memory
7536  * if t==read, value_regno is a register which will receive the value from memory
7537  * if t==write && value_regno==-1, some unknown value is stored into memory
7538  * if t==read && value_regno==-1, don't care what we read from memory
7539  */
7540 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
7541 			    int off, int bpf_size, enum bpf_access_type t,
7542 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7543 {
7544 	struct bpf_reg_state *regs = cur_regs(env);
7545 	struct bpf_reg_state *reg = regs + regno;
7546 	int size, err = 0;
7547 
7548 	size = bpf_size_to_bytes(bpf_size);
7549 	if (size < 0)
7550 		return size;
7551 
7552 	/* alignment checks will add in reg->off themselves */
7553 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7554 	if (err)
7555 		return err;
7556 
7557 	/* for access checks, reg->off is just part of off */
7558 	off += reg->off;
7559 
7560 	if (reg->type == PTR_TO_MAP_KEY) {
7561 		if (t == BPF_WRITE) {
7562 			verbose(env, "write to change key R%d not allowed\n", regno);
7563 			return -EACCES;
7564 		}
7565 
7566 		err = check_mem_region_access(env, regno, off, size,
7567 					      reg->map_ptr->key_size, false);
7568 		if (err)
7569 			return err;
7570 		if (value_regno >= 0)
7571 			mark_reg_unknown(env, regs, value_regno);
7572 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7573 		struct btf_field *kptr_field = NULL;
7574 
7575 		if (t == BPF_WRITE && value_regno >= 0 &&
7576 		    is_pointer_value(env, value_regno)) {
7577 			verbose(env, "R%d leaks addr into map\n", value_regno);
7578 			return -EACCES;
7579 		}
7580 		err = check_map_access_type(env, regno, off, size, t);
7581 		if (err)
7582 			return err;
7583 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
7584 		if (err)
7585 			return err;
7586 		if (tnum_is_const(reg->var_off))
7587 			kptr_field = btf_record_find(reg->map_ptr->record,
7588 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7589 		if (kptr_field) {
7590 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
7591 		} else if (t == BPF_READ && value_regno >= 0) {
7592 			struct bpf_map *map = reg->map_ptr;
7593 
7594 			/* if map is read-only, track its contents as scalars */
7595 			if (tnum_is_const(reg->var_off) &&
7596 			    bpf_map_is_rdonly(map) &&
7597 			    map->ops->map_direct_value_addr) {
7598 				int map_off = off + reg->var_off.value;
7599 				u64 val = 0;
7600 
7601 				err = bpf_map_direct_read(map, map_off, size,
7602 							  &val, is_ldsx);
7603 				if (err)
7604 					return err;
7605 
7606 				regs[value_regno].type = SCALAR_VALUE;
7607 				__mark_reg_known(&regs[value_regno], val);
7608 			} else {
7609 				mark_reg_unknown(env, regs, value_regno);
7610 			}
7611 		}
7612 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7613 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7614 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
7615 
7616 		if (type_may_be_null(reg->type)) {
7617 			verbose(env, "R%d invalid mem access '%s'\n", regno,
7618 				reg_type_str(env, reg->type));
7619 			return -EACCES;
7620 		}
7621 
7622 		if (t == BPF_WRITE && rdonly_mem) {
7623 			verbose(env, "R%d cannot write into %s\n",
7624 				regno, reg_type_str(env, reg->type));
7625 			return -EACCES;
7626 		}
7627 
7628 		if (t == BPF_WRITE && value_regno >= 0 &&
7629 		    is_pointer_value(env, value_regno)) {
7630 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7631 			return -EACCES;
7632 		}
7633 
7634 		/*
7635 		 * Accesses to untrusted PTR_TO_MEM are done through probe
7636 		 * instructions, hence no need to check bounds in that case.
7637 		 */
7638 		if (!rdonly_untrusted)
7639 			err = check_mem_region_access(env, regno, off, size,
7640 						      reg->mem_size, false);
7641 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7642 			mark_reg_unknown(env, regs, value_regno);
7643 	} else if (reg->type == PTR_TO_CTX) {
7644 		struct bpf_retval_range range;
7645 		struct bpf_insn_access_aux info = {
7646 			.reg_type = SCALAR_VALUE,
7647 			.is_ldsx = is_ldsx,
7648 			.log = &env->log,
7649 		};
7650 
7651 		if (t == BPF_WRITE && value_regno >= 0 &&
7652 		    is_pointer_value(env, value_regno)) {
7653 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7654 			return -EACCES;
7655 		}
7656 
7657 		err = check_ptr_off_reg(env, reg, regno);
7658 		if (err < 0)
7659 			return err;
7660 
7661 		err = check_ctx_access(env, insn_idx, off, size, t, &info);
7662 		if (err)
7663 			verbose_linfo(env, insn_idx, "; ");
7664 		if (!err && t == BPF_READ && value_regno >= 0) {
7665 			/* ctx access returns either a scalar, or a
7666 			 * PTR_TO_PACKET[_META,_END]. In the latter
7667 			 * case, we know the offset is zero.
7668 			 */
7669 			if (info.reg_type == SCALAR_VALUE) {
7670 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
7671 					err = __mark_reg_s32_range(env, regs, value_regno,
7672 								   range.minval, range.maxval);
7673 					if (err)
7674 						return err;
7675 				} else {
7676 					mark_reg_unknown(env, regs, value_regno);
7677 				}
7678 			} else {
7679 				mark_reg_known_zero(env, regs,
7680 						    value_regno);
7681 				if (type_may_be_null(info.reg_type))
7682 					regs[value_regno].id = ++env->id_gen;
7683 				/* A load of ctx field could have different
7684 				 * actual load size with the one encoded in the
7685 				 * insn. When the dst is PTR, it is for sure not
7686 				 * a sub-register.
7687 				 */
7688 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7689 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
7690 					regs[value_regno].btf = info.btf;
7691 					regs[value_regno].btf_id = info.btf_id;
7692 					regs[value_regno].ref_obj_id = info.ref_obj_id;
7693 				}
7694 			}
7695 			regs[value_regno].type = info.reg_type;
7696 		}
7697 
7698 	} else if (reg->type == PTR_TO_STACK) {
7699 		/* Basic bounds checks. */
7700 		err = check_stack_access_within_bounds(env, regno, off, size, t);
7701 		if (err)
7702 			return err;
7703 
7704 		if (t == BPF_READ)
7705 			err = check_stack_read(env, regno, off, size,
7706 					       value_regno);
7707 		else
7708 			err = check_stack_write(env, regno, off, size,
7709 						value_regno, insn_idx);
7710 	} else if (reg_is_pkt_pointer(reg)) {
7711 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7712 			verbose(env, "cannot write into packet\n");
7713 			return -EACCES;
7714 		}
7715 		if (t == BPF_WRITE && value_regno >= 0 &&
7716 		    is_pointer_value(env, value_regno)) {
7717 			verbose(env, "R%d leaks addr into packet\n",
7718 				value_regno);
7719 			return -EACCES;
7720 		}
7721 		err = check_packet_access(env, regno, off, size, false);
7722 		if (!err && t == BPF_READ && value_regno >= 0)
7723 			mark_reg_unknown(env, regs, value_regno);
7724 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7725 		if (t == BPF_WRITE && value_regno >= 0 &&
7726 		    is_pointer_value(env, value_regno)) {
7727 			verbose(env, "R%d leaks addr into flow keys\n",
7728 				value_regno);
7729 			return -EACCES;
7730 		}
7731 
7732 		err = check_flow_keys_access(env, off, size);
7733 		if (!err && t == BPF_READ && value_regno >= 0)
7734 			mark_reg_unknown(env, regs, value_regno);
7735 	} else if (type_is_sk_pointer(reg->type)) {
7736 		if (t == BPF_WRITE) {
7737 			verbose(env, "R%d cannot write into %s\n",
7738 				regno, reg_type_str(env, reg->type));
7739 			return -EACCES;
7740 		}
7741 		err = check_sock_access(env, insn_idx, regno, off, size, t);
7742 		if (!err && value_regno >= 0)
7743 			mark_reg_unknown(env, regs, value_regno);
7744 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7745 		err = check_tp_buffer_access(env, reg, regno, off, size);
7746 		if (!err && t == BPF_READ && value_regno >= 0)
7747 			mark_reg_unknown(env, regs, value_regno);
7748 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7749 		   !type_may_be_null(reg->type)) {
7750 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7751 					      value_regno);
7752 	} else if (reg->type == CONST_PTR_TO_MAP) {
7753 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7754 					      value_regno);
7755 	} else if (base_type(reg->type) == PTR_TO_BUF) {
7756 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7757 		u32 *max_access;
7758 
7759 		if (rdonly_mem) {
7760 			if (t == BPF_WRITE) {
7761 				verbose(env, "R%d cannot write into %s\n",
7762 					regno, reg_type_str(env, reg->type));
7763 				return -EACCES;
7764 			}
7765 			max_access = &env->prog->aux->max_rdonly_access;
7766 		} else {
7767 			max_access = &env->prog->aux->max_rdwr_access;
7768 		}
7769 
7770 		err = check_buffer_access(env, reg, regno, off, size, false,
7771 					  max_access);
7772 
7773 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7774 			mark_reg_unknown(env, regs, value_regno);
7775 	} else if (reg->type == PTR_TO_ARENA) {
7776 		if (t == BPF_READ && value_regno >= 0)
7777 			mark_reg_unknown(env, regs, value_regno);
7778 	} else {
7779 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7780 			reg_type_str(env, reg->type));
7781 		return -EACCES;
7782 	}
7783 
7784 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7785 	    regs[value_regno].type == SCALAR_VALUE) {
7786 		if (!is_ldsx)
7787 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7788 			coerce_reg_to_size(&regs[value_regno], size);
7789 		else
7790 			coerce_reg_to_size_sx(&regs[value_regno], size);
7791 	}
7792 	return err;
7793 }
7794 
7795 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7796 			     bool allow_trust_mismatch);
7797 
7798 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
7799 			  bool strict_alignment_once, bool is_ldsx,
7800 			  bool allow_trust_mismatch, const char *ctx)
7801 {
7802 	struct bpf_reg_state *regs = cur_regs(env);
7803 	enum bpf_reg_type src_reg_type;
7804 	int err;
7805 
7806 	/* check src operand */
7807 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7808 	if (err)
7809 		return err;
7810 
7811 	/* check dst operand */
7812 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7813 	if (err)
7814 		return err;
7815 
7816 	src_reg_type = regs[insn->src_reg].type;
7817 
7818 	/* Check if (src_reg + off) is readable. The state of dst_reg will be
7819 	 * updated by this call.
7820 	 */
7821 	err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off,
7822 			       BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
7823 			       strict_alignment_once, is_ldsx);
7824 	err = err ?: save_aux_ptr_type(env, src_reg_type,
7825 				       allow_trust_mismatch);
7826 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
7827 
7828 	return err;
7829 }
7830 
7831 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
7832 			   bool strict_alignment_once)
7833 {
7834 	struct bpf_reg_state *regs = cur_regs(env);
7835 	enum bpf_reg_type dst_reg_type;
7836 	int err;
7837 
7838 	/* check src1 operand */
7839 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7840 	if (err)
7841 		return err;
7842 
7843 	/* check src2 operand */
7844 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7845 	if (err)
7846 		return err;
7847 
7848 	dst_reg_type = regs[insn->dst_reg].type;
7849 
7850 	/* Check if (dst_reg + off) is writeable. */
7851 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7852 			       BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
7853 			       strict_alignment_once, false);
7854 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
7855 
7856 	return err;
7857 }
7858 
7859 static int check_atomic_rmw(struct bpf_verifier_env *env,
7860 			    struct bpf_insn *insn)
7861 {
7862 	int load_reg;
7863 	int err;
7864 
7865 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7866 		verbose(env, "invalid atomic operand size\n");
7867 		return -EINVAL;
7868 	}
7869 
7870 	/* check src1 operand */
7871 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7872 	if (err)
7873 		return err;
7874 
7875 	/* check src2 operand */
7876 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7877 	if (err)
7878 		return err;
7879 
7880 	if (insn->imm == BPF_CMPXCHG) {
7881 		/* Check comparison of R0 with memory location */
7882 		const u32 aux_reg = BPF_REG_0;
7883 
7884 		err = check_reg_arg(env, aux_reg, SRC_OP);
7885 		if (err)
7886 			return err;
7887 
7888 		if (is_pointer_value(env, aux_reg)) {
7889 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7890 			return -EACCES;
7891 		}
7892 	}
7893 
7894 	if (is_pointer_value(env, insn->src_reg)) {
7895 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7896 		return -EACCES;
7897 	}
7898 
7899 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7900 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7901 			insn->dst_reg,
7902 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7903 		return -EACCES;
7904 	}
7905 
7906 	if (insn->imm & BPF_FETCH) {
7907 		if (insn->imm == BPF_CMPXCHG)
7908 			load_reg = BPF_REG_0;
7909 		else
7910 			load_reg = insn->src_reg;
7911 
7912 		/* check and record load of old value */
7913 		err = check_reg_arg(env, load_reg, DST_OP);
7914 		if (err)
7915 			return err;
7916 	} else {
7917 		/* This instruction accesses a memory location but doesn't
7918 		 * actually load it into a register.
7919 		 */
7920 		load_reg = -1;
7921 	}
7922 
7923 	/* Check whether we can read the memory, with second call for fetch
7924 	 * case to simulate the register fill.
7925 	 */
7926 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7927 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7928 	if (!err && load_reg >= 0)
7929 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
7930 				       insn->off, BPF_SIZE(insn->code),
7931 				       BPF_READ, load_reg, true, false);
7932 	if (err)
7933 		return err;
7934 
7935 	if (is_arena_reg(env, insn->dst_reg)) {
7936 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7937 		if (err)
7938 			return err;
7939 	}
7940 	/* Check whether we can write into the same memory. */
7941 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7942 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7943 	if (err)
7944 		return err;
7945 	return 0;
7946 }
7947 
7948 static int check_atomic_load(struct bpf_verifier_env *env,
7949 			     struct bpf_insn *insn)
7950 {
7951 	int err;
7952 
7953 	err = check_load_mem(env, insn, true, false, false, "atomic_load");
7954 	if (err)
7955 		return err;
7956 
7957 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
7958 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
7959 			insn->src_reg,
7960 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
7961 		return -EACCES;
7962 	}
7963 
7964 	return 0;
7965 }
7966 
7967 static int check_atomic_store(struct bpf_verifier_env *env,
7968 			      struct bpf_insn *insn)
7969 {
7970 	int err;
7971 
7972 	err = check_store_reg(env, insn, true);
7973 	if (err)
7974 		return err;
7975 
7976 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7977 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7978 			insn->dst_reg,
7979 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7980 		return -EACCES;
7981 	}
7982 
7983 	return 0;
7984 }
7985 
7986 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
7987 {
7988 	switch (insn->imm) {
7989 	case BPF_ADD:
7990 	case BPF_ADD | BPF_FETCH:
7991 	case BPF_AND:
7992 	case BPF_AND | BPF_FETCH:
7993 	case BPF_OR:
7994 	case BPF_OR | BPF_FETCH:
7995 	case BPF_XOR:
7996 	case BPF_XOR | BPF_FETCH:
7997 	case BPF_XCHG:
7998 	case BPF_CMPXCHG:
7999 		return check_atomic_rmw(env, insn);
8000 	case BPF_LOAD_ACQ:
8001 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
8002 			verbose(env,
8003 				"64-bit load-acquires are only supported on 64-bit arches\n");
8004 			return -EOPNOTSUPP;
8005 		}
8006 		return check_atomic_load(env, insn);
8007 	case BPF_STORE_REL:
8008 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
8009 			verbose(env,
8010 				"64-bit store-releases are only supported on 64-bit arches\n");
8011 			return -EOPNOTSUPP;
8012 		}
8013 		return check_atomic_store(env, insn);
8014 	default:
8015 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
8016 			insn->imm);
8017 		return -EINVAL;
8018 	}
8019 }
8020 
8021 /* When register 'regno' is used to read the stack (either directly or through
8022  * a helper function) make sure that it's within stack boundary and, depending
8023  * on the access type and privileges, that all elements of the stack are
8024  * initialized.
8025  *
8026  * 'off' includes 'regno->off', but not its dynamic part (if any).
8027  *
8028  * All registers that have been spilled on the stack in the slots within the
8029  * read offsets are marked as read.
8030  */
8031 static int check_stack_range_initialized(
8032 		struct bpf_verifier_env *env, int regno, int off,
8033 		int access_size, bool zero_size_allowed,
8034 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
8035 {
8036 	struct bpf_reg_state *reg = reg_state(env, regno);
8037 	struct bpf_func_state *state = func(env, reg);
8038 	int err, min_off, max_off, i, j, slot, spi;
8039 	/* Some accesses can write anything into the stack, others are
8040 	 * read-only.
8041 	 */
8042 	bool clobber = false;
8043 
8044 	if (access_size == 0 && !zero_size_allowed) {
8045 		verbose(env, "invalid zero-sized read\n");
8046 		return -EACCES;
8047 	}
8048 
8049 	if (type == BPF_WRITE)
8050 		clobber = true;
8051 
8052 	err = check_stack_access_within_bounds(env, regno, off, access_size, type);
8053 	if (err)
8054 		return err;
8055 
8056 
8057 	if (tnum_is_const(reg->var_off)) {
8058 		min_off = max_off = reg->var_off.value + off;
8059 	} else {
8060 		/* Variable offset is prohibited for unprivileged mode for
8061 		 * simplicity since it requires corresponding support in
8062 		 * Spectre masking for stack ALU.
8063 		 * See also retrieve_ptr_limit().
8064 		 */
8065 		if (!env->bypass_spec_v1) {
8066 			char tn_buf[48];
8067 
8068 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8069 			verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
8070 				regno, tn_buf);
8071 			return -EACCES;
8072 		}
8073 		/* Only initialized buffer on stack is allowed to be accessed
8074 		 * with variable offset. With uninitialized buffer it's hard to
8075 		 * guarantee that whole memory is marked as initialized on
8076 		 * helper return since specific bounds are unknown what may
8077 		 * cause uninitialized stack leaking.
8078 		 */
8079 		if (meta && meta->raw_mode)
8080 			meta = NULL;
8081 
8082 		min_off = reg->smin_value + off;
8083 		max_off = reg->smax_value + off;
8084 	}
8085 
8086 	if (meta && meta->raw_mode) {
8087 		/* Ensure we won't be overwriting dynptrs when simulating byte
8088 		 * by byte access in check_helper_call using meta.access_size.
8089 		 * This would be a problem if we have a helper in the future
8090 		 * which takes:
8091 		 *
8092 		 *	helper(uninit_mem, len, dynptr)
8093 		 *
8094 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
8095 		 * may end up writing to dynptr itself when touching memory from
8096 		 * arg 1. This can be relaxed on a case by case basis for known
8097 		 * safe cases, but reject due to the possibilitiy of aliasing by
8098 		 * default.
8099 		 */
8100 		for (i = min_off; i < max_off + access_size; i++) {
8101 			int stack_off = -i - 1;
8102 
8103 			spi = __get_spi(i);
8104 			/* raw_mode may write past allocated_stack */
8105 			if (state->allocated_stack <= stack_off)
8106 				continue;
8107 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
8108 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
8109 				return -EACCES;
8110 			}
8111 		}
8112 		meta->access_size = access_size;
8113 		meta->regno = regno;
8114 		return 0;
8115 	}
8116 
8117 	for (i = min_off; i < max_off + access_size; i++) {
8118 		u8 *stype;
8119 
8120 		slot = -i - 1;
8121 		spi = slot / BPF_REG_SIZE;
8122 		if (state->allocated_stack <= slot) {
8123 			verbose(env, "allocated_stack too small\n");
8124 			return -EFAULT;
8125 		}
8126 
8127 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
8128 		if (*stype == STACK_MISC)
8129 			goto mark;
8130 		if ((*stype == STACK_ZERO) ||
8131 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
8132 			if (clobber) {
8133 				/* helper can write anything into the stack */
8134 				*stype = STACK_MISC;
8135 			}
8136 			goto mark;
8137 		}
8138 
8139 		if (is_spilled_reg(&state->stack[spi]) &&
8140 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
8141 		     env->allow_ptr_leaks)) {
8142 			if (clobber) {
8143 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
8144 				for (j = 0; j < BPF_REG_SIZE; j++)
8145 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
8146 			}
8147 			goto mark;
8148 		}
8149 
8150 		if (tnum_is_const(reg->var_off)) {
8151 			verbose(env, "invalid read from stack R%d off %d+%d size %d\n",
8152 				regno, min_off, i - min_off, access_size);
8153 		} else {
8154 			char tn_buf[48];
8155 
8156 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8157 			verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n",
8158 				regno, tn_buf, i - min_off, access_size);
8159 		}
8160 		return -EACCES;
8161 mark:
8162 		/* reading any byte out of 8-byte 'spill_slot' will cause
8163 		 * the whole slot to be marked as 'read'
8164 		 */
8165 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
8166 			      state->stack[spi].spilled_ptr.parent,
8167 			      REG_LIVE_READ64);
8168 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
8169 		 * be sure that whether stack slot is written to or not. Hence,
8170 		 * we must still conservatively propagate reads upwards even if
8171 		 * helper may write to the entire memory range.
8172 		 */
8173 	}
8174 	return 0;
8175 }
8176 
8177 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
8178 				   int access_size, enum bpf_access_type access_type,
8179 				   bool zero_size_allowed,
8180 				   struct bpf_call_arg_meta *meta)
8181 {
8182 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8183 	u32 *max_access;
8184 
8185 	switch (base_type(reg->type)) {
8186 	case PTR_TO_PACKET:
8187 	case PTR_TO_PACKET_META:
8188 		return check_packet_access(env, regno, reg->off, access_size,
8189 					   zero_size_allowed);
8190 	case PTR_TO_MAP_KEY:
8191 		if (access_type == BPF_WRITE) {
8192 			verbose(env, "R%d cannot write into %s\n", regno,
8193 				reg_type_str(env, reg->type));
8194 			return -EACCES;
8195 		}
8196 		return check_mem_region_access(env, regno, reg->off, access_size,
8197 					       reg->map_ptr->key_size, false);
8198 	case PTR_TO_MAP_VALUE:
8199 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
8200 			return -EACCES;
8201 		return check_map_access(env, regno, reg->off, access_size,
8202 					zero_size_allowed, ACCESS_HELPER);
8203 	case PTR_TO_MEM:
8204 		if (type_is_rdonly_mem(reg->type)) {
8205 			if (access_type == BPF_WRITE) {
8206 				verbose(env, "R%d cannot write into %s\n", regno,
8207 					reg_type_str(env, reg->type));
8208 				return -EACCES;
8209 			}
8210 		}
8211 		return check_mem_region_access(env, regno, reg->off,
8212 					       access_size, reg->mem_size,
8213 					       zero_size_allowed);
8214 	case PTR_TO_BUF:
8215 		if (type_is_rdonly_mem(reg->type)) {
8216 			if (access_type == BPF_WRITE) {
8217 				verbose(env, "R%d cannot write into %s\n", regno,
8218 					reg_type_str(env, reg->type));
8219 				return -EACCES;
8220 			}
8221 
8222 			max_access = &env->prog->aux->max_rdonly_access;
8223 		} else {
8224 			max_access = &env->prog->aux->max_rdwr_access;
8225 		}
8226 		return check_buffer_access(env, reg, regno, reg->off,
8227 					   access_size, zero_size_allowed,
8228 					   max_access);
8229 	case PTR_TO_STACK:
8230 		return check_stack_range_initialized(
8231 				env,
8232 				regno, reg->off, access_size,
8233 				zero_size_allowed, access_type, meta);
8234 	case PTR_TO_BTF_ID:
8235 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
8236 					       access_size, BPF_READ, -1);
8237 	case PTR_TO_CTX:
8238 		/* in case the function doesn't know how to access the context,
8239 		 * (because we are in a program of type SYSCALL for example), we
8240 		 * can not statically check its size.
8241 		 * Dynamically check it now.
8242 		 */
8243 		if (!env->ops->convert_ctx_access) {
8244 			int offset = access_size - 1;
8245 
8246 			/* Allow zero-byte read from PTR_TO_CTX */
8247 			if (access_size == 0)
8248 				return zero_size_allowed ? 0 : -EACCES;
8249 
8250 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
8251 						access_type, -1, false, false);
8252 		}
8253 
8254 		fallthrough;
8255 	default: /* scalar_value or invalid ptr */
8256 		/* Allow zero-byte read from NULL, regardless of pointer type */
8257 		if (zero_size_allowed && access_size == 0 &&
8258 		    register_is_null(reg))
8259 			return 0;
8260 
8261 		verbose(env, "R%d type=%s ", regno,
8262 			reg_type_str(env, reg->type));
8263 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
8264 		return -EACCES;
8265 	}
8266 }
8267 
8268 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
8269  * size.
8270  *
8271  * @regno is the register containing the access size. regno-1 is the register
8272  * containing the pointer.
8273  */
8274 static int check_mem_size_reg(struct bpf_verifier_env *env,
8275 			      struct bpf_reg_state *reg, u32 regno,
8276 			      enum bpf_access_type access_type,
8277 			      bool zero_size_allowed,
8278 			      struct bpf_call_arg_meta *meta)
8279 {
8280 	int err;
8281 
8282 	/* This is used to refine r0 return value bounds for helpers
8283 	 * that enforce this value as an upper bound on return values.
8284 	 * See do_refine_retval_range() for helpers that can refine
8285 	 * the return value. C type of helper is u32 so we pull register
8286 	 * bound from umax_value however, if negative verifier errors
8287 	 * out. Only upper bounds can be learned because retval is an
8288 	 * int type and negative retvals are allowed.
8289 	 */
8290 	meta->msize_max_value = reg->umax_value;
8291 
8292 	/* The register is SCALAR_VALUE; the access check happens using
8293 	 * its boundaries. For unprivileged variable accesses, disable
8294 	 * raw mode so that the program is required to initialize all
8295 	 * the memory that the helper could just partially fill up.
8296 	 */
8297 	if (!tnum_is_const(reg->var_off))
8298 		meta = NULL;
8299 
8300 	if (reg->smin_value < 0) {
8301 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
8302 			regno);
8303 		return -EACCES;
8304 	}
8305 
8306 	if (reg->umin_value == 0 && !zero_size_allowed) {
8307 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
8308 			regno, reg->umin_value, reg->umax_value);
8309 		return -EACCES;
8310 	}
8311 
8312 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
8313 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
8314 			regno);
8315 		return -EACCES;
8316 	}
8317 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
8318 				      access_type, zero_size_allowed, meta);
8319 	if (!err)
8320 		err = mark_chain_precision(env, regno);
8321 	return err;
8322 }
8323 
8324 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8325 			 u32 regno, u32 mem_size)
8326 {
8327 	bool may_be_null = type_may_be_null(reg->type);
8328 	struct bpf_reg_state saved_reg;
8329 	int err;
8330 
8331 	if (register_is_null(reg))
8332 		return 0;
8333 
8334 	/* Assuming that the register contains a value check if the memory
8335 	 * access is safe. Temporarily save and restore the register's state as
8336 	 * the conversion shouldn't be visible to a caller.
8337 	 */
8338 	if (may_be_null) {
8339 		saved_reg = *reg;
8340 		mark_ptr_not_null_reg(reg);
8341 	}
8342 
8343 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
8344 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
8345 
8346 	if (may_be_null)
8347 		*reg = saved_reg;
8348 
8349 	return err;
8350 }
8351 
8352 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8353 				    u32 regno)
8354 {
8355 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
8356 	bool may_be_null = type_may_be_null(mem_reg->type);
8357 	struct bpf_reg_state saved_reg;
8358 	struct bpf_call_arg_meta meta;
8359 	int err;
8360 
8361 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
8362 
8363 	memset(&meta, 0, sizeof(meta));
8364 
8365 	if (may_be_null) {
8366 		saved_reg = *mem_reg;
8367 		mark_ptr_not_null_reg(mem_reg);
8368 	}
8369 
8370 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
8371 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
8372 
8373 	if (may_be_null)
8374 		*mem_reg = saved_reg;
8375 
8376 	return err;
8377 }
8378 
8379 enum {
8380 	PROCESS_SPIN_LOCK = (1 << 0),
8381 	PROCESS_RES_LOCK  = (1 << 1),
8382 	PROCESS_LOCK_IRQ  = (1 << 2),
8383 };
8384 
8385 /* Implementation details:
8386  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
8387  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
8388  * Two bpf_map_lookups (even with the same key) will have different reg->id.
8389  * Two separate bpf_obj_new will also have different reg->id.
8390  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
8391  * clears reg->id after value_or_null->value transition, since the verifier only
8392  * cares about the range of access to valid map value pointer and doesn't care
8393  * about actual address of the map element.
8394  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
8395  * reg->id > 0 after value_or_null->value transition. By doing so
8396  * two bpf_map_lookups will be considered two different pointers that
8397  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
8398  * returned from bpf_obj_new.
8399  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8400  * dead-locks.
8401  * Since only one bpf_spin_lock is allowed the checks are simpler than
8402  * reg_is_refcounted() logic. The verifier needs to remember only
8403  * one spin_lock instead of array of acquired_refs.
8404  * env->cur_state->active_locks remembers which map value element or allocated
8405  * object got locked and clears it after bpf_spin_unlock.
8406  */
8407 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags)
8408 {
8409 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
8410 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
8411 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8412 	struct bpf_verifier_state *cur = env->cur_state;
8413 	bool is_const = tnum_is_const(reg->var_off);
8414 	bool is_irq = flags & PROCESS_LOCK_IRQ;
8415 	u64 val = reg->var_off.value;
8416 	struct bpf_map *map = NULL;
8417 	struct btf *btf = NULL;
8418 	struct btf_record *rec;
8419 	u32 spin_lock_off;
8420 	int err;
8421 
8422 	if (!is_const) {
8423 		verbose(env,
8424 			"R%d doesn't have constant offset. %s_lock has to be at the constant offset\n",
8425 			regno, lock_str);
8426 		return -EINVAL;
8427 	}
8428 	if (reg->type == PTR_TO_MAP_VALUE) {
8429 		map = reg->map_ptr;
8430 		if (!map->btf) {
8431 			verbose(env,
8432 				"map '%s' has to have BTF in order to use %s_lock\n",
8433 				map->name, lock_str);
8434 			return -EINVAL;
8435 		}
8436 	} else {
8437 		btf = reg->btf;
8438 	}
8439 
8440 	rec = reg_btf_record(reg);
8441 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
8442 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
8443 			map ? map->name : "kptr", lock_str);
8444 		return -EINVAL;
8445 	}
8446 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
8447 	if (spin_lock_off != val + reg->off) {
8448 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
8449 			val + reg->off, lock_str, spin_lock_off);
8450 		return -EINVAL;
8451 	}
8452 	if (is_lock) {
8453 		void *ptr;
8454 		int type;
8455 
8456 		if (map)
8457 			ptr = map;
8458 		else
8459 			ptr = btf;
8460 
8461 		if (!is_res_lock && cur->active_locks) {
8462 			if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) {
8463 				verbose(env,
8464 					"Locking two bpf_spin_locks are not allowed\n");
8465 				return -EINVAL;
8466 			}
8467 		} else if (is_res_lock && cur->active_locks) {
8468 			if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) {
8469 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
8470 				return -EINVAL;
8471 			}
8472 		}
8473 
8474 		if (is_res_lock && is_irq)
8475 			type = REF_TYPE_RES_LOCK_IRQ;
8476 		else if (is_res_lock)
8477 			type = REF_TYPE_RES_LOCK;
8478 		else
8479 			type = REF_TYPE_LOCK;
8480 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
8481 		if (err < 0) {
8482 			verbose(env, "Failed to acquire lock state\n");
8483 			return err;
8484 		}
8485 	} else {
8486 		void *ptr;
8487 		int type;
8488 
8489 		if (map)
8490 			ptr = map;
8491 		else
8492 			ptr = btf;
8493 
8494 		if (!cur->active_locks) {
8495 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
8496 			return -EINVAL;
8497 		}
8498 
8499 		if (is_res_lock && is_irq)
8500 			type = REF_TYPE_RES_LOCK_IRQ;
8501 		else if (is_res_lock)
8502 			type = REF_TYPE_RES_LOCK;
8503 		else
8504 			type = REF_TYPE_LOCK;
8505 		if (!find_lock_state(cur, type, reg->id, ptr)) {
8506 			verbose(env, "%s_unlock of different lock\n", lock_str);
8507 			return -EINVAL;
8508 		}
8509 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
8510 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
8511 			return -EINVAL;
8512 		}
8513 		if (release_lock_state(cur, type, reg->id, ptr)) {
8514 			verbose(env, "%s_unlock of different lock\n", lock_str);
8515 			return -EINVAL;
8516 		}
8517 
8518 		invalidate_non_owning_refs(env);
8519 	}
8520 	return 0;
8521 }
8522 
8523 static int process_timer_func(struct bpf_verifier_env *env, int regno,
8524 			      struct bpf_call_arg_meta *meta)
8525 {
8526 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8527 	bool is_const = tnum_is_const(reg->var_off);
8528 	struct bpf_map *map = reg->map_ptr;
8529 	u64 val = reg->var_off.value;
8530 
8531 	if (!is_const) {
8532 		verbose(env,
8533 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
8534 			regno);
8535 		return -EINVAL;
8536 	}
8537 	if (!map->btf) {
8538 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
8539 			map->name);
8540 		return -EINVAL;
8541 	}
8542 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
8543 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
8544 		return -EINVAL;
8545 	}
8546 	if (map->record->timer_off != val + reg->off) {
8547 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
8548 			val + reg->off, map->record->timer_off);
8549 		return -EINVAL;
8550 	}
8551 	if (meta->map_ptr) {
8552 		verifier_bug(env, "Two map pointers in a timer helper");
8553 		return -EFAULT;
8554 	}
8555 	meta->map_uid = reg->map_uid;
8556 	meta->map_ptr = map;
8557 	return 0;
8558 }
8559 
8560 static int process_wq_func(struct bpf_verifier_env *env, int regno,
8561 			   struct bpf_kfunc_call_arg_meta *meta)
8562 {
8563 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8564 	struct bpf_map *map = reg->map_ptr;
8565 	u64 val = reg->var_off.value;
8566 
8567 	if (map->record->wq_off != val + reg->off) {
8568 		verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
8569 			val + reg->off, map->record->wq_off);
8570 		return -EINVAL;
8571 	}
8572 	meta->map.uid = reg->map_uid;
8573 	meta->map.ptr = map;
8574 	return 0;
8575 }
8576 
8577 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8578 			     struct bpf_call_arg_meta *meta)
8579 {
8580 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8581 	struct btf_field *kptr_field;
8582 	struct bpf_map *map_ptr;
8583 	struct btf_record *rec;
8584 	u32 kptr_off;
8585 
8586 	if (type_is_ptr_alloc_obj(reg->type)) {
8587 		rec = reg_btf_record(reg);
8588 	} else { /* PTR_TO_MAP_VALUE */
8589 		map_ptr = reg->map_ptr;
8590 		if (!map_ptr->btf) {
8591 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8592 				map_ptr->name);
8593 			return -EINVAL;
8594 		}
8595 		rec = map_ptr->record;
8596 		meta->map_ptr = map_ptr;
8597 	}
8598 
8599 	if (!tnum_is_const(reg->var_off)) {
8600 		verbose(env,
8601 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8602 			regno);
8603 		return -EINVAL;
8604 	}
8605 
8606 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8607 		verbose(env, "R%d has no valid kptr\n", regno);
8608 		return -EINVAL;
8609 	}
8610 
8611 	kptr_off = reg->off + reg->var_off.value;
8612 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8613 	if (!kptr_field) {
8614 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8615 		return -EACCES;
8616 	}
8617 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8618 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8619 		return -EACCES;
8620 	}
8621 	meta->kptr_field = kptr_field;
8622 	return 0;
8623 }
8624 
8625 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8626  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8627  *
8628  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8629  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8630  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8631  *
8632  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
8633  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
8634  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
8635  * mutate the view of the dynptr and also possibly destroy it. In the latter
8636  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
8637  * memory that dynptr points to.
8638  *
8639  * The verifier will keep track both levels of mutation (bpf_dynptr's in
8640  * reg->type and the memory's in reg->dynptr.type), but there is no support for
8641  * readonly dynptr view yet, hence only the first case is tracked and checked.
8642  *
8643  * This is consistent with how C applies the const modifier to a struct object,
8644  * where the pointer itself inside bpf_dynptr becomes const but not what it
8645  * points to.
8646  *
8647  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
8648  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
8649  */
8650 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
8651 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
8652 {
8653 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8654 	int err;
8655 
8656 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
8657 		verbose(env,
8658 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
8659 			regno - 1);
8660 		return -EINVAL;
8661 	}
8662 
8663 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
8664 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
8665 	 */
8666 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
8667 		verifier_bug(env, "misconfigured dynptr helper type flags");
8668 		return -EFAULT;
8669 	}
8670 
8671 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8672 	 *		 constructing a mutable bpf_dynptr object.
8673 	 *
8674 	 *		 Currently, this is only possible with PTR_TO_STACK
8675 	 *		 pointing to a region of at least 16 bytes which doesn't
8676 	 *		 contain an existing bpf_dynptr.
8677 	 *
8678 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
8679 	 *		 mutated or destroyed. However, the memory it points to
8680 	 *		 may be mutated.
8681 	 *
8682 	 *  None       - Points to a initialized dynptr that can be mutated and
8683 	 *		 destroyed, including mutation of the memory it points
8684 	 *		 to.
8685 	 */
8686 	if (arg_type & MEM_UNINIT) {
8687 		int i;
8688 
8689 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8690 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8691 			return -EINVAL;
8692 		}
8693 
8694 		/* we write BPF_DW bits (8 bytes) at a time */
8695 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8696 			err = check_mem_access(env, insn_idx, regno,
8697 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8698 			if (err)
8699 				return err;
8700 		}
8701 
8702 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
8703 	} else /* MEM_RDONLY and None case from above */ {
8704 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8705 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
8706 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
8707 			return -EINVAL;
8708 		}
8709 
8710 		if (!is_dynptr_reg_valid_init(env, reg)) {
8711 			verbose(env,
8712 				"Expected an initialized dynptr as arg #%d\n",
8713 				regno - 1);
8714 			return -EINVAL;
8715 		}
8716 
8717 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
8718 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
8719 			verbose(env,
8720 				"Expected a dynptr of type %s as arg #%d\n",
8721 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
8722 			return -EINVAL;
8723 		}
8724 
8725 		err = mark_dynptr_read(env, reg);
8726 	}
8727 	return err;
8728 }
8729 
8730 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
8731 {
8732 	struct bpf_func_state *state = func(env, reg);
8733 
8734 	return state->stack[spi].spilled_ptr.ref_obj_id;
8735 }
8736 
8737 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8738 {
8739 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8740 }
8741 
8742 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8743 {
8744 	return meta->kfunc_flags & KF_ITER_NEW;
8745 }
8746 
8747 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8748 {
8749 	return meta->kfunc_flags & KF_ITER_NEXT;
8750 }
8751 
8752 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8753 {
8754 	return meta->kfunc_flags & KF_ITER_DESTROY;
8755 }
8756 
8757 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
8758 			      const struct btf_param *arg)
8759 {
8760 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8761 	 * kfunc is iter state pointer
8762 	 */
8763 	if (is_iter_kfunc(meta))
8764 		return arg_idx == 0;
8765 
8766 	/* iter passed as an argument to a generic kfunc */
8767 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8768 }
8769 
8770 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
8771 			    struct bpf_kfunc_call_arg_meta *meta)
8772 {
8773 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8774 	const struct btf_type *t;
8775 	int spi, err, i, nr_slots, btf_id;
8776 
8777 	if (reg->type != PTR_TO_STACK) {
8778 		verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
8779 		return -EINVAL;
8780 	}
8781 
8782 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8783 	 * ensures struct convention, so we wouldn't need to do any BTF
8784 	 * validation here. But given iter state can be passed as a parameter
8785 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8786 	 * conservative here.
8787 	 */
8788 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8789 	if (btf_id < 0) {
8790 		verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
8791 		return -EINVAL;
8792 	}
8793 	t = btf_type_by_id(meta->btf, btf_id);
8794 	nr_slots = t->size / BPF_REG_SIZE;
8795 
8796 	if (is_iter_new_kfunc(meta)) {
8797 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8798 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8799 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8800 				iter_type_str(meta->btf, btf_id), regno - 1);
8801 			return -EINVAL;
8802 		}
8803 
8804 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8805 			err = check_mem_access(env, insn_idx, regno,
8806 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8807 			if (err)
8808 				return err;
8809 		}
8810 
8811 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8812 		if (err)
8813 			return err;
8814 	} else {
8815 		/* iter_next() or iter_destroy(), as well as any kfunc
8816 		 * accepting iter argument, expect initialized iter state
8817 		 */
8818 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8819 		switch (err) {
8820 		case 0:
8821 			break;
8822 		case -EINVAL:
8823 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
8824 				iter_type_str(meta->btf, btf_id), regno - 1);
8825 			return err;
8826 		case -EPROTO:
8827 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8828 			return err;
8829 		default:
8830 			return err;
8831 		}
8832 
8833 		spi = iter_get_spi(env, reg, nr_slots);
8834 		if (spi < 0)
8835 			return spi;
8836 
8837 		err = mark_iter_read(env, reg, spi, nr_slots);
8838 		if (err)
8839 			return err;
8840 
8841 		/* remember meta->iter info for process_iter_next_call() */
8842 		meta->iter.spi = spi;
8843 		meta->iter.frameno = reg->frameno;
8844 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8845 
8846 		if (is_iter_destroy_kfunc(meta)) {
8847 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8848 			if (err)
8849 				return err;
8850 		}
8851 	}
8852 
8853 	return 0;
8854 }
8855 
8856 /* Look for a previous loop entry at insn_idx: nearest parent state
8857  * stopped at insn_idx with callsites matching those in cur->frame.
8858  */
8859 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8860 						  struct bpf_verifier_state *cur,
8861 						  int insn_idx)
8862 {
8863 	struct bpf_verifier_state_list *sl;
8864 	struct bpf_verifier_state *st;
8865 	struct list_head *pos, *head;
8866 
8867 	/* Explored states are pushed in stack order, most recent states come first */
8868 	head = explored_state(env, insn_idx);
8869 	list_for_each(pos, head) {
8870 		sl = container_of(pos, struct bpf_verifier_state_list, node);
8871 		/* If st->branches != 0 state is a part of current DFS verification path,
8872 		 * hence cur & st for a loop.
8873 		 */
8874 		st = &sl->state;
8875 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8876 		    st->dfs_depth < cur->dfs_depth)
8877 			return st;
8878 	}
8879 
8880 	return NULL;
8881 }
8882 
8883 static void reset_idmap_scratch(struct bpf_verifier_env *env);
8884 static bool regs_exact(const struct bpf_reg_state *rold,
8885 		       const struct bpf_reg_state *rcur,
8886 		       struct bpf_idmap *idmap);
8887 
8888 static void maybe_widen_reg(struct bpf_verifier_env *env,
8889 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8890 			    struct bpf_idmap *idmap)
8891 {
8892 	if (rold->type != SCALAR_VALUE)
8893 		return;
8894 	if (rold->type != rcur->type)
8895 		return;
8896 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
8897 		return;
8898 	__mark_reg_unknown(env, rcur);
8899 }
8900 
8901 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8902 				   struct bpf_verifier_state *old,
8903 				   struct bpf_verifier_state *cur)
8904 {
8905 	struct bpf_func_state *fold, *fcur;
8906 	int i, fr;
8907 
8908 	reset_idmap_scratch(env);
8909 	for (fr = old->curframe; fr >= 0; fr--) {
8910 		fold = old->frame[fr];
8911 		fcur = cur->frame[fr];
8912 
8913 		for (i = 0; i < MAX_BPF_REG; i++)
8914 			maybe_widen_reg(env,
8915 					&fold->regs[i],
8916 					&fcur->regs[i],
8917 					&env->idmap_scratch);
8918 
8919 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
8920 			if (!is_spilled_reg(&fold->stack[i]) ||
8921 			    !is_spilled_reg(&fcur->stack[i]))
8922 				continue;
8923 
8924 			maybe_widen_reg(env,
8925 					&fold->stack[i].spilled_ptr,
8926 					&fcur->stack[i].spilled_ptr,
8927 					&env->idmap_scratch);
8928 		}
8929 	}
8930 	return 0;
8931 }
8932 
8933 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8934 						 struct bpf_kfunc_call_arg_meta *meta)
8935 {
8936 	int iter_frameno = meta->iter.frameno;
8937 	int iter_spi = meta->iter.spi;
8938 
8939 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8940 }
8941 
8942 /* process_iter_next_call() is called when verifier gets to iterator's next
8943  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8944  * to it as just "iter_next()" in comments below.
8945  *
8946  * BPF verifier relies on a crucial contract for any iter_next()
8947  * implementation: it should *eventually* return NULL, and once that happens
8948  * it should keep returning NULL. That is, once iterator exhausts elements to
8949  * iterate, it should never reset or spuriously return new elements.
8950  *
8951  * With the assumption of such contract, process_iter_next_call() simulates
8952  * a fork in the verifier state to validate loop logic correctness and safety
8953  * without having to simulate infinite amount of iterations.
8954  *
8955  * In current state, we first assume that iter_next() returned NULL and
8956  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8957  * conditions we should not form an infinite loop and should eventually reach
8958  * exit.
8959  *
8960  * Besides that, we also fork current state and enqueue it for later
8961  * verification. In a forked state we keep iterator state as ACTIVE
8962  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8963  * also bump iteration depth to prevent erroneous infinite loop detection
8964  * later on (see iter_active_depths_differ() comment for details). In this
8965  * state we assume that we'll eventually loop back to another iter_next()
8966  * calls (it could be in exactly same location or in some other instruction,
8967  * it doesn't matter, we don't make any unnecessary assumptions about this,
8968  * everything revolves around iterator state in a stack slot, not which
8969  * instruction is calling iter_next()). When that happens, we either will come
8970  * to iter_next() with equivalent state and can conclude that next iteration
8971  * will proceed in exactly the same way as we just verified, so it's safe to
8972  * assume that loop converges. If not, we'll go on another iteration
8973  * simulation with a different input state, until all possible starting states
8974  * are validated or we reach maximum number of instructions limit.
8975  *
8976  * This way, we will either exhaustively discover all possible input states
8977  * that iterator loop can start with and eventually will converge, or we'll
8978  * effectively regress into bounded loop simulation logic and either reach
8979  * maximum number of instructions if loop is not provably convergent, or there
8980  * is some statically known limit on number of iterations (e.g., if there is
8981  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8982  *
8983  * Iteration convergence logic in is_state_visited() relies on exact
8984  * states comparison, which ignores read and precision marks.
8985  * This is necessary because read and precision marks are not finalized
8986  * while in the loop. Exact comparison might preclude convergence for
8987  * simple programs like below:
8988  *
8989  *     i = 0;
8990  *     while(iter_next(&it))
8991  *       i++;
8992  *
8993  * At each iteration step i++ would produce a new distinct state and
8994  * eventually instruction processing limit would be reached.
8995  *
8996  * To avoid such behavior speculatively forget (widen) range for
8997  * imprecise scalar registers, if those registers were not precise at the
8998  * end of the previous iteration and do not match exactly.
8999  *
9000  * This is a conservative heuristic that allows to verify wide range of programs,
9001  * however it precludes verification of programs that conjure an
9002  * imprecise value on the first loop iteration and use it as precise on a second.
9003  * For example, the following safe program would fail to verify:
9004  *
9005  *     struct bpf_num_iter it;
9006  *     int arr[10];
9007  *     int i = 0, a = 0;
9008  *     bpf_iter_num_new(&it, 0, 10);
9009  *     while (bpf_iter_num_next(&it)) {
9010  *       if (a == 0) {
9011  *         a = 1;
9012  *         i = 7; // Because i changed verifier would forget
9013  *                // it's range on second loop entry.
9014  *       } else {
9015  *         arr[i] = 42; // This would fail to verify.
9016  *       }
9017  *     }
9018  *     bpf_iter_num_destroy(&it);
9019  */
9020 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
9021 				  struct bpf_kfunc_call_arg_meta *meta)
9022 {
9023 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
9024 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
9025 	struct bpf_reg_state *cur_iter, *queued_iter;
9026 
9027 	BTF_TYPE_EMIT(struct bpf_iter);
9028 
9029 	cur_iter = get_iter_from_state(cur_st, meta);
9030 
9031 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
9032 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
9033 		verifier_bug(env, "unexpected iterator state %d (%s)",
9034 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
9035 		return -EFAULT;
9036 	}
9037 
9038 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
9039 		/* Because iter_next() call is a checkpoint is_state_visitied()
9040 		 * should guarantee parent state with same call sites and insn_idx.
9041 		 */
9042 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
9043 		    !same_callsites(cur_st->parent, cur_st)) {
9044 			verifier_bug(env, "bad parent state for iter next call");
9045 			return -EFAULT;
9046 		}
9047 		/* Note cur_st->parent in the call below, it is necessary to skip
9048 		 * checkpoint created for cur_st by is_state_visited()
9049 		 * right at this instruction.
9050 		 */
9051 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
9052 		/* branch out active iter state */
9053 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
9054 		if (!queued_st)
9055 			return -ENOMEM;
9056 
9057 		queued_iter = get_iter_from_state(queued_st, meta);
9058 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
9059 		queued_iter->iter.depth++;
9060 		if (prev_st)
9061 			widen_imprecise_scalars(env, prev_st, queued_st);
9062 
9063 		queued_fr = queued_st->frame[queued_st->curframe];
9064 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
9065 	}
9066 
9067 	/* switch to DRAINED state, but keep the depth unchanged */
9068 	/* mark current iter state as drained and assume returned NULL */
9069 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
9070 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
9071 
9072 	return 0;
9073 }
9074 
9075 static bool arg_type_is_mem_size(enum bpf_arg_type type)
9076 {
9077 	return type == ARG_CONST_SIZE ||
9078 	       type == ARG_CONST_SIZE_OR_ZERO;
9079 }
9080 
9081 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
9082 {
9083 	return base_type(type) == ARG_PTR_TO_MEM &&
9084 	       type & MEM_UNINIT;
9085 }
9086 
9087 static bool arg_type_is_release(enum bpf_arg_type type)
9088 {
9089 	return type & OBJ_RELEASE;
9090 }
9091 
9092 static bool arg_type_is_dynptr(enum bpf_arg_type type)
9093 {
9094 	return base_type(type) == ARG_PTR_TO_DYNPTR;
9095 }
9096 
9097 static int resolve_map_arg_type(struct bpf_verifier_env *env,
9098 				 const struct bpf_call_arg_meta *meta,
9099 				 enum bpf_arg_type *arg_type)
9100 {
9101 	if (!meta->map_ptr) {
9102 		/* kernel subsystem misconfigured verifier */
9103 		verifier_bug(env, "invalid map_ptr to access map->type");
9104 		return -EFAULT;
9105 	}
9106 
9107 	switch (meta->map_ptr->map_type) {
9108 	case BPF_MAP_TYPE_SOCKMAP:
9109 	case BPF_MAP_TYPE_SOCKHASH:
9110 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
9111 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
9112 		} else {
9113 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
9114 			return -EINVAL;
9115 		}
9116 		break;
9117 	case BPF_MAP_TYPE_BLOOM_FILTER:
9118 		if (meta->func_id == BPF_FUNC_map_peek_elem)
9119 			*arg_type = ARG_PTR_TO_MAP_VALUE;
9120 		break;
9121 	default:
9122 		break;
9123 	}
9124 	return 0;
9125 }
9126 
9127 struct bpf_reg_types {
9128 	const enum bpf_reg_type types[10];
9129 	u32 *btf_id;
9130 };
9131 
9132 static const struct bpf_reg_types sock_types = {
9133 	.types = {
9134 		PTR_TO_SOCK_COMMON,
9135 		PTR_TO_SOCKET,
9136 		PTR_TO_TCP_SOCK,
9137 		PTR_TO_XDP_SOCK,
9138 	},
9139 };
9140 
9141 #ifdef CONFIG_NET
9142 static const struct bpf_reg_types btf_id_sock_common_types = {
9143 	.types = {
9144 		PTR_TO_SOCK_COMMON,
9145 		PTR_TO_SOCKET,
9146 		PTR_TO_TCP_SOCK,
9147 		PTR_TO_XDP_SOCK,
9148 		PTR_TO_BTF_ID,
9149 		PTR_TO_BTF_ID | PTR_TRUSTED,
9150 	},
9151 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9152 };
9153 #endif
9154 
9155 static const struct bpf_reg_types mem_types = {
9156 	.types = {
9157 		PTR_TO_STACK,
9158 		PTR_TO_PACKET,
9159 		PTR_TO_PACKET_META,
9160 		PTR_TO_MAP_KEY,
9161 		PTR_TO_MAP_VALUE,
9162 		PTR_TO_MEM,
9163 		PTR_TO_MEM | MEM_RINGBUF,
9164 		PTR_TO_BUF,
9165 		PTR_TO_BTF_ID | PTR_TRUSTED,
9166 	},
9167 };
9168 
9169 static const struct bpf_reg_types spin_lock_types = {
9170 	.types = {
9171 		PTR_TO_MAP_VALUE,
9172 		PTR_TO_BTF_ID | MEM_ALLOC,
9173 	}
9174 };
9175 
9176 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
9177 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
9178 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
9179 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
9180 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
9181 static const struct bpf_reg_types btf_ptr_types = {
9182 	.types = {
9183 		PTR_TO_BTF_ID,
9184 		PTR_TO_BTF_ID | PTR_TRUSTED,
9185 		PTR_TO_BTF_ID | MEM_RCU,
9186 	},
9187 };
9188 static const struct bpf_reg_types percpu_btf_ptr_types = {
9189 	.types = {
9190 		PTR_TO_BTF_ID | MEM_PERCPU,
9191 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
9192 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
9193 	}
9194 };
9195 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
9196 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
9197 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
9198 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
9199 static const struct bpf_reg_types kptr_xchg_dest_types = {
9200 	.types = {
9201 		PTR_TO_MAP_VALUE,
9202 		PTR_TO_BTF_ID | MEM_ALLOC
9203 	}
9204 };
9205 static const struct bpf_reg_types dynptr_types = {
9206 	.types = {
9207 		PTR_TO_STACK,
9208 		CONST_PTR_TO_DYNPTR,
9209 	}
9210 };
9211 
9212 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
9213 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
9214 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
9215 	[ARG_CONST_SIZE]		= &scalar_types,
9216 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
9217 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
9218 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
9219 	[ARG_PTR_TO_CTX]		= &context_types,
9220 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
9221 #ifdef CONFIG_NET
9222 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
9223 #endif
9224 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
9225 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
9226 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
9227 	[ARG_PTR_TO_MEM]		= &mem_types,
9228 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
9229 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
9230 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
9231 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
9232 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
9233 	[ARG_PTR_TO_TIMER]		= &timer_types,
9234 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
9235 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
9236 };
9237 
9238 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
9239 			  enum bpf_arg_type arg_type,
9240 			  const u32 *arg_btf_id,
9241 			  struct bpf_call_arg_meta *meta)
9242 {
9243 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9244 	enum bpf_reg_type expected, type = reg->type;
9245 	const struct bpf_reg_types *compatible;
9246 	int i, j;
9247 
9248 	compatible = compatible_reg_types[base_type(arg_type)];
9249 	if (!compatible) {
9250 		verifier_bug(env, "unsupported arg type %d", arg_type);
9251 		return -EFAULT;
9252 	}
9253 
9254 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
9255 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
9256 	 *
9257 	 * Same for MAYBE_NULL:
9258 	 *
9259 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
9260 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
9261 	 *
9262 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
9263 	 *
9264 	 * Therefore we fold these flags depending on the arg_type before comparison.
9265 	 */
9266 	if (arg_type & MEM_RDONLY)
9267 		type &= ~MEM_RDONLY;
9268 	if (arg_type & PTR_MAYBE_NULL)
9269 		type &= ~PTR_MAYBE_NULL;
9270 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
9271 		type &= ~DYNPTR_TYPE_FLAG_MASK;
9272 
9273 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
9274 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
9275 		type &= ~MEM_ALLOC;
9276 		type &= ~MEM_PERCPU;
9277 	}
9278 
9279 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
9280 		expected = compatible->types[i];
9281 		if (expected == NOT_INIT)
9282 			break;
9283 
9284 		if (type == expected)
9285 			goto found;
9286 	}
9287 
9288 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
9289 	for (j = 0; j + 1 < i; j++)
9290 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
9291 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
9292 	return -EACCES;
9293 
9294 found:
9295 	if (base_type(reg->type) != PTR_TO_BTF_ID)
9296 		return 0;
9297 
9298 	if (compatible == &mem_types) {
9299 		if (!(arg_type & MEM_RDONLY)) {
9300 			verbose(env,
9301 				"%s() may write into memory pointed by R%d type=%s\n",
9302 				func_id_name(meta->func_id),
9303 				regno, reg_type_str(env, reg->type));
9304 			return -EACCES;
9305 		}
9306 		return 0;
9307 	}
9308 
9309 	switch ((int)reg->type) {
9310 	case PTR_TO_BTF_ID:
9311 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9312 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
9313 	case PTR_TO_BTF_ID | MEM_RCU:
9314 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
9315 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
9316 	{
9317 		/* For bpf_sk_release, it needs to match against first member
9318 		 * 'struct sock_common', hence make an exception for it. This
9319 		 * allows bpf_sk_release to work for multiple socket types.
9320 		 */
9321 		bool strict_type_match = arg_type_is_release(arg_type) &&
9322 					 meta->func_id != BPF_FUNC_sk_release;
9323 
9324 		if (type_may_be_null(reg->type) &&
9325 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
9326 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
9327 			return -EACCES;
9328 		}
9329 
9330 		if (!arg_btf_id) {
9331 			if (!compatible->btf_id) {
9332 				verifier_bug(env, "missing arg compatible BTF ID");
9333 				return -EFAULT;
9334 			}
9335 			arg_btf_id = compatible->btf_id;
9336 		}
9337 
9338 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
9339 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9340 				return -EACCES;
9341 		} else {
9342 			if (arg_btf_id == BPF_PTR_POISON) {
9343 				verbose(env, "verifier internal error:");
9344 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
9345 					regno);
9346 				return -EACCES;
9347 			}
9348 
9349 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
9350 						  btf_vmlinux, *arg_btf_id,
9351 						  strict_type_match)) {
9352 				verbose(env, "R%d is of type %s but %s is expected\n",
9353 					regno, btf_type_name(reg->btf, reg->btf_id),
9354 					btf_type_name(btf_vmlinux, *arg_btf_id));
9355 				return -EACCES;
9356 			}
9357 		}
9358 		break;
9359 	}
9360 	case PTR_TO_BTF_ID | MEM_ALLOC:
9361 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
9362 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
9363 		    meta->func_id != BPF_FUNC_kptr_xchg) {
9364 			verifier_bug(env, "unimplemented handling of MEM_ALLOC");
9365 			return -EFAULT;
9366 		}
9367 		/* Check if local kptr in src arg matches kptr in dst arg */
9368 		if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
9369 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9370 				return -EACCES;
9371 		}
9372 		break;
9373 	case PTR_TO_BTF_ID | MEM_PERCPU:
9374 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
9375 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
9376 		/* Handled by helper specific checks */
9377 		break;
9378 	default:
9379 		verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match");
9380 		return -EFAULT;
9381 	}
9382 	return 0;
9383 }
9384 
9385 static struct btf_field *
9386 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
9387 {
9388 	struct btf_field *field;
9389 	struct btf_record *rec;
9390 
9391 	rec = reg_btf_record(reg);
9392 	if (!rec)
9393 		return NULL;
9394 
9395 	field = btf_record_find(rec, off, fields);
9396 	if (!field)
9397 		return NULL;
9398 
9399 	return field;
9400 }
9401 
9402 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
9403 				  const struct bpf_reg_state *reg, int regno,
9404 				  enum bpf_arg_type arg_type)
9405 {
9406 	u32 type = reg->type;
9407 
9408 	/* When referenced register is passed to release function, its fixed
9409 	 * offset must be 0.
9410 	 *
9411 	 * We will check arg_type_is_release reg has ref_obj_id when storing
9412 	 * meta->release_regno.
9413 	 */
9414 	if (arg_type_is_release(arg_type)) {
9415 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
9416 		 * may not directly point to the object being released, but to
9417 		 * dynptr pointing to such object, which might be at some offset
9418 		 * on the stack. In that case, we simply to fallback to the
9419 		 * default handling.
9420 		 */
9421 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
9422 			return 0;
9423 
9424 		/* Doing check_ptr_off_reg check for the offset will catch this
9425 		 * because fixed_off_ok is false, but checking here allows us
9426 		 * to give the user a better error message.
9427 		 */
9428 		if (reg->off) {
9429 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
9430 				regno);
9431 			return -EINVAL;
9432 		}
9433 		return __check_ptr_off_reg(env, reg, regno, false);
9434 	}
9435 
9436 	switch (type) {
9437 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9438 	case PTR_TO_STACK:
9439 	case PTR_TO_PACKET:
9440 	case PTR_TO_PACKET_META:
9441 	case PTR_TO_MAP_KEY:
9442 	case PTR_TO_MAP_VALUE:
9443 	case PTR_TO_MEM:
9444 	case PTR_TO_MEM | MEM_RDONLY:
9445 	case PTR_TO_MEM | MEM_RINGBUF:
9446 	case PTR_TO_BUF:
9447 	case PTR_TO_BUF | MEM_RDONLY:
9448 	case PTR_TO_ARENA:
9449 	case SCALAR_VALUE:
9450 		return 0;
9451 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9452 	 * fixed offset.
9453 	 */
9454 	case PTR_TO_BTF_ID:
9455 	case PTR_TO_BTF_ID | MEM_ALLOC:
9456 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9457 	case PTR_TO_BTF_ID | MEM_RCU:
9458 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9459 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9460 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9461 		 * its fixed offset must be 0. In the other cases, fixed offset
9462 		 * can be non-zero. This was already checked above. So pass
9463 		 * fixed_off_ok as true to allow fixed offset for all other
9464 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
9465 		 * still need to do checks instead of returning.
9466 		 */
9467 		return __check_ptr_off_reg(env, reg, regno, true);
9468 	default:
9469 		return __check_ptr_off_reg(env, reg, regno, false);
9470 	}
9471 }
9472 
9473 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
9474 						const struct bpf_func_proto *fn,
9475 						struct bpf_reg_state *regs)
9476 {
9477 	struct bpf_reg_state *state = NULL;
9478 	int i;
9479 
9480 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
9481 		if (arg_type_is_dynptr(fn->arg_type[i])) {
9482 			if (state) {
9483 				verbose(env, "verifier internal error: multiple dynptr args\n");
9484 				return NULL;
9485 			}
9486 			state = &regs[BPF_REG_1 + i];
9487 		}
9488 
9489 	if (!state)
9490 		verbose(env, "verifier internal error: no dynptr arg found\n");
9491 
9492 	return state;
9493 }
9494 
9495 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9496 {
9497 	struct bpf_func_state *state = func(env, reg);
9498 	int spi;
9499 
9500 	if (reg->type == CONST_PTR_TO_DYNPTR)
9501 		return reg->id;
9502 	spi = dynptr_get_spi(env, reg);
9503 	if (spi < 0)
9504 		return spi;
9505 	return state->stack[spi].spilled_ptr.id;
9506 }
9507 
9508 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9509 {
9510 	struct bpf_func_state *state = func(env, reg);
9511 	int spi;
9512 
9513 	if (reg->type == CONST_PTR_TO_DYNPTR)
9514 		return reg->ref_obj_id;
9515 	spi = dynptr_get_spi(env, reg);
9516 	if (spi < 0)
9517 		return spi;
9518 	return state->stack[spi].spilled_ptr.ref_obj_id;
9519 }
9520 
9521 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
9522 					    struct bpf_reg_state *reg)
9523 {
9524 	struct bpf_func_state *state = func(env, reg);
9525 	int spi;
9526 
9527 	if (reg->type == CONST_PTR_TO_DYNPTR)
9528 		return reg->dynptr.type;
9529 
9530 	spi = __get_spi(reg->off);
9531 	if (spi < 0) {
9532 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
9533 		return BPF_DYNPTR_TYPE_INVALID;
9534 	}
9535 
9536 	return state->stack[spi].spilled_ptr.dynptr.type;
9537 }
9538 
9539 static int check_reg_const_str(struct bpf_verifier_env *env,
9540 			       struct bpf_reg_state *reg, u32 regno)
9541 {
9542 	struct bpf_map *map = reg->map_ptr;
9543 	int err;
9544 	int map_off;
9545 	u64 map_addr;
9546 	char *str_ptr;
9547 
9548 	if (reg->type != PTR_TO_MAP_VALUE)
9549 		return -EINVAL;
9550 
9551 	if (!bpf_map_is_rdonly(map)) {
9552 		verbose(env, "R%d does not point to a readonly map'\n", regno);
9553 		return -EACCES;
9554 	}
9555 
9556 	if (!tnum_is_const(reg->var_off)) {
9557 		verbose(env, "R%d is not a constant address'\n", regno);
9558 		return -EACCES;
9559 	}
9560 
9561 	if (!map->ops->map_direct_value_addr) {
9562 		verbose(env, "no direct value access support for this map type\n");
9563 		return -EACCES;
9564 	}
9565 
9566 	err = check_map_access(env, regno, reg->off,
9567 			       map->value_size - reg->off, false,
9568 			       ACCESS_HELPER);
9569 	if (err)
9570 		return err;
9571 
9572 	map_off = reg->off + reg->var_off.value;
9573 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9574 	if (err) {
9575 		verbose(env, "direct value access on string failed\n");
9576 		return err;
9577 	}
9578 
9579 	str_ptr = (char *)(long)(map_addr);
9580 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9581 		verbose(env, "string is not zero-terminated\n");
9582 		return -EINVAL;
9583 	}
9584 	return 0;
9585 }
9586 
9587 /* Returns constant key value in `value` if possible, else negative error */
9588 static int get_constant_map_key(struct bpf_verifier_env *env,
9589 				struct bpf_reg_state *key,
9590 				u32 key_size,
9591 				s64 *value)
9592 {
9593 	struct bpf_func_state *state = func(env, key);
9594 	struct bpf_reg_state *reg;
9595 	int slot, spi, off;
9596 	int spill_size = 0;
9597 	int zero_size = 0;
9598 	int stack_off;
9599 	int i, err;
9600 	u8 *stype;
9601 
9602 	if (!env->bpf_capable)
9603 		return -EOPNOTSUPP;
9604 	if (key->type != PTR_TO_STACK)
9605 		return -EOPNOTSUPP;
9606 	if (!tnum_is_const(key->var_off))
9607 		return -EOPNOTSUPP;
9608 
9609 	stack_off = key->off + key->var_off.value;
9610 	slot = -stack_off - 1;
9611 	spi = slot / BPF_REG_SIZE;
9612 	off = slot % BPF_REG_SIZE;
9613 	stype = state->stack[spi].slot_type;
9614 
9615 	/* First handle precisely tracked STACK_ZERO */
9616 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9617 		zero_size++;
9618 	if (zero_size >= key_size) {
9619 		*value = 0;
9620 		return 0;
9621 	}
9622 
9623 	/* Check that stack contains a scalar spill of expected size */
9624 	if (!is_spilled_scalar_reg(&state->stack[spi]))
9625 		return -EOPNOTSUPP;
9626 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9627 		spill_size++;
9628 	if (spill_size != key_size)
9629 		return -EOPNOTSUPP;
9630 
9631 	reg = &state->stack[spi].spilled_ptr;
9632 	if (!tnum_is_const(reg->var_off))
9633 		/* Stack value not statically known */
9634 		return -EOPNOTSUPP;
9635 
9636 	/* We are relying on a constant value. So mark as precise
9637 	 * to prevent pruning on it.
9638 	 */
9639 	bt_set_frame_slot(&env->bt, key->frameno, spi);
9640 	err = mark_chain_precision_batch(env, env->cur_state);
9641 	if (err < 0)
9642 		return err;
9643 
9644 	*value = reg->var_off.value;
9645 	return 0;
9646 }
9647 
9648 static bool can_elide_value_nullness(enum bpf_map_type type);
9649 
9650 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9651 			  struct bpf_call_arg_meta *meta,
9652 			  const struct bpf_func_proto *fn,
9653 			  int insn_idx)
9654 {
9655 	u32 regno = BPF_REG_1 + arg;
9656 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9657 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9658 	enum bpf_reg_type type = reg->type;
9659 	u32 *arg_btf_id = NULL;
9660 	u32 key_size;
9661 	int err = 0;
9662 
9663 	if (arg_type == ARG_DONTCARE)
9664 		return 0;
9665 
9666 	err = check_reg_arg(env, regno, SRC_OP);
9667 	if (err)
9668 		return err;
9669 
9670 	if (arg_type == ARG_ANYTHING) {
9671 		if (is_pointer_value(env, regno)) {
9672 			verbose(env, "R%d leaks addr into helper function\n",
9673 				regno);
9674 			return -EACCES;
9675 		}
9676 		return 0;
9677 	}
9678 
9679 	if (type_is_pkt_pointer(type) &&
9680 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9681 		verbose(env, "helper access to the packet is not allowed\n");
9682 		return -EACCES;
9683 	}
9684 
9685 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9686 		err = resolve_map_arg_type(env, meta, &arg_type);
9687 		if (err)
9688 			return err;
9689 	}
9690 
9691 	if (register_is_null(reg) && type_may_be_null(arg_type))
9692 		/* A NULL register has a SCALAR_VALUE type, so skip
9693 		 * type checking.
9694 		 */
9695 		goto skip_type_check;
9696 
9697 	/* arg_btf_id and arg_size are in a union. */
9698 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9699 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9700 		arg_btf_id = fn->arg_btf_id[arg];
9701 
9702 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9703 	if (err)
9704 		return err;
9705 
9706 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
9707 	if (err)
9708 		return err;
9709 
9710 skip_type_check:
9711 	if (arg_type_is_release(arg_type)) {
9712 		if (arg_type_is_dynptr(arg_type)) {
9713 			struct bpf_func_state *state = func(env, reg);
9714 			int spi;
9715 
9716 			/* Only dynptr created on stack can be released, thus
9717 			 * the get_spi and stack state checks for spilled_ptr
9718 			 * should only be done before process_dynptr_func for
9719 			 * PTR_TO_STACK.
9720 			 */
9721 			if (reg->type == PTR_TO_STACK) {
9722 				spi = dynptr_get_spi(env, reg);
9723 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9724 					verbose(env, "arg %d is an unacquired reference\n", regno);
9725 					return -EINVAL;
9726 				}
9727 			} else {
9728 				verbose(env, "cannot release unowned const bpf_dynptr\n");
9729 				return -EINVAL;
9730 			}
9731 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
9732 			verbose(env, "R%d must be referenced when passed to release function\n",
9733 				regno);
9734 			return -EINVAL;
9735 		}
9736 		if (meta->release_regno) {
9737 			verifier_bug(env, "more than one release argument");
9738 			return -EFAULT;
9739 		}
9740 		meta->release_regno = regno;
9741 	}
9742 
9743 	if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9744 		if (meta->ref_obj_id) {
9745 			verbose(env, "more than one arg with ref_obj_id R%d %u %u",
9746 				regno, reg->ref_obj_id,
9747 				meta->ref_obj_id);
9748 			return -EACCES;
9749 		}
9750 		meta->ref_obj_id = reg->ref_obj_id;
9751 	}
9752 
9753 	switch (base_type(arg_type)) {
9754 	case ARG_CONST_MAP_PTR:
9755 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9756 		if (meta->map_ptr) {
9757 			/* Use map_uid (which is unique id of inner map) to reject:
9758 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9759 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9760 			 * if (inner_map1 && inner_map2) {
9761 			 *     timer = bpf_map_lookup_elem(inner_map1);
9762 			 *     if (timer)
9763 			 *         // mismatch would have been allowed
9764 			 *         bpf_timer_init(timer, inner_map2);
9765 			 * }
9766 			 *
9767 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
9768 			 */
9769 			if (meta->map_ptr != reg->map_ptr ||
9770 			    meta->map_uid != reg->map_uid) {
9771 				verbose(env,
9772 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9773 					meta->map_uid, reg->map_uid);
9774 				return -EINVAL;
9775 			}
9776 		}
9777 		meta->map_ptr = reg->map_ptr;
9778 		meta->map_uid = reg->map_uid;
9779 		break;
9780 	case ARG_PTR_TO_MAP_KEY:
9781 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9782 		 * check that [key, key + map->key_size) are within
9783 		 * stack limits and initialized
9784 		 */
9785 		if (!meta->map_ptr) {
9786 			/* in function declaration map_ptr must come before
9787 			 * map_key, so that it's verified and known before
9788 			 * we have to check map_key here. Otherwise it means
9789 			 * that kernel subsystem misconfigured verifier
9790 			 */
9791 			verifier_bug(env, "invalid map_ptr to access map->key");
9792 			return -EFAULT;
9793 		}
9794 		key_size = meta->map_ptr->key_size;
9795 		err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL);
9796 		if (err)
9797 			return err;
9798 		if (can_elide_value_nullness(meta->map_ptr->map_type)) {
9799 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9800 			if (err < 0) {
9801 				meta->const_map_key = -1;
9802 				if (err == -EOPNOTSUPP)
9803 					err = 0;
9804 				else
9805 					return err;
9806 			}
9807 		}
9808 		break;
9809 	case ARG_PTR_TO_MAP_VALUE:
9810 		if (type_may_be_null(arg_type) && register_is_null(reg))
9811 			return 0;
9812 
9813 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9814 		 * check [value, value + map->value_size) validity
9815 		 */
9816 		if (!meta->map_ptr) {
9817 			/* kernel subsystem misconfigured verifier */
9818 			verifier_bug(env, "invalid map_ptr to access map->value");
9819 			return -EFAULT;
9820 		}
9821 		meta->raw_mode = arg_type & MEM_UNINIT;
9822 		err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
9823 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9824 					      false, meta);
9825 		break;
9826 	case ARG_PTR_TO_PERCPU_BTF_ID:
9827 		if (!reg->btf_id) {
9828 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9829 			return -EACCES;
9830 		}
9831 		meta->ret_btf = reg->btf;
9832 		meta->ret_btf_id = reg->btf_id;
9833 		break;
9834 	case ARG_PTR_TO_SPIN_LOCK:
9835 		if (in_rbtree_lock_required_cb(env)) {
9836 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9837 			return -EACCES;
9838 		}
9839 		if (meta->func_id == BPF_FUNC_spin_lock) {
9840 			err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK);
9841 			if (err)
9842 				return err;
9843 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
9844 			err = process_spin_lock(env, regno, 0);
9845 			if (err)
9846 				return err;
9847 		} else {
9848 			verifier_bug(env, "spin lock arg on unexpected helper");
9849 			return -EFAULT;
9850 		}
9851 		break;
9852 	case ARG_PTR_TO_TIMER:
9853 		err = process_timer_func(env, regno, meta);
9854 		if (err)
9855 			return err;
9856 		break;
9857 	case ARG_PTR_TO_FUNC:
9858 		meta->subprogno = reg->subprogno;
9859 		break;
9860 	case ARG_PTR_TO_MEM:
9861 		/* The access to this pointer is only checked when we hit the
9862 		 * next is_mem_size argument below.
9863 		 */
9864 		meta->raw_mode = arg_type & MEM_UNINIT;
9865 		if (arg_type & MEM_FIXED_SIZE) {
9866 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
9867 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9868 						      false, meta);
9869 			if (err)
9870 				return err;
9871 			if (arg_type & MEM_ALIGNED)
9872 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9873 		}
9874 		break;
9875 	case ARG_CONST_SIZE:
9876 		err = check_mem_size_reg(env, reg, regno,
9877 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9878 					 BPF_WRITE : BPF_READ,
9879 					 false, meta);
9880 		break;
9881 	case ARG_CONST_SIZE_OR_ZERO:
9882 		err = check_mem_size_reg(env, reg, regno,
9883 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9884 					 BPF_WRITE : BPF_READ,
9885 					 true, meta);
9886 		break;
9887 	case ARG_PTR_TO_DYNPTR:
9888 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9889 		if (err)
9890 			return err;
9891 		break;
9892 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9893 		if (!tnum_is_const(reg->var_off)) {
9894 			verbose(env, "R%d is not a known constant'\n",
9895 				regno);
9896 			return -EACCES;
9897 		}
9898 		meta->mem_size = reg->var_off.value;
9899 		err = mark_chain_precision(env, regno);
9900 		if (err)
9901 			return err;
9902 		break;
9903 	case ARG_PTR_TO_CONST_STR:
9904 	{
9905 		err = check_reg_const_str(env, reg, regno);
9906 		if (err)
9907 			return err;
9908 		break;
9909 	}
9910 	case ARG_KPTR_XCHG_DEST:
9911 		err = process_kptr_func(env, regno, meta);
9912 		if (err)
9913 			return err;
9914 		break;
9915 	}
9916 
9917 	return err;
9918 }
9919 
9920 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9921 {
9922 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
9923 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9924 
9925 	if (func_id != BPF_FUNC_map_update_elem &&
9926 	    func_id != BPF_FUNC_map_delete_elem)
9927 		return false;
9928 
9929 	/* It's not possible to get access to a locked struct sock in these
9930 	 * contexts, so updating is safe.
9931 	 */
9932 	switch (type) {
9933 	case BPF_PROG_TYPE_TRACING:
9934 		if (eatype == BPF_TRACE_ITER)
9935 			return true;
9936 		break;
9937 	case BPF_PROG_TYPE_SOCK_OPS:
9938 		/* map_update allowed only via dedicated helpers with event type checks */
9939 		if (func_id == BPF_FUNC_map_delete_elem)
9940 			return true;
9941 		break;
9942 	case BPF_PROG_TYPE_SOCKET_FILTER:
9943 	case BPF_PROG_TYPE_SCHED_CLS:
9944 	case BPF_PROG_TYPE_SCHED_ACT:
9945 	case BPF_PROG_TYPE_XDP:
9946 	case BPF_PROG_TYPE_SK_REUSEPORT:
9947 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
9948 	case BPF_PROG_TYPE_SK_LOOKUP:
9949 		return true;
9950 	default:
9951 		break;
9952 	}
9953 
9954 	verbose(env, "cannot update sockmap in this context\n");
9955 	return false;
9956 }
9957 
9958 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
9959 {
9960 	return env->prog->jit_requested &&
9961 	       bpf_jit_supports_subprog_tailcalls();
9962 }
9963 
9964 static int check_map_func_compatibility(struct bpf_verifier_env *env,
9965 					struct bpf_map *map, int func_id)
9966 {
9967 	if (!map)
9968 		return 0;
9969 
9970 	/* We need a two way check, first is from map perspective ... */
9971 	switch (map->map_type) {
9972 	case BPF_MAP_TYPE_PROG_ARRAY:
9973 		if (func_id != BPF_FUNC_tail_call)
9974 			goto error;
9975 		break;
9976 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
9977 		if (func_id != BPF_FUNC_perf_event_read &&
9978 		    func_id != BPF_FUNC_perf_event_output &&
9979 		    func_id != BPF_FUNC_skb_output &&
9980 		    func_id != BPF_FUNC_perf_event_read_value &&
9981 		    func_id != BPF_FUNC_xdp_output)
9982 			goto error;
9983 		break;
9984 	case BPF_MAP_TYPE_RINGBUF:
9985 		if (func_id != BPF_FUNC_ringbuf_output &&
9986 		    func_id != BPF_FUNC_ringbuf_reserve &&
9987 		    func_id != BPF_FUNC_ringbuf_query &&
9988 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
9989 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
9990 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
9991 			goto error;
9992 		break;
9993 	case BPF_MAP_TYPE_USER_RINGBUF:
9994 		if (func_id != BPF_FUNC_user_ringbuf_drain)
9995 			goto error;
9996 		break;
9997 	case BPF_MAP_TYPE_STACK_TRACE:
9998 		if (func_id != BPF_FUNC_get_stackid)
9999 			goto error;
10000 		break;
10001 	case BPF_MAP_TYPE_CGROUP_ARRAY:
10002 		if (func_id != BPF_FUNC_skb_under_cgroup &&
10003 		    func_id != BPF_FUNC_current_task_under_cgroup)
10004 			goto error;
10005 		break;
10006 	case BPF_MAP_TYPE_CGROUP_STORAGE:
10007 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
10008 		if (func_id != BPF_FUNC_get_local_storage)
10009 			goto error;
10010 		break;
10011 	case BPF_MAP_TYPE_DEVMAP:
10012 	case BPF_MAP_TYPE_DEVMAP_HASH:
10013 		if (func_id != BPF_FUNC_redirect_map &&
10014 		    func_id != BPF_FUNC_map_lookup_elem)
10015 			goto error;
10016 		break;
10017 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
10018 	 * appear.
10019 	 */
10020 	case BPF_MAP_TYPE_CPUMAP:
10021 		if (func_id != BPF_FUNC_redirect_map)
10022 			goto error;
10023 		break;
10024 	case BPF_MAP_TYPE_XSKMAP:
10025 		if (func_id != BPF_FUNC_redirect_map &&
10026 		    func_id != BPF_FUNC_map_lookup_elem)
10027 			goto error;
10028 		break;
10029 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10030 	case BPF_MAP_TYPE_HASH_OF_MAPS:
10031 		if (func_id != BPF_FUNC_map_lookup_elem)
10032 			goto error;
10033 		break;
10034 	case BPF_MAP_TYPE_SOCKMAP:
10035 		if (func_id != BPF_FUNC_sk_redirect_map &&
10036 		    func_id != BPF_FUNC_sock_map_update &&
10037 		    func_id != BPF_FUNC_msg_redirect_map &&
10038 		    func_id != BPF_FUNC_sk_select_reuseport &&
10039 		    func_id != BPF_FUNC_map_lookup_elem &&
10040 		    !may_update_sockmap(env, func_id))
10041 			goto error;
10042 		break;
10043 	case BPF_MAP_TYPE_SOCKHASH:
10044 		if (func_id != BPF_FUNC_sk_redirect_hash &&
10045 		    func_id != BPF_FUNC_sock_hash_update &&
10046 		    func_id != BPF_FUNC_msg_redirect_hash &&
10047 		    func_id != BPF_FUNC_sk_select_reuseport &&
10048 		    func_id != BPF_FUNC_map_lookup_elem &&
10049 		    !may_update_sockmap(env, func_id))
10050 			goto error;
10051 		break;
10052 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
10053 		if (func_id != BPF_FUNC_sk_select_reuseport)
10054 			goto error;
10055 		break;
10056 	case BPF_MAP_TYPE_QUEUE:
10057 	case BPF_MAP_TYPE_STACK:
10058 		if (func_id != BPF_FUNC_map_peek_elem &&
10059 		    func_id != BPF_FUNC_map_pop_elem &&
10060 		    func_id != BPF_FUNC_map_push_elem)
10061 			goto error;
10062 		break;
10063 	case BPF_MAP_TYPE_SK_STORAGE:
10064 		if (func_id != BPF_FUNC_sk_storage_get &&
10065 		    func_id != BPF_FUNC_sk_storage_delete &&
10066 		    func_id != BPF_FUNC_kptr_xchg)
10067 			goto error;
10068 		break;
10069 	case BPF_MAP_TYPE_INODE_STORAGE:
10070 		if (func_id != BPF_FUNC_inode_storage_get &&
10071 		    func_id != BPF_FUNC_inode_storage_delete &&
10072 		    func_id != BPF_FUNC_kptr_xchg)
10073 			goto error;
10074 		break;
10075 	case BPF_MAP_TYPE_TASK_STORAGE:
10076 		if (func_id != BPF_FUNC_task_storage_get &&
10077 		    func_id != BPF_FUNC_task_storage_delete &&
10078 		    func_id != BPF_FUNC_kptr_xchg)
10079 			goto error;
10080 		break;
10081 	case BPF_MAP_TYPE_CGRP_STORAGE:
10082 		if (func_id != BPF_FUNC_cgrp_storage_get &&
10083 		    func_id != BPF_FUNC_cgrp_storage_delete &&
10084 		    func_id != BPF_FUNC_kptr_xchg)
10085 			goto error;
10086 		break;
10087 	case BPF_MAP_TYPE_BLOOM_FILTER:
10088 		if (func_id != BPF_FUNC_map_peek_elem &&
10089 		    func_id != BPF_FUNC_map_push_elem)
10090 			goto error;
10091 		break;
10092 	default:
10093 		break;
10094 	}
10095 
10096 	/* ... and second from the function itself. */
10097 	switch (func_id) {
10098 	case BPF_FUNC_tail_call:
10099 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
10100 			goto error;
10101 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
10102 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
10103 			return -EINVAL;
10104 		}
10105 		break;
10106 	case BPF_FUNC_perf_event_read:
10107 	case BPF_FUNC_perf_event_output:
10108 	case BPF_FUNC_perf_event_read_value:
10109 	case BPF_FUNC_skb_output:
10110 	case BPF_FUNC_xdp_output:
10111 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10112 			goto error;
10113 		break;
10114 	case BPF_FUNC_ringbuf_output:
10115 	case BPF_FUNC_ringbuf_reserve:
10116 	case BPF_FUNC_ringbuf_query:
10117 	case BPF_FUNC_ringbuf_reserve_dynptr:
10118 	case BPF_FUNC_ringbuf_submit_dynptr:
10119 	case BPF_FUNC_ringbuf_discard_dynptr:
10120 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
10121 			goto error;
10122 		break;
10123 	case BPF_FUNC_user_ringbuf_drain:
10124 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
10125 			goto error;
10126 		break;
10127 	case BPF_FUNC_get_stackid:
10128 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
10129 			goto error;
10130 		break;
10131 	case BPF_FUNC_current_task_under_cgroup:
10132 	case BPF_FUNC_skb_under_cgroup:
10133 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
10134 			goto error;
10135 		break;
10136 	case BPF_FUNC_redirect_map:
10137 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
10138 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
10139 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
10140 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
10141 			goto error;
10142 		break;
10143 	case BPF_FUNC_sk_redirect_map:
10144 	case BPF_FUNC_msg_redirect_map:
10145 	case BPF_FUNC_sock_map_update:
10146 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10147 			goto error;
10148 		break;
10149 	case BPF_FUNC_sk_redirect_hash:
10150 	case BPF_FUNC_msg_redirect_hash:
10151 	case BPF_FUNC_sock_hash_update:
10152 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10153 			goto error;
10154 		break;
10155 	case BPF_FUNC_get_local_storage:
10156 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10157 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10158 			goto error;
10159 		break;
10160 	case BPF_FUNC_sk_select_reuseport:
10161 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10162 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10163 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
10164 			goto error;
10165 		break;
10166 	case BPF_FUNC_map_pop_elem:
10167 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10168 		    map->map_type != BPF_MAP_TYPE_STACK)
10169 			goto error;
10170 		break;
10171 	case BPF_FUNC_map_peek_elem:
10172 	case BPF_FUNC_map_push_elem:
10173 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10174 		    map->map_type != BPF_MAP_TYPE_STACK &&
10175 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10176 			goto error;
10177 		break;
10178 	case BPF_FUNC_map_lookup_percpu_elem:
10179 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10180 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10181 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10182 			goto error;
10183 		break;
10184 	case BPF_FUNC_sk_storage_get:
10185 	case BPF_FUNC_sk_storage_delete:
10186 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10187 			goto error;
10188 		break;
10189 	case BPF_FUNC_inode_storage_get:
10190 	case BPF_FUNC_inode_storage_delete:
10191 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10192 			goto error;
10193 		break;
10194 	case BPF_FUNC_task_storage_get:
10195 	case BPF_FUNC_task_storage_delete:
10196 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10197 			goto error;
10198 		break;
10199 	case BPF_FUNC_cgrp_storage_get:
10200 	case BPF_FUNC_cgrp_storage_delete:
10201 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10202 			goto error;
10203 		break;
10204 	default:
10205 		break;
10206 	}
10207 
10208 	return 0;
10209 error:
10210 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
10211 		map->map_type, func_id_name(func_id), func_id);
10212 	return -EINVAL;
10213 }
10214 
10215 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
10216 {
10217 	int count = 0;
10218 
10219 	if (arg_type_is_raw_mem(fn->arg1_type))
10220 		count++;
10221 	if (arg_type_is_raw_mem(fn->arg2_type))
10222 		count++;
10223 	if (arg_type_is_raw_mem(fn->arg3_type))
10224 		count++;
10225 	if (arg_type_is_raw_mem(fn->arg4_type))
10226 		count++;
10227 	if (arg_type_is_raw_mem(fn->arg5_type))
10228 		count++;
10229 
10230 	/* We only support one arg being in raw mode at the moment,
10231 	 * which is sufficient for the helper functions we have
10232 	 * right now.
10233 	 */
10234 	return count <= 1;
10235 }
10236 
10237 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10238 {
10239 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10240 	bool has_size = fn->arg_size[arg] != 0;
10241 	bool is_next_size = false;
10242 
10243 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10244 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10245 
10246 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10247 		return is_next_size;
10248 
10249 	return has_size == is_next_size || is_next_size == is_fixed;
10250 }
10251 
10252 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10253 {
10254 	/* bpf_xxx(..., buf, len) call will access 'len'
10255 	 * bytes from memory 'buf'. Both arg types need
10256 	 * to be paired, so make sure there's no buggy
10257 	 * helper function specification.
10258 	 */
10259 	if (arg_type_is_mem_size(fn->arg1_type) ||
10260 	    check_args_pair_invalid(fn, 0) ||
10261 	    check_args_pair_invalid(fn, 1) ||
10262 	    check_args_pair_invalid(fn, 2) ||
10263 	    check_args_pair_invalid(fn, 3) ||
10264 	    check_args_pair_invalid(fn, 4))
10265 		return false;
10266 
10267 	return true;
10268 }
10269 
10270 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10271 {
10272 	int i;
10273 
10274 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10275 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10276 			return !!fn->arg_btf_id[i];
10277 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10278 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
10279 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10280 		    /* arg_btf_id and arg_size are in a union. */
10281 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10282 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10283 			return false;
10284 	}
10285 
10286 	return true;
10287 }
10288 
10289 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
10290 {
10291 	return check_raw_mode_ok(fn) &&
10292 	       check_arg_pair_ok(fn) &&
10293 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
10294 }
10295 
10296 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
10297  * are now invalid, so turn them into unknown SCALAR_VALUE.
10298  *
10299  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
10300  * since these slices point to packet data.
10301  */
10302 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
10303 {
10304 	struct bpf_func_state *state;
10305 	struct bpf_reg_state *reg;
10306 
10307 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10308 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
10309 			mark_reg_invalid(env, reg);
10310 	}));
10311 }
10312 
10313 enum {
10314 	AT_PKT_END = -1,
10315 	BEYOND_PKT_END = -2,
10316 };
10317 
10318 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
10319 {
10320 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10321 	struct bpf_reg_state *reg = &state->regs[regn];
10322 
10323 	if (reg->type != PTR_TO_PACKET)
10324 		/* PTR_TO_PACKET_META is not supported yet */
10325 		return;
10326 
10327 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
10328 	 * How far beyond pkt_end it goes is unknown.
10329 	 * if (!range_open) it's the case of pkt >= pkt_end
10330 	 * if (range_open) it's the case of pkt > pkt_end
10331 	 * hence this pointer is at least 1 byte bigger than pkt_end
10332 	 */
10333 	if (range_open)
10334 		reg->range = BEYOND_PKT_END;
10335 	else
10336 		reg->range = AT_PKT_END;
10337 }
10338 
10339 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id)
10340 {
10341 	int i;
10342 
10343 	for (i = 0; i < state->acquired_refs; i++) {
10344 		if (state->refs[i].type != REF_TYPE_PTR)
10345 			continue;
10346 		if (state->refs[i].id == ref_obj_id) {
10347 			release_reference_state(state, i);
10348 			return 0;
10349 		}
10350 	}
10351 	return -EINVAL;
10352 }
10353 
10354 /* The pointer with the specified id has released its reference to kernel
10355  * resources. Identify all copies of the same pointer and clear the reference.
10356  *
10357  * This is the release function corresponding to acquire_reference(). Idempotent.
10358  */
10359 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id)
10360 {
10361 	struct bpf_verifier_state *vstate = env->cur_state;
10362 	struct bpf_func_state *state;
10363 	struct bpf_reg_state *reg;
10364 	int err;
10365 
10366 	err = release_reference_nomark(vstate, ref_obj_id);
10367 	if (err)
10368 		return err;
10369 
10370 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10371 		if (reg->ref_obj_id == ref_obj_id)
10372 			mark_reg_invalid(env, reg);
10373 	}));
10374 
10375 	return 0;
10376 }
10377 
10378 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
10379 {
10380 	struct bpf_func_state *unused;
10381 	struct bpf_reg_state *reg;
10382 
10383 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10384 		if (type_is_non_owning_ref(reg->type))
10385 			mark_reg_invalid(env, reg);
10386 	}));
10387 }
10388 
10389 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
10390 				    struct bpf_reg_state *regs)
10391 {
10392 	int i;
10393 
10394 	/* after the call registers r0 - r5 were scratched */
10395 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10396 		mark_reg_not_init(env, regs, caller_saved[i]);
10397 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
10398 	}
10399 }
10400 
10401 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
10402 				   struct bpf_func_state *caller,
10403 				   struct bpf_func_state *callee,
10404 				   int insn_idx);
10405 
10406 static int set_callee_state(struct bpf_verifier_env *env,
10407 			    struct bpf_func_state *caller,
10408 			    struct bpf_func_state *callee, int insn_idx);
10409 
10410 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
10411 			    set_callee_state_fn set_callee_state_cb,
10412 			    struct bpf_verifier_state *state)
10413 {
10414 	struct bpf_func_state *caller, *callee;
10415 	int err;
10416 
10417 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
10418 		verbose(env, "the call stack of %d frames is too deep\n",
10419 			state->curframe + 2);
10420 		return -E2BIG;
10421 	}
10422 
10423 	if (state->frame[state->curframe + 1]) {
10424 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
10425 		return -EFAULT;
10426 	}
10427 
10428 	caller = state->frame[state->curframe];
10429 	callee = kzalloc(sizeof(*callee), GFP_KERNEL_ACCOUNT);
10430 	if (!callee)
10431 		return -ENOMEM;
10432 	state->frame[state->curframe + 1] = callee;
10433 
10434 	/* callee cannot access r0, r6 - r9 for reading and has to write
10435 	 * into its own stack before reading from it.
10436 	 * callee can read/write into caller's stack
10437 	 */
10438 	init_func_state(env, callee,
10439 			/* remember the callsite, it will be used by bpf_exit */
10440 			callsite,
10441 			state->curframe + 1 /* frameno within this callchain */,
10442 			subprog /* subprog number within this prog */);
10443 	err = set_callee_state_cb(env, caller, callee, callsite);
10444 	if (err)
10445 		goto err_out;
10446 
10447 	/* only increment it after check_reg_arg() finished */
10448 	state->curframe++;
10449 
10450 	return 0;
10451 
10452 err_out:
10453 	free_func_state(callee);
10454 	state->frame[state->curframe + 1] = NULL;
10455 	return err;
10456 }
10457 
10458 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
10459 				    const struct btf *btf,
10460 				    struct bpf_reg_state *regs)
10461 {
10462 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
10463 	struct bpf_verifier_log *log = &env->log;
10464 	u32 i;
10465 	int ret;
10466 
10467 	ret = btf_prepare_func_args(env, subprog);
10468 	if (ret)
10469 		return ret;
10470 
10471 	/* check that BTF function arguments match actual types that the
10472 	 * verifier sees.
10473 	 */
10474 	for (i = 0; i < sub->arg_cnt; i++) {
10475 		u32 regno = i + 1;
10476 		struct bpf_reg_state *reg = &regs[regno];
10477 		struct bpf_subprog_arg_info *arg = &sub->args[i];
10478 
10479 		if (arg->arg_type == ARG_ANYTHING) {
10480 			if (reg->type != SCALAR_VALUE) {
10481 				bpf_log(log, "R%d is not a scalar\n", regno);
10482 				return -EINVAL;
10483 			}
10484 		} else if (arg->arg_type & PTR_UNTRUSTED) {
10485 			/*
10486 			 * Anything is allowed for untrusted arguments, as these are
10487 			 * read-only and probe read instructions would protect against
10488 			 * invalid memory access.
10489 			 */
10490 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
10491 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10492 			if (ret < 0)
10493 				return ret;
10494 			/* If function expects ctx type in BTF check that caller
10495 			 * is passing PTR_TO_CTX.
10496 			 */
10497 			if (reg->type != PTR_TO_CTX) {
10498 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
10499 				return -EINVAL;
10500 			}
10501 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
10502 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10503 			if (ret < 0)
10504 				return ret;
10505 			if (check_mem_reg(env, reg, regno, arg->mem_size))
10506 				return -EINVAL;
10507 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
10508 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
10509 				return -EINVAL;
10510 			}
10511 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
10512 			/*
10513 			 * Can pass any value and the kernel won't crash, but
10514 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
10515 			 * else is a bug in the bpf program. Point it out to
10516 			 * the user at the verification time instead of
10517 			 * run-time debug nightmare.
10518 			 */
10519 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
10520 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
10521 				return -EINVAL;
10522 			}
10523 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
10524 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
10525 			if (ret)
10526 				return ret;
10527 
10528 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
10529 			if (ret)
10530 				return ret;
10531 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
10532 			struct bpf_call_arg_meta meta;
10533 			int err;
10534 
10535 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
10536 				continue;
10537 
10538 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
10539 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
10540 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
10541 			if (err)
10542 				return err;
10543 		} else {
10544 			verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type);
10545 			return -EFAULT;
10546 		}
10547 	}
10548 
10549 	return 0;
10550 }
10551 
10552 /* Compare BTF of a function call with given bpf_reg_state.
10553  * Returns:
10554  * EFAULT - there is a verifier bug. Abort verification.
10555  * EINVAL - there is a type mismatch or BTF is not available.
10556  * 0 - BTF matches with what bpf_reg_state expects.
10557  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
10558  */
10559 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
10560 				  struct bpf_reg_state *regs)
10561 {
10562 	struct bpf_prog *prog = env->prog;
10563 	struct btf *btf = prog->aux->btf;
10564 	u32 btf_id;
10565 	int err;
10566 
10567 	if (!prog->aux->func_info)
10568 		return -EINVAL;
10569 
10570 	btf_id = prog->aux->func_info[subprog].type_id;
10571 	if (!btf_id)
10572 		return -EFAULT;
10573 
10574 	if (prog->aux->func_info_aux[subprog].unreliable)
10575 		return -EINVAL;
10576 
10577 	err = btf_check_func_arg_match(env, subprog, btf, regs);
10578 	/* Compiler optimizations can remove arguments from static functions
10579 	 * or mismatched type can be passed into a global function.
10580 	 * In such cases mark the function as unreliable from BTF point of view.
10581 	 */
10582 	if (err)
10583 		prog->aux->func_info_aux[subprog].unreliable = true;
10584 	return err;
10585 }
10586 
10587 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10588 			      int insn_idx, int subprog,
10589 			      set_callee_state_fn set_callee_state_cb)
10590 {
10591 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
10592 	struct bpf_func_state *caller, *callee;
10593 	int err;
10594 
10595 	caller = state->frame[state->curframe];
10596 	err = btf_check_subprog_call(env, subprog, caller->regs);
10597 	if (err == -EFAULT)
10598 		return err;
10599 
10600 	/* set_callee_state is used for direct subprog calls, but we are
10601 	 * interested in validating only BPF helpers that can call subprogs as
10602 	 * callbacks
10603 	 */
10604 	env->subprog_info[subprog].is_cb = true;
10605 	if (bpf_pseudo_kfunc_call(insn) &&
10606 	    !is_callback_calling_kfunc(insn->imm)) {
10607 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
10608 			     func_id_name(insn->imm), insn->imm);
10609 		return -EFAULT;
10610 	} else if (!bpf_pseudo_kfunc_call(insn) &&
10611 		   !is_callback_calling_function(insn->imm)) { /* helper */
10612 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
10613 			     func_id_name(insn->imm), insn->imm);
10614 		return -EFAULT;
10615 	}
10616 
10617 	if (is_async_callback_calling_insn(insn)) {
10618 		struct bpf_verifier_state *async_cb;
10619 
10620 		/* there is no real recursion here. timer and workqueue callbacks are async */
10621 		env->subprog_info[subprog].is_async_cb = true;
10622 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
10623 					 insn_idx, subprog,
10624 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm));
10625 		if (!async_cb)
10626 			return -EFAULT;
10627 		callee = async_cb->frame[0];
10628 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
10629 
10630 		/* Convert bpf_timer_set_callback() args into timer callback args */
10631 		err = set_callee_state_cb(env, caller, callee, insn_idx);
10632 		if (err)
10633 			return err;
10634 
10635 		return 0;
10636 	}
10637 
10638 	/* for callback functions enqueue entry to callback and
10639 	 * proceed with next instruction within current frame.
10640 	 */
10641 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
10642 	if (!callback_state)
10643 		return -ENOMEM;
10644 
10645 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
10646 			       callback_state);
10647 	if (err)
10648 		return err;
10649 
10650 	callback_state->callback_unroll_depth++;
10651 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
10652 	caller->callback_depth = 0;
10653 	return 0;
10654 }
10655 
10656 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10657 			   int *insn_idx)
10658 {
10659 	struct bpf_verifier_state *state = env->cur_state;
10660 	struct bpf_func_state *caller;
10661 	int err, subprog, target_insn;
10662 
10663 	target_insn = *insn_idx + insn->imm + 1;
10664 	subprog = find_subprog(env, target_insn);
10665 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
10666 			    target_insn))
10667 		return -EFAULT;
10668 
10669 	caller = state->frame[state->curframe];
10670 	err = btf_check_subprog_call(env, subprog, caller->regs);
10671 	if (err == -EFAULT)
10672 		return err;
10673 	if (subprog_is_global(env, subprog)) {
10674 		const char *sub_name = subprog_name(env, subprog);
10675 
10676 		if (env->cur_state->active_locks) {
10677 			verbose(env, "global function calls are not allowed while holding a lock,\n"
10678 				     "use static function instead\n");
10679 			return -EINVAL;
10680 		}
10681 
10682 		if (env->subprog_info[subprog].might_sleep &&
10683 		    (env->cur_state->active_rcu_lock || env->cur_state->active_preempt_locks ||
10684 		     env->cur_state->active_irq_id || !in_sleepable(env))) {
10685 			verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n"
10686 				     "i.e., in a RCU/IRQ/preempt-disabled section, or in\n"
10687 				     "a non-sleepable BPF program context\n");
10688 			return -EINVAL;
10689 		}
10690 
10691 		if (err) {
10692 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10693 				subprog, sub_name);
10694 			return err;
10695 		}
10696 
10697 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10698 			subprog, sub_name);
10699 		if (env->subprog_info[subprog].changes_pkt_data)
10700 			clear_all_pkt_pointers(env);
10701 		/* mark global subprog for verifying after main prog */
10702 		subprog_aux(env, subprog)->called = true;
10703 		clear_caller_saved_regs(env, caller->regs);
10704 
10705 		/* All global functions return a 64-bit SCALAR_VALUE */
10706 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
10707 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10708 
10709 		/* continue with next insn after call */
10710 		return 0;
10711 	}
10712 
10713 	/* for regular function entry setup new frame and continue
10714 	 * from that frame.
10715 	 */
10716 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10717 	if (err)
10718 		return err;
10719 
10720 	clear_caller_saved_regs(env, caller->regs);
10721 
10722 	/* and go analyze first insn of the callee */
10723 	*insn_idx = env->subprog_info[subprog].start - 1;
10724 
10725 	if (env->log.level & BPF_LOG_LEVEL) {
10726 		verbose(env, "caller:\n");
10727 		print_verifier_state(env, state, caller->frameno, true);
10728 		verbose(env, "callee:\n");
10729 		print_verifier_state(env, state, state->curframe, true);
10730 	}
10731 
10732 	return 0;
10733 }
10734 
10735 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10736 				   struct bpf_func_state *caller,
10737 				   struct bpf_func_state *callee)
10738 {
10739 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10740 	 *      void *callback_ctx, u64 flags);
10741 	 * callback_fn(struct bpf_map *map, void *key, void *value,
10742 	 *      void *callback_ctx);
10743 	 */
10744 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10745 
10746 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10747 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10748 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10749 
10750 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10751 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10752 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10753 
10754 	/* pointer to stack or null */
10755 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10756 
10757 	/* unused */
10758 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10759 	return 0;
10760 }
10761 
10762 static int set_callee_state(struct bpf_verifier_env *env,
10763 			    struct bpf_func_state *caller,
10764 			    struct bpf_func_state *callee, int insn_idx)
10765 {
10766 	int i;
10767 
10768 	/* copy r1 - r5 args that callee can access.  The copy includes parent
10769 	 * pointers, which connects us up to the liveness chain
10770 	 */
10771 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10772 		callee->regs[i] = caller->regs[i];
10773 	return 0;
10774 }
10775 
10776 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10777 				       struct bpf_func_state *caller,
10778 				       struct bpf_func_state *callee,
10779 				       int insn_idx)
10780 {
10781 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10782 	struct bpf_map *map;
10783 	int err;
10784 
10785 	/* valid map_ptr and poison value does not matter */
10786 	map = insn_aux->map_ptr_state.map_ptr;
10787 	if (!map->ops->map_set_for_each_callback_args ||
10788 	    !map->ops->map_for_each_callback) {
10789 		verbose(env, "callback function not allowed for map\n");
10790 		return -ENOTSUPP;
10791 	}
10792 
10793 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10794 	if (err)
10795 		return err;
10796 
10797 	callee->in_callback_fn = true;
10798 	callee->callback_ret_range = retval_range(0, 1);
10799 	return 0;
10800 }
10801 
10802 static int set_loop_callback_state(struct bpf_verifier_env *env,
10803 				   struct bpf_func_state *caller,
10804 				   struct bpf_func_state *callee,
10805 				   int insn_idx)
10806 {
10807 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10808 	 *	    u64 flags);
10809 	 * callback_fn(u64 index, void *callback_ctx);
10810 	 */
10811 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10812 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10813 
10814 	/* unused */
10815 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10816 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10817 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10818 
10819 	callee->in_callback_fn = true;
10820 	callee->callback_ret_range = retval_range(0, 1);
10821 	return 0;
10822 }
10823 
10824 static int set_timer_callback_state(struct bpf_verifier_env *env,
10825 				    struct bpf_func_state *caller,
10826 				    struct bpf_func_state *callee,
10827 				    int insn_idx)
10828 {
10829 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10830 
10831 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10832 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10833 	 */
10834 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10835 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10836 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10837 
10838 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10839 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10840 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10841 
10842 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10843 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10844 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10845 
10846 	/* unused */
10847 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10848 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10849 	callee->in_async_callback_fn = true;
10850 	callee->callback_ret_range = retval_range(0, 1);
10851 	return 0;
10852 }
10853 
10854 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
10855 				       struct bpf_func_state *caller,
10856 				       struct bpf_func_state *callee,
10857 				       int insn_idx)
10858 {
10859 	/* bpf_find_vma(struct task_struct *task, u64 addr,
10860 	 *               void *callback_fn, void *callback_ctx, u64 flags)
10861 	 * (callback_fn)(struct task_struct *task,
10862 	 *               struct vm_area_struct *vma, void *callback_ctx);
10863 	 */
10864 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10865 
10866 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
10867 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10868 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
10869 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
10870 
10871 	/* pointer to stack or null */
10872 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
10873 
10874 	/* unused */
10875 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10876 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10877 	callee->in_callback_fn = true;
10878 	callee->callback_ret_range = retval_range(0, 1);
10879 	return 0;
10880 }
10881 
10882 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10883 					   struct bpf_func_state *caller,
10884 					   struct bpf_func_state *callee,
10885 					   int insn_idx)
10886 {
10887 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10888 	 *			  callback_ctx, u64 flags);
10889 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10890 	 */
10891 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10892 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10893 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10894 
10895 	/* unused */
10896 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10897 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10898 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10899 
10900 	callee->in_callback_fn = true;
10901 	callee->callback_ret_range = retval_range(0, 1);
10902 	return 0;
10903 }
10904 
10905 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10906 					 struct bpf_func_state *caller,
10907 					 struct bpf_func_state *callee,
10908 					 int insn_idx)
10909 {
10910 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10911 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10912 	 *
10913 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10914 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10915 	 * by this point, so look at 'root'
10916 	 */
10917 	struct btf_field *field;
10918 
10919 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10920 				      BPF_RB_ROOT);
10921 	if (!field || !field->graph_root.value_btf_id)
10922 		return -EFAULT;
10923 
10924 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10925 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10926 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10927 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10928 
10929 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10930 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10931 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10932 	callee->in_callback_fn = true;
10933 	callee->callback_ret_range = retval_range(0, 1);
10934 	return 0;
10935 }
10936 
10937 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
10938 
10939 /* Are we currently verifying the callback for a rbtree helper that must
10940  * be called with lock held? If so, no need to complain about unreleased
10941  * lock
10942  */
10943 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
10944 {
10945 	struct bpf_verifier_state *state = env->cur_state;
10946 	struct bpf_insn *insn = env->prog->insnsi;
10947 	struct bpf_func_state *callee;
10948 	int kfunc_btf_id;
10949 
10950 	if (!state->curframe)
10951 		return false;
10952 
10953 	callee = state->frame[state->curframe];
10954 
10955 	if (!callee->in_callback_fn)
10956 		return false;
10957 
10958 	kfunc_btf_id = insn[callee->callsite].imm;
10959 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
10960 }
10961 
10962 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
10963 				bool return_32bit)
10964 {
10965 	if (return_32bit)
10966 		return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
10967 	else
10968 		return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
10969 }
10970 
10971 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
10972 {
10973 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
10974 	struct bpf_func_state *caller, *callee;
10975 	struct bpf_reg_state *r0;
10976 	bool in_callback_fn;
10977 	int err;
10978 
10979 	callee = state->frame[state->curframe];
10980 	r0 = &callee->regs[BPF_REG_0];
10981 	if (r0->type == PTR_TO_STACK) {
10982 		/* technically it's ok to return caller's stack pointer
10983 		 * (or caller's caller's pointer) back to the caller,
10984 		 * since these pointers are valid. Only current stack
10985 		 * pointer will be invalid as soon as function exits,
10986 		 * but let's be conservative
10987 		 */
10988 		verbose(env, "cannot return stack pointer to the caller\n");
10989 		return -EINVAL;
10990 	}
10991 
10992 	caller = state->frame[state->curframe - 1];
10993 	if (callee->in_callback_fn) {
10994 		if (r0->type != SCALAR_VALUE) {
10995 			verbose(env, "R0 not a scalar value\n");
10996 			return -EACCES;
10997 		}
10998 
10999 		/* we are going to rely on register's precise value */
11000 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
11001 		err = err ?: mark_chain_precision(env, BPF_REG_0);
11002 		if (err)
11003 			return err;
11004 
11005 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
11006 		if (!retval_range_within(callee->callback_ret_range, r0, false)) {
11007 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
11008 					       "At callback return", "R0");
11009 			return -EINVAL;
11010 		}
11011 		if (!calls_callback(env, callee->callsite)) {
11012 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
11013 				     *insn_idx, callee->callsite);
11014 			return -EFAULT;
11015 		}
11016 	} else {
11017 		/* return to the caller whatever r0 had in the callee */
11018 		caller->regs[BPF_REG_0] = *r0;
11019 	}
11020 
11021 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
11022 	 * there function call logic would reschedule callback visit. If iteration
11023 	 * converges is_state_visited() would prune that visit eventually.
11024 	 */
11025 	in_callback_fn = callee->in_callback_fn;
11026 	if (in_callback_fn)
11027 		*insn_idx = callee->callsite;
11028 	else
11029 		*insn_idx = callee->callsite + 1;
11030 
11031 	if (env->log.level & BPF_LOG_LEVEL) {
11032 		verbose(env, "returning from callee:\n");
11033 		print_verifier_state(env, state, callee->frameno, true);
11034 		verbose(env, "to caller at %d:\n", *insn_idx);
11035 		print_verifier_state(env, state, caller->frameno, true);
11036 	}
11037 	/* clear everything in the callee. In case of exceptional exits using
11038 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
11039 	free_func_state(callee);
11040 	state->frame[state->curframe--] = NULL;
11041 
11042 	/* for callbacks widen imprecise scalars to make programs like below verify:
11043 	 *
11044 	 *   struct ctx { int i; }
11045 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
11046 	 *   ...
11047 	 *   struct ctx = { .i = 0; }
11048 	 *   bpf_loop(100, cb, &ctx, 0);
11049 	 *
11050 	 * This is similar to what is done in process_iter_next_call() for open
11051 	 * coded iterators.
11052 	 */
11053 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
11054 	if (prev_st) {
11055 		err = widen_imprecise_scalars(env, prev_st, state);
11056 		if (err)
11057 			return err;
11058 	}
11059 	return 0;
11060 }
11061 
11062 static int do_refine_retval_range(struct bpf_verifier_env *env,
11063 				  struct bpf_reg_state *regs, int ret_type,
11064 				  int func_id,
11065 				  struct bpf_call_arg_meta *meta)
11066 {
11067 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
11068 
11069 	if (ret_type != RET_INTEGER)
11070 		return 0;
11071 
11072 	switch (func_id) {
11073 	case BPF_FUNC_get_stack:
11074 	case BPF_FUNC_get_task_stack:
11075 	case BPF_FUNC_probe_read_str:
11076 	case BPF_FUNC_probe_read_kernel_str:
11077 	case BPF_FUNC_probe_read_user_str:
11078 		ret_reg->smax_value = meta->msize_max_value;
11079 		ret_reg->s32_max_value = meta->msize_max_value;
11080 		ret_reg->smin_value = -MAX_ERRNO;
11081 		ret_reg->s32_min_value = -MAX_ERRNO;
11082 		reg_bounds_sync(ret_reg);
11083 		break;
11084 	case BPF_FUNC_get_smp_processor_id:
11085 		ret_reg->umax_value = nr_cpu_ids - 1;
11086 		ret_reg->u32_max_value = nr_cpu_ids - 1;
11087 		ret_reg->smax_value = nr_cpu_ids - 1;
11088 		ret_reg->s32_max_value = nr_cpu_ids - 1;
11089 		ret_reg->umin_value = 0;
11090 		ret_reg->u32_min_value = 0;
11091 		ret_reg->smin_value = 0;
11092 		ret_reg->s32_min_value = 0;
11093 		reg_bounds_sync(ret_reg);
11094 		break;
11095 	}
11096 
11097 	return reg_bounds_sanity_check(env, ret_reg, "retval");
11098 }
11099 
11100 static int
11101 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11102 		int func_id, int insn_idx)
11103 {
11104 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11105 	struct bpf_map *map = meta->map_ptr;
11106 
11107 	if (func_id != BPF_FUNC_tail_call &&
11108 	    func_id != BPF_FUNC_map_lookup_elem &&
11109 	    func_id != BPF_FUNC_map_update_elem &&
11110 	    func_id != BPF_FUNC_map_delete_elem &&
11111 	    func_id != BPF_FUNC_map_push_elem &&
11112 	    func_id != BPF_FUNC_map_pop_elem &&
11113 	    func_id != BPF_FUNC_map_peek_elem &&
11114 	    func_id != BPF_FUNC_for_each_map_elem &&
11115 	    func_id != BPF_FUNC_redirect_map &&
11116 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
11117 		return 0;
11118 
11119 	if (map == NULL) {
11120 		verifier_bug(env, "expected map for helper call");
11121 		return -EFAULT;
11122 	}
11123 
11124 	/* In case of read-only, some additional restrictions
11125 	 * need to be applied in order to prevent altering the
11126 	 * state of the map from program side.
11127 	 */
11128 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
11129 	    (func_id == BPF_FUNC_map_delete_elem ||
11130 	     func_id == BPF_FUNC_map_update_elem ||
11131 	     func_id == BPF_FUNC_map_push_elem ||
11132 	     func_id == BPF_FUNC_map_pop_elem)) {
11133 		verbose(env, "write into map forbidden\n");
11134 		return -EACCES;
11135 	}
11136 
11137 	if (!aux->map_ptr_state.map_ptr)
11138 		bpf_map_ptr_store(aux, meta->map_ptr,
11139 				  !meta->map_ptr->bypass_spec_v1, false);
11140 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
11141 		bpf_map_ptr_store(aux, meta->map_ptr,
11142 				  !meta->map_ptr->bypass_spec_v1, true);
11143 	return 0;
11144 }
11145 
11146 static int
11147 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11148 		int func_id, int insn_idx)
11149 {
11150 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11151 	struct bpf_reg_state *regs = cur_regs(env), *reg;
11152 	struct bpf_map *map = meta->map_ptr;
11153 	u64 val, max;
11154 	int err;
11155 
11156 	if (func_id != BPF_FUNC_tail_call)
11157 		return 0;
11158 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
11159 		verbose(env, "expected prog array map for tail call");
11160 		return -EINVAL;
11161 	}
11162 
11163 	reg = &regs[BPF_REG_3];
11164 	val = reg->var_off.value;
11165 	max = map->max_entries;
11166 
11167 	if (!(is_reg_const(reg, false) && val < max)) {
11168 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11169 		return 0;
11170 	}
11171 
11172 	err = mark_chain_precision(env, BPF_REG_3);
11173 	if (err)
11174 		return err;
11175 	if (bpf_map_key_unseen(aux))
11176 		bpf_map_key_store(aux, val);
11177 	else if (!bpf_map_key_poisoned(aux) &&
11178 		  bpf_map_key_immediate(aux) != val)
11179 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11180 	return 0;
11181 }
11182 
11183 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
11184 {
11185 	struct bpf_verifier_state *state = env->cur_state;
11186 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11187 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
11188 	bool refs_lingering = false;
11189 	int i;
11190 
11191 	if (!exception_exit && cur_func(env)->frameno)
11192 		return 0;
11193 
11194 	for (i = 0; i < state->acquired_refs; i++) {
11195 		if (state->refs[i].type != REF_TYPE_PTR)
11196 			continue;
11197 		/* Allow struct_ops programs to return a referenced kptr back to
11198 		 * kernel. Type checks are performed later in check_return_code.
11199 		 */
11200 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
11201 		    reg->ref_obj_id == state->refs[i].id)
11202 			continue;
11203 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
11204 			state->refs[i].id, state->refs[i].insn_idx);
11205 		refs_lingering = true;
11206 	}
11207 	return refs_lingering ? -EINVAL : 0;
11208 }
11209 
11210 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
11211 {
11212 	int err;
11213 
11214 	if (check_lock && env->cur_state->active_locks) {
11215 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
11216 		return -EINVAL;
11217 	}
11218 
11219 	err = check_reference_leak(env, exception_exit);
11220 	if (err) {
11221 		verbose(env, "%s would lead to reference leak\n", prefix);
11222 		return err;
11223 	}
11224 
11225 	if (check_lock && env->cur_state->active_irq_id) {
11226 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
11227 		return -EINVAL;
11228 	}
11229 
11230 	if (check_lock && env->cur_state->active_rcu_lock) {
11231 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
11232 		return -EINVAL;
11233 	}
11234 
11235 	if (check_lock && env->cur_state->active_preempt_locks) {
11236 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
11237 		return -EINVAL;
11238 	}
11239 
11240 	return 0;
11241 }
11242 
11243 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
11244 				   struct bpf_reg_state *regs)
11245 {
11246 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
11247 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
11248 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
11249 	struct bpf_bprintf_data data = {};
11250 	int err, fmt_map_off, num_args;
11251 	u64 fmt_addr;
11252 	char *fmt;
11253 
11254 	/* data must be an array of u64 */
11255 	if (data_len_reg->var_off.value % 8)
11256 		return -EINVAL;
11257 	num_args = data_len_reg->var_off.value / 8;
11258 
11259 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
11260 	 * and map_direct_value_addr is set.
11261 	 */
11262 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
11263 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
11264 						  fmt_map_off);
11265 	if (err) {
11266 		verbose(env, "failed to retrieve map value address\n");
11267 		return -EFAULT;
11268 	}
11269 	fmt = (char *)(long)fmt_addr + fmt_map_off;
11270 
11271 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
11272 	 * can focus on validating the format specifiers.
11273 	 */
11274 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
11275 	if (err < 0)
11276 		verbose(env, "Invalid format string\n");
11277 
11278 	return err;
11279 }
11280 
11281 static int check_get_func_ip(struct bpf_verifier_env *env)
11282 {
11283 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11284 	int func_id = BPF_FUNC_get_func_ip;
11285 
11286 	if (type == BPF_PROG_TYPE_TRACING) {
11287 		if (!bpf_prog_has_trampoline(env->prog)) {
11288 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
11289 				func_id_name(func_id), func_id);
11290 			return -ENOTSUPP;
11291 		}
11292 		return 0;
11293 	} else if (type == BPF_PROG_TYPE_KPROBE) {
11294 		return 0;
11295 	}
11296 
11297 	verbose(env, "func %s#%d not supported for program type %d\n",
11298 		func_id_name(func_id), func_id, type);
11299 	return -ENOTSUPP;
11300 }
11301 
11302 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
11303 {
11304 	return &env->insn_aux_data[env->insn_idx];
11305 }
11306 
11307 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
11308 {
11309 	struct bpf_reg_state *regs = cur_regs(env);
11310 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
11311 	bool reg_is_null = register_is_null(reg);
11312 
11313 	if (reg_is_null)
11314 		mark_chain_precision(env, BPF_REG_4);
11315 
11316 	return reg_is_null;
11317 }
11318 
11319 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
11320 {
11321 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
11322 
11323 	if (!state->initialized) {
11324 		state->initialized = 1;
11325 		state->fit_for_inline = loop_flag_is_zero(env);
11326 		state->callback_subprogno = subprogno;
11327 		return;
11328 	}
11329 
11330 	if (!state->fit_for_inline)
11331 		return;
11332 
11333 	state->fit_for_inline = (loop_flag_is_zero(env) &&
11334 				 state->callback_subprogno == subprogno);
11335 }
11336 
11337 /* Returns whether or not the given map type can potentially elide
11338  * lookup return value nullness check. This is possible if the key
11339  * is statically known.
11340  */
11341 static bool can_elide_value_nullness(enum bpf_map_type type)
11342 {
11343 	switch (type) {
11344 	case BPF_MAP_TYPE_ARRAY:
11345 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11346 		return true;
11347 	default:
11348 		return false;
11349 	}
11350 }
11351 
11352 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
11353 			    const struct bpf_func_proto **ptr)
11354 {
11355 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
11356 		return -ERANGE;
11357 
11358 	if (!env->ops->get_func_proto)
11359 		return -EINVAL;
11360 
11361 	*ptr = env->ops->get_func_proto(func_id, env->prog);
11362 	return *ptr ? 0 : -EINVAL;
11363 }
11364 
11365 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11366 			     int *insn_idx_p)
11367 {
11368 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11369 	bool returns_cpu_specific_alloc_ptr = false;
11370 	const struct bpf_func_proto *fn = NULL;
11371 	enum bpf_return_type ret_type;
11372 	enum bpf_type_flag ret_flag;
11373 	struct bpf_reg_state *regs;
11374 	struct bpf_call_arg_meta meta;
11375 	int insn_idx = *insn_idx_p;
11376 	bool changes_data;
11377 	int i, err, func_id;
11378 
11379 	/* find function prototype */
11380 	func_id = insn->imm;
11381 	err = get_helper_proto(env, insn->imm, &fn);
11382 	if (err == -ERANGE) {
11383 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
11384 		return -EINVAL;
11385 	}
11386 
11387 	if (err) {
11388 		verbose(env, "program of this type cannot use helper %s#%d\n",
11389 			func_id_name(func_id), func_id);
11390 		return err;
11391 	}
11392 
11393 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
11394 	if (!env->prog->gpl_compatible && fn->gpl_only) {
11395 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
11396 		return -EINVAL;
11397 	}
11398 
11399 	if (fn->allowed && !fn->allowed(env->prog)) {
11400 		verbose(env, "helper call is not allowed in probe\n");
11401 		return -EINVAL;
11402 	}
11403 
11404 	if (!in_sleepable(env) && fn->might_sleep) {
11405 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
11406 		return -EINVAL;
11407 	}
11408 
11409 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
11410 	changes_data = bpf_helper_changes_pkt_data(func_id);
11411 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
11412 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
11413 		return -EFAULT;
11414 	}
11415 
11416 	memset(&meta, 0, sizeof(meta));
11417 	meta.pkt_access = fn->pkt_access;
11418 
11419 	err = check_func_proto(fn, func_id);
11420 	if (err) {
11421 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
11422 		return err;
11423 	}
11424 
11425 	if (env->cur_state->active_rcu_lock) {
11426 		if (fn->might_sleep) {
11427 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
11428 				func_id_name(func_id), func_id);
11429 			return -EINVAL;
11430 		}
11431 
11432 		if (in_sleepable(env) && is_storage_get_function(func_id))
11433 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11434 	}
11435 
11436 	if (env->cur_state->active_preempt_locks) {
11437 		if (fn->might_sleep) {
11438 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
11439 				func_id_name(func_id), func_id);
11440 			return -EINVAL;
11441 		}
11442 
11443 		if (in_sleepable(env) && is_storage_get_function(func_id))
11444 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11445 	}
11446 
11447 	if (env->cur_state->active_irq_id) {
11448 		if (fn->might_sleep) {
11449 			verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n",
11450 				func_id_name(func_id), func_id);
11451 			return -EINVAL;
11452 		}
11453 
11454 		if (in_sleepable(env) && is_storage_get_function(func_id))
11455 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11456 	}
11457 
11458 	meta.func_id = func_id;
11459 	/* check args */
11460 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
11461 		err = check_func_arg(env, i, &meta, fn, insn_idx);
11462 		if (err)
11463 			return err;
11464 	}
11465 
11466 	err = record_func_map(env, &meta, func_id, insn_idx);
11467 	if (err)
11468 		return err;
11469 
11470 	err = record_func_key(env, &meta, func_id, insn_idx);
11471 	if (err)
11472 		return err;
11473 
11474 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
11475 	 * is inferred from register state.
11476 	 */
11477 	for (i = 0; i < meta.access_size; i++) {
11478 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
11479 				       BPF_WRITE, -1, false, false);
11480 		if (err)
11481 			return err;
11482 	}
11483 
11484 	regs = cur_regs(env);
11485 
11486 	if (meta.release_regno) {
11487 		err = -EINVAL;
11488 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
11489 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
11490 		 * is safe to do directly.
11491 		 */
11492 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
11493 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
11494 				verifier_bug(env, "CONST_PTR_TO_DYNPTR cannot be released");
11495 				return -EFAULT;
11496 			}
11497 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
11498 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
11499 			u32 ref_obj_id = meta.ref_obj_id;
11500 			bool in_rcu = in_rcu_cs(env);
11501 			struct bpf_func_state *state;
11502 			struct bpf_reg_state *reg;
11503 
11504 			err = release_reference_nomark(env->cur_state, ref_obj_id);
11505 			if (!err) {
11506 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11507 					if (reg->ref_obj_id == ref_obj_id) {
11508 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11509 							reg->ref_obj_id = 0;
11510 							reg->type &= ~MEM_ALLOC;
11511 							reg->type |= MEM_RCU;
11512 						} else {
11513 							mark_reg_invalid(env, reg);
11514 						}
11515 					}
11516 				}));
11517 			}
11518 		} else if (meta.ref_obj_id) {
11519 			err = release_reference(env, meta.ref_obj_id);
11520 		} else if (register_is_null(&regs[meta.release_regno])) {
11521 			/* meta.ref_obj_id can only be 0 if register that is meant to be
11522 			 * released is NULL, which must be > R0.
11523 			 */
11524 			err = 0;
11525 		}
11526 		if (err) {
11527 			verbose(env, "func %s#%d reference has not been acquired before\n",
11528 				func_id_name(func_id), func_id);
11529 			return err;
11530 		}
11531 	}
11532 
11533 	switch (func_id) {
11534 	case BPF_FUNC_tail_call:
11535 		err = check_resource_leak(env, false, true, "tail_call");
11536 		if (err)
11537 			return err;
11538 		break;
11539 	case BPF_FUNC_get_local_storage:
11540 		/* check that flags argument in get_local_storage(map, flags) is 0,
11541 		 * this is required because get_local_storage() can't return an error.
11542 		 */
11543 		if (!register_is_null(&regs[BPF_REG_2])) {
11544 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
11545 			return -EINVAL;
11546 		}
11547 		break;
11548 	case BPF_FUNC_for_each_map_elem:
11549 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11550 					 set_map_elem_callback_state);
11551 		break;
11552 	case BPF_FUNC_timer_set_callback:
11553 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11554 					 set_timer_callback_state);
11555 		break;
11556 	case BPF_FUNC_find_vma:
11557 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11558 					 set_find_vma_callback_state);
11559 		break;
11560 	case BPF_FUNC_snprintf:
11561 		err = check_bpf_snprintf_call(env, regs);
11562 		break;
11563 	case BPF_FUNC_loop:
11564 		update_loop_inline_state(env, meta.subprogno);
11565 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
11566 		 * is finished, thus mark it precise.
11567 		 */
11568 		err = mark_chain_precision(env, BPF_REG_1);
11569 		if (err)
11570 			return err;
11571 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
11572 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11573 						 set_loop_callback_state);
11574 		} else {
11575 			cur_func(env)->callback_depth = 0;
11576 			if (env->log.level & BPF_LOG_LEVEL2)
11577 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
11578 					env->cur_state->curframe);
11579 		}
11580 		break;
11581 	case BPF_FUNC_dynptr_from_mem:
11582 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
11583 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
11584 				reg_type_str(env, regs[BPF_REG_1].type));
11585 			return -EACCES;
11586 		}
11587 		break;
11588 	case BPF_FUNC_set_retval:
11589 		if (prog_type == BPF_PROG_TYPE_LSM &&
11590 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11591 			if (!env->prog->aux->attach_func_proto->type) {
11592 				/* Make sure programs that attach to void
11593 				 * hooks don't try to modify return value.
11594 				 */
11595 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11596 				return -EINVAL;
11597 			}
11598 		}
11599 		break;
11600 	case BPF_FUNC_dynptr_data:
11601 	{
11602 		struct bpf_reg_state *reg;
11603 		int id, ref_obj_id;
11604 
11605 		reg = get_dynptr_arg_reg(env, fn, regs);
11606 		if (!reg)
11607 			return -EFAULT;
11608 
11609 
11610 		if (meta.dynptr_id) {
11611 			verifier_bug(env, "meta.dynptr_id already set");
11612 			return -EFAULT;
11613 		}
11614 		if (meta.ref_obj_id) {
11615 			verifier_bug(env, "meta.ref_obj_id already set");
11616 			return -EFAULT;
11617 		}
11618 
11619 		id = dynptr_id(env, reg);
11620 		if (id < 0) {
11621 			verifier_bug(env, "failed to obtain dynptr id");
11622 			return id;
11623 		}
11624 
11625 		ref_obj_id = dynptr_ref_obj_id(env, reg);
11626 		if (ref_obj_id < 0) {
11627 			verifier_bug(env, "failed to obtain dynptr ref_obj_id");
11628 			return ref_obj_id;
11629 		}
11630 
11631 		meta.dynptr_id = id;
11632 		meta.ref_obj_id = ref_obj_id;
11633 
11634 		break;
11635 	}
11636 	case BPF_FUNC_dynptr_write:
11637 	{
11638 		enum bpf_dynptr_type dynptr_type;
11639 		struct bpf_reg_state *reg;
11640 
11641 		reg = get_dynptr_arg_reg(env, fn, regs);
11642 		if (!reg)
11643 			return -EFAULT;
11644 
11645 		dynptr_type = dynptr_get_type(env, reg);
11646 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11647 			return -EFAULT;
11648 
11649 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
11650 		    dynptr_type == BPF_DYNPTR_TYPE_SKB_META)
11651 			/* this will trigger clear_all_pkt_pointers(), which will
11652 			 * invalidate all dynptr slices associated with the skb
11653 			 */
11654 			changes_data = true;
11655 
11656 		break;
11657 	}
11658 	case BPF_FUNC_per_cpu_ptr:
11659 	case BPF_FUNC_this_cpu_ptr:
11660 	{
11661 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
11662 		const struct btf_type *type;
11663 
11664 		if (reg->type & MEM_RCU) {
11665 			type = btf_type_by_id(reg->btf, reg->btf_id);
11666 			if (!type || !btf_type_is_struct(type)) {
11667 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
11668 				return -EFAULT;
11669 			}
11670 			returns_cpu_specific_alloc_ptr = true;
11671 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11672 		}
11673 		break;
11674 	}
11675 	case BPF_FUNC_user_ringbuf_drain:
11676 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11677 					 set_user_ringbuf_callback_state);
11678 		break;
11679 	}
11680 
11681 	if (err)
11682 		return err;
11683 
11684 	/* reset caller saved regs */
11685 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11686 		mark_reg_not_init(env, regs, caller_saved[i]);
11687 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11688 	}
11689 
11690 	/* helper call returns 64-bit value. */
11691 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
11692 
11693 	/* update return register (already marked as written above) */
11694 	ret_type = fn->ret_type;
11695 	ret_flag = type_flag(ret_type);
11696 
11697 	switch (base_type(ret_type)) {
11698 	case RET_INTEGER:
11699 		/* sets type to SCALAR_VALUE */
11700 		mark_reg_unknown(env, regs, BPF_REG_0);
11701 		break;
11702 	case RET_VOID:
11703 		regs[BPF_REG_0].type = NOT_INIT;
11704 		break;
11705 	case RET_PTR_TO_MAP_VALUE:
11706 		/* There is no offset yet applied, variable or fixed */
11707 		mark_reg_known_zero(env, regs, BPF_REG_0);
11708 		/* remember map_ptr, so that check_map_access()
11709 		 * can check 'value_size' boundary of memory access
11710 		 * to map element returned from bpf_map_lookup_elem()
11711 		 */
11712 		if (meta.map_ptr == NULL) {
11713 			verifier_bug(env, "unexpected null map_ptr");
11714 			return -EFAULT;
11715 		}
11716 
11717 		if (func_id == BPF_FUNC_map_lookup_elem &&
11718 		    can_elide_value_nullness(meta.map_ptr->map_type) &&
11719 		    meta.const_map_key >= 0 &&
11720 		    meta.const_map_key < meta.map_ptr->max_entries)
11721 			ret_flag &= ~PTR_MAYBE_NULL;
11722 
11723 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
11724 		regs[BPF_REG_0].map_uid = meta.map_uid;
11725 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11726 		if (!type_may_be_null(ret_flag) &&
11727 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
11728 			regs[BPF_REG_0].id = ++env->id_gen;
11729 		}
11730 		break;
11731 	case RET_PTR_TO_SOCKET:
11732 		mark_reg_known_zero(env, regs, BPF_REG_0);
11733 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11734 		break;
11735 	case RET_PTR_TO_SOCK_COMMON:
11736 		mark_reg_known_zero(env, regs, BPF_REG_0);
11737 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11738 		break;
11739 	case RET_PTR_TO_TCP_SOCK:
11740 		mark_reg_known_zero(env, regs, BPF_REG_0);
11741 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11742 		break;
11743 	case RET_PTR_TO_MEM:
11744 		mark_reg_known_zero(env, regs, BPF_REG_0);
11745 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11746 		regs[BPF_REG_0].mem_size = meta.mem_size;
11747 		break;
11748 	case RET_PTR_TO_MEM_OR_BTF_ID:
11749 	{
11750 		const struct btf_type *t;
11751 
11752 		mark_reg_known_zero(env, regs, BPF_REG_0);
11753 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11754 		if (!btf_type_is_struct(t)) {
11755 			u32 tsize;
11756 			const struct btf_type *ret;
11757 			const char *tname;
11758 
11759 			/* resolve the type size of ksym. */
11760 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11761 			if (IS_ERR(ret)) {
11762 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11763 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
11764 					tname, PTR_ERR(ret));
11765 				return -EINVAL;
11766 			}
11767 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11768 			regs[BPF_REG_0].mem_size = tsize;
11769 		} else {
11770 			if (returns_cpu_specific_alloc_ptr) {
11771 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11772 			} else {
11773 				/* MEM_RDONLY may be carried from ret_flag, but it
11774 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11775 				 * it will confuse the check of PTR_TO_BTF_ID in
11776 				 * check_mem_access().
11777 				 */
11778 				ret_flag &= ~MEM_RDONLY;
11779 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11780 			}
11781 
11782 			regs[BPF_REG_0].btf = meta.ret_btf;
11783 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11784 		}
11785 		break;
11786 	}
11787 	case RET_PTR_TO_BTF_ID:
11788 	{
11789 		struct btf *ret_btf;
11790 		int ret_btf_id;
11791 
11792 		mark_reg_known_zero(env, regs, BPF_REG_0);
11793 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11794 		if (func_id == BPF_FUNC_kptr_xchg) {
11795 			ret_btf = meta.kptr_field->kptr.btf;
11796 			ret_btf_id = meta.kptr_field->kptr.btf_id;
11797 			if (!btf_is_kernel(ret_btf)) {
11798 				regs[BPF_REG_0].type |= MEM_ALLOC;
11799 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11800 					regs[BPF_REG_0].type |= MEM_PERCPU;
11801 			}
11802 		} else {
11803 			if (fn->ret_btf_id == BPF_PTR_POISON) {
11804 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
11805 					     func_id_name(func_id));
11806 				return -EFAULT;
11807 			}
11808 			ret_btf = btf_vmlinux;
11809 			ret_btf_id = *fn->ret_btf_id;
11810 		}
11811 		if (ret_btf_id == 0) {
11812 			verbose(env, "invalid return type %u of func %s#%d\n",
11813 				base_type(ret_type), func_id_name(func_id),
11814 				func_id);
11815 			return -EINVAL;
11816 		}
11817 		regs[BPF_REG_0].btf = ret_btf;
11818 		regs[BPF_REG_0].btf_id = ret_btf_id;
11819 		break;
11820 	}
11821 	default:
11822 		verbose(env, "unknown return type %u of func %s#%d\n",
11823 			base_type(ret_type), func_id_name(func_id), func_id);
11824 		return -EINVAL;
11825 	}
11826 
11827 	if (type_may_be_null(regs[BPF_REG_0].type))
11828 		regs[BPF_REG_0].id = ++env->id_gen;
11829 
11830 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
11831 		verifier_bug(env, "func %s#%d sets ref_obj_id more than once",
11832 			     func_id_name(func_id), func_id);
11833 		return -EFAULT;
11834 	}
11835 
11836 	if (is_dynptr_ref_function(func_id))
11837 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
11838 
11839 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
11840 		/* For release_reference() */
11841 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11842 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
11843 		int id = acquire_reference(env, insn_idx);
11844 
11845 		if (id < 0)
11846 			return id;
11847 		/* For mark_ptr_or_null_reg() */
11848 		regs[BPF_REG_0].id = id;
11849 		/* For release_reference() */
11850 		regs[BPF_REG_0].ref_obj_id = id;
11851 	}
11852 
11853 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
11854 	if (err)
11855 		return err;
11856 
11857 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
11858 	if (err)
11859 		return err;
11860 
11861 	if ((func_id == BPF_FUNC_get_stack ||
11862 	     func_id == BPF_FUNC_get_task_stack) &&
11863 	    !env->prog->has_callchain_buf) {
11864 		const char *err_str;
11865 
11866 #ifdef CONFIG_PERF_EVENTS
11867 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
11868 		err_str = "cannot get callchain buffer for func %s#%d\n";
11869 #else
11870 		err = -ENOTSUPP;
11871 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
11872 #endif
11873 		if (err) {
11874 			verbose(env, err_str, func_id_name(func_id), func_id);
11875 			return err;
11876 		}
11877 
11878 		env->prog->has_callchain_buf = true;
11879 	}
11880 
11881 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
11882 		env->prog->call_get_stack = true;
11883 
11884 	if (func_id == BPF_FUNC_get_func_ip) {
11885 		if (check_get_func_ip(env))
11886 			return -ENOTSUPP;
11887 		env->prog->call_get_func_ip = true;
11888 	}
11889 
11890 	if (changes_data)
11891 		clear_all_pkt_pointers(env);
11892 	return 0;
11893 }
11894 
11895 /* mark_btf_func_reg_size() is used when the reg size is determined by
11896  * the BTF func_proto's return value size and argument.
11897  */
11898 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
11899 				     u32 regno, size_t reg_size)
11900 {
11901 	struct bpf_reg_state *reg = &regs[regno];
11902 
11903 	if (regno == BPF_REG_0) {
11904 		/* Function return value */
11905 		reg->live |= REG_LIVE_WRITTEN;
11906 		reg->subreg_def = reg_size == sizeof(u64) ?
11907 			DEF_NOT_SUBREG : env->insn_idx + 1;
11908 	} else {
11909 		/* Function argument */
11910 		if (reg_size == sizeof(u64)) {
11911 			mark_insn_zext(env, reg);
11912 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
11913 		} else {
11914 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
11915 		}
11916 	}
11917 }
11918 
11919 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
11920 				   size_t reg_size)
11921 {
11922 	return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size);
11923 }
11924 
11925 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
11926 {
11927 	return meta->kfunc_flags & KF_ACQUIRE;
11928 }
11929 
11930 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
11931 {
11932 	return meta->kfunc_flags & KF_RELEASE;
11933 }
11934 
11935 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
11936 {
11937 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
11938 }
11939 
11940 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
11941 {
11942 	return meta->kfunc_flags & KF_SLEEPABLE;
11943 }
11944 
11945 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
11946 {
11947 	return meta->kfunc_flags & KF_DESTRUCTIVE;
11948 }
11949 
11950 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
11951 {
11952 	return meta->kfunc_flags & KF_RCU;
11953 }
11954 
11955 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
11956 {
11957 	return meta->kfunc_flags & KF_RCU_PROTECTED;
11958 }
11959 
11960 static bool is_kfunc_arg_mem_size(const struct btf *btf,
11961 				  const struct btf_param *arg,
11962 				  const struct bpf_reg_state *reg)
11963 {
11964 	const struct btf_type *t;
11965 
11966 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11967 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11968 		return false;
11969 
11970 	return btf_param_match_suffix(btf, arg, "__sz");
11971 }
11972 
11973 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
11974 					const struct btf_param *arg,
11975 					const struct bpf_reg_state *reg)
11976 {
11977 	const struct btf_type *t;
11978 
11979 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11980 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11981 		return false;
11982 
11983 	return btf_param_match_suffix(btf, arg, "__szk");
11984 }
11985 
11986 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
11987 {
11988 	return btf_param_match_suffix(btf, arg, "__opt");
11989 }
11990 
11991 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
11992 {
11993 	return btf_param_match_suffix(btf, arg, "__k");
11994 }
11995 
11996 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
11997 {
11998 	return btf_param_match_suffix(btf, arg, "__ign");
11999 }
12000 
12001 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
12002 {
12003 	return btf_param_match_suffix(btf, arg, "__map");
12004 }
12005 
12006 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
12007 {
12008 	return btf_param_match_suffix(btf, arg, "__alloc");
12009 }
12010 
12011 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
12012 {
12013 	return btf_param_match_suffix(btf, arg, "__uninit");
12014 }
12015 
12016 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
12017 {
12018 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
12019 }
12020 
12021 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
12022 {
12023 	return btf_param_match_suffix(btf, arg, "__nullable");
12024 }
12025 
12026 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
12027 {
12028 	return btf_param_match_suffix(btf, arg, "__str");
12029 }
12030 
12031 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
12032 {
12033 	return btf_param_match_suffix(btf, arg, "__irq_flag");
12034 }
12035 
12036 static bool is_kfunc_arg_prog(const struct btf *btf, const struct btf_param *arg)
12037 {
12038 	return btf_param_match_suffix(btf, arg, "__prog");
12039 }
12040 
12041 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
12042 					  const struct btf_param *arg,
12043 					  const char *name)
12044 {
12045 	int len, target_len = strlen(name);
12046 	const char *param_name;
12047 
12048 	param_name = btf_name_by_offset(btf, arg->name_off);
12049 	if (str_is_empty(param_name))
12050 		return false;
12051 	len = strlen(param_name);
12052 	if (len != target_len)
12053 		return false;
12054 	if (strcmp(param_name, name))
12055 		return false;
12056 
12057 	return true;
12058 }
12059 
12060 enum {
12061 	KF_ARG_DYNPTR_ID,
12062 	KF_ARG_LIST_HEAD_ID,
12063 	KF_ARG_LIST_NODE_ID,
12064 	KF_ARG_RB_ROOT_ID,
12065 	KF_ARG_RB_NODE_ID,
12066 	KF_ARG_WORKQUEUE_ID,
12067 	KF_ARG_RES_SPIN_LOCK_ID,
12068 };
12069 
12070 BTF_ID_LIST(kf_arg_btf_ids)
12071 BTF_ID(struct, bpf_dynptr)
12072 BTF_ID(struct, bpf_list_head)
12073 BTF_ID(struct, bpf_list_node)
12074 BTF_ID(struct, bpf_rb_root)
12075 BTF_ID(struct, bpf_rb_node)
12076 BTF_ID(struct, bpf_wq)
12077 BTF_ID(struct, bpf_res_spin_lock)
12078 
12079 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
12080 				    const struct btf_param *arg, int type)
12081 {
12082 	const struct btf_type *t;
12083 	u32 res_id;
12084 
12085 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12086 	if (!t)
12087 		return false;
12088 	if (!btf_type_is_ptr(t))
12089 		return false;
12090 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
12091 	if (!t)
12092 		return false;
12093 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
12094 }
12095 
12096 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
12097 {
12098 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
12099 }
12100 
12101 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
12102 {
12103 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
12104 }
12105 
12106 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
12107 {
12108 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
12109 }
12110 
12111 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
12112 {
12113 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
12114 }
12115 
12116 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
12117 {
12118 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
12119 }
12120 
12121 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
12122 {
12123 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
12124 }
12125 
12126 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
12127 {
12128 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
12129 }
12130 
12131 static bool is_rbtree_node_type(const struct btf_type *t)
12132 {
12133 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
12134 }
12135 
12136 static bool is_list_node_type(const struct btf_type *t)
12137 {
12138 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
12139 }
12140 
12141 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
12142 				  const struct btf_param *arg)
12143 {
12144 	const struct btf_type *t;
12145 
12146 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
12147 	if (!t)
12148 		return false;
12149 
12150 	return true;
12151 }
12152 
12153 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
12154 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
12155 					const struct btf *btf,
12156 					const struct btf_type *t, int rec)
12157 {
12158 	const struct btf_type *member_type;
12159 	const struct btf_member *member;
12160 	u32 i;
12161 
12162 	if (!btf_type_is_struct(t))
12163 		return false;
12164 
12165 	for_each_member(i, t, member) {
12166 		const struct btf_array *array;
12167 
12168 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
12169 		if (btf_type_is_struct(member_type)) {
12170 			if (rec >= 3) {
12171 				verbose(env, "max struct nesting depth exceeded\n");
12172 				return false;
12173 			}
12174 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
12175 				return false;
12176 			continue;
12177 		}
12178 		if (btf_type_is_array(member_type)) {
12179 			array = btf_array(member_type);
12180 			if (!array->nelems)
12181 				return false;
12182 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
12183 			if (!btf_type_is_scalar(member_type))
12184 				return false;
12185 			continue;
12186 		}
12187 		if (!btf_type_is_scalar(member_type))
12188 			return false;
12189 	}
12190 	return true;
12191 }
12192 
12193 enum kfunc_ptr_arg_type {
12194 	KF_ARG_PTR_TO_CTX,
12195 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
12196 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
12197 	KF_ARG_PTR_TO_DYNPTR,
12198 	KF_ARG_PTR_TO_ITER,
12199 	KF_ARG_PTR_TO_LIST_HEAD,
12200 	KF_ARG_PTR_TO_LIST_NODE,
12201 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
12202 	KF_ARG_PTR_TO_MEM,
12203 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
12204 	KF_ARG_PTR_TO_CALLBACK,
12205 	KF_ARG_PTR_TO_RB_ROOT,
12206 	KF_ARG_PTR_TO_RB_NODE,
12207 	KF_ARG_PTR_TO_NULL,
12208 	KF_ARG_PTR_TO_CONST_STR,
12209 	KF_ARG_PTR_TO_MAP,
12210 	KF_ARG_PTR_TO_WORKQUEUE,
12211 	KF_ARG_PTR_TO_IRQ_FLAG,
12212 	KF_ARG_PTR_TO_RES_SPIN_LOCK,
12213 };
12214 
12215 enum special_kfunc_type {
12216 	KF_bpf_obj_new_impl,
12217 	KF_bpf_obj_drop_impl,
12218 	KF_bpf_refcount_acquire_impl,
12219 	KF_bpf_list_push_front_impl,
12220 	KF_bpf_list_push_back_impl,
12221 	KF_bpf_list_pop_front,
12222 	KF_bpf_list_pop_back,
12223 	KF_bpf_list_front,
12224 	KF_bpf_list_back,
12225 	KF_bpf_cast_to_kern_ctx,
12226 	KF_bpf_rdonly_cast,
12227 	KF_bpf_rcu_read_lock,
12228 	KF_bpf_rcu_read_unlock,
12229 	KF_bpf_rbtree_remove,
12230 	KF_bpf_rbtree_add_impl,
12231 	KF_bpf_rbtree_first,
12232 	KF_bpf_rbtree_root,
12233 	KF_bpf_rbtree_left,
12234 	KF_bpf_rbtree_right,
12235 	KF_bpf_dynptr_from_skb,
12236 	KF_bpf_dynptr_from_xdp,
12237 	KF_bpf_dynptr_from_skb_meta,
12238 	KF_bpf_dynptr_slice,
12239 	KF_bpf_dynptr_slice_rdwr,
12240 	KF_bpf_dynptr_clone,
12241 	KF_bpf_percpu_obj_new_impl,
12242 	KF_bpf_percpu_obj_drop_impl,
12243 	KF_bpf_throw,
12244 	KF_bpf_wq_set_callback_impl,
12245 	KF_bpf_preempt_disable,
12246 	KF_bpf_preempt_enable,
12247 	KF_bpf_iter_css_task_new,
12248 	KF_bpf_session_cookie,
12249 	KF_bpf_get_kmem_cache,
12250 	KF_bpf_local_irq_save,
12251 	KF_bpf_local_irq_restore,
12252 	KF_bpf_iter_num_new,
12253 	KF_bpf_iter_num_next,
12254 	KF_bpf_iter_num_destroy,
12255 	KF_bpf_set_dentry_xattr,
12256 	KF_bpf_remove_dentry_xattr,
12257 	KF_bpf_res_spin_lock,
12258 	KF_bpf_res_spin_unlock,
12259 	KF_bpf_res_spin_lock_irqsave,
12260 	KF_bpf_res_spin_unlock_irqrestore,
12261 	KF___bpf_trap,
12262 };
12263 
12264 BTF_ID_LIST(special_kfunc_list)
12265 BTF_ID(func, bpf_obj_new_impl)
12266 BTF_ID(func, bpf_obj_drop_impl)
12267 BTF_ID(func, bpf_refcount_acquire_impl)
12268 BTF_ID(func, bpf_list_push_front_impl)
12269 BTF_ID(func, bpf_list_push_back_impl)
12270 BTF_ID(func, bpf_list_pop_front)
12271 BTF_ID(func, bpf_list_pop_back)
12272 BTF_ID(func, bpf_list_front)
12273 BTF_ID(func, bpf_list_back)
12274 BTF_ID(func, bpf_cast_to_kern_ctx)
12275 BTF_ID(func, bpf_rdonly_cast)
12276 BTF_ID(func, bpf_rcu_read_lock)
12277 BTF_ID(func, bpf_rcu_read_unlock)
12278 BTF_ID(func, bpf_rbtree_remove)
12279 BTF_ID(func, bpf_rbtree_add_impl)
12280 BTF_ID(func, bpf_rbtree_first)
12281 BTF_ID(func, bpf_rbtree_root)
12282 BTF_ID(func, bpf_rbtree_left)
12283 BTF_ID(func, bpf_rbtree_right)
12284 #ifdef CONFIG_NET
12285 BTF_ID(func, bpf_dynptr_from_skb)
12286 BTF_ID(func, bpf_dynptr_from_xdp)
12287 BTF_ID(func, bpf_dynptr_from_skb_meta)
12288 #else
12289 BTF_ID_UNUSED
12290 BTF_ID_UNUSED
12291 BTF_ID_UNUSED
12292 #endif
12293 BTF_ID(func, bpf_dynptr_slice)
12294 BTF_ID(func, bpf_dynptr_slice_rdwr)
12295 BTF_ID(func, bpf_dynptr_clone)
12296 BTF_ID(func, bpf_percpu_obj_new_impl)
12297 BTF_ID(func, bpf_percpu_obj_drop_impl)
12298 BTF_ID(func, bpf_throw)
12299 BTF_ID(func, bpf_wq_set_callback_impl)
12300 BTF_ID(func, bpf_preempt_disable)
12301 BTF_ID(func, bpf_preempt_enable)
12302 #ifdef CONFIG_CGROUPS
12303 BTF_ID(func, bpf_iter_css_task_new)
12304 #else
12305 BTF_ID_UNUSED
12306 #endif
12307 #ifdef CONFIG_BPF_EVENTS
12308 BTF_ID(func, bpf_session_cookie)
12309 #else
12310 BTF_ID_UNUSED
12311 #endif
12312 BTF_ID(func, bpf_get_kmem_cache)
12313 BTF_ID(func, bpf_local_irq_save)
12314 BTF_ID(func, bpf_local_irq_restore)
12315 BTF_ID(func, bpf_iter_num_new)
12316 BTF_ID(func, bpf_iter_num_next)
12317 BTF_ID(func, bpf_iter_num_destroy)
12318 #ifdef CONFIG_BPF_LSM
12319 BTF_ID(func, bpf_set_dentry_xattr)
12320 BTF_ID(func, bpf_remove_dentry_xattr)
12321 #else
12322 BTF_ID_UNUSED
12323 BTF_ID_UNUSED
12324 #endif
12325 BTF_ID(func, bpf_res_spin_lock)
12326 BTF_ID(func, bpf_res_spin_unlock)
12327 BTF_ID(func, bpf_res_spin_lock_irqsave)
12328 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
12329 BTF_ID(func, __bpf_trap)
12330 
12331 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
12332 {
12333 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
12334 	    meta->arg_owning_ref) {
12335 		return false;
12336 	}
12337 
12338 	return meta->kfunc_flags & KF_RET_NULL;
12339 }
12340 
12341 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
12342 {
12343 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
12344 }
12345 
12346 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
12347 {
12348 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
12349 }
12350 
12351 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
12352 {
12353 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
12354 }
12355 
12356 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
12357 {
12358 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
12359 }
12360 
12361 static enum kfunc_ptr_arg_type
12362 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
12363 		       struct bpf_kfunc_call_arg_meta *meta,
12364 		       const struct btf_type *t, const struct btf_type *ref_t,
12365 		       const char *ref_tname, const struct btf_param *args,
12366 		       int argno, int nargs)
12367 {
12368 	u32 regno = argno + 1;
12369 	struct bpf_reg_state *regs = cur_regs(env);
12370 	struct bpf_reg_state *reg = &regs[regno];
12371 	bool arg_mem_size = false;
12372 
12373 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
12374 		return KF_ARG_PTR_TO_CTX;
12375 
12376 	/* In this function, we verify the kfunc's BTF as per the argument type,
12377 	 * leaving the rest of the verification with respect to the register
12378 	 * type to our caller. When a set of conditions hold in the BTF type of
12379 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
12380 	 */
12381 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
12382 		return KF_ARG_PTR_TO_CTX;
12383 
12384 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
12385 		return KF_ARG_PTR_TO_NULL;
12386 
12387 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
12388 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
12389 
12390 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
12391 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
12392 
12393 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
12394 		return KF_ARG_PTR_TO_DYNPTR;
12395 
12396 	if (is_kfunc_arg_iter(meta, argno, &args[argno]))
12397 		return KF_ARG_PTR_TO_ITER;
12398 
12399 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
12400 		return KF_ARG_PTR_TO_LIST_HEAD;
12401 
12402 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
12403 		return KF_ARG_PTR_TO_LIST_NODE;
12404 
12405 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
12406 		return KF_ARG_PTR_TO_RB_ROOT;
12407 
12408 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
12409 		return KF_ARG_PTR_TO_RB_NODE;
12410 
12411 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
12412 		return KF_ARG_PTR_TO_CONST_STR;
12413 
12414 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
12415 		return KF_ARG_PTR_TO_MAP;
12416 
12417 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
12418 		return KF_ARG_PTR_TO_WORKQUEUE;
12419 
12420 	if (is_kfunc_arg_irq_flag(meta->btf, &args[argno]))
12421 		return KF_ARG_PTR_TO_IRQ_FLAG;
12422 
12423 	if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno]))
12424 		return KF_ARG_PTR_TO_RES_SPIN_LOCK;
12425 
12426 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
12427 		if (!btf_type_is_struct(ref_t)) {
12428 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
12429 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
12430 			return -EINVAL;
12431 		}
12432 		return KF_ARG_PTR_TO_BTF_ID;
12433 	}
12434 
12435 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
12436 		return KF_ARG_PTR_TO_CALLBACK;
12437 
12438 	if (argno + 1 < nargs &&
12439 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
12440 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
12441 		arg_mem_size = true;
12442 
12443 	/* This is the catch all argument type of register types supported by
12444 	 * check_helper_mem_access. However, we only allow when argument type is
12445 	 * pointer to scalar, or struct composed (recursively) of scalars. When
12446 	 * arg_mem_size is true, the pointer can be void *.
12447 	 */
12448 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
12449 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
12450 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
12451 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
12452 		return -EINVAL;
12453 	}
12454 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
12455 }
12456 
12457 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
12458 					struct bpf_reg_state *reg,
12459 					const struct btf_type *ref_t,
12460 					const char *ref_tname, u32 ref_id,
12461 					struct bpf_kfunc_call_arg_meta *meta,
12462 					int argno)
12463 {
12464 	const struct btf_type *reg_ref_t;
12465 	bool strict_type_match = false;
12466 	const struct btf *reg_btf;
12467 	const char *reg_ref_tname;
12468 	bool taking_projection;
12469 	bool struct_same;
12470 	u32 reg_ref_id;
12471 
12472 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
12473 		reg_btf = reg->btf;
12474 		reg_ref_id = reg->btf_id;
12475 	} else {
12476 		reg_btf = btf_vmlinux;
12477 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
12478 	}
12479 
12480 	/* Enforce strict type matching for calls to kfuncs that are acquiring
12481 	 * or releasing a reference, or are no-cast aliases. We do _not_
12482 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
12483 	 * as we want to enable BPF programs to pass types that are bitwise
12484 	 * equivalent without forcing them to explicitly cast with something
12485 	 * like bpf_cast_to_kern_ctx().
12486 	 *
12487 	 * For example, say we had a type like the following:
12488 	 *
12489 	 * struct bpf_cpumask {
12490 	 *	cpumask_t cpumask;
12491 	 *	refcount_t usage;
12492 	 * };
12493 	 *
12494 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
12495 	 * to a struct cpumask, so it would be safe to pass a struct
12496 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
12497 	 *
12498 	 * The philosophy here is similar to how we allow scalars of different
12499 	 * types to be passed to kfuncs as long as the size is the same. The
12500 	 * only difference here is that we're simply allowing
12501 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
12502 	 * resolve types.
12503 	 */
12504 	if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
12505 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
12506 		strict_type_match = true;
12507 
12508 	WARN_ON_ONCE(is_kfunc_release(meta) &&
12509 		     (reg->off || !tnum_is_const(reg->var_off) ||
12510 		      reg->var_off.value));
12511 
12512 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
12513 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
12514 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
12515 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
12516 	 * actually use it -- it must cast to the underlying type. So we allow
12517 	 * caller to pass in the underlying type.
12518 	 */
12519 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
12520 	if (!taking_projection && !struct_same) {
12521 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
12522 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
12523 			btf_type_str(reg_ref_t), reg_ref_tname);
12524 		return -EINVAL;
12525 	}
12526 	return 0;
12527 }
12528 
12529 static int process_irq_flag(struct bpf_verifier_env *env, int regno,
12530 			     struct bpf_kfunc_call_arg_meta *meta)
12531 {
12532 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
12533 	int err, kfunc_class = IRQ_NATIVE_KFUNC;
12534 	bool irq_save;
12535 
12536 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
12537 	    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
12538 		irq_save = true;
12539 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12540 			kfunc_class = IRQ_LOCK_KFUNC;
12541 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
12542 		   meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
12543 		irq_save = false;
12544 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12545 			kfunc_class = IRQ_LOCK_KFUNC;
12546 	} else {
12547 		verifier_bug(env, "unknown irq flags kfunc");
12548 		return -EFAULT;
12549 	}
12550 
12551 	if (irq_save) {
12552 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
12553 			verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1);
12554 			return -EINVAL;
12555 		}
12556 
12557 		err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false);
12558 		if (err)
12559 			return err;
12560 
12561 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
12562 		if (err)
12563 			return err;
12564 	} else {
12565 		err = is_irq_flag_reg_valid_init(env, reg);
12566 		if (err) {
12567 			verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1);
12568 			return err;
12569 		}
12570 
12571 		err = mark_irq_flag_read(env, reg);
12572 		if (err)
12573 			return err;
12574 
12575 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
12576 		if (err)
12577 			return err;
12578 	}
12579 	return 0;
12580 }
12581 
12582 
12583 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12584 {
12585 	struct btf_record *rec = reg_btf_record(reg);
12586 
12587 	if (!env->cur_state->active_locks) {
12588 		verifier_bug(env, "%s w/o active lock", __func__);
12589 		return -EFAULT;
12590 	}
12591 
12592 	if (type_flag(reg->type) & NON_OWN_REF) {
12593 		verifier_bug(env, "NON_OWN_REF already set");
12594 		return -EFAULT;
12595 	}
12596 
12597 	reg->type |= NON_OWN_REF;
12598 	if (rec->refcount_off >= 0)
12599 		reg->type |= MEM_RCU;
12600 
12601 	return 0;
12602 }
12603 
12604 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
12605 {
12606 	struct bpf_verifier_state *state = env->cur_state;
12607 	struct bpf_func_state *unused;
12608 	struct bpf_reg_state *reg;
12609 	int i;
12610 
12611 	if (!ref_obj_id) {
12612 		verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion");
12613 		return -EFAULT;
12614 	}
12615 
12616 	for (i = 0; i < state->acquired_refs; i++) {
12617 		if (state->refs[i].id != ref_obj_id)
12618 			continue;
12619 
12620 		/* Clear ref_obj_id here so release_reference doesn't clobber
12621 		 * the whole reg
12622 		 */
12623 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12624 			if (reg->ref_obj_id == ref_obj_id) {
12625 				reg->ref_obj_id = 0;
12626 				ref_set_non_owning(env, reg);
12627 			}
12628 		}));
12629 		return 0;
12630 	}
12631 
12632 	verifier_bug(env, "ref state missing for ref_obj_id");
12633 	return -EFAULT;
12634 }
12635 
12636 /* Implementation details:
12637  *
12638  * Each register points to some region of memory, which we define as an
12639  * allocation. Each allocation may embed a bpf_spin_lock which protects any
12640  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12641  * allocation. The lock and the data it protects are colocated in the same
12642  * memory region.
12643  *
12644  * Hence, everytime a register holds a pointer value pointing to such
12645  * allocation, the verifier preserves a unique reg->id for it.
12646  *
12647  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12648  * bpf_spin_lock is called.
12649  *
12650  * To enable this, lock state in the verifier captures two values:
12651  *	active_lock.ptr = Register's type specific pointer
12652  *	active_lock.id  = A unique ID for each register pointer value
12653  *
12654  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12655  * supported register types.
12656  *
12657  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12658  * allocated objects is the reg->btf pointer.
12659  *
12660  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12661  * can establish the provenance of the map value statically for each distinct
12662  * lookup into such maps. They always contain a single map value hence unique
12663  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12664  *
12665  * So, in case of global variables, they use array maps with max_entries = 1,
12666  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12667  * into the same map value as max_entries is 1, as described above).
12668  *
12669  * In case of inner map lookups, the inner map pointer has same map_ptr as the
12670  * outer map pointer (in verifier context), but each lookup into an inner map
12671  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12672  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12673  * will get different reg->id assigned to each lookup, hence different
12674  * active_lock.id.
12675  *
12676  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12677  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12678  * returned from bpf_obj_new. Each allocation receives a new reg->id.
12679  */
12680 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12681 {
12682 	struct bpf_reference_state *s;
12683 	void *ptr;
12684 	u32 id;
12685 
12686 	switch ((int)reg->type) {
12687 	case PTR_TO_MAP_VALUE:
12688 		ptr = reg->map_ptr;
12689 		break;
12690 	case PTR_TO_BTF_ID | MEM_ALLOC:
12691 		ptr = reg->btf;
12692 		break;
12693 	default:
12694 		verifier_bug(env, "unknown reg type for lock check");
12695 		return -EFAULT;
12696 	}
12697 	id = reg->id;
12698 
12699 	if (!env->cur_state->active_locks)
12700 		return -EINVAL;
12701 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
12702 	if (!s) {
12703 		verbose(env, "held lock and object are not in the same allocation\n");
12704 		return -EINVAL;
12705 	}
12706 	return 0;
12707 }
12708 
12709 static bool is_bpf_list_api_kfunc(u32 btf_id)
12710 {
12711 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12712 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12713 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12714 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
12715 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
12716 	       btf_id == special_kfunc_list[KF_bpf_list_back];
12717 }
12718 
12719 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
12720 {
12721 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12722 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12723 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
12724 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
12725 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12726 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
12727 }
12728 
12729 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
12730 {
12731 	return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
12732 	       btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
12733 	       btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
12734 }
12735 
12736 static bool is_bpf_graph_api_kfunc(u32 btf_id)
12737 {
12738 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
12739 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
12740 }
12741 
12742 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
12743 {
12744 	return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
12745 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
12746 	       btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
12747 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
12748 }
12749 
12750 static bool kfunc_spin_allowed(u32 btf_id)
12751 {
12752 	return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) ||
12753 	       is_bpf_res_spin_lock_kfunc(btf_id);
12754 }
12755 
12756 static bool is_sync_callback_calling_kfunc(u32 btf_id)
12757 {
12758 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
12759 }
12760 
12761 static bool is_async_callback_calling_kfunc(u32 btf_id)
12762 {
12763 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12764 }
12765 
12766 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
12767 {
12768 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
12769 	       insn->imm == special_kfunc_list[KF_bpf_throw];
12770 }
12771 
12772 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
12773 {
12774 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12775 }
12776 
12777 static bool is_callback_calling_kfunc(u32 btf_id)
12778 {
12779 	return is_sync_callback_calling_kfunc(btf_id) ||
12780 	       is_async_callback_calling_kfunc(btf_id);
12781 }
12782 
12783 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
12784 {
12785 	return is_bpf_rbtree_api_kfunc(btf_id);
12786 }
12787 
12788 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
12789 					  enum btf_field_type head_field_type,
12790 					  u32 kfunc_btf_id)
12791 {
12792 	bool ret;
12793 
12794 	switch (head_field_type) {
12795 	case BPF_LIST_HEAD:
12796 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
12797 		break;
12798 	case BPF_RB_ROOT:
12799 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
12800 		break;
12801 	default:
12802 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
12803 			btf_field_type_name(head_field_type));
12804 		return false;
12805 	}
12806 
12807 	if (!ret)
12808 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
12809 			btf_field_type_name(head_field_type));
12810 	return ret;
12811 }
12812 
12813 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
12814 					  enum btf_field_type node_field_type,
12815 					  u32 kfunc_btf_id)
12816 {
12817 	bool ret;
12818 
12819 	switch (node_field_type) {
12820 	case BPF_LIST_NODE:
12821 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12822 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
12823 		break;
12824 	case BPF_RB_NODE:
12825 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12826 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12827 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12828 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
12829 		break;
12830 	default:
12831 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
12832 			btf_field_type_name(node_field_type));
12833 		return false;
12834 	}
12835 
12836 	if (!ret)
12837 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
12838 			btf_field_type_name(node_field_type));
12839 	return ret;
12840 }
12841 
12842 static int
12843 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
12844 				   struct bpf_reg_state *reg, u32 regno,
12845 				   struct bpf_kfunc_call_arg_meta *meta,
12846 				   enum btf_field_type head_field_type,
12847 				   struct btf_field **head_field)
12848 {
12849 	const char *head_type_name;
12850 	struct btf_field *field;
12851 	struct btf_record *rec;
12852 	u32 head_off;
12853 
12854 	if (meta->btf != btf_vmlinux) {
12855 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
12856 		return -EFAULT;
12857 	}
12858 
12859 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
12860 		return -EFAULT;
12861 
12862 	head_type_name = btf_field_type_name(head_field_type);
12863 	if (!tnum_is_const(reg->var_off)) {
12864 		verbose(env,
12865 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12866 			regno, head_type_name);
12867 		return -EINVAL;
12868 	}
12869 
12870 	rec = reg_btf_record(reg);
12871 	head_off = reg->off + reg->var_off.value;
12872 	field = btf_record_find(rec, head_off, head_field_type);
12873 	if (!field) {
12874 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
12875 		return -EINVAL;
12876 	}
12877 
12878 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
12879 	if (check_reg_allocation_locked(env, reg)) {
12880 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
12881 			rec->spin_lock_off, head_type_name);
12882 		return -EINVAL;
12883 	}
12884 
12885 	if (*head_field) {
12886 		verifier_bug(env, "repeating %s arg", head_type_name);
12887 		return -EFAULT;
12888 	}
12889 	*head_field = field;
12890 	return 0;
12891 }
12892 
12893 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
12894 					   struct bpf_reg_state *reg, u32 regno,
12895 					   struct bpf_kfunc_call_arg_meta *meta)
12896 {
12897 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
12898 							  &meta->arg_list_head.field);
12899 }
12900 
12901 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
12902 					     struct bpf_reg_state *reg, u32 regno,
12903 					     struct bpf_kfunc_call_arg_meta *meta)
12904 {
12905 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
12906 							  &meta->arg_rbtree_root.field);
12907 }
12908 
12909 static int
12910 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
12911 				   struct bpf_reg_state *reg, u32 regno,
12912 				   struct bpf_kfunc_call_arg_meta *meta,
12913 				   enum btf_field_type head_field_type,
12914 				   enum btf_field_type node_field_type,
12915 				   struct btf_field **node_field)
12916 {
12917 	const char *node_type_name;
12918 	const struct btf_type *et, *t;
12919 	struct btf_field *field;
12920 	u32 node_off;
12921 
12922 	if (meta->btf != btf_vmlinux) {
12923 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
12924 		return -EFAULT;
12925 	}
12926 
12927 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
12928 		return -EFAULT;
12929 
12930 	node_type_name = btf_field_type_name(node_field_type);
12931 	if (!tnum_is_const(reg->var_off)) {
12932 		verbose(env,
12933 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12934 			regno, node_type_name);
12935 		return -EINVAL;
12936 	}
12937 
12938 	node_off = reg->off + reg->var_off.value;
12939 	field = reg_find_field_offset(reg, node_off, node_field_type);
12940 	if (!field) {
12941 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
12942 		return -EINVAL;
12943 	}
12944 
12945 	field = *node_field;
12946 
12947 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
12948 	t = btf_type_by_id(reg->btf, reg->btf_id);
12949 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
12950 				  field->graph_root.value_btf_id, true)) {
12951 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
12952 			"in struct %s, but arg is at offset=%d in struct %s\n",
12953 			btf_field_type_name(head_field_type),
12954 			btf_field_type_name(node_field_type),
12955 			field->graph_root.node_offset,
12956 			btf_name_by_offset(field->graph_root.btf, et->name_off),
12957 			node_off, btf_name_by_offset(reg->btf, t->name_off));
12958 		return -EINVAL;
12959 	}
12960 	meta->arg_btf = reg->btf;
12961 	meta->arg_btf_id = reg->btf_id;
12962 
12963 	if (node_off != field->graph_root.node_offset) {
12964 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
12965 			node_off, btf_field_type_name(node_field_type),
12966 			field->graph_root.node_offset,
12967 			btf_name_by_offset(field->graph_root.btf, et->name_off));
12968 		return -EINVAL;
12969 	}
12970 
12971 	return 0;
12972 }
12973 
12974 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
12975 					   struct bpf_reg_state *reg, u32 regno,
12976 					   struct bpf_kfunc_call_arg_meta *meta)
12977 {
12978 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
12979 						  BPF_LIST_HEAD, BPF_LIST_NODE,
12980 						  &meta->arg_list_head.field);
12981 }
12982 
12983 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
12984 					     struct bpf_reg_state *reg, u32 regno,
12985 					     struct bpf_kfunc_call_arg_meta *meta)
12986 {
12987 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
12988 						  BPF_RB_ROOT, BPF_RB_NODE,
12989 						  &meta->arg_rbtree_root.field);
12990 }
12991 
12992 /*
12993  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
12994  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
12995  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
12996  * them can only be attached to some specific hook points.
12997  */
12998 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
12999 {
13000 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13001 
13002 	switch (prog_type) {
13003 	case BPF_PROG_TYPE_LSM:
13004 		return true;
13005 	case BPF_PROG_TYPE_TRACING:
13006 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
13007 			return true;
13008 		fallthrough;
13009 	default:
13010 		return in_sleepable(env);
13011 	}
13012 }
13013 
13014 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13015 			    int insn_idx)
13016 {
13017 	const char *func_name = meta->func_name, *ref_tname;
13018 	const struct btf *btf = meta->btf;
13019 	const struct btf_param *args;
13020 	struct btf_record *rec;
13021 	u32 i, nargs;
13022 	int ret;
13023 
13024 	args = (const struct btf_param *)(meta->func_proto + 1);
13025 	nargs = btf_type_vlen(meta->func_proto);
13026 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
13027 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
13028 			MAX_BPF_FUNC_REG_ARGS);
13029 		return -EINVAL;
13030 	}
13031 
13032 	/* Check that BTF function arguments match actual types that the
13033 	 * verifier sees.
13034 	 */
13035 	for (i = 0; i < nargs; i++) {
13036 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
13037 		const struct btf_type *t, *ref_t, *resolve_ret;
13038 		enum bpf_arg_type arg_type = ARG_DONTCARE;
13039 		u32 regno = i + 1, ref_id, type_size;
13040 		bool is_ret_buf_sz = false;
13041 		int kf_arg_type;
13042 
13043 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
13044 
13045 		if (is_kfunc_arg_ignore(btf, &args[i]))
13046 			continue;
13047 
13048 		if (is_kfunc_arg_prog(btf, &args[i])) {
13049 			/* Used to reject repeated use of __prog. */
13050 			if (meta->arg_prog) {
13051 				verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc");
13052 				return -EFAULT;
13053 			}
13054 			meta->arg_prog = true;
13055 			cur_aux(env)->arg_prog = regno;
13056 			continue;
13057 		}
13058 
13059 		if (btf_type_is_scalar(t)) {
13060 			if (reg->type != SCALAR_VALUE) {
13061 				verbose(env, "R%d is not a scalar\n", regno);
13062 				return -EINVAL;
13063 			}
13064 
13065 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
13066 				if (meta->arg_constant.found) {
13067 					verifier_bug(env, "only one constant argument permitted");
13068 					return -EFAULT;
13069 				}
13070 				if (!tnum_is_const(reg->var_off)) {
13071 					verbose(env, "R%d must be a known constant\n", regno);
13072 					return -EINVAL;
13073 				}
13074 				ret = mark_chain_precision(env, regno);
13075 				if (ret < 0)
13076 					return ret;
13077 				meta->arg_constant.found = true;
13078 				meta->arg_constant.value = reg->var_off.value;
13079 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
13080 				meta->r0_rdonly = true;
13081 				is_ret_buf_sz = true;
13082 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
13083 				is_ret_buf_sz = true;
13084 			}
13085 
13086 			if (is_ret_buf_sz) {
13087 				if (meta->r0_size) {
13088 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
13089 					return -EINVAL;
13090 				}
13091 
13092 				if (!tnum_is_const(reg->var_off)) {
13093 					verbose(env, "R%d is not a const\n", regno);
13094 					return -EINVAL;
13095 				}
13096 
13097 				meta->r0_size = reg->var_off.value;
13098 				ret = mark_chain_precision(env, regno);
13099 				if (ret)
13100 					return ret;
13101 			}
13102 			continue;
13103 		}
13104 
13105 		if (!btf_type_is_ptr(t)) {
13106 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
13107 			return -EINVAL;
13108 		}
13109 
13110 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
13111 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
13112 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
13113 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
13114 			return -EACCES;
13115 		}
13116 
13117 		if (reg->ref_obj_id) {
13118 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
13119 				verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u",
13120 					     regno, reg->ref_obj_id,
13121 					     meta->ref_obj_id);
13122 				return -EFAULT;
13123 			}
13124 			meta->ref_obj_id = reg->ref_obj_id;
13125 			if (is_kfunc_release(meta))
13126 				meta->release_regno = regno;
13127 		}
13128 
13129 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
13130 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13131 
13132 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
13133 		if (kf_arg_type < 0)
13134 			return kf_arg_type;
13135 
13136 		switch (kf_arg_type) {
13137 		case KF_ARG_PTR_TO_NULL:
13138 			continue;
13139 		case KF_ARG_PTR_TO_MAP:
13140 			if (!reg->map_ptr) {
13141 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
13142 				return -EINVAL;
13143 			}
13144 			if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) {
13145 				/* Use map_uid (which is unique id of inner map) to reject:
13146 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
13147 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
13148 				 * if (inner_map1 && inner_map2) {
13149 				 *     wq = bpf_map_lookup_elem(inner_map1);
13150 				 *     if (wq)
13151 				 *         // mismatch would have been allowed
13152 				 *         bpf_wq_init(wq, inner_map2);
13153 				 * }
13154 				 *
13155 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
13156 				 */
13157 				if (meta->map.ptr != reg->map_ptr ||
13158 				    meta->map.uid != reg->map_uid) {
13159 					verbose(env,
13160 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
13161 						meta->map.uid, reg->map_uid);
13162 					return -EINVAL;
13163 				}
13164 			}
13165 			meta->map.ptr = reg->map_ptr;
13166 			meta->map.uid = reg->map_uid;
13167 			fallthrough;
13168 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13169 		case KF_ARG_PTR_TO_BTF_ID:
13170 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
13171 				break;
13172 
13173 			if (!is_trusted_reg(reg)) {
13174 				if (!is_kfunc_rcu(meta)) {
13175 					verbose(env, "R%d must be referenced or trusted\n", regno);
13176 					return -EINVAL;
13177 				}
13178 				if (!is_rcu_reg(reg)) {
13179 					verbose(env, "R%d must be a rcu pointer\n", regno);
13180 					return -EINVAL;
13181 				}
13182 			}
13183 			fallthrough;
13184 		case KF_ARG_PTR_TO_CTX:
13185 		case KF_ARG_PTR_TO_DYNPTR:
13186 		case KF_ARG_PTR_TO_ITER:
13187 		case KF_ARG_PTR_TO_LIST_HEAD:
13188 		case KF_ARG_PTR_TO_LIST_NODE:
13189 		case KF_ARG_PTR_TO_RB_ROOT:
13190 		case KF_ARG_PTR_TO_RB_NODE:
13191 		case KF_ARG_PTR_TO_MEM:
13192 		case KF_ARG_PTR_TO_MEM_SIZE:
13193 		case KF_ARG_PTR_TO_CALLBACK:
13194 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13195 		case KF_ARG_PTR_TO_CONST_STR:
13196 		case KF_ARG_PTR_TO_WORKQUEUE:
13197 		case KF_ARG_PTR_TO_IRQ_FLAG:
13198 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13199 			break;
13200 		default:
13201 			verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type);
13202 			return -EFAULT;
13203 		}
13204 
13205 		if (is_kfunc_release(meta) && reg->ref_obj_id)
13206 			arg_type |= OBJ_RELEASE;
13207 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
13208 		if (ret < 0)
13209 			return ret;
13210 
13211 		switch (kf_arg_type) {
13212 		case KF_ARG_PTR_TO_CTX:
13213 			if (reg->type != PTR_TO_CTX) {
13214 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
13215 					i, reg_type_str(env, reg->type));
13216 				return -EINVAL;
13217 			}
13218 
13219 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13220 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
13221 				if (ret < 0)
13222 					return -EINVAL;
13223 				meta->ret_btf_id  = ret;
13224 			}
13225 			break;
13226 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13227 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
13228 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
13229 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
13230 					return -EINVAL;
13231 				}
13232 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
13233 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13234 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
13235 					return -EINVAL;
13236 				}
13237 			} else {
13238 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13239 				return -EINVAL;
13240 			}
13241 			if (!reg->ref_obj_id) {
13242 				verbose(env, "allocated object must be referenced\n");
13243 				return -EINVAL;
13244 			}
13245 			if (meta->btf == btf_vmlinux) {
13246 				meta->arg_btf = reg->btf;
13247 				meta->arg_btf_id = reg->btf_id;
13248 			}
13249 			break;
13250 		case KF_ARG_PTR_TO_DYNPTR:
13251 		{
13252 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
13253 			int clone_ref_obj_id = 0;
13254 
13255 			if (reg->type == CONST_PTR_TO_DYNPTR)
13256 				dynptr_arg_type |= MEM_RDONLY;
13257 
13258 			if (is_kfunc_arg_uninit(btf, &args[i]))
13259 				dynptr_arg_type |= MEM_UNINIT;
13260 
13261 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
13262 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
13263 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
13264 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
13265 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
13266 				dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
13267 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
13268 				   (dynptr_arg_type & MEM_UNINIT)) {
13269 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
13270 
13271 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
13272 					verifier_bug(env, "no dynptr type for parent of clone");
13273 					return -EFAULT;
13274 				}
13275 
13276 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
13277 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
13278 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
13279 					verifier_bug(env, "missing ref obj id for parent of clone");
13280 					return -EFAULT;
13281 				}
13282 			}
13283 
13284 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
13285 			if (ret < 0)
13286 				return ret;
13287 
13288 			if (!(dynptr_arg_type & MEM_UNINIT)) {
13289 				int id = dynptr_id(env, reg);
13290 
13291 				if (id < 0) {
13292 					verifier_bug(env, "failed to obtain dynptr id");
13293 					return id;
13294 				}
13295 				meta->initialized_dynptr.id = id;
13296 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
13297 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
13298 			}
13299 
13300 			break;
13301 		}
13302 		case KF_ARG_PTR_TO_ITER:
13303 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
13304 				if (!check_css_task_iter_allowlist(env)) {
13305 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
13306 					return -EINVAL;
13307 				}
13308 			}
13309 			ret = process_iter_arg(env, regno, insn_idx, meta);
13310 			if (ret < 0)
13311 				return ret;
13312 			break;
13313 		case KF_ARG_PTR_TO_LIST_HEAD:
13314 			if (reg->type != PTR_TO_MAP_VALUE &&
13315 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13316 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13317 				return -EINVAL;
13318 			}
13319 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13320 				verbose(env, "allocated object must be referenced\n");
13321 				return -EINVAL;
13322 			}
13323 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
13324 			if (ret < 0)
13325 				return ret;
13326 			break;
13327 		case KF_ARG_PTR_TO_RB_ROOT:
13328 			if (reg->type != PTR_TO_MAP_VALUE &&
13329 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13330 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13331 				return -EINVAL;
13332 			}
13333 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13334 				verbose(env, "allocated object must be referenced\n");
13335 				return -EINVAL;
13336 			}
13337 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
13338 			if (ret < 0)
13339 				return ret;
13340 			break;
13341 		case KF_ARG_PTR_TO_LIST_NODE:
13342 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13343 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13344 				return -EINVAL;
13345 			}
13346 			if (!reg->ref_obj_id) {
13347 				verbose(env, "allocated object must be referenced\n");
13348 				return -EINVAL;
13349 			}
13350 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
13351 			if (ret < 0)
13352 				return ret;
13353 			break;
13354 		case KF_ARG_PTR_TO_RB_NODE:
13355 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13356 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13357 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
13358 					return -EINVAL;
13359 				}
13360 				if (!reg->ref_obj_id) {
13361 					verbose(env, "allocated object must be referenced\n");
13362 					return -EINVAL;
13363 				}
13364 			} else {
13365 				if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) {
13366 					verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
13367 					return -EINVAL;
13368 				}
13369 				if (in_rbtree_lock_required_cb(env)) {
13370 					verbose(env, "%s not allowed in rbtree cb\n", func_name);
13371 					return -EINVAL;
13372 				}
13373 			}
13374 
13375 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
13376 			if (ret < 0)
13377 				return ret;
13378 			break;
13379 		case KF_ARG_PTR_TO_MAP:
13380 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
13381 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
13382 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
13383 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13384 			fallthrough;
13385 		case KF_ARG_PTR_TO_BTF_ID:
13386 			/* Only base_type is checked, further checks are done here */
13387 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
13388 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
13389 			    !reg2btf_ids[base_type(reg->type)]) {
13390 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
13391 				verbose(env, "expected %s or socket\n",
13392 					reg_type_str(env, base_type(reg->type) |
13393 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
13394 				return -EINVAL;
13395 			}
13396 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
13397 			if (ret < 0)
13398 				return ret;
13399 			break;
13400 		case KF_ARG_PTR_TO_MEM:
13401 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
13402 			if (IS_ERR(resolve_ret)) {
13403 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
13404 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
13405 				return -EINVAL;
13406 			}
13407 			ret = check_mem_reg(env, reg, regno, type_size);
13408 			if (ret < 0)
13409 				return ret;
13410 			break;
13411 		case KF_ARG_PTR_TO_MEM_SIZE:
13412 		{
13413 			struct bpf_reg_state *buff_reg = &regs[regno];
13414 			const struct btf_param *buff_arg = &args[i];
13415 			struct bpf_reg_state *size_reg = &regs[regno + 1];
13416 			const struct btf_param *size_arg = &args[i + 1];
13417 
13418 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
13419 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
13420 				if (ret < 0) {
13421 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
13422 					return ret;
13423 				}
13424 			}
13425 
13426 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
13427 				if (meta->arg_constant.found) {
13428 					verifier_bug(env, "only one constant argument permitted");
13429 					return -EFAULT;
13430 				}
13431 				if (!tnum_is_const(size_reg->var_off)) {
13432 					verbose(env, "R%d must be a known constant\n", regno + 1);
13433 					return -EINVAL;
13434 				}
13435 				meta->arg_constant.found = true;
13436 				meta->arg_constant.value = size_reg->var_off.value;
13437 			}
13438 
13439 			/* Skip next '__sz' or '__szk' argument */
13440 			i++;
13441 			break;
13442 		}
13443 		case KF_ARG_PTR_TO_CALLBACK:
13444 			if (reg->type != PTR_TO_FUNC) {
13445 				verbose(env, "arg%d expected pointer to func\n", i);
13446 				return -EINVAL;
13447 			}
13448 			meta->subprogno = reg->subprogno;
13449 			break;
13450 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13451 			if (!type_is_ptr_alloc_obj(reg->type)) {
13452 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
13453 				return -EINVAL;
13454 			}
13455 			if (!type_is_non_owning_ref(reg->type))
13456 				meta->arg_owning_ref = true;
13457 
13458 			rec = reg_btf_record(reg);
13459 			if (!rec) {
13460 				verifier_bug(env, "Couldn't find btf_record");
13461 				return -EFAULT;
13462 			}
13463 
13464 			if (rec->refcount_off < 0) {
13465 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
13466 				return -EINVAL;
13467 			}
13468 
13469 			meta->arg_btf = reg->btf;
13470 			meta->arg_btf_id = reg->btf_id;
13471 			break;
13472 		case KF_ARG_PTR_TO_CONST_STR:
13473 			if (reg->type != PTR_TO_MAP_VALUE) {
13474 				verbose(env, "arg#%d doesn't point to a const string\n", i);
13475 				return -EINVAL;
13476 			}
13477 			ret = check_reg_const_str(env, reg, regno);
13478 			if (ret)
13479 				return ret;
13480 			break;
13481 		case KF_ARG_PTR_TO_WORKQUEUE:
13482 			if (reg->type != PTR_TO_MAP_VALUE) {
13483 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13484 				return -EINVAL;
13485 			}
13486 			ret = process_wq_func(env, regno, meta);
13487 			if (ret < 0)
13488 				return ret;
13489 			break;
13490 		case KF_ARG_PTR_TO_IRQ_FLAG:
13491 			if (reg->type != PTR_TO_STACK) {
13492 				verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i);
13493 				return -EINVAL;
13494 			}
13495 			ret = process_irq_flag(env, regno, meta);
13496 			if (ret < 0)
13497 				return ret;
13498 			break;
13499 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13500 		{
13501 			int flags = PROCESS_RES_LOCK;
13502 
13503 			if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13504 				verbose(env, "arg#%d doesn't point to map value or allocated object\n", i);
13505 				return -EINVAL;
13506 			}
13507 
13508 			if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
13509 				return -EFAULT;
13510 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13511 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
13512 				flags |= PROCESS_SPIN_LOCK;
13513 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
13514 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
13515 				flags |= PROCESS_LOCK_IRQ;
13516 			ret = process_spin_lock(env, regno, flags);
13517 			if (ret < 0)
13518 				return ret;
13519 			break;
13520 		}
13521 		}
13522 	}
13523 
13524 	if (is_kfunc_release(meta) && !meta->release_regno) {
13525 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
13526 			func_name);
13527 		return -EINVAL;
13528 	}
13529 
13530 	return 0;
13531 }
13532 
13533 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
13534 			    struct bpf_insn *insn,
13535 			    struct bpf_kfunc_call_arg_meta *meta,
13536 			    const char **kfunc_name)
13537 {
13538 	const struct btf_type *func, *func_proto;
13539 	u32 func_id, *kfunc_flags;
13540 	const char *func_name;
13541 	struct btf *desc_btf;
13542 
13543 	if (kfunc_name)
13544 		*kfunc_name = NULL;
13545 
13546 	if (!insn->imm)
13547 		return -EINVAL;
13548 
13549 	desc_btf = find_kfunc_desc_btf(env, insn->off);
13550 	if (IS_ERR(desc_btf))
13551 		return PTR_ERR(desc_btf);
13552 
13553 	func_id = insn->imm;
13554 	func = btf_type_by_id(desc_btf, func_id);
13555 	func_name = btf_name_by_offset(desc_btf, func->name_off);
13556 	if (kfunc_name)
13557 		*kfunc_name = func_name;
13558 	func_proto = btf_type_by_id(desc_btf, func->type);
13559 
13560 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
13561 	if (!kfunc_flags) {
13562 		return -EACCES;
13563 	}
13564 
13565 	memset(meta, 0, sizeof(*meta));
13566 	meta->btf = desc_btf;
13567 	meta->func_id = func_id;
13568 	meta->kfunc_flags = *kfunc_flags;
13569 	meta->func_proto = func_proto;
13570 	meta->func_name = func_name;
13571 
13572 	return 0;
13573 }
13574 
13575 /* check special kfuncs and return:
13576  *  1  - not fall-through to 'else' branch, continue verification
13577  *  0  - fall-through to 'else' branch
13578  * < 0 - not fall-through to 'else' branch, return error
13579  */
13580 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13581 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
13582 			       const struct btf_type *ptr_type, struct btf *desc_btf)
13583 {
13584 	const struct btf_type *ret_t;
13585 	int err = 0;
13586 
13587 	if (meta->btf != btf_vmlinux)
13588 		return 0;
13589 
13590 	if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
13591 	    meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13592 		struct btf_struct_meta *struct_meta;
13593 		struct btf *ret_btf;
13594 		u32 ret_btf_id;
13595 
13596 		if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
13597 			return -ENOMEM;
13598 
13599 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
13600 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13601 			return -EINVAL;
13602 		}
13603 
13604 		ret_btf = env->prog->aux->btf;
13605 		ret_btf_id = meta->arg_constant.value;
13606 
13607 		/* This may be NULL due to user not supplying a BTF */
13608 		if (!ret_btf) {
13609 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13610 			return -EINVAL;
13611 		}
13612 
13613 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13614 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
13615 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13616 			return -EINVAL;
13617 		}
13618 
13619 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13620 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13621 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13622 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13623 				return -EINVAL;
13624 			}
13625 
13626 			if (!bpf_global_percpu_ma_set) {
13627 				mutex_lock(&bpf_percpu_ma_lock);
13628 				if (!bpf_global_percpu_ma_set) {
13629 					/* Charge memory allocated with bpf_global_percpu_ma to
13630 					 * root memcg. The obj_cgroup for root memcg is NULL.
13631 					 */
13632 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13633 					if (!err)
13634 						bpf_global_percpu_ma_set = true;
13635 				}
13636 				mutex_unlock(&bpf_percpu_ma_lock);
13637 				if (err)
13638 					return err;
13639 			}
13640 
13641 			mutex_lock(&bpf_percpu_ma_lock);
13642 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13643 			mutex_unlock(&bpf_percpu_ma_lock);
13644 			if (err)
13645 				return err;
13646 		}
13647 
13648 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13649 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13650 			if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13651 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13652 				return -EINVAL;
13653 			}
13654 
13655 			if (struct_meta) {
13656 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13657 				return -EINVAL;
13658 			}
13659 		}
13660 
13661 		mark_reg_known_zero(env, regs, BPF_REG_0);
13662 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13663 		regs[BPF_REG_0].btf = ret_btf;
13664 		regs[BPF_REG_0].btf_id = ret_btf_id;
13665 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
13666 			regs[BPF_REG_0].type |= MEM_PERCPU;
13667 
13668 		insn_aux->obj_new_size = ret_t->size;
13669 		insn_aux->kptr_struct_meta = struct_meta;
13670 	} else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
13671 		mark_reg_known_zero(env, regs, BPF_REG_0);
13672 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13673 		regs[BPF_REG_0].btf = meta->arg_btf;
13674 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
13675 
13676 		insn_aux->kptr_struct_meta =
13677 			btf_find_struct_meta(meta->arg_btf,
13678 					     meta->arg_btf_id);
13679 	} else if (is_list_node_type(ptr_type)) {
13680 		struct btf_field *field = meta->arg_list_head.field;
13681 
13682 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13683 	} else if (is_rbtree_node_type(ptr_type)) {
13684 		struct btf_field *field = meta->arg_rbtree_root.field;
13685 
13686 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13687 	} else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13688 		mark_reg_known_zero(env, regs, BPF_REG_0);
13689 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13690 		regs[BPF_REG_0].btf = desc_btf;
13691 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
13692 	} else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
13693 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
13694 		if (!ret_t) {
13695 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
13696 				meta->arg_constant.value);
13697 			return -EINVAL;
13698 		} else if (btf_type_is_struct(ret_t)) {
13699 			mark_reg_known_zero(env, regs, BPF_REG_0);
13700 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13701 			regs[BPF_REG_0].btf = desc_btf;
13702 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
13703 		} else if (btf_type_is_void(ret_t)) {
13704 			mark_reg_known_zero(env, regs, BPF_REG_0);
13705 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
13706 			regs[BPF_REG_0].mem_size = 0;
13707 		} else {
13708 			verbose(env,
13709 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
13710 			return -EINVAL;
13711 		}
13712 	} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13713 		   meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13714 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type);
13715 
13716 		mark_reg_known_zero(env, regs, BPF_REG_0);
13717 
13718 		if (!meta->arg_constant.found) {
13719 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
13720 			return -EFAULT;
13721 		}
13722 
13723 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
13724 
13725 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
13726 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
13727 
13728 		if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
13729 			regs[BPF_REG_0].type |= MEM_RDONLY;
13730 		} else {
13731 			/* this will set env->seen_direct_write to true */
13732 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
13733 				verbose(env, "the prog does not allow writes to packet data\n");
13734 				return -EINVAL;
13735 			}
13736 		}
13737 
13738 		if (!meta->initialized_dynptr.id) {
13739 			verifier_bug(env, "no dynptr id");
13740 			return -EFAULT;
13741 		}
13742 		regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id;
13743 
13744 		/* we don't need to set BPF_REG_0's ref obj id
13745 		 * because packet slices are not refcounted (see
13746 		 * dynptr_type_refcounted)
13747 		 */
13748 	} else {
13749 		return 0;
13750 	}
13751 
13752 	return 1;
13753 }
13754 
13755 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
13756 
13757 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
13758 			    int *insn_idx_p)
13759 {
13760 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
13761 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
13762 	struct bpf_reg_state *regs = cur_regs(env);
13763 	const char *func_name, *ptr_type_name;
13764 	const struct btf_type *t, *ptr_type;
13765 	struct bpf_kfunc_call_arg_meta meta;
13766 	struct bpf_insn_aux_data *insn_aux;
13767 	int err, insn_idx = *insn_idx_p;
13768 	const struct btf_param *args;
13769 	struct btf *desc_btf;
13770 
13771 	/* skip for now, but return error when we find this in fixup_kfunc_call */
13772 	if (!insn->imm)
13773 		return 0;
13774 
13775 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
13776 	if (err == -EACCES && func_name)
13777 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
13778 	if (err)
13779 		return err;
13780 	desc_btf = meta.btf;
13781 	insn_aux = &env->insn_aux_data[insn_idx];
13782 
13783 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
13784 
13785 	if (!insn->off &&
13786 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
13787 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
13788 		struct bpf_verifier_state *branch;
13789 		struct bpf_reg_state *regs;
13790 
13791 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13792 		if (!branch) {
13793 			verbose(env, "failed to push state for failed lock acquisition\n");
13794 			return -ENOMEM;
13795 		}
13796 
13797 		regs = branch->frame[branch->curframe]->regs;
13798 
13799 		/* Clear r0-r5 registers in forked state */
13800 		for (i = 0; i < CALLER_SAVED_REGS; i++)
13801 			mark_reg_not_init(env, regs, caller_saved[i]);
13802 
13803 		mark_reg_unknown(env, regs, BPF_REG_0);
13804 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
13805 		if (err) {
13806 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
13807 			return err;
13808 		}
13809 		__mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32));
13810 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
13811 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
13812 		return -EFAULT;
13813 	}
13814 
13815 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
13816 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
13817 		return -EACCES;
13818 	}
13819 
13820 	sleepable = is_kfunc_sleepable(&meta);
13821 	if (sleepable && !in_sleepable(env)) {
13822 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
13823 		return -EACCES;
13824 	}
13825 
13826 	/* Check the arguments */
13827 	err = check_kfunc_args(env, &meta, insn_idx);
13828 	if (err < 0)
13829 		return err;
13830 
13831 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13832 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13833 					 set_rbtree_add_callback_state);
13834 		if (err) {
13835 			verbose(env, "kfunc %s#%d failed callback verification\n",
13836 				func_name, meta.func_id);
13837 			return err;
13838 		}
13839 	}
13840 
13841 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
13842 		meta.r0_size = sizeof(u64);
13843 		meta.r0_rdonly = false;
13844 	}
13845 
13846 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
13847 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13848 					 set_timer_callback_state);
13849 		if (err) {
13850 			verbose(env, "kfunc %s#%d failed callback verification\n",
13851 				func_name, meta.func_id);
13852 			return err;
13853 		}
13854 	}
13855 
13856 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
13857 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
13858 
13859 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
13860 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
13861 
13862 	if (env->cur_state->active_rcu_lock) {
13863 		struct bpf_func_state *state;
13864 		struct bpf_reg_state *reg;
13865 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
13866 
13867 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
13868 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
13869 			return -EACCES;
13870 		}
13871 
13872 		if (rcu_lock) {
13873 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
13874 			return -EINVAL;
13875 		} else if (rcu_unlock) {
13876 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
13877 				if (reg->type & MEM_RCU) {
13878 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
13879 					reg->type |= PTR_UNTRUSTED;
13880 				}
13881 			}));
13882 			env->cur_state->active_rcu_lock = false;
13883 		} else if (sleepable) {
13884 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
13885 			return -EACCES;
13886 		}
13887 	} else if (rcu_lock) {
13888 		env->cur_state->active_rcu_lock = true;
13889 	} else if (rcu_unlock) {
13890 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
13891 		return -EINVAL;
13892 	}
13893 
13894 	if (env->cur_state->active_preempt_locks) {
13895 		if (preempt_disable) {
13896 			env->cur_state->active_preempt_locks++;
13897 		} else if (preempt_enable) {
13898 			env->cur_state->active_preempt_locks--;
13899 		} else if (sleepable) {
13900 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
13901 			return -EACCES;
13902 		}
13903 	} else if (preempt_disable) {
13904 		env->cur_state->active_preempt_locks++;
13905 	} else if (preempt_enable) {
13906 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
13907 		return -EINVAL;
13908 	}
13909 
13910 	if (env->cur_state->active_irq_id && sleepable) {
13911 		verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name);
13912 		return -EACCES;
13913 	}
13914 
13915 	/* In case of release function, we get register number of refcounted
13916 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
13917 	 */
13918 	if (meta.release_regno) {
13919 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
13920 		if (err) {
13921 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13922 				func_name, meta.func_id);
13923 			return err;
13924 		}
13925 	}
13926 
13927 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
13928 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
13929 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13930 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
13931 		insn_aux->insert_off = regs[BPF_REG_2].off;
13932 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
13933 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
13934 		if (err) {
13935 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
13936 				func_name, meta.func_id);
13937 			return err;
13938 		}
13939 
13940 		err = release_reference(env, release_ref_obj_id);
13941 		if (err) {
13942 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13943 				func_name, meta.func_id);
13944 			return err;
13945 		}
13946 	}
13947 
13948 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
13949 		if (!bpf_jit_supports_exceptions()) {
13950 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
13951 				func_name, meta.func_id);
13952 			return -ENOTSUPP;
13953 		}
13954 		env->seen_exception = true;
13955 
13956 		/* In the case of the default callback, the cookie value passed
13957 		 * to bpf_throw becomes the return value of the program.
13958 		 */
13959 		if (!env->exception_callback_subprog) {
13960 			err = check_return_code(env, BPF_REG_1, "R1");
13961 			if (err < 0)
13962 				return err;
13963 		}
13964 	}
13965 
13966 	for (i = 0; i < CALLER_SAVED_REGS; i++)
13967 		mark_reg_not_init(env, regs, caller_saved[i]);
13968 
13969 	/* Check return type */
13970 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
13971 
13972 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
13973 		/* Only exception is bpf_obj_new_impl */
13974 		if (meta.btf != btf_vmlinux ||
13975 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
13976 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
13977 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
13978 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
13979 			return -EINVAL;
13980 		}
13981 	}
13982 
13983 	if (btf_type_is_scalar(t)) {
13984 		mark_reg_unknown(env, regs, BPF_REG_0);
13985 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13986 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
13987 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
13988 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
13989 	} else if (btf_type_is_ptr(t)) {
13990 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
13991 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
13992 		if (err) {
13993 			if (err < 0)
13994 				return err;
13995 		} else if (btf_type_is_void(ptr_type)) {
13996 			/* kfunc returning 'void *' is equivalent to returning scalar */
13997 			mark_reg_unknown(env, regs, BPF_REG_0);
13998 		} else if (!__btf_type_is_struct(ptr_type)) {
13999 			if (!meta.r0_size) {
14000 				__u32 sz;
14001 
14002 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
14003 					meta.r0_size = sz;
14004 					meta.r0_rdonly = true;
14005 				}
14006 			}
14007 			if (!meta.r0_size) {
14008 				ptr_type_name = btf_name_by_offset(desc_btf,
14009 								   ptr_type->name_off);
14010 				verbose(env,
14011 					"kernel function %s returns pointer type %s %s is not supported\n",
14012 					func_name,
14013 					btf_type_str(ptr_type),
14014 					ptr_type_name);
14015 				return -EINVAL;
14016 			}
14017 
14018 			mark_reg_known_zero(env, regs, BPF_REG_0);
14019 			regs[BPF_REG_0].type = PTR_TO_MEM;
14020 			regs[BPF_REG_0].mem_size = meta.r0_size;
14021 
14022 			if (meta.r0_rdonly)
14023 				regs[BPF_REG_0].type |= MEM_RDONLY;
14024 
14025 			/* Ensures we don't access the memory after a release_reference() */
14026 			if (meta.ref_obj_id)
14027 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
14028 		} else {
14029 			mark_reg_known_zero(env, regs, BPF_REG_0);
14030 			regs[BPF_REG_0].btf = desc_btf;
14031 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
14032 			regs[BPF_REG_0].btf_id = ptr_type_id;
14033 
14034 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
14035 				regs[BPF_REG_0].type |= PTR_UNTRUSTED;
14036 
14037 			if (is_iter_next_kfunc(&meta)) {
14038 				struct bpf_reg_state *cur_iter;
14039 
14040 				cur_iter = get_iter_from_state(env->cur_state, &meta);
14041 
14042 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
14043 					regs[BPF_REG_0].type |= MEM_RCU;
14044 				else
14045 					regs[BPF_REG_0].type |= PTR_TRUSTED;
14046 			}
14047 		}
14048 
14049 		if (is_kfunc_ret_null(&meta)) {
14050 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
14051 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
14052 			regs[BPF_REG_0].id = ++env->id_gen;
14053 		}
14054 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
14055 		if (is_kfunc_acquire(&meta)) {
14056 			int id = acquire_reference(env, insn_idx);
14057 
14058 			if (id < 0)
14059 				return id;
14060 			if (is_kfunc_ret_null(&meta))
14061 				regs[BPF_REG_0].id = id;
14062 			regs[BPF_REG_0].ref_obj_id = id;
14063 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
14064 			ref_set_non_owning(env, &regs[BPF_REG_0]);
14065 		}
14066 
14067 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
14068 			regs[BPF_REG_0].id = ++env->id_gen;
14069 	} else if (btf_type_is_void(t)) {
14070 		if (meta.btf == btf_vmlinux) {
14071 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
14072 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
14073 				insn_aux->kptr_struct_meta =
14074 					btf_find_struct_meta(meta.arg_btf,
14075 							     meta.arg_btf_id);
14076 			}
14077 		}
14078 	}
14079 
14080 	nargs = btf_type_vlen(meta.func_proto);
14081 	args = (const struct btf_param *)(meta.func_proto + 1);
14082 	for (i = 0; i < nargs; i++) {
14083 		u32 regno = i + 1;
14084 
14085 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
14086 		if (btf_type_is_ptr(t))
14087 			mark_btf_func_reg_size(env, regno, sizeof(void *));
14088 		else
14089 			/* scalar. ensured by btf_check_kfunc_arg_match() */
14090 			mark_btf_func_reg_size(env, regno, t->size);
14091 	}
14092 
14093 	if (is_iter_next_kfunc(&meta)) {
14094 		err = process_iter_next_call(env, insn_idx, &meta);
14095 		if (err)
14096 			return err;
14097 	}
14098 
14099 	return 0;
14100 }
14101 
14102 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
14103 				  const struct bpf_reg_state *reg,
14104 				  enum bpf_reg_type type)
14105 {
14106 	bool known = tnum_is_const(reg->var_off);
14107 	s64 val = reg->var_off.value;
14108 	s64 smin = reg->smin_value;
14109 
14110 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
14111 		verbose(env, "math between %s pointer and %lld is not allowed\n",
14112 			reg_type_str(env, type), val);
14113 		return false;
14114 	}
14115 
14116 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
14117 		verbose(env, "%s pointer offset %d is not allowed\n",
14118 			reg_type_str(env, type), reg->off);
14119 		return false;
14120 	}
14121 
14122 	if (smin == S64_MIN) {
14123 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
14124 			reg_type_str(env, type));
14125 		return false;
14126 	}
14127 
14128 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
14129 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
14130 			smin, reg_type_str(env, type));
14131 		return false;
14132 	}
14133 
14134 	return true;
14135 }
14136 
14137 enum {
14138 	REASON_BOUNDS	= -1,
14139 	REASON_TYPE	= -2,
14140 	REASON_PATHS	= -3,
14141 	REASON_LIMIT	= -4,
14142 	REASON_STACK	= -5,
14143 };
14144 
14145 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
14146 			      u32 *alu_limit, bool mask_to_left)
14147 {
14148 	u32 max = 0, ptr_limit = 0;
14149 
14150 	switch (ptr_reg->type) {
14151 	case PTR_TO_STACK:
14152 		/* Offset 0 is out-of-bounds, but acceptable start for the
14153 		 * left direction, see BPF_REG_FP. Also, unknown scalar
14154 		 * offset where we would need to deal with min/max bounds is
14155 		 * currently prohibited for unprivileged.
14156 		 */
14157 		max = MAX_BPF_STACK + mask_to_left;
14158 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
14159 		break;
14160 	case PTR_TO_MAP_VALUE:
14161 		max = ptr_reg->map_ptr->value_size;
14162 		ptr_limit = (mask_to_left ?
14163 			     ptr_reg->smin_value :
14164 			     ptr_reg->umax_value) + ptr_reg->off;
14165 		break;
14166 	default:
14167 		return REASON_TYPE;
14168 	}
14169 
14170 	if (ptr_limit >= max)
14171 		return REASON_LIMIT;
14172 	*alu_limit = ptr_limit;
14173 	return 0;
14174 }
14175 
14176 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
14177 				    const struct bpf_insn *insn)
14178 {
14179 	return env->bypass_spec_v1 ||
14180 		BPF_SRC(insn->code) == BPF_K ||
14181 		cur_aux(env)->nospec;
14182 }
14183 
14184 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
14185 				       u32 alu_state, u32 alu_limit)
14186 {
14187 	/* If we arrived here from different branches with different
14188 	 * state or limits to sanitize, then this won't work.
14189 	 */
14190 	if (aux->alu_state &&
14191 	    (aux->alu_state != alu_state ||
14192 	     aux->alu_limit != alu_limit))
14193 		return REASON_PATHS;
14194 
14195 	/* Corresponding fixup done in do_misc_fixups(). */
14196 	aux->alu_state = alu_state;
14197 	aux->alu_limit = alu_limit;
14198 	return 0;
14199 }
14200 
14201 static int sanitize_val_alu(struct bpf_verifier_env *env,
14202 			    struct bpf_insn *insn)
14203 {
14204 	struct bpf_insn_aux_data *aux = cur_aux(env);
14205 
14206 	if (can_skip_alu_sanitation(env, insn))
14207 		return 0;
14208 
14209 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
14210 }
14211 
14212 static bool sanitize_needed(u8 opcode)
14213 {
14214 	return opcode == BPF_ADD || opcode == BPF_SUB;
14215 }
14216 
14217 struct bpf_sanitize_info {
14218 	struct bpf_insn_aux_data aux;
14219 	bool mask_to_left;
14220 };
14221 
14222 static struct bpf_verifier_state *
14223 sanitize_speculative_path(struct bpf_verifier_env *env,
14224 			  const struct bpf_insn *insn,
14225 			  u32 next_idx, u32 curr_idx)
14226 {
14227 	struct bpf_verifier_state *branch;
14228 	struct bpf_reg_state *regs;
14229 
14230 	branch = push_stack(env, next_idx, curr_idx, true);
14231 	if (branch && insn) {
14232 		regs = branch->frame[branch->curframe]->regs;
14233 		if (BPF_SRC(insn->code) == BPF_K) {
14234 			mark_reg_unknown(env, regs, insn->dst_reg);
14235 		} else if (BPF_SRC(insn->code) == BPF_X) {
14236 			mark_reg_unknown(env, regs, insn->dst_reg);
14237 			mark_reg_unknown(env, regs, insn->src_reg);
14238 		}
14239 	}
14240 	return branch;
14241 }
14242 
14243 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
14244 			    struct bpf_insn *insn,
14245 			    const struct bpf_reg_state *ptr_reg,
14246 			    const struct bpf_reg_state *off_reg,
14247 			    struct bpf_reg_state *dst_reg,
14248 			    struct bpf_sanitize_info *info,
14249 			    const bool commit_window)
14250 {
14251 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
14252 	struct bpf_verifier_state *vstate = env->cur_state;
14253 	bool off_is_imm = tnum_is_const(off_reg->var_off);
14254 	bool off_is_neg = off_reg->smin_value < 0;
14255 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
14256 	u8 opcode = BPF_OP(insn->code);
14257 	u32 alu_state, alu_limit;
14258 	struct bpf_reg_state tmp;
14259 	bool ret;
14260 	int err;
14261 
14262 	if (can_skip_alu_sanitation(env, insn))
14263 		return 0;
14264 
14265 	/* We already marked aux for masking from non-speculative
14266 	 * paths, thus we got here in the first place. We only care
14267 	 * to explore bad access from here.
14268 	 */
14269 	if (vstate->speculative)
14270 		goto do_sim;
14271 
14272 	if (!commit_window) {
14273 		if (!tnum_is_const(off_reg->var_off) &&
14274 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
14275 			return REASON_BOUNDS;
14276 
14277 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
14278 				     (opcode == BPF_SUB && !off_is_neg);
14279 	}
14280 
14281 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
14282 	if (err < 0)
14283 		return err;
14284 
14285 	if (commit_window) {
14286 		/* In commit phase we narrow the masking window based on
14287 		 * the observed pointer move after the simulated operation.
14288 		 */
14289 		alu_state = info->aux.alu_state;
14290 		alu_limit = abs(info->aux.alu_limit - alu_limit);
14291 	} else {
14292 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
14293 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
14294 		alu_state |= ptr_is_dst_reg ?
14295 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
14296 
14297 		/* Limit pruning on unknown scalars to enable deep search for
14298 		 * potential masking differences from other program paths.
14299 		 */
14300 		if (!off_is_imm)
14301 			env->explore_alu_limits = true;
14302 	}
14303 
14304 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
14305 	if (err < 0)
14306 		return err;
14307 do_sim:
14308 	/* If we're in commit phase, we're done here given we already
14309 	 * pushed the truncated dst_reg into the speculative verification
14310 	 * stack.
14311 	 *
14312 	 * Also, when register is a known constant, we rewrite register-based
14313 	 * operation to immediate-based, and thus do not need masking (and as
14314 	 * a consequence, do not need to simulate the zero-truncation either).
14315 	 */
14316 	if (commit_window || off_is_imm)
14317 		return 0;
14318 
14319 	/* Simulate and find potential out-of-bounds access under
14320 	 * speculative execution from truncation as a result of
14321 	 * masking when off was not within expected range. If off
14322 	 * sits in dst, then we temporarily need to move ptr there
14323 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
14324 	 * for cases where we use K-based arithmetic in one direction
14325 	 * and truncated reg-based in the other in order to explore
14326 	 * bad access.
14327 	 */
14328 	if (!ptr_is_dst_reg) {
14329 		tmp = *dst_reg;
14330 		copy_register_state(dst_reg, ptr_reg);
14331 	}
14332 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
14333 					env->insn_idx);
14334 	if (!ptr_is_dst_reg && ret)
14335 		*dst_reg = tmp;
14336 	return !ret ? REASON_STACK : 0;
14337 }
14338 
14339 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
14340 {
14341 	struct bpf_verifier_state *vstate = env->cur_state;
14342 
14343 	/* If we simulate paths under speculation, we don't update the
14344 	 * insn as 'seen' such that when we verify unreachable paths in
14345 	 * the non-speculative domain, sanitize_dead_code() can still
14346 	 * rewrite/sanitize them.
14347 	 */
14348 	if (!vstate->speculative)
14349 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
14350 }
14351 
14352 static int sanitize_err(struct bpf_verifier_env *env,
14353 			const struct bpf_insn *insn, int reason,
14354 			const struct bpf_reg_state *off_reg,
14355 			const struct bpf_reg_state *dst_reg)
14356 {
14357 	static const char *err = "pointer arithmetic with it prohibited for !root";
14358 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
14359 	u32 dst = insn->dst_reg, src = insn->src_reg;
14360 
14361 	switch (reason) {
14362 	case REASON_BOUNDS:
14363 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
14364 			off_reg == dst_reg ? dst : src, err);
14365 		break;
14366 	case REASON_TYPE:
14367 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
14368 			off_reg == dst_reg ? src : dst, err);
14369 		break;
14370 	case REASON_PATHS:
14371 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
14372 			dst, op, err);
14373 		break;
14374 	case REASON_LIMIT:
14375 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
14376 			dst, op, err);
14377 		break;
14378 	case REASON_STACK:
14379 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
14380 			dst, err);
14381 		return -ENOMEM;
14382 	default:
14383 		verifier_bug(env, "unknown reason (%d)", reason);
14384 		break;
14385 	}
14386 
14387 	return -EACCES;
14388 }
14389 
14390 /* check that stack access falls within stack limits and that 'reg' doesn't
14391  * have a variable offset.
14392  *
14393  * Variable offset is prohibited for unprivileged mode for simplicity since it
14394  * requires corresponding support in Spectre masking for stack ALU.  See also
14395  * retrieve_ptr_limit().
14396  *
14397  *
14398  * 'off' includes 'reg->off'.
14399  */
14400 static int check_stack_access_for_ptr_arithmetic(
14401 				struct bpf_verifier_env *env,
14402 				int regno,
14403 				const struct bpf_reg_state *reg,
14404 				int off)
14405 {
14406 	if (!tnum_is_const(reg->var_off)) {
14407 		char tn_buf[48];
14408 
14409 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
14410 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
14411 			regno, tn_buf, off);
14412 		return -EACCES;
14413 	}
14414 
14415 	if (off >= 0 || off < -MAX_BPF_STACK) {
14416 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
14417 			"prohibited for !root; off=%d\n", regno, off);
14418 		return -EACCES;
14419 	}
14420 
14421 	return 0;
14422 }
14423 
14424 static int sanitize_check_bounds(struct bpf_verifier_env *env,
14425 				 const struct bpf_insn *insn,
14426 				 const struct bpf_reg_state *dst_reg)
14427 {
14428 	u32 dst = insn->dst_reg;
14429 
14430 	/* For unprivileged we require that resulting offset must be in bounds
14431 	 * in order to be able to sanitize access later on.
14432 	 */
14433 	if (env->bypass_spec_v1)
14434 		return 0;
14435 
14436 	switch (dst_reg->type) {
14437 	case PTR_TO_STACK:
14438 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
14439 					dst_reg->off + dst_reg->var_off.value))
14440 			return -EACCES;
14441 		break;
14442 	case PTR_TO_MAP_VALUE:
14443 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
14444 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
14445 				"prohibited for !root\n", dst);
14446 			return -EACCES;
14447 		}
14448 		break;
14449 	default:
14450 		return -EOPNOTSUPP;
14451 	}
14452 
14453 	return 0;
14454 }
14455 
14456 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
14457  * Caller should also handle BPF_MOV case separately.
14458  * If we return -EACCES, caller may want to try again treating pointer as a
14459  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
14460  */
14461 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
14462 				   struct bpf_insn *insn,
14463 				   const struct bpf_reg_state *ptr_reg,
14464 				   const struct bpf_reg_state *off_reg)
14465 {
14466 	struct bpf_verifier_state *vstate = env->cur_state;
14467 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14468 	struct bpf_reg_state *regs = state->regs, *dst_reg;
14469 	bool known = tnum_is_const(off_reg->var_off);
14470 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
14471 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
14472 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
14473 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
14474 	struct bpf_sanitize_info info = {};
14475 	u8 opcode = BPF_OP(insn->code);
14476 	u32 dst = insn->dst_reg;
14477 	int ret, bounds_ret;
14478 
14479 	dst_reg = &regs[dst];
14480 
14481 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
14482 	    smin_val > smax_val || umin_val > umax_val) {
14483 		/* Taint dst register if offset had invalid bounds derived from
14484 		 * e.g. dead branches.
14485 		 */
14486 		__mark_reg_unknown(env, dst_reg);
14487 		return 0;
14488 	}
14489 
14490 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
14491 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
14492 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14493 			__mark_reg_unknown(env, dst_reg);
14494 			return 0;
14495 		}
14496 
14497 		verbose(env,
14498 			"R%d 32-bit pointer arithmetic prohibited\n",
14499 			dst);
14500 		return -EACCES;
14501 	}
14502 
14503 	if (ptr_reg->type & PTR_MAYBE_NULL) {
14504 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
14505 			dst, reg_type_str(env, ptr_reg->type));
14506 		return -EACCES;
14507 	}
14508 
14509 	/*
14510 	 * Accesses to untrusted PTR_TO_MEM are done through probe
14511 	 * instructions, hence no need to track offsets.
14512 	 */
14513 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
14514 		return 0;
14515 
14516 	switch (base_type(ptr_reg->type)) {
14517 	case PTR_TO_CTX:
14518 	case PTR_TO_MAP_VALUE:
14519 	case PTR_TO_MAP_KEY:
14520 	case PTR_TO_STACK:
14521 	case PTR_TO_PACKET_META:
14522 	case PTR_TO_PACKET:
14523 	case PTR_TO_TP_BUFFER:
14524 	case PTR_TO_BTF_ID:
14525 	case PTR_TO_MEM:
14526 	case PTR_TO_BUF:
14527 	case PTR_TO_FUNC:
14528 	case CONST_PTR_TO_DYNPTR:
14529 		break;
14530 	case PTR_TO_FLOW_KEYS:
14531 		if (known)
14532 			break;
14533 		fallthrough;
14534 	case CONST_PTR_TO_MAP:
14535 		/* smin_val represents the known value */
14536 		if (known && smin_val == 0 && opcode == BPF_ADD)
14537 			break;
14538 		fallthrough;
14539 	default:
14540 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
14541 			dst, reg_type_str(env, ptr_reg->type));
14542 		return -EACCES;
14543 	}
14544 
14545 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
14546 	 * The id may be overwritten later if we create a new variable offset.
14547 	 */
14548 	dst_reg->type = ptr_reg->type;
14549 	dst_reg->id = ptr_reg->id;
14550 
14551 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
14552 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
14553 		return -EINVAL;
14554 
14555 	/* pointer types do not carry 32-bit bounds at the moment. */
14556 	__mark_reg32_unbounded(dst_reg);
14557 
14558 	if (sanitize_needed(opcode)) {
14559 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
14560 				       &info, false);
14561 		if (ret < 0)
14562 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14563 	}
14564 
14565 	switch (opcode) {
14566 	case BPF_ADD:
14567 		/* We can take a fixed offset as long as it doesn't overflow
14568 		 * the s32 'off' field
14569 		 */
14570 		if (known && (ptr_reg->off + smin_val ==
14571 			      (s64)(s32)(ptr_reg->off + smin_val))) {
14572 			/* pointer += K.  Accumulate it into fixed offset */
14573 			dst_reg->smin_value = smin_ptr;
14574 			dst_reg->smax_value = smax_ptr;
14575 			dst_reg->umin_value = umin_ptr;
14576 			dst_reg->umax_value = umax_ptr;
14577 			dst_reg->var_off = ptr_reg->var_off;
14578 			dst_reg->off = ptr_reg->off + smin_val;
14579 			dst_reg->raw = ptr_reg->raw;
14580 			break;
14581 		}
14582 		/* A new variable offset is created.  Note that off_reg->off
14583 		 * == 0, since it's a scalar.
14584 		 * dst_reg gets the pointer type and since some positive
14585 		 * integer value was added to the pointer, give it a new 'id'
14586 		 * if it's a PTR_TO_PACKET.
14587 		 * this creates a new 'base' pointer, off_reg (variable) gets
14588 		 * added into the variable offset, and we copy the fixed offset
14589 		 * from ptr_reg.
14590 		 */
14591 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
14592 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
14593 			dst_reg->smin_value = S64_MIN;
14594 			dst_reg->smax_value = S64_MAX;
14595 		}
14596 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
14597 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
14598 			dst_reg->umin_value = 0;
14599 			dst_reg->umax_value = U64_MAX;
14600 		}
14601 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
14602 		dst_reg->off = ptr_reg->off;
14603 		dst_reg->raw = ptr_reg->raw;
14604 		if (reg_is_pkt_pointer(ptr_reg)) {
14605 			dst_reg->id = ++env->id_gen;
14606 			/* something was added to pkt_ptr, set range to zero */
14607 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14608 		}
14609 		break;
14610 	case BPF_SUB:
14611 		if (dst_reg == off_reg) {
14612 			/* scalar -= pointer.  Creates an unknown scalar */
14613 			verbose(env, "R%d tried to subtract pointer from scalar\n",
14614 				dst);
14615 			return -EACCES;
14616 		}
14617 		/* We don't allow subtraction from FP, because (according to
14618 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
14619 		 * be able to deal with it.
14620 		 */
14621 		if (ptr_reg->type == PTR_TO_STACK) {
14622 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
14623 				dst);
14624 			return -EACCES;
14625 		}
14626 		if (known && (ptr_reg->off - smin_val ==
14627 			      (s64)(s32)(ptr_reg->off - smin_val))) {
14628 			/* pointer -= K.  Subtract it from fixed offset */
14629 			dst_reg->smin_value = smin_ptr;
14630 			dst_reg->smax_value = smax_ptr;
14631 			dst_reg->umin_value = umin_ptr;
14632 			dst_reg->umax_value = umax_ptr;
14633 			dst_reg->var_off = ptr_reg->var_off;
14634 			dst_reg->id = ptr_reg->id;
14635 			dst_reg->off = ptr_reg->off - smin_val;
14636 			dst_reg->raw = ptr_reg->raw;
14637 			break;
14638 		}
14639 		/* A new variable offset is created.  If the subtrahend is known
14640 		 * nonnegative, then any reg->range we had before is still good.
14641 		 */
14642 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
14643 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
14644 			/* Overflow possible, we know nothing */
14645 			dst_reg->smin_value = S64_MIN;
14646 			dst_reg->smax_value = S64_MAX;
14647 		}
14648 		if (umin_ptr < umax_val) {
14649 			/* Overflow possible, we know nothing */
14650 			dst_reg->umin_value = 0;
14651 			dst_reg->umax_value = U64_MAX;
14652 		} else {
14653 			/* Cannot overflow (as long as bounds are consistent) */
14654 			dst_reg->umin_value = umin_ptr - umax_val;
14655 			dst_reg->umax_value = umax_ptr - umin_val;
14656 		}
14657 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
14658 		dst_reg->off = ptr_reg->off;
14659 		dst_reg->raw = ptr_reg->raw;
14660 		if (reg_is_pkt_pointer(ptr_reg)) {
14661 			dst_reg->id = ++env->id_gen;
14662 			/* something was added to pkt_ptr, set range to zero */
14663 			if (smin_val < 0)
14664 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14665 		}
14666 		break;
14667 	case BPF_AND:
14668 	case BPF_OR:
14669 	case BPF_XOR:
14670 		/* bitwise ops on pointers are troublesome, prohibit. */
14671 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
14672 			dst, bpf_alu_string[opcode >> 4]);
14673 		return -EACCES;
14674 	default:
14675 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
14676 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
14677 			dst, bpf_alu_string[opcode >> 4]);
14678 		return -EACCES;
14679 	}
14680 
14681 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
14682 		return -EINVAL;
14683 	reg_bounds_sync(dst_reg);
14684 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
14685 	if (bounds_ret == -EACCES)
14686 		return bounds_ret;
14687 	if (sanitize_needed(opcode)) {
14688 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
14689 				       &info, true);
14690 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
14691 				    && !env->cur_state->speculative
14692 				    && bounds_ret
14693 				    && !ret,
14694 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
14695 			return -EFAULT;
14696 		}
14697 		if (ret < 0)
14698 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14699 	}
14700 
14701 	return 0;
14702 }
14703 
14704 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
14705 				 struct bpf_reg_state *src_reg)
14706 {
14707 	s32 *dst_smin = &dst_reg->s32_min_value;
14708 	s32 *dst_smax = &dst_reg->s32_max_value;
14709 	u32 *dst_umin = &dst_reg->u32_min_value;
14710 	u32 *dst_umax = &dst_reg->u32_max_value;
14711 	u32 umin_val = src_reg->u32_min_value;
14712 	u32 umax_val = src_reg->u32_max_value;
14713 	bool min_overflow, max_overflow;
14714 
14715 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
14716 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
14717 		*dst_smin = S32_MIN;
14718 		*dst_smax = S32_MAX;
14719 	}
14720 
14721 	/* If either all additions overflow or no additions overflow, then
14722 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14723 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
14724 	 * the output bounds to unbounded.
14725 	 */
14726 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14727 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14728 
14729 	if (!min_overflow && max_overflow) {
14730 		*dst_umin = 0;
14731 		*dst_umax = U32_MAX;
14732 	}
14733 }
14734 
14735 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
14736 			       struct bpf_reg_state *src_reg)
14737 {
14738 	s64 *dst_smin = &dst_reg->smin_value;
14739 	s64 *dst_smax = &dst_reg->smax_value;
14740 	u64 *dst_umin = &dst_reg->umin_value;
14741 	u64 *dst_umax = &dst_reg->umax_value;
14742 	u64 umin_val = src_reg->umin_value;
14743 	u64 umax_val = src_reg->umax_value;
14744 	bool min_overflow, max_overflow;
14745 
14746 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
14747 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
14748 		*dst_smin = S64_MIN;
14749 		*dst_smax = S64_MAX;
14750 	}
14751 
14752 	/* If either all additions overflow or no additions overflow, then
14753 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14754 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
14755 	 * the output bounds to unbounded.
14756 	 */
14757 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14758 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14759 
14760 	if (!min_overflow && max_overflow) {
14761 		*dst_umin = 0;
14762 		*dst_umax = U64_MAX;
14763 	}
14764 }
14765 
14766 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
14767 				 struct bpf_reg_state *src_reg)
14768 {
14769 	s32 *dst_smin = &dst_reg->s32_min_value;
14770 	s32 *dst_smax = &dst_reg->s32_max_value;
14771 	u32 *dst_umin = &dst_reg->u32_min_value;
14772 	u32 *dst_umax = &dst_reg->u32_max_value;
14773 	u32 umin_val = src_reg->u32_min_value;
14774 	u32 umax_val = src_reg->u32_max_value;
14775 	bool min_underflow, max_underflow;
14776 
14777 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
14778 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
14779 		/* Overflow possible, we know nothing */
14780 		*dst_smin = S32_MIN;
14781 		*dst_smax = S32_MAX;
14782 	}
14783 
14784 	/* If either all subtractions underflow or no subtractions
14785 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
14786 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
14787 	 * underflow), set the output bounds to unbounded.
14788 	 */
14789 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
14790 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
14791 
14792 	if (min_underflow && !max_underflow) {
14793 		*dst_umin = 0;
14794 		*dst_umax = U32_MAX;
14795 	}
14796 }
14797 
14798 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
14799 			       struct bpf_reg_state *src_reg)
14800 {
14801 	s64 *dst_smin = &dst_reg->smin_value;
14802 	s64 *dst_smax = &dst_reg->smax_value;
14803 	u64 *dst_umin = &dst_reg->umin_value;
14804 	u64 *dst_umax = &dst_reg->umax_value;
14805 	u64 umin_val = src_reg->umin_value;
14806 	u64 umax_val = src_reg->umax_value;
14807 	bool min_underflow, max_underflow;
14808 
14809 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
14810 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
14811 		/* Overflow possible, we know nothing */
14812 		*dst_smin = S64_MIN;
14813 		*dst_smax = S64_MAX;
14814 	}
14815 
14816 	/* If either all subtractions underflow or no subtractions
14817 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
14818 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
14819 	 * underflow), set the output bounds to unbounded.
14820 	 */
14821 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
14822 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
14823 
14824 	if (min_underflow && !max_underflow) {
14825 		*dst_umin = 0;
14826 		*dst_umax = U64_MAX;
14827 	}
14828 }
14829 
14830 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
14831 				 struct bpf_reg_state *src_reg)
14832 {
14833 	s32 *dst_smin = &dst_reg->s32_min_value;
14834 	s32 *dst_smax = &dst_reg->s32_max_value;
14835 	u32 *dst_umin = &dst_reg->u32_min_value;
14836 	u32 *dst_umax = &dst_reg->u32_max_value;
14837 	s32 tmp_prod[4];
14838 
14839 	if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) ||
14840 	    check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) {
14841 		/* Overflow possible, we know nothing */
14842 		*dst_umin = 0;
14843 		*dst_umax = U32_MAX;
14844 	}
14845 	if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) ||
14846 	    check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) ||
14847 	    check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) ||
14848 	    check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) {
14849 		/* Overflow possible, we know nothing */
14850 		*dst_smin = S32_MIN;
14851 		*dst_smax = S32_MAX;
14852 	} else {
14853 		*dst_smin = min_array(tmp_prod, 4);
14854 		*dst_smax = max_array(tmp_prod, 4);
14855 	}
14856 }
14857 
14858 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
14859 			       struct bpf_reg_state *src_reg)
14860 {
14861 	s64 *dst_smin = &dst_reg->smin_value;
14862 	s64 *dst_smax = &dst_reg->smax_value;
14863 	u64 *dst_umin = &dst_reg->umin_value;
14864 	u64 *dst_umax = &dst_reg->umax_value;
14865 	s64 tmp_prod[4];
14866 
14867 	if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) ||
14868 	    check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) {
14869 		/* Overflow possible, we know nothing */
14870 		*dst_umin = 0;
14871 		*dst_umax = U64_MAX;
14872 	}
14873 	if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) ||
14874 	    check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) ||
14875 	    check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) ||
14876 	    check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) {
14877 		/* Overflow possible, we know nothing */
14878 		*dst_smin = S64_MIN;
14879 		*dst_smax = S64_MAX;
14880 	} else {
14881 		*dst_smin = min_array(tmp_prod, 4);
14882 		*dst_smax = max_array(tmp_prod, 4);
14883 	}
14884 }
14885 
14886 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
14887 				 struct bpf_reg_state *src_reg)
14888 {
14889 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14890 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14891 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14892 	u32 umax_val = src_reg->u32_max_value;
14893 
14894 	if (src_known && dst_known) {
14895 		__mark_reg32_known(dst_reg, var32_off.value);
14896 		return;
14897 	}
14898 
14899 	/* We get our minimum from the var_off, since that's inherently
14900 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14901 	 */
14902 	dst_reg->u32_min_value = var32_off.value;
14903 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
14904 
14905 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14906 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14907 	 */
14908 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14909 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14910 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14911 	} else {
14912 		dst_reg->s32_min_value = S32_MIN;
14913 		dst_reg->s32_max_value = S32_MAX;
14914 	}
14915 }
14916 
14917 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
14918 			       struct bpf_reg_state *src_reg)
14919 {
14920 	bool src_known = tnum_is_const(src_reg->var_off);
14921 	bool dst_known = tnum_is_const(dst_reg->var_off);
14922 	u64 umax_val = src_reg->umax_value;
14923 
14924 	if (src_known && dst_known) {
14925 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14926 		return;
14927 	}
14928 
14929 	/* We get our minimum from the var_off, since that's inherently
14930 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14931 	 */
14932 	dst_reg->umin_value = dst_reg->var_off.value;
14933 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
14934 
14935 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14936 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14937 	 */
14938 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
14939 		dst_reg->smin_value = dst_reg->umin_value;
14940 		dst_reg->smax_value = dst_reg->umax_value;
14941 	} else {
14942 		dst_reg->smin_value = S64_MIN;
14943 		dst_reg->smax_value = S64_MAX;
14944 	}
14945 	/* We may learn something more from the var_off */
14946 	__update_reg_bounds(dst_reg);
14947 }
14948 
14949 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
14950 				struct bpf_reg_state *src_reg)
14951 {
14952 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14953 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14954 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14955 	u32 umin_val = src_reg->u32_min_value;
14956 
14957 	if (src_known && dst_known) {
14958 		__mark_reg32_known(dst_reg, var32_off.value);
14959 		return;
14960 	}
14961 
14962 	/* We get our maximum from the var_off, and our minimum is the
14963 	 * maximum of the operands' minima
14964 	 */
14965 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
14966 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
14967 
14968 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14969 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14970 	 */
14971 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14972 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14973 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14974 	} else {
14975 		dst_reg->s32_min_value = S32_MIN;
14976 		dst_reg->s32_max_value = S32_MAX;
14977 	}
14978 }
14979 
14980 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
14981 			      struct bpf_reg_state *src_reg)
14982 {
14983 	bool src_known = tnum_is_const(src_reg->var_off);
14984 	bool dst_known = tnum_is_const(dst_reg->var_off);
14985 	u64 umin_val = src_reg->umin_value;
14986 
14987 	if (src_known && dst_known) {
14988 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14989 		return;
14990 	}
14991 
14992 	/* We get our maximum from the var_off, and our minimum is the
14993 	 * maximum of the operands' minima
14994 	 */
14995 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
14996 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
14997 
14998 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14999 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15000 	 */
15001 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15002 		dst_reg->smin_value = dst_reg->umin_value;
15003 		dst_reg->smax_value = dst_reg->umax_value;
15004 	} else {
15005 		dst_reg->smin_value = S64_MIN;
15006 		dst_reg->smax_value = S64_MAX;
15007 	}
15008 	/* We may learn something more from the var_off */
15009 	__update_reg_bounds(dst_reg);
15010 }
15011 
15012 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
15013 				 struct bpf_reg_state *src_reg)
15014 {
15015 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15016 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15017 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15018 
15019 	if (src_known && dst_known) {
15020 		__mark_reg32_known(dst_reg, var32_off.value);
15021 		return;
15022 	}
15023 
15024 	/* We get both minimum and maximum from the var32_off. */
15025 	dst_reg->u32_min_value = var32_off.value;
15026 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15027 
15028 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15029 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15030 	 */
15031 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15032 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15033 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15034 	} else {
15035 		dst_reg->s32_min_value = S32_MIN;
15036 		dst_reg->s32_max_value = S32_MAX;
15037 	}
15038 }
15039 
15040 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
15041 			       struct bpf_reg_state *src_reg)
15042 {
15043 	bool src_known = tnum_is_const(src_reg->var_off);
15044 	bool dst_known = tnum_is_const(dst_reg->var_off);
15045 
15046 	if (src_known && dst_known) {
15047 		/* dst_reg->var_off.value has been updated earlier */
15048 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15049 		return;
15050 	}
15051 
15052 	/* We get both minimum and maximum from the var_off. */
15053 	dst_reg->umin_value = dst_reg->var_off.value;
15054 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15055 
15056 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15057 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15058 	 */
15059 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15060 		dst_reg->smin_value = dst_reg->umin_value;
15061 		dst_reg->smax_value = dst_reg->umax_value;
15062 	} else {
15063 		dst_reg->smin_value = S64_MIN;
15064 		dst_reg->smax_value = S64_MAX;
15065 	}
15066 
15067 	__update_reg_bounds(dst_reg);
15068 }
15069 
15070 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15071 				   u64 umin_val, u64 umax_val)
15072 {
15073 	/* We lose all sign bit information (except what we can pick
15074 	 * up from var_off)
15075 	 */
15076 	dst_reg->s32_min_value = S32_MIN;
15077 	dst_reg->s32_max_value = S32_MAX;
15078 	/* If we might shift our top bit out, then we know nothing */
15079 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
15080 		dst_reg->u32_min_value = 0;
15081 		dst_reg->u32_max_value = U32_MAX;
15082 	} else {
15083 		dst_reg->u32_min_value <<= umin_val;
15084 		dst_reg->u32_max_value <<= umax_val;
15085 	}
15086 }
15087 
15088 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15089 				 struct bpf_reg_state *src_reg)
15090 {
15091 	u32 umax_val = src_reg->u32_max_value;
15092 	u32 umin_val = src_reg->u32_min_value;
15093 	/* u32 alu operation will zext upper bits */
15094 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15095 
15096 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15097 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
15098 	/* Not required but being careful mark reg64 bounds as unknown so
15099 	 * that we are forced to pick them up from tnum and zext later and
15100 	 * if some path skips this step we are still safe.
15101 	 */
15102 	__mark_reg64_unbounded(dst_reg);
15103 	__update_reg32_bounds(dst_reg);
15104 }
15105 
15106 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
15107 				   u64 umin_val, u64 umax_val)
15108 {
15109 	/* Special case <<32 because it is a common compiler pattern to sign
15110 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
15111 	 * positive we know this shift will also be positive so we can track
15112 	 * bounds correctly. Otherwise we lose all sign bit information except
15113 	 * what we can pick up from var_off. Perhaps we can generalize this
15114 	 * later to shifts of any length.
15115 	 */
15116 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
15117 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
15118 	else
15119 		dst_reg->smax_value = S64_MAX;
15120 
15121 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
15122 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
15123 	else
15124 		dst_reg->smin_value = S64_MIN;
15125 
15126 	/* If we might shift our top bit out, then we know nothing */
15127 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
15128 		dst_reg->umin_value = 0;
15129 		dst_reg->umax_value = U64_MAX;
15130 	} else {
15131 		dst_reg->umin_value <<= umin_val;
15132 		dst_reg->umax_value <<= umax_val;
15133 	}
15134 }
15135 
15136 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
15137 			       struct bpf_reg_state *src_reg)
15138 {
15139 	u64 umax_val = src_reg->umax_value;
15140 	u64 umin_val = src_reg->umin_value;
15141 
15142 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
15143 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
15144 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15145 
15146 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
15147 	/* We may learn something more from the var_off */
15148 	__update_reg_bounds(dst_reg);
15149 }
15150 
15151 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
15152 				 struct bpf_reg_state *src_reg)
15153 {
15154 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15155 	u32 umax_val = src_reg->u32_max_value;
15156 	u32 umin_val = src_reg->u32_min_value;
15157 
15158 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15159 	 * be negative, then either:
15160 	 * 1) src_reg might be zero, so the sign bit of the result is
15161 	 *    unknown, so we lose our signed bounds
15162 	 * 2) it's known negative, thus the unsigned bounds capture the
15163 	 *    signed bounds
15164 	 * 3) the signed bounds cross zero, so they tell us nothing
15165 	 *    about the result
15166 	 * If the value in dst_reg is known nonnegative, then again the
15167 	 * unsigned bounds capture the signed bounds.
15168 	 * Thus, in all cases it suffices to blow away our signed bounds
15169 	 * and rely on inferring new ones from the unsigned bounds and
15170 	 * var_off of the result.
15171 	 */
15172 	dst_reg->s32_min_value = S32_MIN;
15173 	dst_reg->s32_max_value = S32_MAX;
15174 
15175 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
15176 	dst_reg->u32_min_value >>= umax_val;
15177 	dst_reg->u32_max_value >>= umin_val;
15178 
15179 	__mark_reg64_unbounded(dst_reg);
15180 	__update_reg32_bounds(dst_reg);
15181 }
15182 
15183 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
15184 			       struct bpf_reg_state *src_reg)
15185 {
15186 	u64 umax_val = src_reg->umax_value;
15187 	u64 umin_val = src_reg->umin_value;
15188 
15189 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15190 	 * be negative, then either:
15191 	 * 1) src_reg might be zero, so the sign bit of the result is
15192 	 *    unknown, so we lose our signed bounds
15193 	 * 2) it's known negative, thus the unsigned bounds capture the
15194 	 *    signed bounds
15195 	 * 3) the signed bounds cross zero, so they tell us nothing
15196 	 *    about the result
15197 	 * If the value in dst_reg is known nonnegative, then again the
15198 	 * unsigned bounds capture the signed bounds.
15199 	 * Thus, in all cases it suffices to blow away our signed bounds
15200 	 * and rely on inferring new ones from the unsigned bounds and
15201 	 * var_off of the result.
15202 	 */
15203 	dst_reg->smin_value = S64_MIN;
15204 	dst_reg->smax_value = S64_MAX;
15205 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
15206 	dst_reg->umin_value >>= umax_val;
15207 	dst_reg->umax_value >>= umin_val;
15208 
15209 	/* Its not easy to operate on alu32 bounds here because it depends
15210 	 * on bits being shifted in. Take easy way out and mark unbounded
15211 	 * so we can recalculate later from tnum.
15212 	 */
15213 	__mark_reg32_unbounded(dst_reg);
15214 	__update_reg_bounds(dst_reg);
15215 }
15216 
15217 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
15218 				  struct bpf_reg_state *src_reg)
15219 {
15220 	u64 umin_val = src_reg->u32_min_value;
15221 
15222 	/* Upon reaching here, src_known is true and
15223 	 * umax_val is equal to umin_val.
15224 	 */
15225 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
15226 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
15227 
15228 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
15229 
15230 	/* blow away the dst_reg umin_value/umax_value and rely on
15231 	 * dst_reg var_off to refine the result.
15232 	 */
15233 	dst_reg->u32_min_value = 0;
15234 	dst_reg->u32_max_value = U32_MAX;
15235 
15236 	__mark_reg64_unbounded(dst_reg);
15237 	__update_reg32_bounds(dst_reg);
15238 }
15239 
15240 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
15241 				struct bpf_reg_state *src_reg)
15242 {
15243 	u64 umin_val = src_reg->umin_value;
15244 
15245 	/* Upon reaching here, src_known is true and umax_val is equal
15246 	 * to umin_val.
15247 	 */
15248 	dst_reg->smin_value >>= umin_val;
15249 	dst_reg->smax_value >>= umin_val;
15250 
15251 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
15252 
15253 	/* blow away the dst_reg umin_value/umax_value and rely on
15254 	 * dst_reg var_off to refine the result.
15255 	 */
15256 	dst_reg->umin_value = 0;
15257 	dst_reg->umax_value = U64_MAX;
15258 
15259 	/* Its not easy to operate on alu32 bounds here because it depends
15260 	 * on bits being shifted in from upper 32-bits. Take easy way out
15261 	 * and mark unbounded so we can recalculate later from tnum.
15262 	 */
15263 	__mark_reg32_unbounded(dst_reg);
15264 	__update_reg_bounds(dst_reg);
15265 }
15266 
15267 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
15268 					     const struct bpf_reg_state *src_reg)
15269 {
15270 	bool src_is_const = false;
15271 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
15272 
15273 	if (insn_bitness == 32) {
15274 		if (tnum_subreg_is_const(src_reg->var_off)
15275 		    && src_reg->s32_min_value == src_reg->s32_max_value
15276 		    && src_reg->u32_min_value == src_reg->u32_max_value)
15277 			src_is_const = true;
15278 	} else {
15279 		if (tnum_is_const(src_reg->var_off)
15280 		    && src_reg->smin_value == src_reg->smax_value
15281 		    && src_reg->umin_value == src_reg->umax_value)
15282 			src_is_const = true;
15283 	}
15284 
15285 	switch (BPF_OP(insn->code)) {
15286 	case BPF_ADD:
15287 	case BPF_SUB:
15288 	case BPF_NEG:
15289 	case BPF_AND:
15290 	case BPF_XOR:
15291 	case BPF_OR:
15292 	case BPF_MUL:
15293 		return true;
15294 
15295 	/* Shift operators range is only computable if shift dimension operand
15296 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
15297 	 * includes shifts by a negative number.
15298 	 */
15299 	case BPF_LSH:
15300 	case BPF_RSH:
15301 	case BPF_ARSH:
15302 		return (src_is_const && src_reg->umax_value < insn_bitness);
15303 	default:
15304 		return false;
15305 	}
15306 }
15307 
15308 /* WARNING: This function does calculations on 64-bit values, but the actual
15309  * execution may occur on 32-bit values. Therefore, things like bitshifts
15310  * need extra checks in the 32-bit case.
15311  */
15312 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
15313 				      struct bpf_insn *insn,
15314 				      struct bpf_reg_state *dst_reg,
15315 				      struct bpf_reg_state src_reg)
15316 {
15317 	u8 opcode = BPF_OP(insn->code);
15318 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15319 	int ret;
15320 
15321 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
15322 		__mark_reg_unknown(env, dst_reg);
15323 		return 0;
15324 	}
15325 
15326 	if (sanitize_needed(opcode)) {
15327 		ret = sanitize_val_alu(env, insn);
15328 		if (ret < 0)
15329 			return sanitize_err(env, insn, ret, NULL, NULL);
15330 	}
15331 
15332 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
15333 	 * There are two classes of instructions: The first class we track both
15334 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
15335 	 * greatest amount of precision when alu operations are mixed with jmp32
15336 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
15337 	 * and BPF_OR. This is possible because these ops have fairly easy to
15338 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
15339 	 * See alu32 verifier tests for examples. The second class of
15340 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
15341 	 * with regards to tracking sign/unsigned bounds because the bits may
15342 	 * cross subreg boundaries in the alu64 case. When this happens we mark
15343 	 * the reg unbounded in the subreg bound space and use the resulting
15344 	 * tnum to calculate an approximation of the sign/unsigned bounds.
15345 	 */
15346 	switch (opcode) {
15347 	case BPF_ADD:
15348 		scalar32_min_max_add(dst_reg, &src_reg);
15349 		scalar_min_max_add(dst_reg, &src_reg);
15350 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
15351 		break;
15352 	case BPF_SUB:
15353 		scalar32_min_max_sub(dst_reg, &src_reg);
15354 		scalar_min_max_sub(dst_reg, &src_reg);
15355 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
15356 		break;
15357 	case BPF_NEG:
15358 		env->fake_reg[0] = *dst_reg;
15359 		__mark_reg_known(dst_reg, 0);
15360 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
15361 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
15362 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
15363 		break;
15364 	case BPF_MUL:
15365 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
15366 		scalar32_min_max_mul(dst_reg, &src_reg);
15367 		scalar_min_max_mul(dst_reg, &src_reg);
15368 		break;
15369 	case BPF_AND:
15370 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
15371 		scalar32_min_max_and(dst_reg, &src_reg);
15372 		scalar_min_max_and(dst_reg, &src_reg);
15373 		break;
15374 	case BPF_OR:
15375 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
15376 		scalar32_min_max_or(dst_reg, &src_reg);
15377 		scalar_min_max_or(dst_reg, &src_reg);
15378 		break;
15379 	case BPF_XOR:
15380 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
15381 		scalar32_min_max_xor(dst_reg, &src_reg);
15382 		scalar_min_max_xor(dst_reg, &src_reg);
15383 		break;
15384 	case BPF_LSH:
15385 		if (alu32)
15386 			scalar32_min_max_lsh(dst_reg, &src_reg);
15387 		else
15388 			scalar_min_max_lsh(dst_reg, &src_reg);
15389 		break;
15390 	case BPF_RSH:
15391 		if (alu32)
15392 			scalar32_min_max_rsh(dst_reg, &src_reg);
15393 		else
15394 			scalar_min_max_rsh(dst_reg, &src_reg);
15395 		break;
15396 	case BPF_ARSH:
15397 		if (alu32)
15398 			scalar32_min_max_arsh(dst_reg, &src_reg);
15399 		else
15400 			scalar_min_max_arsh(dst_reg, &src_reg);
15401 		break;
15402 	default:
15403 		break;
15404 	}
15405 
15406 	/* ALU32 ops are zero extended into 64bit register */
15407 	if (alu32)
15408 		zext_32_to_64(dst_reg);
15409 	reg_bounds_sync(dst_reg);
15410 	return 0;
15411 }
15412 
15413 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
15414  * and var_off.
15415  */
15416 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
15417 				   struct bpf_insn *insn)
15418 {
15419 	struct bpf_verifier_state *vstate = env->cur_state;
15420 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15421 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
15422 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
15423 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15424 	u8 opcode = BPF_OP(insn->code);
15425 	int err;
15426 
15427 	dst_reg = &regs[insn->dst_reg];
15428 	src_reg = NULL;
15429 
15430 	if (dst_reg->type == PTR_TO_ARENA) {
15431 		struct bpf_insn_aux_data *aux = cur_aux(env);
15432 
15433 		if (BPF_CLASS(insn->code) == BPF_ALU64)
15434 			/*
15435 			 * 32-bit operations zero upper bits automatically.
15436 			 * 64-bit operations need to be converted to 32.
15437 			 */
15438 			aux->needs_zext = true;
15439 
15440 		/* Any arithmetic operations are allowed on arena pointers */
15441 		return 0;
15442 	}
15443 
15444 	if (dst_reg->type != SCALAR_VALUE)
15445 		ptr_reg = dst_reg;
15446 
15447 	if (BPF_SRC(insn->code) == BPF_X) {
15448 		src_reg = &regs[insn->src_reg];
15449 		if (src_reg->type != SCALAR_VALUE) {
15450 			if (dst_reg->type != SCALAR_VALUE) {
15451 				/* Combining two pointers by any ALU op yields
15452 				 * an arbitrary scalar. Disallow all math except
15453 				 * pointer subtraction
15454 				 */
15455 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
15456 					mark_reg_unknown(env, regs, insn->dst_reg);
15457 					return 0;
15458 				}
15459 				verbose(env, "R%d pointer %s pointer prohibited\n",
15460 					insn->dst_reg,
15461 					bpf_alu_string[opcode >> 4]);
15462 				return -EACCES;
15463 			} else {
15464 				/* scalar += pointer
15465 				 * This is legal, but we have to reverse our
15466 				 * src/dest handling in computing the range
15467 				 */
15468 				err = mark_chain_precision(env, insn->dst_reg);
15469 				if (err)
15470 					return err;
15471 				return adjust_ptr_min_max_vals(env, insn,
15472 							       src_reg, dst_reg);
15473 			}
15474 		} else if (ptr_reg) {
15475 			/* pointer += scalar */
15476 			err = mark_chain_precision(env, insn->src_reg);
15477 			if (err)
15478 				return err;
15479 			return adjust_ptr_min_max_vals(env, insn,
15480 						       dst_reg, src_reg);
15481 		} else if (dst_reg->precise) {
15482 			/* if dst_reg is precise, src_reg should be precise as well */
15483 			err = mark_chain_precision(env, insn->src_reg);
15484 			if (err)
15485 				return err;
15486 		}
15487 	} else {
15488 		/* Pretend the src is a reg with a known value, since we only
15489 		 * need to be able to read from this state.
15490 		 */
15491 		off_reg.type = SCALAR_VALUE;
15492 		__mark_reg_known(&off_reg, insn->imm);
15493 		src_reg = &off_reg;
15494 		if (ptr_reg) /* pointer += K */
15495 			return adjust_ptr_min_max_vals(env, insn,
15496 						       ptr_reg, src_reg);
15497 	}
15498 
15499 	/* Got here implies adding two SCALAR_VALUEs */
15500 	if (WARN_ON_ONCE(ptr_reg)) {
15501 		print_verifier_state(env, vstate, vstate->curframe, true);
15502 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
15503 		return -EFAULT;
15504 	}
15505 	if (WARN_ON(!src_reg)) {
15506 		print_verifier_state(env, vstate, vstate->curframe, true);
15507 		verbose(env, "verifier internal error: no src_reg\n");
15508 		return -EFAULT;
15509 	}
15510 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
15511 	if (err)
15512 		return err;
15513 	/*
15514 	 * Compilers can generate the code
15515 	 * r1 = r2
15516 	 * r1 += 0x1
15517 	 * if r2 < 1000 goto ...
15518 	 * use r1 in memory access
15519 	 * So for 64-bit alu remember constant delta between r2 and r1 and
15520 	 * update r1 after 'if' condition.
15521 	 */
15522 	if (env->bpf_capable &&
15523 	    BPF_OP(insn->code) == BPF_ADD && !alu32 &&
15524 	    dst_reg->id && is_reg_const(src_reg, false)) {
15525 		u64 val = reg_const_value(src_reg, false);
15526 
15527 		if ((dst_reg->id & BPF_ADD_CONST) ||
15528 		    /* prevent overflow in sync_linked_regs() later */
15529 		    val > (u32)S32_MAX) {
15530 			/*
15531 			 * If the register already went through rX += val
15532 			 * we cannot accumulate another val into rx->off.
15533 			 */
15534 			dst_reg->off = 0;
15535 			dst_reg->id = 0;
15536 		} else {
15537 			dst_reg->id |= BPF_ADD_CONST;
15538 			dst_reg->off = val;
15539 		}
15540 	} else {
15541 		/*
15542 		 * Make sure ID is cleared otherwise dst_reg min/max could be
15543 		 * incorrectly propagated into other registers by sync_linked_regs()
15544 		 */
15545 		dst_reg->id = 0;
15546 	}
15547 	return 0;
15548 }
15549 
15550 /* check validity of 32-bit and 64-bit arithmetic operations */
15551 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
15552 {
15553 	struct bpf_reg_state *regs = cur_regs(env);
15554 	u8 opcode = BPF_OP(insn->code);
15555 	int err;
15556 
15557 	if (opcode == BPF_END || opcode == BPF_NEG) {
15558 		if (opcode == BPF_NEG) {
15559 			if (BPF_SRC(insn->code) != BPF_K ||
15560 			    insn->src_reg != BPF_REG_0 ||
15561 			    insn->off != 0 || insn->imm != 0) {
15562 				verbose(env, "BPF_NEG uses reserved fields\n");
15563 				return -EINVAL;
15564 			}
15565 		} else {
15566 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
15567 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
15568 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
15569 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
15570 				verbose(env, "BPF_END uses reserved fields\n");
15571 				return -EINVAL;
15572 			}
15573 		}
15574 
15575 		/* check src operand */
15576 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15577 		if (err)
15578 			return err;
15579 
15580 		if (is_pointer_value(env, insn->dst_reg)) {
15581 			verbose(env, "R%d pointer arithmetic prohibited\n",
15582 				insn->dst_reg);
15583 			return -EACCES;
15584 		}
15585 
15586 		/* check dest operand */
15587 		if (opcode == BPF_NEG) {
15588 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15589 			err = err ?: adjust_scalar_min_max_vals(env, insn,
15590 							 &regs[insn->dst_reg],
15591 							 regs[insn->dst_reg]);
15592 		} else {
15593 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
15594 		}
15595 		if (err)
15596 			return err;
15597 
15598 	} else if (opcode == BPF_MOV) {
15599 
15600 		if (BPF_SRC(insn->code) == BPF_X) {
15601 			if (BPF_CLASS(insn->code) == BPF_ALU) {
15602 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
15603 				    insn->imm) {
15604 					verbose(env, "BPF_MOV uses reserved fields\n");
15605 					return -EINVAL;
15606 				}
15607 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
15608 				if (insn->imm != 1 && insn->imm != 1u << 16) {
15609 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
15610 					return -EINVAL;
15611 				}
15612 				if (!env->prog->aux->arena) {
15613 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
15614 					return -EINVAL;
15615 				}
15616 			} else {
15617 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
15618 				     insn->off != 32) || insn->imm) {
15619 					verbose(env, "BPF_MOV uses reserved fields\n");
15620 					return -EINVAL;
15621 				}
15622 			}
15623 
15624 			/* check src operand */
15625 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15626 			if (err)
15627 				return err;
15628 		} else {
15629 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
15630 				verbose(env, "BPF_MOV uses reserved fields\n");
15631 				return -EINVAL;
15632 			}
15633 		}
15634 
15635 		/* check dest operand, mark as required later */
15636 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15637 		if (err)
15638 			return err;
15639 
15640 		if (BPF_SRC(insn->code) == BPF_X) {
15641 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
15642 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
15643 
15644 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15645 				if (insn->imm) {
15646 					/* off == BPF_ADDR_SPACE_CAST */
15647 					mark_reg_unknown(env, regs, insn->dst_reg);
15648 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
15649 						dst_reg->type = PTR_TO_ARENA;
15650 						/* PTR_TO_ARENA is 32-bit */
15651 						dst_reg->subreg_def = env->insn_idx + 1;
15652 					}
15653 				} else if (insn->off == 0) {
15654 					/* case: R1 = R2
15655 					 * copy register state to dest reg
15656 					 */
15657 					assign_scalar_id_before_mov(env, src_reg);
15658 					copy_register_state(dst_reg, src_reg);
15659 					dst_reg->live |= REG_LIVE_WRITTEN;
15660 					dst_reg->subreg_def = DEF_NOT_SUBREG;
15661 				} else {
15662 					/* case: R1 = (s8, s16 s32)R2 */
15663 					if (is_pointer_value(env, insn->src_reg)) {
15664 						verbose(env,
15665 							"R%d sign-extension part of pointer\n",
15666 							insn->src_reg);
15667 						return -EACCES;
15668 					} else if (src_reg->type == SCALAR_VALUE) {
15669 						bool no_sext;
15670 
15671 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15672 						if (no_sext)
15673 							assign_scalar_id_before_mov(env, src_reg);
15674 						copy_register_state(dst_reg, src_reg);
15675 						if (!no_sext)
15676 							dst_reg->id = 0;
15677 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
15678 						dst_reg->live |= REG_LIVE_WRITTEN;
15679 						dst_reg->subreg_def = DEF_NOT_SUBREG;
15680 					} else {
15681 						mark_reg_unknown(env, regs, insn->dst_reg);
15682 					}
15683 				}
15684 			} else {
15685 				/* R1 = (u32) R2 */
15686 				if (is_pointer_value(env, insn->src_reg)) {
15687 					verbose(env,
15688 						"R%d partial copy of pointer\n",
15689 						insn->src_reg);
15690 					return -EACCES;
15691 				} else if (src_reg->type == SCALAR_VALUE) {
15692 					if (insn->off == 0) {
15693 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
15694 
15695 						if (is_src_reg_u32)
15696 							assign_scalar_id_before_mov(env, src_reg);
15697 						copy_register_state(dst_reg, src_reg);
15698 						/* Make sure ID is cleared if src_reg is not in u32
15699 						 * range otherwise dst_reg min/max could be incorrectly
15700 						 * propagated into src_reg by sync_linked_regs()
15701 						 */
15702 						if (!is_src_reg_u32)
15703 							dst_reg->id = 0;
15704 						dst_reg->live |= REG_LIVE_WRITTEN;
15705 						dst_reg->subreg_def = env->insn_idx + 1;
15706 					} else {
15707 						/* case: W1 = (s8, s16)W2 */
15708 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15709 
15710 						if (no_sext)
15711 							assign_scalar_id_before_mov(env, src_reg);
15712 						copy_register_state(dst_reg, src_reg);
15713 						if (!no_sext)
15714 							dst_reg->id = 0;
15715 						dst_reg->live |= REG_LIVE_WRITTEN;
15716 						dst_reg->subreg_def = env->insn_idx + 1;
15717 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
15718 					}
15719 				} else {
15720 					mark_reg_unknown(env, regs,
15721 							 insn->dst_reg);
15722 				}
15723 				zext_32_to_64(dst_reg);
15724 				reg_bounds_sync(dst_reg);
15725 			}
15726 		} else {
15727 			/* case: R = imm
15728 			 * remember the value we stored into this reg
15729 			 */
15730 			/* clear any state __mark_reg_known doesn't set */
15731 			mark_reg_unknown(env, regs, insn->dst_reg);
15732 			regs[insn->dst_reg].type = SCALAR_VALUE;
15733 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15734 				__mark_reg_known(regs + insn->dst_reg,
15735 						 insn->imm);
15736 			} else {
15737 				__mark_reg_known(regs + insn->dst_reg,
15738 						 (u32)insn->imm);
15739 			}
15740 		}
15741 
15742 	} else if (opcode > BPF_END) {
15743 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
15744 		return -EINVAL;
15745 
15746 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
15747 
15748 		if (BPF_SRC(insn->code) == BPF_X) {
15749 			if (insn->imm != 0 || insn->off > 1 ||
15750 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15751 				verbose(env, "BPF_ALU uses reserved fields\n");
15752 				return -EINVAL;
15753 			}
15754 			/* check src1 operand */
15755 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15756 			if (err)
15757 				return err;
15758 		} else {
15759 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
15760 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15761 				verbose(env, "BPF_ALU uses reserved fields\n");
15762 				return -EINVAL;
15763 			}
15764 		}
15765 
15766 		/* check src2 operand */
15767 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15768 		if (err)
15769 			return err;
15770 
15771 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
15772 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
15773 			verbose(env, "div by zero\n");
15774 			return -EINVAL;
15775 		}
15776 
15777 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
15778 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
15779 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
15780 
15781 			if (insn->imm < 0 || insn->imm >= size) {
15782 				verbose(env, "invalid shift %d\n", insn->imm);
15783 				return -EINVAL;
15784 			}
15785 		}
15786 
15787 		/* check dest operand */
15788 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15789 		err = err ?: adjust_reg_min_max_vals(env, insn);
15790 		if (err)
15791 			return err;
15792 	}
15793 
15794 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
15795 }
15796 
15797 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
15798 				   struct bpf_reg_state *dst_reg,
15799 				   enum bpf_reg_type type,
15800 				   bool range_right_open)
15801 {
15802 	struct bpf_func_state *state;
15803 	struct bpf_reg_state *reg;
15804 	int new_range;
15805 
15806 	if (dst_reg->off < 0 ||
15807 	    (dst_reg->off == 0 && range_right_open))
15808 		/* This doesn't give us any range */
15809 		return;
15810 
15811 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
15812 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
15813 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
15814 		 * than pkt_end, but that's because it's also less than pkt.
15815 		 */
15816 		return;
15817 
15818 	new_range = dst_reg->off;
15819 	if (range_right_open)
15820 		new_range++;
15821 
15822 	/* Examples for register markings:
15823 	 *
15824 	 * pkt_data in dst register:
15825 	 *
15826 	 *   r2 = r3;
15827 	 *   r2 += 8;
15828 	 *   if (r2 > pkt_end) goto <handle exception>
15829 	 *   <access okay>
15830 	 *
15831 	 *   r2 = r3;
15832 	 *   r2 += 8;
15833 	 *   if (r2 < pkt_end) goto <access okay>
15834 	 *   <handle exception>
15835 	 *
15836 	 *   Where:
15837 	 *     r2 == dst_reg, pkt_end == src_reg
15838 	 *     r2=pkt(id=n,off=8,r=0)
15839 	 *     r3=pkt(id=n,off=0,r=0)
15840 	 *
15841 	 * pkt_data in src register:
15842 	 *
15843 	 *   r2 = r3;
15844 	 *   r2 += 8;
15845 	 *   if (pkt_end >= r2) goto <access okay>
15846 	 *   <handle exception>
15847 	 *
15848 	 *   r2 = r3;
15849 	 *   r2 += 8;
15850 	 *   if (pkt_end <= r2) goto <handle exception>
15851 	 *   <access okay>
15852 	 *
15853 	 *   Where:
15854 	 *     pkt_end == dst_reg, r2 == src_reg
15855 	 *     r2=pkt(id=n,off=8,r=0)
15856 	 *     r3=pkt(id=n,off=0,r=0)
15857 	 *
15858 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
15859 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
15860 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
15861 	 * the check.
15862 	 */
15863 
15864 	/* If our ids match, then we must have the same max_value.  And we
15865 	 * don't care about the other reg's fixed offset, since if it's too big
15866 	 * the range won't allow anything.
15867 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
15868 	 */
15869 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15870 		if (reg->type == type && reg->id == dst_reg->id)
15871 			/* keep the maximum range already checked */
15872 			reg->range = max(reg->range, new_range);
15873 	}));
15874 }
15875 
15876 /*
15877  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
15878  */
15879 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15880 				  u8 opcode, bool is_jmp32)
15881 {
15882 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
15883 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
15884 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
15885 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
15886 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
15887 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
15888 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
15889 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
15890 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
15891 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
15892 
15893 	switch (opcode) {
15894 	case BPF_JEQ:
15895 		/* constants, umin/umax and smin/smax checks would be
15896 		 * redundant in this case because they all should match
15897 		 */
15898 		if (tnum_is_const(t1) && tnum_is_const(t2))
15899 			return t1.value == t2.value;
15900 		/* non-overlapping ranges */
15901 		if (umin1 > umax2 || umax1 < umin2)
15902 			return 0;
15903 		if (smin1 > smax2 || smax1 < smin2)
15904 			return 0;
15905 		if (!is_jmp32) {
15906 			/* if 64-bit ranges are inconclusive, see if we can
15907 			 * utilize 32-bit subrange knowledge to eliminate
15908 			 * branches that can't be taken a priori
15909 			 */
15910 			if (reg1->u32_min_value > reg2->u32_max_value ||
15911 			    reg1->u32_max_value < reg2->u32_min_value)
15912 				return 0;
15913 			if (reg1->s32_min_value > reg2->s32_max_value ||
15914 			    reg1->s32_max_value < reg2->s32_min_value)
15915 				return 0;
15916 		}
15917 		break;
15918 	case BPF_JNE:
15919 		/* constants, umin/umax and smin/smax checks would be
15920 		 * redundant in this case because they all should match
15921 		 */
15922 		if (tnum_is_const(t1) && tnum_is_const(t2))
15923 			return t1.value != t2.value;
15924 		/* non-overlapping ranges */
15925 		if (umin1 > umax2 || umax1 < umin2)
15926 			return 1;
15927 		if (smin1 > smax2 || smax1 < smin2)
15928 			return 1;
15929 		if (!is_jmp32) {
15930 			/* if 64-bit ranges are inconclusive, see if we can
15931 			 * utilize 32-bit subrange knowledge to eliminate
15932 			 * branches that can't be taken a priori
15933 			 */
15934 			if (reg1->u32_min_value > reg2->u32_max_value ||
15935 			    reg1->u32_max_value < reg2->u32_min_value)
15936 				return 1;
15937 			if (reg1->s32_min_value > reg2->s32_max_value ||
15938 			    reg1->s32_max_value < reg2->s32_min_value)
15939 				return 1;
15940 		}
15941 		break;
15942 	case BPF_JSET:
15943 		if (!is_reg_const(reg2, is_jmp32)) {
15944 			swap(reg1, reg2);
15945 			swap(t1, t2);
15946 		}
15947 		if (!is_reg_const(reg2, is_jmp32))
15948 			return -1;
15949 		if ((~t1.mask & t1.value) & t2.value)
15950 			return 1;
15951 		if (!((t1.mask | t1.value) & t2.value))
15952 			return 0;
15953 		break;
15954 	case BPF_JGT:
15955 		if (umin1 > umax2)
15956 			return 1;
15957 		else if (umax1 <= umin2)
15958 			return 0;
15959 		break;
15960 	case BPF_JSGT:
15961 		if (smin1 > smax2)
15962 			return 1;
15963 		else if (smax1 <= smin2)
15964 			return 0;
15965 		break;
15966 	case BPF_JLT:
15967 		if (umax1 < umin2)
15968 			return 1;
15969 		else if (umin1 >= umax2)
15970 			return 0;
15971 		break;
15972 	case BPF_JSLT:
15973 		if (smax1 < smin2)
15974 			return 1;
15975 		else if (smin1 >= smax2)
15976 			return 0;
15977 		break;
15978 	case BPF_JGE:
15979 		if (umin1 >= umax2)
15980 			return 1;
15981 		else if (umax1 < umin2)
15982 			return 0;
15983 		break;
15984 	case BPF_JSGE:
15985 		if (smin1 >= smax2)
15986 			return 1;
15987 		else if (smax1 < smin2)
15988 			return 0;
15989 		break;
15990 	case BPF_JLE:
15991 		if (umax1 <= umin2)
15992 			return 1;
15993 		else if (umin1 > umax2)
15994 			return 0;
15995 		break;
15996 	case BPF_JSLE:
15997 		if (smax1 <= smin2)
15998 			return 1;
15999 		else if (smin1 > smax2)
16000 			return 0;
16001 		break;
16002 	}
16003 
16004 	return -1;
16005 }
16006 
16007 static int flip_opcode(u32 opcode)
16008 {
16009 	/* How can we transform "a <op> b" into "b <op> a"? */
16010 	static const u8 opcode_flip[16] = {
16011 		/* these stay the same */
16012 		[BPF_JEQ  >> 4] = BPF_JEQ,
16013 		[BPF_JNE  >> 4] = BPF_JNE,
16014 		[BPF_JSET >> 4] = BPF_JSET,
16015 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
16016 		[BPF_JGE  >> 4] = BPF_JLE,
16017 		[BPF_JGT  >> 4] = BPF_JLT,
16018 		[BPF_JLE  >> 4] = BPF_JGE,
16019 		[BPF_JLT  >> 4] = BPF_JGT,
16020 		[BPF_JSGE >> 4] = BPF_JSLE,
16021 		[BPF_JSGT >> 4] = BPF_JSLT,
16022 		[BPF_JSLE >> 4] = BPF_JSGE,
16023 		[BPF_JSLT >> 4] = BPF_JSGT
16024 	};
16025 	return opcode_flip[opcode >> 4];
16026 }
16027 
16028 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
16029 				   struct bpf_reg_state *src_reg,
16030 				   u8 opcode)
16031 {
16032 	struct bpf_reg_state *pkt;
16033 
16034 	if (src_reg->type == PTR_TO_PACKET_END) {
16035 		pkt = dst_reg;
16036 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
16037 		pkt = src_reg;
16038 		opcode = flip_opcode(opcode);
16039 	} else {
16040 		return -1;
16041 	}
16042 
16043 	if (pkt->range >= 0)
16044 		return -1;
16045 
16046 	switch (opcode) {
16047 	case BPF_JLE:
16048 		/* pkt <= pkt_end */
16049 		fallthrough;
16050 	case BPF_JGT:
16051 		/* pkt > pkt_end */
16052 		if (pkt->range == BEYOND_PKT_END)
16053 			/* pkt has at last one extra byte beyond pkt_end */
16054 			return opcode == BPF_JGT;
16055 		break;
16056 	case BPF_JLT:
16057 		/* pkt < pkt_end */
16058 		fallthrough;
16059 	case BPF_JGE:
16060 		/* pkt >= pkt_end */
16061 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
16062 			return opcode == BPF_JGE;
16063 		break;
16064 	}
16065 	return -1;
16066 }
16067 
16068 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
16069  * and return:
16070  *  1 - branch will be taken and "goto target" will be executed
16071  *  0 - branch will not be taken and fall-through to next insn
16072  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
16073  *      range [0,10]
16074  */
16075 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16076 			   u8 opcode, bool is_jmp32)
16077 {
16078 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
16079 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
16080 
16081 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
16082 		u64 val;
16083 
16084 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
16085 		if (!is_reg_const(reg2, is_jmp32)) {
16086 			opcode = flip_opcode(opcode);
16087 			swap(reg1, reg2);
16088 		}
16089 		/* and ensure that reg2 is a constant */
16090 		if (!is_reg_const(reg2, is_jmp32))
16091 			return -1;
16092 
16093 		if (!reg_not_null(reg1))
16094 			return -1;
16095 
16096 		/* If pointer is valid tests against zero will fail so we can
16097 		 * use this to direct branch taken.
16098 		 */
16099 		val = reg_const_value(reg2, is_jmp32);
16100 		if (val != 0)
16101 			return -1;
16102 
16103 		switch (opcode) {
16104 		case BPF_JEQ:
16105 			return 0;
16106 		case BPF_JNE:
16107 			return 1;
16108 		default:
16109 			return -1;
16110 		}
16111 	}
16112 
16113 	/* now deal with two scalars, but not necessarily constants */
16114 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
16115 }
16116 
16117 /* Opcode that corresponds to a *false* branch condition.
16118  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
16119  */
16120 static u8 rev_opcode(u8 opcode)
16121 {
16122 	switch (opcode) {
16123 	case BPF_JEQ:		return BPF_JNE;
16124 	case BPF_JNE:		return BPF_JEQ;
16125 	/* JSET doesn't have it's reverse opcode in BPF, so add
16126 	 * BPF_X flag to denote the reverse of that operation
16127 	 */
16128 	case BPF_JSET:		return BPF_JSET | BPF_X;
16129 	case BPF_JSET | BPF_X:	return BPF_JSET;
16130 	case BPF_JGE:		return BPF_JLT;
16131 	case BPF_JGT:		return BPF_JLE;
16132 	case BPF_JLE:		return BPF_JGT;
16133 	case BPF_JLT:		return BPF_JGE;
16134 	case BPF_JSGE:		return BPF_JSLT;
16135 	case BPF_JSGT:		return BPF_JSLE;
16136 	case BPF_JSLE:		return BPF_JSGT;
16137 	case BPF_JSLT:		return BPF_JSGE;
16138 	default:		return 0;
16139 	}
16140 }
16141 
16142 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
16143 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16144 				u8 opcode, bool is_jmp32)
16145 {
16146 	struct tnum t;
16147 	u64 val;
16148 
16149 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
16150 	switch (opcode) {
16151 	case BPF_JGE:
16152 	case BPF_JGT:
16153 	case BPF_JSGE:
16154 	case BPF_JSGT:
16155 		opcode = flip_opcode(opcode);
16156 		swap(reg1, reg2);
16157 		break;
16158 	default:
16159 		break;
16160 	}
16161 
16162 	switch (opcode) {
16163 	case BPF_JEQ:
16164 		if (is_jmp32) {
16165 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16166 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16167 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16168 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16169 			reg2->u32_min_value = reg1->u32_min_value;
16170 			reg2->u32_max_value = reg1->u32_max_value;
16171 			reg2->s32_min_value = reg1->s32_min_value;
16172 			reg2->s32_max_value = reg1->s32_max_value;
16173 
16174 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
16175 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16176 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
16177 		} else {
16178 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
16179 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16180 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
16181 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16182 			reg2->umin_value = reg1->umin_value;
16183 			reg2->umax_value = reg1->umax_value;
16184 			reg2->smin_value = reg1->smin_value;
16185 			reg2->smax_value = reg1->smax_value;
16186 
16187 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
16188 			reg2->var_off = reg1->var_off;
16189 		}
16190 		break;
16191 	case BPF_JNE:
16192 		if (!is_reg_const(reg2, is_jmp32))
16193 			swap(reg1, reg2);
16194 		if (!is_reg_const(reg2, is_jmp32))
16195 			break;
16196 
16197 		/* try to recompute the bound of reg1 if reg2 is a const and
16198 		 * is exactly the edge of reg1.
16199 		 */
16200 		val = reg_const_value(reg2, is_jmp32);
16201 		if (is_jmp32) {
16202 			/* u32_min_value is not equal to 0xffffffff at this point,
16203 			 * because otherwise u32_max_value is 0xffffffff as well,
16204 			 * in such a case both reg1 and reg2 would be constants,
16205 			 * jump would be predicted and reg_set_min_max() won't
16206 			 * be called.
16207 			 *
16208 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
16209 			 * below.
16210 			 */
16211 			if (reg1->u32_min_value == (u32)val)
16212 				reg1->u32_min_value++;
16213 			if (reg1->u32_max_value == (u32)val)
16214 				reg1->u32_max_value--;
16215 			if (reg1->s32_min_value == (s32)val)
16216 				reg1->s32_min_value++;
16217 			if (reg1->s32_max_value == (s32)val)
16218 				reg1->s32_max_value--;
16219 		} else {
16220 			if (reg1->umin_value == (u64)val)
16221 				reg1->umin_value++;
16222 			if (reg1->umax_value == (u64)val)
16223 				reg1->umax_value--;
16224 			if (reg1->smin_value == (s64)val)
16225 				reg1->smin_value++;
16226 			if (reg1->smax_value == (s64)val)
16227 				reg1->smax_value--;
16228 		}
16229 		break;
16230 	case BPF_JSET:
16231 		if (!is_reg_const(reg2, is_jmp32))
16232 			swap(reg1, reg2);
16233 		if (!is_reg_const(reg2, is_jmp32))
16234 			break;
16235 		val = reg_const_value(reg2, is_jmp32);
16236 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
16237 		 * requires single bit to learn something useful. E.g., if we
16238 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
16239 		 * are actually set? We can learn something definite only if
16240 		 * it's a single-bit value to begin with.
16241 		 *
16242 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
16243 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
16244 		 * bit 1 is set, which we can readily use in adjustments.
16245 		 */
16246 		if (!is_power_of_2(val))
16247 			break;
16248 		if (is_jmp32) {
16249 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
16250 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16251 		} else {
16252 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
16253 		}
16254 		break;
16255 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
16256 		if (!is_reg_const(reg2, is_jmp32))
16257 			swap(reg1, reg2);
16258 		if (!is_reg_const(reg2, is_jmp32))
16259 			break;
16260 		val = reg_const_value(reg2, is_jmp32);
16261 		/* Forget the ranges before narrowing tnums, to avoid invariant
16262 		 * violations if we're on a dead branch.
16263 		 */
16264 		__mark_reg_unbounded(reg1);
16265 		if (is_jmp32) {
16266 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
16267 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16268 		} else {
16269 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
16270 		}
16271 		break;
16272 	case BPF_JLE:
16273 		if (is_jmp32) {
16274 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16275 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16276 		} else {
16277 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16278 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
16279 		}
16280 		break;
16281 	case BPF_JLT:
16282 		if (is_jmp32) {
16283 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
16284 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
16285 		} else {
16286 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
16287 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
16288 		}
16289 		break;
16290 	case BPF_JSLE:
16291 		if (is_jmp32) {
16292 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16293 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16294 		} else {
16295 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16296 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
16297 		}
16298 		break;
16299 	case BPF_JSLT:
16300 		if (is_jmp32) {
16301 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
16302 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
16303 		} else {
16304 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
16305 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
16306 		}
16307 		break;
16308 	default:
16309 		return;
16310 	}
16311 }
16312 
16313 /* Adjusts the register min/max values in the case that the dst_reg and
16314  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
16315  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
16316  * Technically we can do similar adjustments for pointers to the same object,
16317  * but we don't support that right now.
16318  */
16319 static int reg_set_min_max(struct bpf_verifier_env *env,
16320 			   struct bpf_reg_state *true_reg1,
16321 			   struct bpf_reg_state *true_reg2,
16322 			   struct bpf_reg_state *false_reg1,
16323 			   struct bpf_reg_state *false_reg2,
16324 			   u8 opcode, bool is_jmp32)
16325 {
16326 	int err;
16327 
16328 	/* If either register is a pointer, we can't learn anything about its
16329 	 * variable offset from the compare (unless they were a pointer into
16330 	 * the same object, but we don't bother with that).
16331 	 */
16332 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
16333 		return 0;
16334 
16335 	/* fallthrough (FALSE) branch */
16336 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
16337 	reg_bounds_sync(false_reg1);
16338 	reg_bounds_sync(false_reg2);
16339 
16340 	/* jump (TRUE) branch */
16341 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
16342 	reg_bounds_sync(true_reg1);
16343 	reg_bounds_sync(true_reg2);
16344 
16345 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
16346 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
16347 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
16348 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
16349 	return err;
16350 }
16351 
16352 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
16353 				 struct bpf_reg_state *reg, u32 id,
16354 				 bool is_null)
16355 {
16356 	if (type_may_be_null(reg->type) && reg->id == id &&
16357 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
16358 		/* Old offset (both fixed and variable parts) should have been
16359 		 * known-zero, because we don't allow pointer arithmetic on
16360 		 * pointers that might be NULL. If we see this happening, don't
16361 		 * convert the register.
16362 		 *
16363 		 * But in some cases, some helpers that return local kptrs
16364 		 * advance offset for the returned pointer. In those cases, it
16365 		 * is fine to expect to see reg->off.
16366 		 */
16367 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
16368 			return;
16369 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
16370 		    WARN_ON_ONCE(reg->off))
16371 			return;
16372 
16373 		if (is_null) {
16374 			reg->type = SCALAR_VALUE;
16375 			/* We don't need id and ref_obj_id from this point
16376 			 * onwards anymore, thus we should better reset it,
16377 			 * so that state pruning has chances to take effect.
16378 			 */
16379 			reg->id = 0;
16380 			reg->ref_obj_id = 0;
16381 
16382 			return;
16383 		}
16384 
16385 		mark_ptr_not_null_reg(reg);
16386 
16387 		if (!reg_may_point_to_spin_lock(reg)) {
16388 			/* For not-NULL ptr, reg->ref_obj_id will be reset
16389 			 * in release_reference().
16390 			 *
16391 			 * reg->id is still used by spin_lock ptr. Other
16392 			 * than spin_lock ptr type, reg->id can be reset.
16393 			 */
16394 			reg->id = 0;
16395 		}
16396 	}
16397 }
16398 
16399 /* The logic is similar to find_good_pkt_pointers(), both could eventually
16400  * be folded together at some point.
16401  */
16402 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
16403 				  bool is_null)
16404 {
16405 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
16406 	struct bpf_reg_state *regs = state->regs, *reg;
16407 	u32 ref_obj_id = regs[regno].ref_obj_id;
16408 	u32 id = regs[regno].id;
16409 
16410 	if (ref_obj_id && ref_obj_id == id && is_null)
16411 		/* regs[regno] is in the " == NULL" branch.
16412 		 * No one could have freed the reference state before
16413 		 * doing the NULL check.
16414 		 */
16415 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
16416 
16417 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16418 		mark_ptr_or_null_reg(state, reg, id, is_null);
16419 	}));
16420 }
16421 
16422 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
16423 				   struct bpf_reg_state *dst_reg,
16424 				   struct bpf_reg_state *src_reg,
16425 				   struct bpf_verifier_state *this_branch,
16426 				   struct bpf_verifier_state *other_branch)
16427 {
16428 	if (BPF_SRC(insn->code) != BPF_X)
16429 		return false;
16430 
16431 	/* Pointers are always 64-bit. */
16432 	if (BPF_CLASS(insn->code) == BPF_JMP32)
16433 		return false;
16434 
16435 	switch (BPF_OP(insn->code)) {
16436 	case BPF_JGT:
16437 		if ((dst_reg->type == PTR_TO_PACKET &&
16438 		     src_reg->type == PTR_TO_PACKET_END) ||
16439 		    (dst_reg->type == PTR_TO_PACKET_META &&
16440 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16441 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
16442 			find_good_pkt_pointers(this_branch, dst_reg,
16443 					       dst_reg->type, false);
16444 			mark_pkt_end(other_branch, insn->dst_reg, true);
16445 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16446 			    src_reg->type == PTR_TO_PACKET) ||
16447 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16448 			    src_reg->type == PTR_TO_PACKET_META)) {
16449 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
16450 			find_good_pkt_pointers(other_branch, src_reg,
16451 					       src_reg->type, true);
16452 			mark_pkt_end(this_branch, insn->src_reg, false);
16453 		} else {
16454 			return false;
16455 		}
16456 		break;
16457 	case BPF_JLT:
16458 		if ((dst_reg->type == PTR_TO_PACKET &&
16459 		     src_reg->type == PTR_TO_PACKET_END) ||
16460 		    (dst_reg->type == PTR_TO_PACKET_META &&
16461 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16462 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
16463 			find_good_pkt_pointers(other_branch, dst_reg,
16464 					       dst_reg->type, true);
16465 			mark_pkt_end(this_branch, insn->dst_reg, false);
16466 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16467 			    src_reg->type == PTR_TO_PACKET) ||
16468 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16469 			    src_reg->type == PTR_TO_PACKET_META)) {
16470 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
16471 			find_good_pkt_pointers(this_branch, src_reg,
16472 					       src_reg->type, false);
16473 			mark_pkt_end(other_branch, insn->src_reg, true);
16474 		} else {
16475 			return false;
16476 		}
16477 		break;
16478 	case BPF_JGE:
16479 		if ((dst_reg->type == PTR_TO_PACKET &&
16480 		     src_reg->type == PTR_TO_PACKET_END) ||
16481 		    (dst_reg->type == PTR_TO_PACKET_META &&
16482 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16483 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
16484 			find_good_pkt_pointers(this_branch, dst_reg,
16485 					       dst_reg->type, true);
16486 			mark_pkt_end(other_branch, insn->dst_reg, false);
16487 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16488 			    src_reg->type == PTR_TO_PACKET) ||
16489 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16490 			    src_reg->type == PTR_TO_PACKET_META)) {
16491 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
16492 			find_good_pkt_pointers(other_branch, src_reg,
16493 					       src_reg->type, false);
16494 			mark_pkt_end(this_branch, insn->src_reg, true);
16495 		} else {
16496 			return false;
16497 		}
16498 		break;
16499 	case BPF_JLE:
16500 		if ((dst_reg->type == PTR_TO_PACKET &&
16501 		     src_reg->type == PTR_TO_PACKET_END) ||
16502 		    (dst_reg->type == PTR_TO_PACKET_META &&
16503 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16504 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
16505 			find_good_pkt_pointers(other_branch, dst_reg,
16506 					       dst_reg->type, false);
16507 			mark_pkt_end(this_branch, insn->dst_reg, true);
16508 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16509 			    src_reg->type == PTR_TO_PACKET) ||
16510 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16511 			    src_reg->type == PTR_TO_PACKET_META)) {
16512 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
16513 			find_good_pkt_pointers(this_branch, src_reg,
16514 					       src_reg->type, true);
16515 			mark_pkt_end(other_branch, insn->src_reg, false);
16516 		} else {
16517 			return false;
16518 		}
16519 		break;
16520 	default:
16521 		return false;
16522 	}
16523 
16524 	return true;
16525 }
16526 
16527 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
16528 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
16529 {
16530 	struct linked_reg *e;
16531 
16532 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
16533 		return;
16534 
16535 	e = linked_regs_push(reg_set);
16536 	if (e) {
16537 		e->frameno = frameno;
16538 		e->is_reg = is_reg;
16539 		e->regno = spi_or_reg;
16540 	} else {
16541 		reg->id = 0;
16542 	}
16543 }
16544 
16545 /* For all R being scalar registers or spilled scalar registers
16546  * in verifier state, save R in linked_regs if R->id == id.
16547  * If there are too many Rs sharing same id, reset id for leftover Rs.
16548  */
16549 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
16550 				struct linked_regs *linked_regs)
16551 {
16552 	struct bpf_func_state *func;
16553 	struct bpf_reg_state *reg;
16554 	int i, j;
16555 
16556 	id = id & ~BPF_ADD_CONST;
16557 	for (i = vstate->curframe; i >= 0; i--) {
16558 		func = vstate->frame[i];
16559 		for (j = 0; j < BPF_REG_FP; j++) {
16560 			reg = &func->regs[j];
16561 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
16562 		}
16563 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
16564 			if (!is_spilled_reg(&func->stack[j]))
16565 				continue;
16566 			reg = &func->stack[j].spilled_ptr;
16567 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
16568 		}
16569 	}
16570 }
16571 
16572 /* For all R in linked_regs, copy known_reg range into R
16573  * if R->id == known_reg->id.
16574  */
16575 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
16576 			     struct linked_regs *linked_regs)
16577 {
16578 	struct bpf_reg_state fake_reg;
16579 	struct bpf_reg_state *reg;
16580 	struct linked_reg *e;
16581 	int i;
16582 
16583 	for (i = 0; i < linked_regs->cnt; ++i) {
16584 		e = &linked_regs->entries[i];
16585 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
16586 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
16587 		if (reg->type != SCALAR_VALUE || reg == known_reg)
16588 			continue;
16589 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
16590 			continue;
16591 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
16592 		    reg->off == known_reg->off) {
16593 			s32 saved_subreg_def = reg->subreg_def;
16594 
16595 			copy_register_state(reg, known_reg);
16596 			reg->subreg_def = saved_subreg_def;
16597 		} else {
16598 			s32 saved_subreg_def = reg->subreg_def;
16599 			s32 saved_off = reg->off;
16600 
16601 			fake_reg.type = SCALAR_VALUE;
16602 			__mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
16603 
16604 			/* reg = known_reg; reg += delta */
16605 			copy_register_state(reg, known_reg);
16606 			/*
16607 			 * Must preserve off, id and add_const flag,
16608 			 * otherwise another sync_linked_regs() will be incorrect.
16609 			 */
16610 			reg->off = saved_off;
16611 			reg->subreg_def = saved_subreg_def;
16612 
16613 			scalar32_min_max_add(reg, &fake_reg);
16614 			scalar_min_max_add(reg, &fake_reg);
16615 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
16616 		}
16617 	}
16618 }
16619 
16620 static int check_cond_jmp_op(struct bpf_verifier_env *env,
16621 			     struct bpf_insn *insn, int *insn_idx)
16622 {
16623 	struct bpf_verifier_state *this_branch = env->cur_state;
16624 	struct bpf_verifier_state *other_branch;
16625 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
16626 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
16627 	struct bpf_reg_state *eq_branch_regs;
16628 	struct linked_regs linked_regs = {};
16629 	u8 opcode = BPF_OP(insn->code);
16630 	int insn_flags = 0;
16631 	bool is_jmp32;
16632 	int pred = -1;
16633 	int err;
16634 
16635 	/* Only conditional jumps are expected to reach here. */
16636 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
16637 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
16638 		return -EINVAL;
16639 	}
16640 
16641 	if (opcode == BPF_JCOND) {
16642 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
16643 		int idx = *insn_idx;
16644 
16645 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
16646 		    insn->src_reg != BPF_MAY_GOTO ||
16647 		    insn->dst_reg || insn->imm) {
16648 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
16649 			return -EINVAL;
16650 		}
16651 		prev_st = find_prev_entry(env, cur_st->parent, idx);
16652 
16653 		/* branch out 'fallthrough' insn as a new state to explore */
16654 		queued_st = push_stack(env, idx + 1, idx, false);
16655 		if (!queued_st)
16656 			return -ENOMEM;
16657 
16658 		queued_st->may_goto_depth++;
16659 		if (prev_st)
16660 			widen_imprecise_scalars(env, prev_st, queued_st);
16661 		*insn_idx += insn->off;
16662 		return 0;
16663 	}
16664 
16665 	/* check src2 operand */
16666 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16667 	if (err)
16668 		return err;
16669 
16670 	dst_reg = &regs[insn->dst_reg];
16671 	if (BPF_SRC(insn->code) == BPF_X) {
16672 		if (insn->imm != 0) {
16673 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16674 			return -EINVAL;
16675 		}
16676 
16677 		/* check src1 operand */
16678 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16679 		if (err)
16680 			return err;
16681 
16682 		src_reg = &regs[insn->src_reg];
16683 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
16684 		    is_pointer_value(env, insn->src_reg)) {
16685 			verbose(env, "R%d pointer comparison prohibited\n",
16686 				insn->src_reg);
16687 			return -EACCES;
16688 		}
16689 
16690 		if (src_reg->type == PTR_TO_STACK)
16691 			insn_flags |= INSN_F_SRC_REG_STACK;
16692 		if (dst_reg->type == PTR_TO_STACK)
16693 			insn_flags |= INSN_F_DST_REG_STACK;
16694 	} else {
16695 		if (insn->src_reg != BPF_REG_0) {
16696 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16697 			return -EINVAL;
16698 		}
16699 		src_reg = &env->fake_reg[0];
16700 		memset(src_reg, 0, sizeof(*src_reg));
16701 		src_reg->type = SCALAR_VALUE;
16702 		__mark_reg_known(src_reg, insn->imm);
16703 
16704 		if (dst_reg->type == PTR_TO_STACK)
16705 			insn_flags |= INSN_F_DST_REG_STACK;
16706 	}
16707 
16708 	if (insn_flags) {
16709 		err = push_jmp_history(env, this_branch, insn_flags, 0);
16710 		if (err)
16711 			return err;
16712 	}
16713 
16714 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
16715 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
16716 	if (pred >= 0) {
16717 		/* If we get here with a dst_reg pointer type it is because
16718 		 * above is_branch_taken() special cased the 0 comparison.
16719 		 */
16720 		if (!__is_pointer_value(false, dst_reg))
16721 			err = mark_chain_precision(env, insn->dst_reg);
16722 		if (BPF_SRC(insn->code) == BPF_X && !err &&
16723 		    !__is_pointer_value(false, src_reg))
16724 			err = mark_chain_precision(env, insn->src_reg);
16725 		if (err)
16726 			return err;
16727 	}
16728 
16729 	if (pred == 1) {
16730 		/* Only follow the goto, ignore fall-through. If needed, push
16731 		 * the fall-through branch for simulation under speculative
16732 		 * execution.
16733 		 */
16734 		if (!env->bypass_spec_v1 &&
16735 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
16736 					       *insn_idx))
16737 			return -EFAULT;
16738 		if (env->log.level & BPF_LOG_LEVEL)
16739 			print_insn_state(env, this_branch, this_branch->curframe);
16740 		*insn_idx += insn->off;
16741 		return 0;
16742 	} else if (pred == 0) {
16743 		/* Only follow the fall-through branch, since that's where the
16744 		 * program will go. If needed, push the goto branch for
16745 		 * simulation under speculative execution.
16746 		 */
16747 		if (!env->bypass_spec_v1 &&
16748 		    !sanitize_speculative_path(env, insn,
16749 					       *insn_idx + insn->off + 1,
16750 					       *insn_idx))
16751 			return -EFAULT;
16752 		if (env->log.level & BPF_LOG_LEVEL)
16753 			print_insn_state(env, this_branch, this_branch->curframe);
16754 		return 0;
16755 	}
16756 
16757 	/* Push scalar registers sharing same ID to jump history,
16758 	 * do this before creating 'other_branch', so that both
16759 	 * 'this_branch' and 'other_branch' share this history
16760 	 * if parent state is created.
16761 	 */
16762 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
16763 		collect_linked_regs(this_branch, src_reg->id, &linked_regs);
16764 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
16765 		collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
16766 	if (linked_regs.cnt > 1) {
16767 		err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
16768 		if (err)
16769 			return err;
16770 	}
16771 
16772 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
16773 				  false);
16774 	if (!other_branch)
16775 		return -EFAULT;
16776 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
16777 
16778 	if (BPF_SRC(insn->code) == BPF_X) {
16779 		err = reg_set_min_max(env,
16780 				      &other_branch_regs[insn->dst_reg],
16781 				      &other_branch_regs[insn->src_reg],
16782 				      dst_reg, src_reg, opcode, is_jmp32);
16783 	} else /* BPF_SRC(insn->code) == BPF_K */ {
16784 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
16785 		 * so that these are two different memory locations. The
16786 		 * src_reg is not used beyond here in context of K.
16787 		 */
16788 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
16789 		       sizeof(env->fake_reg[0]));
16790 		err = reg_set_min_max(env,
16791 				      &other_branch_regs[insn->dst_reg],
16792 				      &env->fake_reg[0],
16793 				      dst_reg, &env->fake_reg[1],
16794 				      opcode, is_jmp32);
16795 	}
16796 	if (err)
16797 		return err;
16798 
16799 	if (BPF_SRC(insn->code) == BPF_X &&
16800 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
16801 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
16802 		sync_linked_regs(this_branch, src_reg, &linked_regs);
16803 		sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
16804 	}
16805 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
16806 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
16807 		sync_linked_regs(this_branch, dst_reg, &linked_regs);
16808 		sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
16809 	}
16810 
16811 	/* if one pointer register is compared to another pointer
16812 	 * register check if PTR_MAYBE_NULL could be lifted.
16813 	 * E.g. register A - maybe null
16814 	 *      register B - not null
16815 	 * for JNE A, B, ... - A is not null in the false branch;
16816 	 * for JEQ A, B, ... - A is not null in the true branch.
16817 	 *
16818 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
16819 	 * not need to be null checked by the BPF program, i.e.,
16820 	 * could be null even without PTR_MAYBE_NULL marking, so
16821 	 * only propagate nullness when neither reg is that type.
16822 	 */
16823 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
16824 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
16825 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
16826 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
16827 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
16828 		eq_branch_regs = NULL;
16829 		switch (opcode) {
16830 		case BPF_JEQ:
16831 			eq_branch_regs = other_branch_regs;
16832 			break;
16833 		case BPF_JNE:
16834 			eq_branch_regs = regs;
16835 			break;
16836 		default:
16837 			/* do nothing */
16838 			break;
16839 		}
16840 		if (eq_branch_regs) {
16841 			if (type_may_be_null(src_reg->type))
16842 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
16843 			else
16844 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
16845 		}
16846 	}
16847 
16848 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
16849 	 * NOTE: these optimizations below are related with pointer comparison
16850 	 *       which will never be JMP32.
16851 	 */
16852 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
16853 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
16854 	    type_may_be_null(dst_reg->type)) {
16855 		/* Mark all identical registers in each branch as either
16856 		 * safe or unknown depending R == 0 or R != 0 conditional.
16857 		 */
16858 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
16859 				      opcode == BPF_JNE);
16860 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
16861 				      opcode == BPF_JEQ);
16862 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
16863 					   this_branch, other_branch) &&
16864 		   is_pointer_value(env, insn->dst_reg)) {
16865 		verbose(env, "R%d pointer comparison prohibited\n",
16866 			insn->dst_reg);
16867 		return -EACCES;
16868 	}
16869 	if (env->log.level & BPF_LOG_LEVEL)
16870 		print_insn_state(env, this_branch, this_branch->curframe);
16871 	return 0;
16872 }
16873 
16874 /* verify BPF_LD_IMM64 instruction */
16875 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
16876 {
16877 	struct bpf_insn_aux_data *aux = cur_aux(env);
16878 	struct bpf_reg_state *regs = cur_regs(env);
16879 	struct bpf_reg_state *dst_reg;
16880 	struct bpf_map *map;
16881 	int err;
16882 
16883 	if (BPF_SIZE(insn->code) != BPF_DW) {
16884 		verbose(env, "invalid BPF_LD_IMM insn\n");
16885 		return -EINVAL;
16886 	}
16887 	if (insn->off != 0) {
16888 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
16889 		return -EINVAL;
16890 	}
16891 
16892 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
16893 	if (err)
16894 		return err;
16895 
16896 	dst_reg = &regs[insn->dst_reg];
16897 	if (insn->src_reg == 0) {
16898 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
16899 
16900 		dst_reg->type = SCALAR_VALUE;
16901 		__mark_reg_known(&regs[insn->dst_reg], imm);
16902 		return 0;
16903 	}
16904 
16905 	/* All special src_reg cases are listed below. From this point onwards
16906 	 * we either succeed and assign a corresponding dst_reg->type after
16907 	 * zeroing the offset, or fail and reject the program.
16908 	 */
16909 	mark_reg_known_zero(env, regs, insn->dst_reg);
16910 
16911 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
16912 		dst_reg->type = aux->btf_var.reg_type;
16913 		switch (base_type(dst_reg->type)) {
16914 		case PTR_TO_MEM:
16915 			dst_reg->mem_size = aux->btf_var.mem_size;
16916 			break;
16917 		case PTR_TO_BTF_ID:
16918 			dst_reg->btf = aux->btf_var.btf;
16919 			dst_reg->btf_id = aux->btf_var.btf_id;
16920 			break;
16921 		default:
16922 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
16923 			return -EFAULT;
16924 		}
16925 		return 0;
16926 	}
16927 
16928 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
16929 		struct bpf_prog_aux *aux = env->prog->aux;
16930 		u32 subprogno = find_subprog(env,
16931 					     env->insn_idx + insn->imm + 1);
16932 
16933 		if (!aux->func_info) {
16934 			verbose(env, "missing btf func_info\n");
16935 			return -EINVAL;
16936 		}
16937 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
16938 			verbose(env, "callback function not static\n");
16939 			return -EINVAL;
16940 		}
16941 
16942 		dst_reg->type = PTR_TO_FUNC;
16943 		dst_reg->subprogno = subprogno;
16944 		return 0;
16945 	}
16946 
16947 	map = env->used_maps[aux->map_index];
16948 	dst_reg->map_ptr = map;
16949 
16950 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
16951 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
16952 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
16953 			__mark_reg_unknown(env, dst_reg);
16954 			return 0;
16955 		}
16956 		dst_reg->type = PTR_TO_MAP_VALUE;
16957 		dst_reg->off = aux->map_off;
16958 		WARN_ON_ONCE(map->max_entries != 1);
16959 		/* We want reg->id to be same (0) as map_value is not distinct */
16960 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
16961 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
16962 		dst_reg->type = CONST_PTR_TO_MAP;
16963 	} else {
16964 		verifier_bug(env, "unexpected src reg value for ldimm64");
16965 		return -EFAULT;
16966 	}
16967 
16968 	return 0;
16969 }
16970 
16971 static bool may_access_skb(enum bpf_prog_type type)
16972 {
16973 	switch (type) {
16974 	case BPF_PROG_TYPE_SOCKET_FILTER:
16975 	case BPF_PROG_TYPE_SCHED_CLS:
16976 	case BPF_PROG_TYPE_SCHED_ACT:
16977 		return true;
16978 	default:
16979 		return false;
16980 	}
16981 }
16982 
16983 /* verify safety of LD_ABS|LD_IND instructions:
16984  * - they can only appear in the programs where ctx == skb
16985  * - since they are wrappers of function calls, they scratch R1-R5 registers,
16986  *   preserve R6-R9, and store return value into R0
16987  *
16988  * Implicit input:
16989  *   ctx == skb == R6 == CTX
16990  *
16991  * Explicit input:
16992  *   SRC == any register
16993  *   IMM == 32-bit immediate
16994  *
16995  * Output:
16996  *   R0 - 8/16/32-bit skb data converted to cpu endianness
16997  */
16998 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
16999 {
17000 	struct bpf_reg_state *regs = cur_regs(env);
17001 	static const int ctx_reg = BPF_REG_6;
17002 	u8 mode = BPF_MODE(insn->code);
17003 	int i, err;
17004 
17005 	if (!may_access_skb(resolve_prog_type(env->prog))) {
17006 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
17007 		return -EINVAL;
17008 	}
17009 
17010 	if (!env->ops->gen_ld_abs) {
17011 		verifier_bug(env, "gen_ld_abs is null");
17012 		return -EFAULT;
17013 	}
17014 
17015 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
17016 	    BPF_SIZE(insn->code) == BPF_DW ||
17017 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
17018 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
17019 		return -EINVAL;
17020 	}
17021 
17022 	/* check whether implicit source operand (register R6) is readable */
17023 	err = check_reg_arg(env, ctx_reg, SRC_OP);
17024 	if (err)
17025 		return err;
17026 
17027 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
17028 	 * gen_ld_abs() may terminate the program at runtime, leading to
17029 	 * reference leak.
17030 	 */
17031 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
17032 	if (err)
17033 		return err;
17034 
17035 	if (regs[ctx_reg].type != PTR_TO_CTX) {
17036 		verbose(env,
17037 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
17038 		return -EINVAL;
17039 	}
17040 
17041 	if (mode == BPF_IND) {
17042 		/* check explicit source operand */
17043 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
17044 		if (err)
17045 			return err;
17046 	}
17047 
17048 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
17049 	if (err < 0)
17050 		return err;
17051 
17052 	/* reset caller saved regs to unreadable */
17053 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
17054 		mark_reg_not_init(env, regs, caller_saved[i]);
17055 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
17056 	}
17057 
17058 	/* mark destination R0 register as readable, since it contains
17059 	 * the value fetched from the packet.
17060 	 * Already marked as written above.
17061 	 */
17062 	mark_reg_unknown(env, regs, BPF_REG_0);
17063 	/* ld_abs load up to 32-bit skb data. */
17064 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
17065 	return 0;
17066 }
17067 
17068 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
17069 {
17070 	const char *exit_ctx = "At program exit";
17071 	struct tnum enforce_attach_type_range = tnum_unknown;
17072 	const struct bpf_prog *prog = env->prog;
17073 	struct bpf_reg_state *reg = reg_state(env, regno);
17074 	struct bpf_retval_range range = retval_range(0, 1);
17075 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17076 	int err;
17077 	struct bpf_func_state *frame = env->cur_state->frame[0];
17078 	const bool is_subprog = frame->subprogno;
17079 	bool return_32bit = false;
17080 	const struct btf_type *reg_type, *ret_type = NULL;
17081 
17082 	/* LSM and struct_ops func-ptr's return type could be "void" */
17083 	if (!is_subprog || frame->in_exception_callback_fn) {
17084 		switch (prog_type) {
17085 		case BPF_PROG_TYPE_LSM:
17086 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
17087 				/* See below, can be 0 or 0-1 depending on hook. */
17088 				break;
17089 			if (!prog->aux->attach_func_proto->type)
17090 				return 0;
17091 			break;
17092 		case BPF_PROG_TYPE_STRUCT_OPS:
17093 			if (!prog->aux->attach_func_proto->type)
17094 				return 0;
17095 
17096 			if (frame->in_exception_callback_fn)
17097 				break;
17098 
17099 			/* Allow a struct_ops program to return a referenced kptr if it
17100 			 * matches the operator's return type and is in its unmodified
17101 			 * form. A scalar zero (i.e., a null pointer) is also allowed.
17102 			 */
17103 			reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
17104 			ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
17105 							prog->aux->attach_func_proto->type,
17106 							NULL);
17107 			if (ret_type && ret_type == reg_type && reg->ref_obj_id)
17108 				return __check_ptr_off_reg(env, reg, regno, false);
17109 			break;
17110 		default:
17111 			break;
17112 		}
17113 	}
17114 
17115 	/* eBPF calling convention is such that R0 is used
17116 	 * to return the value from eBPF program.
17117 	 * Make sure that it's readable at this time
17118 	 * of bpf_exit, which means that program wrote
17119 	 * something into it earlier
17120 	 */
17121 	err = check_reg_arg(env, regno, SRC_OP);
17122 	if (err)
17123 		return err;
17124 
17125 	if (is_pointer_value(env, regno)) {
17126 		verbose(env, "R%d leaks addr as return value\n", regno);
17127 		return -EACCES;
17128 	}
17129 
17130 	if (frame->in_async_callback_fn) {
17131 		/* enforce return zero from async callbacks like timer */
17132 		exit_ctx = "At async callback return";
17133 		range = retval_range(0, 0);
17134 		goto enforce_retval;
17135 	}
17136 
17137 	if (is_subprog && !frame->in_exception_callback_fn) {
17138 		if (reg->type != SCALAR_VALUE) {
17139 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
17140 				regno, reg_type_str(env, reg->type));
17141 			return -EINVAL;
17142 		}
17143 		return 0;
17144 	}
17145 
17146 	switch (prog_type) {
17147 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
17148 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
17149 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
17150 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
17151 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
17152 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
17153 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
17154 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
17155 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
17156 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
17157 			range = retval_range(1, 1);
17158 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
17159 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
17160 			range = retval_range(0, 3);
17161 		break;
17162 	case BPF_PROG_TYPE_CGROUP_SKB:
17163 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
17164 			range = retval_range(0, 3);
17165 			enforce_attach_type_range = tnum_range(2, 3);
17166 		}
17167 		break;
17168 	case BPF_PROG_TYPE_CGROUP_SOCK:
17169 	case BPF_PROG_TYPE_SOCK_OPS:
17170 	case BPF_PROG_TYPE_CGROUP_DEVICE:
17171 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
17172 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
17173 		break;
17174 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17175 		if (!env->prog->aux->attach_btf_id)
17176 			return 0;
17177 		range = retval_range(0, 0);
17178 		break;
17179 	case BPF_PROG_TYPE_TRACING:
17180 		switch (env->prog->expected_attach_type) {
17181 		case BPF_TRACE_FENTRY:
17182 		case BPF_TRACE_FEXIT:
17183 			range = retval_range(0, 0);
17184 			break;
17185 		case BPF_TRACE_RAW_TP:
17186 		case BPF_MODIFY_RETURN:
17187 			return 0;
17188 		case BPF_TRACE_ITER:
17189 			break;
17190 		default:
17191 			return -ENOTSUPP;
17192 		}
17193 		break;
17194 	case BPF_PROG_TYPE_KPROBE:
17195 		switch (env->prog->expected_attach_type) {
17196 		case BPF_TRACE_KPROBE_SESSION:
17197 		case BPF_TRACE_UPROBE_SESSION:
17198 			range = retval_range(0, 1);
17199 			break;
17200 		default:
17201 			return 0;
17202 		}
17203 		break;
17204 	case BPF_PROG_TYPE_SK_LOOKUP:
17205 		range = retval_range(SK_DROP, SK_PASS);
17206 		break;
17207 
17208 	case BPF_PROG_TYPE_LSM:
17209 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
17210 			/* no range found, any return value is allowed */
17211 			if (!get_func_retval_range(env->prog, &range))
17212 				return 0;
17213 			/* no restricted range, any return value is allowed */
17214 			if (range.minval == S32_MIN && range.maxval == S32_MAX)
17215 				return 0;
17216 			return_32bit = true;
17217 		} else if (!env->prog->aux->attach_func_proto->type) {
17218 			/* Make sure programs that attach to void
17219 			 * hooks don't try to modify return value.
17220 			 */
17221 			range = retval_range(1, 1);
17222 		}
17223 		break;
17224 
17225 	case BPF_PROG_TYPE_NETFILTER:
17226 		range = retval_range(NF_DROP, NF_ACCEPT);
17227 		break;
17228 	case BPF_PROG_TYPE_STRUCT_OPS:
17229 		if (!ret_type)
17230 			return 0;
17231 		range = retval_range(0, 0);
17232 		break;
17233 	case BPF_PROG_TYPE_EXT:
17234 		/* freplace program can return anything as its return value
17235 		 * depends on the to-be-replaced kernel func or bpf program.
17236 		 */
17237 	default:
17238 		return 0;
17239 	}
17240 
17241 enforce_retval:
17242 	if (reg->type != SCALAR_VALUE) {
17243 		verbose(env, "%s the register R%d is not a known value (%s)\n",
17244 			exit_ctx, regno, reg_type_str(env, reg->type));
17245 		return -EINVAL;
17246 	}
17247 
17248 	err = mark_chain_precision(env, regno);
17249 	if (err)
17250 		return err;
17251 
17252 	if (!retval_range_within(range, reg, return_32bit)) {
17253 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
17254 		if (!is_subprog &&
17255 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
17256 		    prog_type == BPF_PROG_TYPE_LSM &&
17257 		    !prog->aux->attach_func_proto->type)
17258 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
17259 		return -EINVAL;
17260 	}
17261 
17262 	if (!tnum_is_unknown(enforce_attach_type_range) &&
17263 	    tnum_in(enforce_attach_type_range, reg->var_off))
17264 		env->prog->enforce_expected_attach_type = 1;
17265 	return 0;
17266 }
17267 
17268 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
17269 {
17270 	struct bpf_subprog_info *subprog;
17271 
17272 	subprog = find_containing_subprog(env, off);
17273 	subprog->changes_pkt_data = true;
17274 }
17275 
17276 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off)
17277 {
17278 	struct bpf_subprog_info *subprog;
17279 
17280 	subprog = find_containing_subprog(env, off);
17281 	subprog->might_sleep = true;
17282 }
17283 
17284 /* 't' is an index of a call-site.
17285  * 'w' is a callee entry point.
17286  * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
17287  * Rely on DFS traversal order and absence of recursive calls to guarantee that
17288  * callee's change_pkt_data marks would be correct at that moment.
17289  */
17290 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
17291 {
17292 	struct bpf_subprog_info *caller, *callee;
17293 
17294 	caller = find_containing_subprog(env, t);
17295 	callee = find_containing_subprog(env, w);
17296 	caller->changes_pkt_data |= callee->changes_pkt_data;
17297 	caller->might_sleep |= callee->might_sleep;
17298 }
17299 
17300 /* non-recursive DFS pseudo code
17301  * 1  procedure DFS-iterative(G,v):
17302  * 2      label v as discovered
17303  * 3      let S be a stack
17304  * 4      S.push(v)
17305  * 5      while S is not empty
17306  * 6            t <- S.peek()
17307  * 7            if t is what we're looking for:
17308  * 8                return t
17309  * 9            for all edges e in G.adjacentEdges(t) do
17310  * 10               if edge e is already labelled
17311  * 11                   continue with the next edge
17312  * 12               w <- G.adjacentVertex(t,e)
17313  * 13               if vertex w is not discovered and not explored
17314  * 14                   label e as tree-edge
17315  * 15                   label w as discovered
17316  * 16                   S.push(w)
17317  * 17                   continue at 5
17318  * 18               else if vertex w is discovered
17319  * 19                   label e as back-edge
17320  * 20               else
17321  * 21                   // vertex w is explored
17322  * 22                   label e as forward- or cross-edge
17323  * 23           label t as explored
17324  * 24           S.pop()
17325  *
17326  * convention:
17327  * 0x10 - discovered
17328  * 0x11 - discovered and fall-through edge labelled
17329  * 0x12 - discovered and fall-through and branch edges labelled
17330  * 0x20 - explored
17331  */
17332 
17333 enum {
17334 	DISCOVERED = 0x10,
17335 	EXPLORED = 0x20,
17336 	FALLTHROUGH = 1,
17337 	BRANCH = 2,
17338 };
17339 
17340 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
17341 {
17342 	env->insn_aux_data[idx].prune_point = true;
17343 }
17344 
17345 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
17346 {
17347 	return env->insn_aux_data[insn_idx].prune_point;
17348 }
17349 
17350 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
17351 {
17352 	env->insn_aux_data[idx].force_checkpoint = true;
17353 }
17354 
17355 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
17356 {
17357 	return env->insn_aux_data[insn_idx].force_checkpoint;
17358 }
17359 
17360 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
17361 {
17362 	env->insn_aux_data[idx].calls_callback = true;
17363 }
17364 
17365 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
17366 {
17367 	return env->insn_aux_data[insn_idx].calls_callback;
17368 }
17369 
17370 enum {
17371 	DONE_EXPLORING = 0,
17372 	KEEP_EXPLORING = 1,
17373 };
17374 
17375 /* t, w, e - match pseudo-code above:
17376  * t - index of current instruction
17377  * w - next instruction
17378  * e - edge
17379  */
17380 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
17381 {
17382 	int *insn_stack = env->cfg.insn_stack;
17383 	int *insn_state = env->cfg.insn_state;
17384 
17385 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
17386 		return DONE_EXPLORING;
17387 
17388 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
17389 		return DONE_EXPLORING;
17390 
17391 	if (w < 0 || w >= env->prog->len) {
17392 		verbose_linfo(env, t, "%d: ", t);
17393 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
17394 		return -EINVAL;
17395 	}
17396 
17397 	if (e == BRANCH) {
17398 		/* mark branch target for state pruning */
17399 		mark_prune_point(env, w);
17400 		mark_jmp_point(env, w);
17401 	}
17402 
17403 	if (insn_state[w] == 0) {
17404 		/* tree-edge */
17405 		insn_state[t] = DISCOVERED | e;
17406 		insn_state[w] = DISCOVERED;
17407 		if (env->cfg.cur_stack >= env->prog->len)
17408 			return -E2BIG;
17409 		insn_stack[env->cfg.cur_stack++] = w;
17410 		return KEEP_EXPLORING;
17411 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
17412 		if (env->bpf_capable)
17413 			return DONE_EXPLORING;
17414 		verbose_linfo(env, t, "%d: ", t);
17415 		verbose_linfo(env, w, "%d: ", w);
17416 		verbose(env, "back-edge from insn %d to %d\n", t, w);
17417 		return -EINVAL;
17418 	} else if (insn_state[w] == EXPLORED) {
17419 		/* forward- or cross-edge */
17420 		insn_state[t] = DISCOVERED | e;
17421 	} else {
17422 		verifier_bug(env, "insn state internal bug");
17423 		return -EFAULT;
17424 	}
17425 	return DONE_EXPLORING;
17426 }
17427 
17428 static int visit_func_call_insn(int t, struct bpf_insn *insns,
17429 				struct bpf_verifier_env *env,
17430 				bool visit_callee)
17431 {
17432 	int ret, insn_sz;
17433 	int w;
17434 
17435 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
17436 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
17437 	if (ret)
17438 		return ret;
17439 
17440 	mark_prune_point(env, t + insn_sz);
17441 	/* when we exit from subprog, we need to record non-linear history */
17442 	mark_jmp_point(env, t + insn_sz);
17443 
17444 	if (visit_callee) {
17445 		w = t + insns[t].imm + 1;
17446 		mark_prune_point(env, t);
17447 		merge_callee_effects(env, t, w);
17448 		ret = push_insn(t, w, BRANCH, env);
17449 	}
17450 	return ret;
17451 }
17452 
17453 /* Bitmask with 1s for all caller saved registers */
17454 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
17455 
17456 /* True if do_misc_fixups() replaces calls to helper number 'imm',
17457  * replacement patch is presumed to follow bpf_fastcall contract
17458  * (see mark_fastcall_pattern_for_call() below).
17459  */
17460 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
17461 {
17462 	switch (imm) {
17463 #ifdef CONFIG_X86_64
17464 	case BPF_FUNC_get_smp_processor_id:
17465 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
17466 #endif
17467 	default:
17468 		return false;
17469 	}
17470 }
17471 
17472 struct call_summary {
17473 	u8 num_params;
17474 	bool is_void;
17475 	bool fastcall;
17476 };
17477 
17478 /* If @call is a kfunc or helper call, fills @cs and returns true,
17479  * otherwise returns false.
17480  */
17481 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
17482 			     struct call_summary *cs)
17483 {
17484 	struct bpf_kfunc_call_arg_meta meta;
17485 	const struct bpf_func_proto *fn;
17486 	int i;
17487 
17488 	if (bpf_helper_call(call)) {
17489 
17490 		if (get_helper_proto(env, call->imm, &fn) < 0)
17491 			/* error would be reported later */
17492 			return false;
17493 		cs->fastcall = fn->allow_fastcall &&
17494 			       (verifier_inlines_helper_call(env, call->imm) ||
17495 				bpf_jit_inlines_helper_call(call->imm));
17496 		cs->is_void = fn->ret_type == RET_VOID;
17497 		cs->num_params = 0;
17498 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
17499 			if (fn->arg_type[i] == ARG_DONTCARE)
17500 				break;
17501 			cs->num_params++;
17502 		}
17503 		return true;
17504 	}
17505 
17506 	if (bpf_pseudo_kfunc_call(call)) {
17507 		int err;
17508 
17509 		err = fetch_kfunc_meta(env, call, &meta, NULL);
17510 		if (err < 0)
17511 			/* error would be reported later */
17512 			return false;
17513 		cs->num_params = btf_type_vlen(meta.func_proto);
17514 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
17515 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
17516 		return true;
17517 	}
17518 
17519 	return false;
17520 }
17521 
17522 /* LLVM define a bpf_fastcall function attribute.
17523  * This attribute means that function scratches only some of
17524  * the caller saved registers defined by ABI.
17525  * For BPF the set of such registers could be defined as follows:
17526  * - R0 is scratched only if function is non-void;
17527  * - R1-R5 are scratched only if corresponding parameter type is defined
17528  *   in the function prototype.
17529  *
17530  * The contract between kernel and clang allows to simultaneously use
17531  * such functions and maintain backwards compatibility with old
17532  * kernels that don't understand bpf_fastcall calls:
17533  *
17534  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
17535  *   registers are not scratched by the call;
17536  *
17537  * - as a post-processing step, clang visits each bpf_fastcall call and adds
17538  *   spill/fill for every live r0-r5;
17539  *
17540  * - stack offsets used for the spill/fill are allocated as lowest
17541  *   stack offsets in whole function and are not used for any other
17542  *   purposes;
17543  *
17544  * - when kernel loads a program, it looks for such patterns
17545  *   (bpf_fastcall function surrounded by spills/fills) and checks if
17546  *   spill/fill stack offsets are used exclusively in fastcall patterns;
17547  *
17548  * - if so, and if verifier or current JIT inlines the call to the
17549  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
17550  *   spill/fill pairs;
17551  *
17552  * - when old kernel loads a program, presence of spill/fill pairs
17553  *   keeps BPF program valid, albeit slightly less efficient.
17554  *
17555  * For example:
17556  *
17557  *   r1 = 1;
17558  *   r2 = 2;
17559  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17560  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
17561  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17562  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
17563  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
17564  *   r0 = r1;                            exit;
17565  *   r0 += r2;
17566  *   exit;
17567  *
17568  * The purpose of mark_fastcall_pattern_for_call is to:
17569  * - look for such patterns;
17570  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
17571  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
17572  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
17573  *   at which bpf_fastcall spill/fill stack slots start;
17574  * - update env->subprog_info[*]->keep_fastcall_stack.
17575  *
17576  * The .fastcall_pattern and .fastcall_stack_off are used by
17577  * check_fastcall_stack_contract() to check if every stack access to
17578  * fastcall spill/fill stack slot originates from spill/fill
17579  * instructions, members of fastcall patterns.
17580  *
17581  * If such condition holds true for a subprogram, fastcall patterns could
17582  * be rewritten by remove_fastcall_spills_fills().
17583  * Otherwise bpf_fastcall patterns are not changed in the subprogram
17584  * (code, presumably, generated by an older clang version).
17585  *
17586  * For example, it is *not* safe to remove spill/fill below:
17587  *
17588  *   r1 = 1;
17589  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17590  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17591  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
17592  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
17593  *   r0 += r1;                           exit;
17594  *   exit;
17595  */
17596 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
17597 					   struct bpf_subprog_info *subprog,
17598 					   int insn_idx, s16 lowest_off)
17599 {
17600 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
17601 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
17602 	u32 clobbered_regs_mask;
17603 	struct call_summary cs;
17604 	u32 expected_regs_mask;
17605 	s16 off;
17606 	int i;
17607 
17608 	if (!get_call_summary(env, call, &cs))
17609 		return;
17610 
17611 	/* A bitmask specifying which caller saved registers are clobbered
17612 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
17613 	 * bpf_fastcall contract:
17614 	 * - includes R0 if function is non-void;
17615 	 * - includes R1-R5 if corresponding parameter has is described
17616 	 *   in the function prototype.
17617 	 */
17618 	clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
17619 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
17620 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
17621 
17622 	/* match pairs of form:
17623 	 *
17624 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
17625 	 * ...
17626 	 * call %[to_be_inlined]
17627 	 * ...
17628 	 * rX = *(u64 *)(r10 - Y)
17629 	 */
17630 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
17631 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
17632 			break;
17633 		stx = &insns[insn_idx - i];
17634 		ldx = &insns[insn_idx + i];
17635 		/* must be a stack spill/fill pair */
17636 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17637 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
17638 		    stx->dst_reg != BPF_REG_10 ||
17639 		    ldx->src_reg != BPF_REG_10)
17640 			break;
17641 		/* must be a spill/fill for the same reg */
17642 		if (stx->src_reg != ldx->dst_reg)
17643 			break;
17644 		/* must be one of the previously unseen registers */
17645 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
17646 			break;
17647 		/* must be a spill/fill for the same expected offset,
17648 		 * no need to check offset alignment, BPF_DW stack access
17649 		 * is always 8-byte aligned.
17650 		 */
17651 		if (stx->off != off || ldx->off != off)
17652 			break;
17653 		expected_regs_mask &= ~BIT(stx->src_reg);
17654 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
17655 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
17656 	}
17657 	if (i == 1)
17658 		return;
17659 
17660 	/* Conditionally set 'fastcall_spills_num' to allow forward
17661 	 * compatibility when more helper functions are marked as
17662 	 * bpf_fastcall at compile time than current kernel supports, e.g:
17663 	 *
17664 	 *   1: *(u64 *)(r10 - 8) = r1
17665 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
17666 	 *   3: r1 = *(u64 *)(r10 - 8)
17667 	 *   4: *(u64 *)(r10 - 8) = r1
17668 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
17669 	 *   6: r1 = *(u64 *)(r10 - 8)
17670 	 *
17671 	 * There is no need to block bpf_fastcall rewrite for such program.
17672 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
17673 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
17674 	 * does not remove spill/fill pair {4,6}.
17675 	 */
17676 	if (cs.fastcall)
17677 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
17678 	else
17679 		subprog->keep_fastcall_stack = 1;
17680 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
17681 }
17682 
17683 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
17684 {
17685 	struct bpf_subprog_info *subprog = env->subprog_info;
17686 	struct bpf_insn *insn;
17687 	s16 lowest_off;
17688 	int s, i;
17689 
17690 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
17691 		/* find lowest stack spill offset used in this subprog */
17692 		lowest_off = 0;
17693 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17694 			insn = env->prog->insnsi + i;
17695 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17696 			    insn->dst_reg != BPF_REG_10)
17697 				continue;
17698 			lowest_off = min(lowest_off, insn->off);
17699 		}
17700 		/* use this offset to find fastcall patterns */
17701 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17702 			insn = env->prog->insnsi + i;
17703 			if (insn->code != (BPF_JMP | BPF_CALL))
17704 				continue;
17705 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
17706 		}
17707 	}
17708 	return 0;
17709 }
17710 
17711 /* Visits the instruction at index t and returns one of the following:
17712  *  < 0 - an error occurred
17713  *  DONE_EXPLORING - the instruction was fully explored
17714  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
17715  */
17716 static int visit_insn(int t, struct bpf_verifier_env *env)
17717 {
17718 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
17719 	int ret, off, insn_sz;
17720 
17721 	if (bpf_pseudo_func(insn))
17722 		return visit_func_call_insn(t, insns, env, true);
17723 
17724 	/* All non-branch instructions have a single fall-through edge. */
17725 	if (BPF_CLASS(insn->code) != BPF_JMP &&
17726 	    BPF_CLASS(insn->code) != BPF_JMP32) {
17727 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
17728 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
17729 	}
17730 
17731 	switch (BPF_OP(insn->code)) {
17732 	case BPF_EXIT:
17733 		return DONE_EXPLORING;
17734 
17735 	case BPF_CALL:
17736 		if (is_async_callback_calling_insn(insn))
17737 			/* Mark this call insn as a prune point to trigger
17738 			 * is_state_visited() check before call itself is
17739 			 * processed by __check_func_call(). Otherwise new
17740 			 * async state will be pushed for further exploration.
17741 			 */
17742 			mark_prune_point(env, t);
17743 		/* For functions that invoke callbacks it is not known how many times
17744 		 * callback would be called. Verifier models callback calling functions
17745 		 * by repeatedly visiting callback bodies and returning to origin call
17746 		 * instruction.
17747 		 * In order to stop such iteration verifier needs to identify when a
17748 		 * state identical some state from a previous iteration is reached.
17749 		 * Check below forces creation of checkpoint before callback calling
17750 		 * instruction to allow search for such identical states.
17751 		 */
17752 		if (is_sync_callback_calling_insn(insn)) {
17753 			mark_calls_callback(env, t);
17754 			mark_force_checkpoint(env, t);
17755 			mark_prune_point(env, t);
17756 			mark_jmp_point(env, t);
17757 		}
17758 		if (bpf_helper_call(insn)) {
17759 			const struct bpf_func_proto *fp;
17760 
17761 			ret = get_helper_proto(env, insn->imm, &fp);
17762 			/* If called in a non-sleepable context program will be
17763 			 * rejected anyway, so we should end up with precise
17764 			 * sleepable marks on subprogs, except for dead code
17765 			 * elimination.
17766 			 */
17767 			if (ret == 0 && fp->might_sleep)
17768 				mark_subprog_might_sleep(env, t);
17769 			if (bpf_helper_changes_pkt_data(insn->imm))
17770 				mark_subprog_changes_pkt_data(env, t);
17771 		} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17772 			struct bpf_kfunc_call_arg_meta meta;
17773 
17774 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
17775 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
17776 				mark_prune_point(env, t);
17777 				/* Checking and saving state checkpoints at iter_next() call
17778 				 * is crucial for fast convergence of open-coded iterator loop
17779 				 * logic, so we need to force it. If we don't do that,
17780 				 * is_state_visited() might skip saving a checkpoint, causing
17781 				 * unnecessarily long sequence of not checkpointed
17782 				 * instructions and jumps, leading to exhaustion of jump
17783 				 * history buffer, and potentially other undesired outcomes.
17784 				 * It is expected that with correct open-coded iterators
17785 				 * convergence will happen quickly, so we don't run a risk of
17786 				 * exhausting memory.
17787 				 */
17788 				mark_force_checkpoint(env, t);
17789 			}
17790 			/* Same as helpers, if called in a non-sleepable context
17791 			 * program will be rejected anyway, so we should end up
17792 			 * with precise sleepable marks on subprogs, except for
17793 			 * dead code elimination.
17794 			 */
17795 			if (ret == 0 && is_kfunc_sleepable(&meta))
17796 				mark_subprog_might_sleep(env, t);
17797 		}
17798 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
17799 
17800 	case BPF_JA:
17801 		if (BPF_SRC(insn->code) != BPF_K)
17802 			return -EINVAL;
17803 
17804 		if (BPF_CLASS(insn->code) == BPF_JMP)
17805 			off = insn->off;
17806 		else
17807 			off = insn->imm;
17808 
17809 		/* unconditional jump with single edge */
17810 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
17811 		if (ret)
17812 			return ret;
17813 
17814 		mark_prune_point(env, t + off + 1);
17815 		mark_jmp_point(env, t + off + 1);
17816 
17817 		return ret;
17818 
17819 	default:
17820 		/* conditional jump with two edges */
17821 		mark_prune_point(env, t);
17822 		if (is_may_goto_insn(insn))
17823 			mark_force_checkpoint(env, t);
17824 
17825 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
17826 		if (ret)
17827 			return ret;
17828 
17829 		return push_insn(t, t + insn->off + 1, BRANCH, env);
17830 	}
17831 }
17832 
17833 /* non-recursive depth-first-search to detect loops in BPF program
17834  * loop == back-edge in directed graph
17835  */
17836 static int check_cfg(struct bpf_verifier_env *env)
17837 {
17838 	int insn_cnt = env->prog->len;
17839 	int *insn_stack, *insn_state, *insn_postorder;
17840 	int ex_insn_beg, i, ret = 0;
17841 
17842 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
17843 	if (!insn_state)
17844 		return -ENOMEM;
17845 
17846 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
17847 	if (!insn_stack) {
17848 		kvfree(insn_state);
17849 		return -ENOMEM;
17850 	}
17851 
17852 	insn_postorder = env->cfg.insn_postorder =
17853 		kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
17854 	if (!insn_postorder) {
17855 		kvfree(insn_state);
17856 		kvfree(insn_stack);
17857 		return -ENOMEM;
17858 	}
17859 
17860 	ex_insn_beg = env->exception_callback_subprog
17861 		      ? env->subprog_info[env->exception_callback_subprog].start
17862 		      : 0;
17863 
17864 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
17865 	insn_stack[0] = 0; /* 0 is the first instruction */
17866 	env->cfg.cur_stack = 1;
17867 
17868 walk_cfg:
17869 	while (env->cfg.cur_stack > 0) {
17870 		int t = insn_stack[env->cfg.cur_stack - 1];
17871 
17872 		ret = visit_insn(t, env);
17873 		switch (ret) {
17874 		case DONE_EXPLORING:
17875 			insn_state[t] = EXPLORED;
17876 			env->cfg.cur_stack--;
17877 			insn_postorder[env->cfg.cur_postorder++] = t;
17878 			break;
17879 		case KEEP_EXPLORING:
17880 			break;
17881 		default:
17882 			if (ret > 0) {
17883 				verifier_bug(env, "visit_insn internal bug");
17884 				ret = -EFAULT;
17885 			}
17886 			goto err_free;
17887 		}
17888 	}
17889 
17890 	if (env->cfg.cur_stack < 0) {
17891 		verifier_bug(env, "pop stack internal bug");
17892 		ret = -EFAULT;
17893 		goto err_free;
17894 	}
17895 
17896 	if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) {
17897 		insn_state[ex_insn_beg] = DISCOVERED;
17898 		insn_stack[0] = ex_insn_beg;
17899 		env->cfg.cur_stack = 1;
17900 		goto walk_cfg;
17901 	}
17902 
17903 	for (i = 0; i < insn_cnt; i++) {
17904 		struct bpf_insn *insn = &env->prog->insnsi[i];
17905 
17906 		if (insn_state[i] != EXPLORED) {
17907 			verbose(env, "unreachable insn %d\n", i);
17908 			ret = -EINVAL;
17909 			goto err_free;
17910 		}
17911 		if (bpf_is_ldimm64(insn)) {
17912 			if (insn_state[i + 1] != 0) {
17913 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
17914 				ret = -EINVAL;
17915 				goto err_free;
17916 			}
17917 			i++; /* skip second half of ldimm64 */
17918 		}
17919 	}
17920 	ret = 0; /* cfg looks good */
17921 	env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
17922 	env->prog->aux->might_sleep = env->subprog_info[0].might_sleep;
17923 
17924 err_free:
17925 	kvfree(insn_state);
17926 	kvfree(insn_stack);
17927 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
17928 	return ret;
17929 }
17930 
17931 static int check_abnormal_return(struct bpf_verifier_env *env)
17932 {
17933 	int i;
17934 
17935 	for (i = 1; i < env->subprog_cnt; i++) {
17936 		if (env->subprog_info[i].has_ld_abs) {
17937 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
17938 			return -EINVAL;
17939 		}
17940 		if (env->subprog_info[i].has_tail_call) {
17941 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
17942 			return -EINVAL;
17943 		}
17944 	}
17945 	return 0;
17946 }
17947 
17948 /* The minimum supported BTF func info size */
17949 #define MIN_BPF_FUNCINFO_SIZE	8
17950 #define MAX_FUNCINFO_REC_SIZE	252
17951 
17952 static int check_btf_func_early(struct bpf_verifier_env *env,
17953 				const union bpf_attr *attr,
17954 				bpfptr_t uattr)
17955 {
17956 	u32 krec_size = sizeof(struct bpf_func_info);
17957 	const struct btf_type *type, *func_proto;
17958 	u32 i, nfuncs, urec_size, min_size;
17959 	struct bpf_func_info *krecord;
17960 	struct bpf_prog *prog;
17961 	const struct btf *btf;
17962 	u32 prev_offset = 0;
17963 	bpfptr_t urecord;
17964 	int ret = -ENOMEM;
17965 
17966 	nfuncs = attr->func_info_cnt;
17967 	if (!nfuncs) {
17968 		if (check_abnormal_return(env))
17969 			return -EINVAL;
17970 		return 0;
17971 	}
17972 
17973 	urec_size = attr->func_info_rec_size;
17974 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
17975 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
17976 	    urec_size % sizeof(u32)) {
17977 		verbose(env, "invalid func info rec size %u\n", urec_size);
17978 		return -EINVAL;
17979 	}
17980 
17981 	prog = env->prog;
17982 	btf = prog->aux->btf;
17983 
17984 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
17985 	min_size = min_t(u32, krec_size, urec_size);
17986 
17987 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
17988 	if (!krecord)
17989 		return -ENOMEM;
17990 
17991 	for (i = 0; i < nfuncs; i++) {
17992 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
17993 		if (ret) {
17994 			if (ret == -E2BIG) {
17995 				verbose(env, "nonzero tailing record in func info");
17996 				/* set the size kernel expects so loader can zero
17997 				 * out the rest of the record.
17998 				 */
17999 				if (copy_to_bpfptr_offset(uattr,
18000 							  offsetof(union bpf_attr, func_info_rec_size),
18001 							  &min_size, sizeof(min_size)))
18002 					ret = -EFAULT;
18003 			}
18004 			goto err_free;
18005 		}
18006 
18007 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
18008 			ret = -EFAULT;
18009 			goto err_free;
18010 		}
18011 
18012 		/* check insn_off */
18013 		ret = -EINVAL;
18014 		if (i == 0) {
18015 			if (krecord[i].insn_off) {
18016 				verbose(env,
18017 					"nonzero insn_off %u for the first func info record",
18018 					krecord[i].insn_off);
18019 				goto err_free;
18020 			}
18021 		} else if (krecord[i].insn_off <= prev_offset) {
18022 			verbose(env,
18023 				"same or smaller insn offset (%u) than previous func info record (%u)",
18024 				krecord[i].insn_off, prev_offset);
18025 			goto err_free;
18026 		}
18027 
18028 		/* check type_id */
18029 		type = btf_type_by_id(btf, krecord[i].type_id);
18030 		if (!type || !btf_type_is_func(type)) {
18031 			verbose(env, "invalid type id %d in func info",
18032 				krecord[i].type_id);
18033 			goto err_free;
18034 		}
18035 
18036 		func_proto = btf_type_by_id(btf, type->type);
18037 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
18038 			/* btf_func_check() already verified it during BTF load */
18039 			goto err_free;
18040 
18041 		prev_offset = krecord[i].insn_off;
18042 		bpfptr_add(&urecord, urec_size);
18043 	}
18044 
18045 	prog->aux->func_info = krecord;
18046 	prog->aux->func_info_cnt = nfuncs;
18047 	return 0;
18048 
18049 err_free:
18050 	kvfree(krecord);
18051 	return ret;
18052 }
18053 
18054 static int check_btf_func(struct bpf_verifier_env *env,
18055 			  const union bpf_attr *attr,
18056 			  bpfptr_t uattr)
18057 {
18058 	const struct btf_type *type, *func_proto, *ret_type;
18059 	u32 i, nfuncs, urec_size;
18060 	struct bpf_func_info *krecord;
18061 	struct bpf_func_info_aux *info_aux = NULL;
18062 	struct bpf_prog *prog;
18063 	const struct btf *btf;
18064 	bpfptr_t urecord;
18065 	bool scalar_return;
18066 	int ret = -ENOMEM;
18067 
18068 	nfuncs = attr->func_info_cnt;
18069 	if (!nfuncs) {
18070 		if (check_abnormal_return(env))
18071 			return -EINVAL;
18072 		return 0;
18073 	}
18074 	if (nfuncs != env->subprog_cnt) {
18075 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
18076 		return -EINVAL;
18077 	}
18078 
18079 	urec_size = attr->func_info_rec_size;
18080 
18081 	prog = env->prog;
18082 	btf = prog->aux->btf;
18083 
18084 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18085 
18086 	krecord = prog->aux->func_info;
18087 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18088 	if (!info_aux)
18089 		return -ENOMEM;
18090 
18091 	for (i = 0; i < nfuncs; i++) {
18092 		/* check insn_off */
18093 		ret = -EINVAL;
18094 
18095 		if (env->subprog_info[i].start != krecord[i].insn_off) {
18096 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
18097 			goto err_free;
18098 		}
18099 
18100 		/* Already checked type_id */
18101 		type = btf_type_by_id(btf, krecord[i].type_id);
18102 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
18103 		/* Already checked func_proto */
18104 		func_proto = btf_type_by_id(btf, type->type);
18105 
18106 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
18107 		scalar_return =
18108 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
18109 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
18110 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
18111 			goto err_free;
18112 		}
18113 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
18114 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
18115 			goto err_free;
18116 		}
18117 
18118 		bpfptr_add(&urecord, urec_size);
18119 	}
18120 
18121 	prog->aux->func_info_aux = info_aux;
18122 	return 0;
18123 
18124 err_free:
18125 	kfree(info_aux);
18126 	return ret;
18127 }
18128 
18129 static void adjust_btf_func(struct bpf_verifier_env *env)
18130 {
18131 	struct bpf_prog_aux *aux = env->prog->aux;
18132 	int i;
18133 
18134 	if (!aux->func_info)
18135 		return;
18136 
18137 	/* func_info is not available for hidden subprogs */
18138 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
18139 		aux->func_info[i].insn_off = env->subprog_info[i].start;
18140 }
18141 
18142 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
18143 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
18144 
18145 static int check_btf_line(struct bpf_verifier_env *env,
18146 			  const union bpf_attr *attr,
18147 			  bpfptr_t uattr)
18148 {
18149 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
18150 	struct bpf_subprog_info *sub;
18151 	struct bpf_line_info *linfo;
18152 	struct bpf_prog *prog;
18153 	const struct btf *btf;
18154 	bpfptr_t ulinfo;
18155 	int err;
18156 
18157 	nr_linfo = attr->line_info_cnt;
18158 	if (!nr_linfo)
18159 		return 0;
18160 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
18161 		return -EINVAL;
18162 
18163 	rec_size = attr->line_info_rec_size;
18164 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
18165 	    rec_size > MAX_LINEINFO_REC_SIZE ||
18166 	    rec_size & (sizeof(u32) - 1))
18167 		return -EINVAL;
18168 
18169 	/* Need to zero it in case the userspace may
18170 	 * pass in a smaller bpf_line_info object.
18171 	 */
18172 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
18173 			 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18174 	if (!linfo)
18175 		return -ENOMEM;
18176 
18177 	prog = env->prog;
18178 	btf = prog->aux->btf;
18179 
18180 	s = 0;
18181 	sub = env->subprog_info;
18182 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
18183 	expected_size = sizeof(struct bpf_line_info);
18184 	ncopy = min_t(u32, expected_size, rec_size);
18185 	for (i = 0; i < nr_linfo; i++) {
18186 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
18187 		if (err) {
18188 			if (err == -E2BIG) {
18189 				verbose(env, "nonzero tailing record in line_info");
18190 				if (copy_to_bpfptr_offset(uattr,
18191 							  offsetof(union bpf_attr, line_info_rec_size),
18192 							  &expected_size, sizeof(expected_size)))
18193 					err = -EFAULT;
18194 			}
18195 			goto err_free;
18196 		}
18197 
18198 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
18199 			err = -EFAULT;
18200 			goto err_free;
18201 		}
18202 
18203 		/*
18204 		 * Check insn_off to ensure
18205 		 * 1) strictly increasing AND
18206 		 * 2) bounded by prog->len
18207 		 *
18208 		 * The linfo[0].insn_off == 0 check logically falls into
18209 		 * the later "missing bpf_line_info for func..." case
18210 		 * because the first linfo[0].insn_off must be the
18211 		 * first sub also and the first sub must have
18212 		 * subprog_info[0].start == 0.
18213 		 */
18214 		if ((i && linfo[i].insn_off <= prev_offset) ||
18215 		    linfo[i].insn_off >= prog->len) {
18216 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
18217 				i, linfo[i].insn_off, prev_offset,
18218 				prog->len);
18219 			err = -EINVAL;
18220 			goto err_free;
18221 		}
18222 
18223 		if (!prog->insnsi[linfo[i].insn_off].code) {
18224 			verbose(env,
18225 				"Invalid insn code at line_info[%u].insn_off\n",
18226 				i);
18227 			err = -EINVAL;
18228 			goto err_free;
18229 		}
18230 
18231 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
18232 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
18233 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
18234 			err = -EINVAL;
18235 			goto err_free;
18236 		}
18237 
18238 		if (s != env->subprog_cnt) {
18239 			if (linfo[i].insn_off == sub[s].start) {
18240 				sub[s].linfo_idx = i;
18241 				s++;
18242 			} else if (sub[s].start < linfo[i].insn_off) {
18243 				verbose(env, "missing bpf_line_info for func#%u\n", s);
18244 				err = -EINVAL;
18245 				goto err_free;
18246 			}
18247 		}
18248 
18249 		prev_offset = linfo[i].insn_off;
18250 		bpfptr_add(&ulinfo, rec_size);
18251 	}
18252 
18253 	if (s != env->subprog_cnt) {
18254 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
18255 			env->subprog_cnt - s, s);
18256 		err = -EINVAL;
18257 		goto err_free;
18258 	}
18259 
18260 	prog->aux->linfo = linfo;
18261 	prog->aux->nr_linfo = nr_linfo;
18262 
18263 	return 0;
18264 
18265 err_free:
18266 	kvfree(linfo);
18267 	return err;
18268 }
18269 
18270 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
18271 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
18272 
18273 static int check_core_relo(struct bpf_verifier_env *env,
18274 			   const union bpf_attr *attr,
18275 			   bpfptr_t uattr)
18276 {
18277 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
18278 	struct bpf_core_relo core_relo = {};
18279 	struct bpf_prog *prog = env->prog;
18280 	const struct btf *btf = prog->aux->btf;
18281 	struct bpf_core_ctx ctx = {
18282 		.log = &env->log,
18283 		.btf = btf,
18284 	};
18285 	bpfptr_t u_core_relo;
18286 	int err;
18287 
18288 	nr_core_relo = attr->core_relo_cnt;
18289 	if (!nr_core_relo)
18290 		return 0;
18291 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
18292 		return -EINVAL;
18293 
18294 	rec_size = attr->core_relo_rec_size;
18295 	if (rec_size < MIN_CORE_RELO_SIZE ||
18296 	    rec_size > MAX_CORE_RELO_SIZE ||
18297 	    rec_size % sizeof(u32))
18298 		return -EINVAL;
18299 
18300 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
18301 	expected_size = sizeof(struct bpf_core_relo);
18302 	ncopy = min_t(u32, expected_size, rec_size);
18303 
18304 	/* Unlike func_info and line_info, copy and apply each CO-RE
18305 	 * relocation record one at a time.
18306 	 */
18307 	for (i = 0; i < nr_core_relo; i++) {
18308 		/* future proofing when sizeof(bpf_core_relo) changes */
18309 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
18310 		if (err) {
18311 			if (err == -E2BIG) {
18312 				verbose(env, "nonzero tailing record in core_relo");
18313 				if (copy_to_bpfptr_offset(uattr,
18314 							  offsetof(union bpf_attr, core_relo_rec_size),
18315 							  &expected_size, sizeof(expected_size)))
18316 					err = -EFAULT;
18317 			}
18318 			break;
18319 		}
18320 
18321 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
18322 			err = -EFAULT;
18323 			break;
18324 		}
18325 
18326 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
18327 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
18328 				i, core_relo.insn_off, prog->len);
18329 			err = -EINVAL;
18330 			break;
18331 		}
18332 
18333 		err = bpf_core_apply(&ctx, &core_relo, i,
18334 				     &prog->insnsi[core_relo.insn_off / 8]);
18335 		if (err)
18336 			break;
18337 		bpfptr_add(&u_core_relo, rec_size);
18338 	}
18339 	return err;
18340 }
18341 
18342 static int check_btf_info_early(struct bpf_verifier_env *env,
18343 				const union bpf_attr *attr,
18344 				bpfptr_t uattr)
18345 {
18346 	struct btf *btf;
18347 	int err;
18348 
18349 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18350 		if (check_abnormal_return(env))
18351 			return -EINVAL;
18352 		return 0;
18353 	}
18354 
18355 	btf = btf_get_by_fd(attr->prog_btf_fd);
18356 	if (IS_ERR(btf))
18357 		return PTR_ERR(btf);
18358 	if (btf_is_kernel(btf)) {
18359 		btf_put(btf);
18360 		return -EACCES;
18361 	}
18362 	env->prog->aux->btf = btf;
18363 
18364 	err = check_btf_func_early(env, attr, uattr);
18365 	if (err)
18366 		return err;
18367 	return 0;
18368 }
18369 
18370 static int check_btf_info(struct bpf_verifier_env *env,
18371 			  const union bpf_attr *attr,
18372 			  bpfptr_t uattr)
18373 {
18374 	int err;
18375 
18376 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18377 		if (check_abnormal_return(env))
18378 			return -EINVAL;
18379 		return 0;
18380 	}
18381 
18382 	err = check_btf_func(env, attr, uattr);
18383 	if (err)
18384 		return err;
18385 
18386 	err = check_btf_line(env, attr, uattr);
18387 	if (err)
18388 		return err;
18389 
18390 	err = check_core_relo(env, attr, uattr);
18391 	if (err)
18392 		return err;
18393 
18394 	return 0;
18395 }
18396 
18397 /* check %cur's range satisfies %old's */
18398 static bool range_within(const struct bpf_reg_state *old,
18399 			 const struct bpf_reg_state *cur)
18400 {
18401 	return old->umin_value <= cur->umin_value &&
18402 	       old->umax_value >= cur->umax_value &&
18403 	       old->smin_value <= cur->smin_value &&
18404 	       old->smax_value >= cur->smax_value &&
18405 	       old->u32_min_value <= cur->u32_min_value &&
18406 	       old->u32_max_value >= cur->u32_max_value &&
18407 	       old->s32_min_value <= cur->s32_min_value &&
18408 	       old->s32_max_value >= cur->s32_max_value;
18409 }
18410 
18411 /* If in the old state two registers had the same id, then they need to have
18412  * the same id in the new state as well.  But that id could be different from
18413  * the old state, so we need to track the mapping from old to new ids.
18414  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
18415  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
18416  * regs with a different old id could still have new id 9, we don't care about
18417  * that.
18418  * So we look through our idmap to see if this old id has been seen before.  If
18419  * so, we require the new id to match; otherwise, we add the id pair to the map.
18420  */
18421 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18422 {
18423 	struct bpf_id_pair *map = idmap->map;
18424 	unsigned int i;
18425 
18426 	/* either both IDs should be set or both should be zero */
18427 	if (!!old_id != !!cur_id)
18428 		return false;
18429 
18430 	if (old_id == 0) /* cur_id == 0 as well */
18431 		return true;
18432 
18433 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
18434 		if (!map[i].old) {
18435 			/* Reached an empty slot; haven't seen this id before */
18436 			map[i].old = old_id;
18437 			map[i].cur = cur_id;
18438 			return true;
18439 		}
18440 		if (map[i].old == old_id)
18441 			return map[i].cur == cur_id;
18442 		if (map[i].cur == cur_id)
18443 			return false;
18444 	}
18445 	/* We ran out of idmap slots, which should be impossible */
18446 	WARN_ON_ONCE(1);
18447 	return false;
18448 }
18449 
18450 /* Similar to check_ids(), but allocate a unique temporary ID
18451  * for 'old_id' or 'cur_id' of zero.
18452  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
18453  */
18454 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18455 {
18456 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
18457 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
18458 
18459 	return check_ids(old_id, cur_id, idmap);
18460 }
18461 
18462 static void clean_func_state(struct bpf_verifier_env *env,
18463 			     struct bpf_func_state *st)
18464 {
18465 	enum bpf_reg_liveness live;
18466 	int i, j;
18467 
18468 	for (i = 0; i < BPF_REG_FP; i++) {
18469 		live = st->regs[i].live;
18470 		/* liveness must not touch this register anymore */
18471 		st->regs[i].live |= REG_LIVE_DONE;
18472 		if (!(live & REG_LIVE_READ))
18473 			/* since the register is unused, clear its state
18474 			 * to make further comparison simpler
18475 			 */
18476 			__mark_reg_not_init(env, &st->regs[i]);
18477 	}
18478 
18479 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
18480 		live = st->stack[i].spilled_ptr.live;
18481 		/* liveness must not touch this stack slot anymore */
18482 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
18483 		if (!(live & REG_LIVE_READ)) {
18484 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
18485 			for (j = 0; j < BPF_REG_SIZE; j++)
18486 				st->stack[i].slot_type[j] = STACK_INVALID;
18487 		}
18488 	}
18489 }
18490 
18491 static void clean_verifier_state(struct bpf_verifier_env *env,
18492 				 struct bpf_verifier_state *st)
18493 {
18494 	int i;
18495 
18496 	for (i = 0; i <= st->curframe; i++)
18497 		clean_func_state(env, st->frame[i]);
18498 }
18499 
18500 /* the parentage chains form a tree.
18501  * the verifier states are added to state lists at given insn and
18502  * pushed into state stack for future exploration.
18503  * when the verifier reaches bpf_exit insn some of the verifier states
18504  * stored in the state lists have their final liveness state already,
18505  * but a lot of states will get revised from liveness point of view when
18506  * the verifier explores other branches.
18507  * Example:
18508  * 1: r0 = 1
18509  * 2: if r1 == 100 goto pc+1
18510  * 3: r0 = 2
18511  * 4: exit
18512  * when the verifier reaches exit insn the register r0 in the state list of
18513  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
18514  * of insn 2 and goes exploring further. At the insn 4 it will walk the
18515  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
18516  *
18517  * Since the verifier pushes the branch states as it sees them while exploring
18518  * the program the condition of walking the branch instruction for the second
18519  * time means that all states below this branch were already explored and
18520  * their final liveness marks are already propagated.
18521  * Hence when the verifier completes the search of state list in is_state_visited()
18522  * we can call this clean_live_states() function to mark all liveness states
18523  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
18524  * will not be used.
18525  * This function also clears the registers and stack for states that !READ
18526  * to simplify state merging.
18527  *
18528  * Important note here that walking the same branch instruction in the callee
18529  * doesn't meant that the states are DONE. The verifier has to compare
18530  * the callsites
18531  */
18532 static void clean_live_states(struct bpf_verifier_env *env, int insn,
18533 			      struct bpf_verifier_state *cur)
18534 {
18535 	struct bpf_verifier_state_list *sl;
18536 	struct list_head *pos, *head;
18537 
18538 	head = explored_state(env, insn);
18539 	list_for_each(pos, head) {
18540 		sl = container_of(pos, struct bpf_verifier_state_list, node);
18541 		if (sl->state.branches)
18542 			continue;
18543 		if (sl->state.insn_idx != insn ||
18544 		    !same_callsites(&sl->state, cur))
18545 			continue;
18546 		if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE)
18547 			/* all regs in this state in all frames were already marked */
18548 			continue;
18549 		if (incomplete_read_marks(env, &sl->state))
18550 			continue;
18551 		clean_verifier_state(env, &sl->state);
18552 	}
18553 }
18554 
18555 static bool regs_exact(const struct bpf_reg_state *rold,
18556 		       const struct bpf_reg_state *rcur,
18557 		       struct bpf_idmap *idmap)
18558 {
18559 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
18560 	       check_ids(rold->id, rcur->id, idmap) &&
18561 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
18562 }
18563 
18564 enum exact_level {
18565 	NOT_EXACT,
18566 	EXACT,
18567 	RANGE_WITHIN
18568 };
18569 
18570 /* Returns true if (rold safe implies rcur safe) */
18571 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
18572 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
18573 		    enum exact_level exact)
18574 {
18575 	if (exact == EXACT)
18576 		return regs_exact(rold, rcur, idmap);
18577 
18578 	if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
18579 		/* explored state didn't use this */
18580 		return true;
18581 	if (rold->type == NOT_INIT) {
18582 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
18583 			/* explored state can't have used this */
18584 			return true;
18585 	}
18586 
18587 	/* Enforce that register types have to match exactly, including their
18588 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
18589 	 * rule.
18590 	 *
18591 	 * One can make a point that using a pointer register as unbounded
18592 	 * SCALAR would be technically acceptable, but this could lead to
18593 	 * pointer leaks because scalars are allowed to leak while pointers
18594 	 * are not. We could make this safe in special cases if root is
18595 	 * calling us, but it's probably not worth the hassle.
18596 	 *
18597 	 * Also, register types that are *not* MAYBE_NULL could technically be
18598 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
18599 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
18600 	 * to the same map).
18601 	 * However, if the old MAYBE_NULL register then got NULL checked,
18602 	 * doing so could have affected others with the same id, and we can't
18603 	 * check for that because we lost the id when we converted to
18604 	 * a non-MAYBE_NULL variant.
18605 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
18606 	 * non-MAYBE_NULL registers as well.
18607 	 */
18608 	if (rold->type != rcur->type)
18609 		return false;
18610 
18611 	switch (base_type(rold->type)) {
18612 	case SCALAR_VALUE:
18613 		if (env->explore_alu_limits) {
18614 			/* explore_alu_limits disables tnum_in() and range_within()
18615 			 * logic and requires everything to be strict
18616 			 */
18617 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
18618 			       check_scalar_ids(rold->id, rcur->id, idmap);
18619 		}
18620 		if (!rold->precise && exact == NOT_EXACT)
18621 			return true;
18622 		if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
18623 			return false;
18624 		if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
18625 			return false;
18626 		/* Why check_ids() for scalar registers?
18627 		 *
18628 		 * Consider the following BPF code:
18629 		 *   1: r6 = ... unbound scalar, ID=a ...
18630 		 *   2: r7 = ... unbound scalar, ID=b ...
18631 		 *   3: if (r6 > r7) goto +1
18632 		 *   4: r6 = r7
18633 		 *   5: if (r6 > X) goto ...
18634 		 *   6: ... memory operation using r7 ...
18635 		 *
18636 		 * First verification path is [1-6]:
18637 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
18638 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
18639 		 *   r7 <= X, because r6 and r7 share same id.
18640 		 * Next verification path is [1-4, 6].
18641 		 *
18642 		 * Instruction (6) would be reached in two states:
18643 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
18644 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
18645 		 *
18646 		 * Use check_ids() to distinguish these states.
18647 		 * ---
18648 		 * Also verify that new value satisfies old value range knowledge.
18649 		 */
18650 		return range_within(rold, rcur) &&
18651 		       tnum_in(rold->var_off, rcur->var_off) &&
18652 		       check_scalar_ids(rold->id, rcur->id, idmap);
18653 	case PTR_TO_MAP_KEY:
18654 	case PTR_TO_MAP_VALUE:
18655 	case PTR_TO_MEM:
18656 	case PTR_TO_BUF:
18657 	case PTR_TO_TP_BUFFER:
18658 		/* If the new min/max/var_off satisfy the old ones and
18659 		 * everything else matches, we are OK.
18660 		 */
18661 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
18662 		       range_within(rold, rcur) &&
18663 		       tnum_in(rold->var_off, rcur->var_off) &&
18664 		       check_ids(rold->id, rcur->id, idmap) &&
18665 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
18666 	case PTR_TO_PACKET_META:
18667 	case PTR_TO_PACKET:
18668 		/* We must have at least as much range as the old ptr
18669 		 * did, so that any accesses which were safe before are
18670 		 * still safe.  This is true even if old range < old off,
18671 		 * since someone could have accessed through (ptr - k), or
18672 		 * even done ptr -= k in a register, to get a safe access.
18673 		 */
18674 		if (rold->range > rcur->range)
18675 			return false;
18676 		/* If the offsets don't match, we can't trust our alignment;
18677 		 * nor can we be sure that we won't fall out of range.
18678 		 */
18679 		if (rold->off != rcur->off)
18680 			return false;
18681 		/* id relations must be preserved */
18682 		if (!check_ids(rold->id, rcur->id, idmap))
18683 			return false;
18684 		/* new val must satisfy old val knowledge */
18685 		return range_within(rold, rcur) &&
18686 		       tnum_in(rold->var_off, rcur->var_off);
18687 	case PTR_TO_STACK:
18688 		/* two stack pointers are equal only if they're pointing to
18689 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
18690 		 */
18691 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
18692 	case PTR_TO_ARENA:
18693 		return true;
18694 	default:
18695 		return regs_exact(rold, rcur, idmap);
18696 	}
18697 }
18698 
18699 static struct bpf_reg_state unbound_reg;
18700 
18701 static __init int unbound_reg_init(void)
18702 {
18703 	__mark_reg_unknown_imprecise(&unbound_reg);
18704 	unbound_reg.live |= REG_LIVE_READ;
18705 	return 0;
18706 }
18707 late_initcall(unbound_reg_init);
18708 
18709 static bool is_stack_all_misc(struct bpf_verifier_env *env,
18710 			      struct bpf_stack_state *stack)
18711 {
18712 	u32 i;
18713 
18714 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
18715 		if ((stack->slot_type[i] == STACK_MISC) ||
18716 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
18717 			continue;
18718 		return false;
18719 	}
18720 
18721 	return true;
18722 }
18723 
18724 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
18725 						  struct bpf_stack_state *stack)
18726 {
18727 	if (is_spilled_scalar_reg64(stack))
18728 		return &stack->spilled_ptr;
18729 
18730 	if (is_stack_all_misc(env, stack))
18731 		return &unbound_reg;
18732 
18733 	return NULL;
18734 }
18735 
18736 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
18737 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
18738 		      enum exact_level exact)
18739 {
18740 	int i, spi;
18741 
18742 	/* walk slots of the explored stack and ignore any additional
18743 	 * slots in the current stack, since explored(safe) state
18744 	 * didn't use them
18745 	 */
18746 	for (i = 0; i < old->allocated_stack; i++) {
18747 		struct bpf_reg_state *old_reg, *cur_reg;
18748 
18749 		spi = i / BPF_REG_SIZE;
18750 
18751 		if (exact != NOT_EXACT &&
18752 		    (i >= cur->allocated_stack ||
18753 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
18754 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
18755 			return false;
18756 
18757 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
18758 		    && exact == NOT_EXACT) {
18759 			i += BPF_REG_SIZE - 1;
18760 			/* explored state didn't use this */
18761 			continue;
18762 		}
18763 
18764 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
18765 			continue;
18766 
18767 		if (env->allow_uninit_stack &&
18768 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
18769 			continue;
18770 
18771 		/* explored stack has more populated slots than current stack
18772 		 * and these slots were used
18773 		 */
18774 		if (i >= cur->allocated_stack)
18775 			return false;
18776 
18777 		/* 64-bit scalar spill vs all slots MISC and vice versa.
18778 		 * Load from all slots MISC produces unbound scalar.
18779 		 * Construct a fake register for such stack and call
18780 		 * regsafe() to ensure scalar ids are compared.
18781 		 */
18782 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
18783 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
18784 		if (old_reg && cur_reg) {
18785 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
18786 				return false;
18787 			i += BPF_REG_SIZE - 1;
18788 			continue;
18789 		}
18790 
18791 		/* if old state was safe with misc data in the stack
18792 		 * it will be safe with zero-initialized stack.
18793 		 * The opposite is not true
18794 		 */
18795 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
18796 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
18797 			continue;
18798 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
18799 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
18800 			/* Ex: old explored (safe) state has STACK_SPILL in
18801 			 * this stack slot, but current has STACK_MISC ->
18802 			 * this verifier states are not equivalent,
18803 			 * return false to continue verification of this path
18804 			 */
18805 			return false;
18806 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
18807 			continue;
18808 		/* Both old and cur are having same slot_type */
18809 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
18810 		case STACK_SPILL:
18811 			/* when explored and current stack slot are both storing
18812 			 * spilled registers, check that stored pointers types
18813 			 * are the same as well.
18814 			 * Ex: explored safe path could have stored
18815 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
18816 			 * but current path has stored:
18817 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
18818 			 * such verifier states are not equivalent.
18819 			 * return false to continue verification of this path
18820 			 */
18821 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
18822 				     &cur->stack[spi].spilled_ptr, idmap, exact))
18823 				return false;
18824 			break;
18825 		case STACK_DYNPTR:
18826 			old_reg = &old->stack[spi].spilled_ptr;
18827 			cur_reg = &cur->stack[spi].spilled_ptr;
18828 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
18829 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
18830 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18831 				return false;
18832 			break;
18833 		case STACK_ITER:
18834 			old_reg = &old->stack[spi].spilled_ptr;
18835 			cur_reg = &cur->stack[spi].spilled_ptr;
18836 			/* iter.depth is not compared between states as it
18837 			 * doesn't matter for correctness and would otherwise
18838 			 * prevent convergence; we maintain it only to prevent
18839 			 * infinite loop check triggering, see
18840 			 * iter_active_depths_differ()
18841 			 */
18842 			if (old_reg->iter.btf != cur_reg->iter.btf ||
18843 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
18844 			    old_reg->iter.state != cur_reg->iter.state ||
18845 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
18846 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18847 				return false;
18848 			break;
18849 		case STACK_IRQ_FLAG:
18850 			old_reg = &old->stack[spi].spilled_ptr;
18851 			cur_reg = &cur->stack[spi].spilled_ptr;
18852 			if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) ||
18853 			    old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class)
18854 				return false;
18855 			break;
18856 		case STACK_MISC:
18857 		case STACK_ZERO:
18858 		case STACK_INVALID:
18859 			continue;
18860 		/* Ensure that new unhandled slot types return false by default */
18861 		default:
18862 			return false;
18863 		}
18864 	}
18865 	return true;
18866 }
18867 
18868 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
18869 		    struct bpf_idmap *idmap)
18870 {
18871 	int i;
18872 
18873 	if (old->acquired_refs != cur->acquired_refs)
18874 		return false;
18875 
18876 	if (old->active_locks != cur->active_locks)
18877 		return false;
18878 
18879 	if (old->active_preempt_locks != cur->active_preempt_locks)
18880 		return false;
18881 
18882 	if (old->active_rcu_lock != cur->active_rcu_lock)
18883 		return false;
18884 
18885 	if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
18886 		return false;
18887 
18888 	if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) ||
18889 	    old->active_lock_ptr != cur->active_lock_ptr)
18890 		return false;
18891 
18892 	for (i = 0; i < old->acquired_refs; i++) {
18893 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
18894 		    old->refs[i].type != cur->refs[i].type)
18895 			return false;
18896 		switch (old->refs[i].type) {
18897 		case REF_TYPE_PTR:
18898 		case REF_TYPE_IRQ:
18899 			break;
18900 		case REF_TYPE_LOCK:
18901 		case REF_TYPE_RES_LOCK:
18902 		case REF_TYPE_RES_LOCK_IRQ:
18903 			if (old->refs[i].ptr != cur->refs[i].ptr)
18904 				return false;
18905 			break;
18906 		default:
18907 			WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
18908 			return false;
18909 		}
18910 	}
18911 
18912 	return true;
18913 }
18914 
18915 /* compare two verifier states
18916  *
18917  * all states stored in state_list are known to be valid, since
18918  * verifier reached 'bpf_exit' instruction through them
18919  *
18920  * this function is called when verifier exploring different branches of
18921  * execution popped from the state stack. If it sees an old state that has
18922  * more strict register state and more strict stack state then this execution
18923  * branch doesn't need to be explored further, since verifier already
18924  * concluded that more strict state leads to valid finish.
18925  *
18926  * Therefore two states are equivalent if register state is more conservative
18927  * and explored stack state is more conservative than the current one.
18928  * Example:
18929  *       explored                   current
18930  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
18931  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
18932  *
18933  * In other words if current stack state (one being explored) has more
18934  * valid slots than old one that already passed validation, it means
18935  * the verifier can stop exploring and conclude that current state is valid too
18936  *
18937  * Similarly with registers. If explored state has register type as invalid
18938  * whereas register type in current state is meaningful, it means that
18939  * the current state will reach 'bpf_exit' instruction safely
18940  */
18941 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
18942 			      struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact)
18943 {
18944 	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
18945 	u16 i;
18946 
18947 	if (old->callback_depth > cur->callback_depth)
18948 		return false;
18949 
18950 	for (i = 0; i < MAX_BPF_REG; i++)
18951 		if (((1 << i) & live_regs) &&
18952 		    !regsafe(env, &old->regs[i], &cur->regs[i],
18953 			     &env->idmap_scratch, exact))
18954 			return false;
18955 
18956 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
18957 		return false;
18958 
18959 	return true;
18960 }
18961 
18962 static void reset_idmap_scratch(struct bpf_verifier_env *env)
18963 {
18964 	env->idmap_scratch.tmp_id_gen = env->id_gen;
18965 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
18966 }
18967 
18968 static bool states_equal(struct bpf_verifier_env *env,
18969 			 struct bpf_verifier_state *old,
18970 			 struct bpf_verifier_state *cur,
18971 			 enum exact_level exact)
18972 {
18973 	u32 insn_idx;
18974 	int i;
18975 
18976 	if (old->curframe != cur->curframe)
18977 		return false;
18978 
18979 	reset_idmap_scratch(env);
18980 
18981 	/* Verification state from speculative execution simulation
18982 	 * must never prune a non-speculative execution one.
18983 	 */
18984 	if (old->speculative && !cur->speculative)
18985 		return false;
18986 
18987 	if (old->in_sleepable != cur->in_sleepable)
18988 		return false;
18989 
18990 	if (!refsafe(old, cur, &env->idmap_scratch))
18991 		return false;
18992 
18993 	/* for states to be equal callsites have to be the same
18994 	 * and all frame states need to be equivalent
18995 	 */
18996 	for (i = 0; i <= old->curframe; i++) {
18997 		insn_idx = frame_insn_idx(old, i);
18998 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
18999 			return false;
19000 		if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
19001 			return false;
19002 	}
19003 	return true;
19004 }
19005 
19006 /* Return 0 if no propagation happened. Return negative error code if error
19007  * happened. Otherwise, return the propagated bit.
19008  */
19009 static int propagate_liveness_reg(struct bpf_verifier_env *env,
19010 				  struct bpf_reg_state *reg,
19011 				  struct bpf_reg_state *parent_reg)
19012 {
19013 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
19014 	u8 flag = reg->live & REG_LIVE_READ;
19015 	int err;
19016 
19017 	/* When comes here, read flags of PARENT_REG or REG could be any of
19018 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
19019 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
19020 	 */
19021 	if (parent_flag == REG_LIVE_READ64 ||
19022 	    /* Or if there is no read flag from REG. */
19023 	    !flag ||
19024 	    /* Or if the read flag from REG is the same as PARENT_REG. */
19025 	    parent_flag == flag)
19026 		return 0;
19027 
19028 	err = mark_reg_read(env, reg, parent_reg, flag);
19029 	if (err)
19030 		return err;
19031 
19032 	return flag;
19033 }
19034 
19035 /* A write screens off any subsequent reads; but write marks come from the
19036  * straight-line code between a state and its parent.  When we arrive at an
19037  * equivalent state (jump target or such) we didn't arrive by the straight-line
19038  * code, so read marks in the state must propagate to the parent regardless
19039  * of the state's write marks. That's what 'parent == state->parent' comparison
19040  * in mark_reg_read() is for.
19041  */
19042 static int propagate_liveness(struct bpf_verifier_env *env,
19043 			      const struct bpf_verifier_state *vstate,
19044 			      struct bpf_verifier_state *vparent,
19045 			      bool *changed)
19046 {
19047 	struct bpf_reg_state *state_reg, *parent_reg;
19048 	struct bpf_func_state *state, *parent;
19049 	int i, frame, err = 0;
19050 	bool tmp = false;
19051 
19052 	changed = changed ?: &tmp;
19053 	if (vparent->curframe != vstate->curframe) {
19054 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
19055 		     vparent->curframe, vstate->curframe);
19056 		return -EFAULT;
19057 	}
19058 	/* Propagate read liveness of registers... */
19059 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
19060 	for (frame = 0; frame <= vstate->curframe; frame++) {
19061 		parent = vparent->frame[frame];
19062 		state = vstate->frame[frame];
19063 		parent_reg = parent->regs;
19064 		state_reg = state->regs;
19065 		/* We don't need to worry about FP liveness, it's read-only */
19066 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
19067 			err = propagate_liveness_reg(env, &state_reg[i],
19068 						     &parent_reg[i]);
19069 			if (err < 0)
19070 				return err;
19071 			*changed |= err > 0;
19072 			if (err == REG_LIVE_READ64)
19073 				mark_insn_zext(env, &parent_reg[i]);
19074 		}
19075 
19076 		/* Propagate stack slots. */
19077 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
19078 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
19079 			parent_reg = &parent->stack[i].spilled_ptr;
19080 			state_reg = &state->stack[i].spilled_ptr;
19081 			err = propagate_liveness_reg(env, state_reg,
19082 						     parent_reg);
19083 			*changed |= err > 0;
19084 			if (err < 0)
19085 				return err;
19086 		}
19087 	}
19088 	return 0;
19089 }
19090 
19091 /* find precise scalars in the previous equivalent state and
19092  * propagate them into the current state
19093  */
19094 static int propagate_precision(struct bpf_verifier_env *env,
19095 			       const struct bpf_verifier_state *old,
19096 			       struct bpf_verifier_state *cur,
19097 			       bool *changed)
19098 {
19099 	struct bpf_reg_state *state_reg;
19100 	struct bpf_func_state *state;
19101 	int i, err = 0, fr;
19102 	bool first;
19103 
19104 	for (fr = old->curframe; fr >= 0; fr--) {
19105 		state = old->frame[fr];
19106 		state_reg = state->regs;
19107 		first = true;
19108 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
19109 			if (state_reg->type != SCALAR_VALUE ||
19110 			    !state_reg->precise ||
19111 			    !(state_reg->live & REG_LIVE_READ))
19112 				continue;
19113 			if (env->log.level & BPF_LOG_LEVEL2) {
19114 				if (first)
19115 					verbose(env, "frame %d: propagating r%d", fr, i);
19116 				else
19117 					verbose(env, ",r%d", i);
19118 			}
19119 			bt_set_frame_reg(&env->bt, fr, i);
19120 			first = false;
19121 		}
19122 
19123 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19124 			if (!is_spilled_reg(&state->stack[i]))
19125 				continue;
19126 			state_reg = &state->stack[i].spilled_ptr;
19127 			if (state_reg->type != SCALAR_VALUE ||
19128 			    !state_reg->precise ||
19129 			    !(state_reg->live & REG_LIVE_READ))
19130 				continue;
19131 			if (env->log.level & BPF_LOG_LEVEL2) {
19132 				if (first)
19133 					verbose(env, "frame %d: propagating fp%d",
19134 						fr, (-i - 1) * BPF_REG_SIZE);
19135 				else
19136 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
19137 			}
19138 			bt_set_frame_slot(&env->bt, fr, i);
19139 			first = false;
19140 		}
19141 		if (!first)
19142 			verbose(env, "\n");
19143 	}
19144 
19145 	err = __mark_chain_precision(env, cur, -1, changed);
19146 	if (err < 0)
19147 		return err;
19148 
19149 	return 0;
19150 }
19151 
19152 #define MAX_BACKEDGE_ITERS 64
19153 
19154 /* Propagate read and precision marks from visit->backedges[*].state->equal_state
19155  * to corresponding parent states of visit->backedges[*].state until fixed point is reached,
19156  * then free visit->backedges.
19157  * After execution of this function incomplete_read_marks() will return false
19158  * for all states corresponding to @visit->callchain.
19159  */
19160 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit)
19161 {
19162 	struct bpf_scc_backedge *backedge;
19163 	struct bpf_verifier_state *st;
19164 	bool changed;
19165 	int i, err;
19166 
19167 	i = 0;
19168 	do {
19169 		if (i++ > MAX_BACKEDGE_ITERS) {
19170 			if (env->log.level & BPF_LOG_LEVEL2)
19171 				verbose(env, "%s: too many iterations\n", __func__);
19172 			for (backedge = visit->backedges; backedge; backedge = backedge->next)
19173 				mark_all_scalars_precise(env, &backedge->state);
19174 			break;
19175 		}
19176 		changed = false;
19177 		for (backedge = visit->backedges; backedge; backedge = backedge->next) {
19178 			st = &backedge->state;
19179 			err = propagate_liveness(env, st->equal_state, st, &changed);
19180 			if (err)
19181 				return err;
19182 			err = propagate_precision(env, st->equal_state, st, &changed);
19183 			if (err)
19184 				return err;
19185 		}
19186 	} while (changed);
19187 
19188 	free_backedges(visit);
19189 	return 0;
19190 }
19191 
19192 static bool states_maybe_looping(struct bpf_verifier_state *old,
19193 				 struct bpf_verifier_state *cur)
19194 {
19195 	struct bpf_func_state *fold, *fcur;
19196 	int i, fr = cur->curframe;
19197 
19198 	if (old->curframe != fr)
19199 		return false;
19200 
19201 	fold = old->frame[fr];
19202 	fcur = cur->frame[fr];
19203 	for (i = 0; i < MAX_BPF_REG; i++)
19204 		if (memcmp(&fold->regs[i], &fcur->regs[i],
19205 			   offsetof(struct bpf_reg_state, parent)))
19206 			return false;
19207 	return true;
19208 }
19209 
19210 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
19211 {
19212 	return env->insn_aux_data[insn_idx].is_iter_next;
19213 }
19214 
19215 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
19216  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
19217  * states to match, which otherwise would look like an infinite loop. So while
19218  * iter_next() calls are taken care of, we still need to be careful and
19219  * prevent erroneous and too eager declaration of "infinite loop", when
19220  * iterators are involved.
19221  *
19222  * Here's a situation in pseudo-BPF assembly form:
19223  *
19224  *   0: again:                          ; set up iter_next() call args
19225  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
19226  *   2:   call bpf_iter_num_next        ; this is iter_next() call
19227  *   3:   if r0 == 0 goto done
19228  *   4:   ... something useful here ...
19229  *   5:   goto again                    ; another iteration
19230  *   6: done:
19231  *   7:   r1 = &it
19232  *   8:   call bpf_iter_num_destroy     ; clean up iter state
19233  *   9:   exit
19234  *
19235  * This is a typical loop. Let's assume that we have a prune point at 1:,
19236  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
19237  * again`, assuming other heuristics don't get in a way).
19238  *
19239  * When we first time come to 1:, let's say we have some state X. We proceed
19240  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
19241  * Now we come back to validate that forked ACTIVE state. We proceed through
19242  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
19243  * are converging. But the problem is that we don't know that yet, as this
19244  * convergence has to happen at iter_next() call site only. So if nothing is
19245  * done, at 1: verifier will use bounded loop logic and declare infinite
19246  * looping (and would be *technically* correct, if not for iterator's
19247  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
19248  * don't want that. So what we do in process_iter_next_call() when we go on
19249  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
19250  * a different iteration. So when we suspect an infinite loop, we additionally
19251  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
19252  * pretend we are not looping and wait for next iter_next() call.
19253  *
19254  * This only applies to ACTIVE state. In DRAINED state we don't expect to
19255  * loop, because that would actually mean infinite loop, as DRAINED state is
19256  * "sticky", and so we'll keep returning into the same instruction with the
19257  * same state (at least in one of possible code paths).
19258  *
19259  * This approach allows to keep infinite loop heuristic even in the face of
19260  * active iterator. E.g., C snippet below is and will be detected as
19261  * infinitely looping:
19262  *
19263  *   struct bpf_iter_num it;
19264  *   int *p, x;
19265  *
19266  *   bpf_iter_num_new(&it, 0, 10);
19267  *   while ((p = bpf_iter_num_next(&t))) {
19268  *       x = p;
19269  *       while (x--) {} // <<-- infinite loop here
19270  *   }
19271  *
19272  */
19273 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
19274 {
19275 	struct bpf_reg_state *slot, *cur_slot;
19276 	struct bpf_func_state *state;
19277 	int i, fr;
19278 
19279 	for (fr = old->curframe; fr >= 0; fr--) {
19280 		state = old->frame[fr];
19281 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19282 			if (state->stack[i].slot_type[0] != STACK_ITER)
19283 				continue;
19284 
19285 			slot = &state->stack[i].spilled_ptr;
19286 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
19287 				continue;
19288 
19289 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
19290 			if (cur_slot->iter.depth != slot->iter.depth)
19291 				return true;
19292 		}
19293 	}
19294 	return false;
19295 }
19296 
19297 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
19298 {
19299 	struct bpf_verifier_state_list *new_sl;
19300 	struct bpf_verifier_state_list *sl;
19301 	struct bpf_verifier_state *cur = env->cur_state, *new;
19302 	bool force_new_state, add_new_state, loop;
19303 	int i, j, n, err, states_cnt = 0;
19304 	struct list_head *pos, *tmp, *head;
19305 
19306 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
19307 			  /* Avoid accumulating infinitely long jmp history */
19308 			  cur->jmp_history_cnt > 40;
19309 
19310 	/* bpf progs typically have pruning point every 4 instructions
19311 	 * http://vger.kernel.org/bpfconf2019.html#session-1
19312 	 * Do not add new state for future pruning if the verifier hasn't seen
19313 	 * at least 2 jumps and at least 8 instructions.
19314 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
19315 	 * In tests that amounts to up to 50% reduction into total verifier
19316 	 * memory consumption and 20% verifier time speedup.
19317 	 */
19318 	add_new_state = force_new_state;
19319 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
19320 	    env->insn_processed - env->prev_insn_processed >= 8)
19321 		add_new_state = true;
19322 
19323 	clean_live_states(env, insn_idx, cur);
19324 
19325 	loop = false;
19326 	head = explored_state(env, insn_idx);
19327 	list_for_each_safe(pos, tmp, head) {
19328 		sl = container_of(pos, struct bpf_verifier_state_list, node);
19329 		states_cnt++;
19330 		if (sl->state.insn_idx != insn_idx)
19331 			continue;
19332 
19333 		if (sl->state.branches) {
19334 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
19335 
19336 			if (frame->in_async_callback_fn &&
19337 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
19338 				/* Different async_entry_cnt means that the verifier is
19339 				 * processing another entry into async callback.
19340 				 * Seeing the same state is not an indication of infinite
19341 				 * loop or infinite recursion.
19342 				 * But finding the same state doesn't mean that it's safe
19343 				 * to stop processing the current state. The previous state
19344 				 * hasn't yet reached bpf_exit, since state.branches > 0.
19345 				 * Checking in_async_callback_fn alone is not enough either.
19346 				 * Since the verifier still needs to catch infinite loops
19347 				 * inside async callbacks.
19348 				 */
19349 				goto skip_inf_loop_check;
19350 			}
19351 			/* BPF open-coded iterators loop detection is special.
19352 			 * states_maybe_looping() logic is too simplistic in detecting
19353 			 * states that *might* be equivalent, because it doesn't know
19354 			 * about ID remapping, so don't even perform it.
19355 			 * See process_iter_next_call() and iter_active_depths_differ()
19356 			 * for overview of the logic. When current and one of parent
19357 			 * states are detected as equivalent, it's a good thing: we prove
19358 			 * convergence and can stop simulating further iterations.
19359 			 * It's safe to assume that iterator loop will finish, taking into
19360 			 * account iter_next() contract of eventually returning
19361 			 * sticky NULL result.
19362 			 *
19363 			 * Note, that states have to be compared exactly in this case because
19364 			 * read and precision marks might not be finalized inside the loop.
19365 			 * E.g. as in the program below:
19366 			 *
19367 			 *     1. r7 = -16
19368 			 *     2. r6 = bpf_get_prandom_u32()
19369 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
19370 			 *     4.   if (r6 != 42) {
19371 			 *     5.     r7 = -32
19372 			 *     6.     r6 = bpf_get_prandom_u32()
19373 			 *     7.     continue
19374 			 *     8.   }
19375 			 *     9.   r0 = r10
19376 			 *    10.   r0 += r7
19377 			 *    11.   r8 = *(u64 *)(r0 + 0)
19378 			 *    12.   r6 = bpf_get_prandom_u32()
19379 			 *    13. }
19380 			 *
19381 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
19382 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
19383 			 * not have read or precision mark for r7 yet, thus inexact states
19384 			 * comparison would discard current state with r7=-32
19385 			 * => unsafe memory access at 11 would not be caught.
19386 			 */
19387 			if (is_iter_next_insn(env, insn_idx)) {
19388 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19389 					struct bpf_func_state *cur_frame;
19390 					struct bpf_reg_state *iter_state, *iter_reg;
19391 					int spi;
19392 
19393 					cur_frame = cur->frame[cur->curframe];
19394 					/* btf_check_iter_kfuncs() enforces that
19395 					 * iter state pointer is always the first arg
19396 					 */
19397 					iter_reg = &cur_frame->regs[BPF_REG_1];
19398 					/* current state is valid due to states_equal(),
19399 					 * so we can assume valid iter and reg state,
19400 					 * no need for extra (re-)validations
19401 					 */
19402 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
19403 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
19404 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
19405 						loop = true;
19406 						goto hit;
19407 					}
19408 				}
19409 				goto skip_inf_loop_check;
19410 			}
19411 			if (is_may_goto_insn_at(env, insn_idx)) {
19412 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
19413 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19414 					loop = true;
19415 					goto hit;
19416 				}
19417 			}
19418 			if (calls_callback(env, insn_idx)) {
19419 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
19420 					goto hit;
19421 				goto skip_inf_loop_check;
19422 			}
19423 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
19424 			if (states_maybe_looping(&sl->state, cur) &&
19425 			    states_equal(env, &sl->state, cur, EXACT) &&
19426 			    !iter_active_depths_differ(&sl->state, cur) &&
19427 			    sl->state.may_goto_depth == cur->may_goto_depth &&
19428 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
19429 				verbose_linfo(env, insn_idx, "; ");
19430 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
19431 				verbose(env, "cur state:");
19432 				print_verifier_state(env, cur, cur->curframe, true);
19433 				verbose(env, "old state:");
19434 				print_verifier_state(env, &sl->state, cur->curframe, true);
19435 				return -EINVAL;
19436 			}
19437 			/* if the verifier is processing a loop, avoid adding new state
19438 			 * too often, since different loop iterations have distinct
19439 			 * states and may not help future pruning.
19440 			 * This threshold shouldn't be too low to make sure that
19441 			 * a loop with large bound will be rejected quickly.
19442 			 * The most abusive loop will be:
19443 			 * r1 += 1
19444 			 * if r1 < 1000000 goto pc-2
19445 			 * 1M insn_procssed limit / 100 == 10k peak states.
19446 			 * This threshold shouldn't be too high either, since states
19447 			 * at the end of the loop are likely to be useful in pruning.
19448 			 */
19449 skip_inf_loop_check:
19450 			if (!force_new_state &&
19451 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
19452 			    env->insn_processed - env->prev_insn_processed < 100)
19453 				add_new_state = false;
19454 			goto miss;
19455 		}
19456 		/* See comments for mark_all_regs_read_and_precise() */
19457 		loop = incomplete_read_marks(env, &sl->state);
19458 		if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) {
19459 hit:
19460 			sl->hit_cnt++;
19461 			/* reached equivalent register/stack state,
19462 			 * prune the search.
19463 			 * Registers read by the continuation are read by us.
19464 			 * If we have any write marks in env->cur_state, they
19465 			 * will prevent corresponding reads in the continuation
19466 			 * from reaching our parent (an explored_state).  Our
19467 			 * own state will get the read marks recorded, but
19468 			 * they'll be immediately forgotten as we're pruning
19469 			 * this state and will pop a new one.
19470 			 */
19471 			err = propagate_liveness(env, &sl->state, cur, NULL);
19472 
19473 			/* if previous state reached the exit with precision and
19474 			 * current state is equivalent to it (except precision marks)
19475 			 * the precision needs to be propagated back in
19476 			 * the current state.
19477 			 */
19478 			if (is_jmp_point(env, env->insn_idx))
19479 				err = err ? : push_jmp_history(env, cur, 0, 0);
19480 			err = err ? : propagate_precision(env, &sl->state, cur, NULL);
19481 			if (err)
19482 				return err;
19483 			/* When processing iterator based loops above propagate_liveness and
19484 			 * propagate_precision calls are not sufficient to transfer all relevant
19485 			 * read and precision marks. E.g. consider the following case:
19486 			 *
19487 			 *  .-> A --.  Assume the states are visited in the order A, B, C.
19488 			 *  |   |   |  Assume that state B reaches a state equivalent to state A.
19489 			 *  |   v   v  At this point, state C is not processed yet, so state A
19490 			 *  '-- B   C  has not received any read or precision marks from C.
19491 			 *             Thus, marks propagated from A to B are incomplete.
19492 			 *
19493 			 * The verifier mitigates this by performing the following steps:
19494 			 *
19495 			 * - Prior to the main verification pass, strongly connected components
19496 			 *   (SCCs) are computed over the program's control flow graph,
19497 			 *   intraprocedurally.
19498 			 *
19499 			 * - During the main verification pass, `maybe_enter_scc()` checks
19500 			 *   whether the current verifier state is entering an SCC. If so, an
19501 			 *   instance of a `bpf_scc_visit` object is created, and the state
19502 			 *   entering the SCC is recorded as the entry state.
19503 			 *
19504 			 * - This instance is associated not with the SCC itself, but with a
19505 			 *   `bpf_scc_callchain`: a tuple consisting of the call sites leading to
19506 			 *   the SCC and the SCC id. See `compute_scc_callchain()`.
19507 			 *
19508 			 * - When a verification path encounters a `states_equal(...,
19509 			 *   RANGE_WITHIN)` condition, there exists a call chain describing the
19510 			 *   current state and a corresponding `bpf_scc_visit` instance. A copy
19511 			 *   of the current state is created and added to
19512 			 *   `bpf_scc_visit->backedges`.
19513 			 *
19514 			 * - When a verification path terminates, `maybe_exit_scc()` is called
19515 			 *   from `update_branch_counts()`. For states with `branches == 0`, it
19516 			 *   checks whether the state is the entry state of any `bpf_scc_visit`
19517 			 *   instance. If it is, this indicates that all paths originating from
19518 			 *   this SCC visit have been explored. `propagate_backedges()` is then
19519 			 *   called, which propagates read and precision marks through the
19520 			 *   backedges until a fixed point is reached.
19521 			 *   (In the earlier example, this would propagate marks from A to B,
19522 			 *    from C to A, and then again from A to B.)
19523 			 *
19524 			 * A note on callchains
19525 			 * --------------------
19526 			 *
19527 			 * Consider the following example:
19528 			 *
19529 			 *     void foo() { loop { ... SCC#1 ... } }
19530 			 *     void main() {
19531 			 *       A: foo();
19532 			 *       B: ...
19533 			 *       C: foo();
19534 			 *     }
19535 			 *
19536 			 * Here, there are two distinct callchains leading to SCC#1:
19537 			 * - (A, SCC#1)
19538 			 * - (C, SCC#1)
19539 			 *
19540 			 * Each callchain identifies a separate `bpf_scc_visit` instance that
19541 			 * accumulates backedge states. The `propagate_{liveness,precision}()`
19542 			 * functions traverse the parent state of each backedge state, which
19543 			 * means these parent states must remain valid (i.e., not freed) while
19544 			 * the corresponding `bpf_scc_visit` instance exists.
19545 			 *
19546 			 * Associating `bpf_scc_visit` instances directly with SCCs instead of
19547 			 * callchains would break this invariant:
19548 			 * - States explored during `C: foo()` would contribute backedges to
19549 			 *   SCC#1, but SCC#1 would only be exited once the exploration of
19550 			 *   `A: foo()` completes.
19551 			 * - By that time, the states explored between `A: foo()` and `C: foo()`
19552 			 *   (i.e., `B: ...`) may have already been freed, causing the parent
19553 			 *   links for states from `C: foo()` to become invalid.
19554 			 */
19555 			if (loop) {
19556 				struct bpf_scc_backedge *backedge;
19557 
19558 				backedge = kzalloc(sizeof(*backedge), GFP_KERNEL_ACCOUNT);
19559 				if (!backedge)
19560 					return -ENOMEM;
19561 				err = copy_verifier_state(&backedge->state, cur);
19562 				backedge->state.equal_state = &sl->state;
19563 				backedge->state.insn_idx = insn_idx;
19564 				err = err ?: add_scc_backedge(env, &sl->state, backedge);
19565 				if (err) {
19566 					free_verifier_state(&backedge->state, false);
19567 					kvfree(backedge);
19568 					return err;
19569 				}
19570 			}
19571 			return 1;
19572 		}
19573 miss:
19574 		/* when new state is not going to be added do not increase miss count.
19575 		 * Otherwise several loop iterations will remove the state
19576 		 * recorded earlier. The goal of these heuristics is to have
19577 		 * states from some iterations of the loop (some in the beginning
19578 		 * and some at the end) to help pruning.
19579 		 */
19580 		if (add_new_state)
19581 			sl->miss_cnt++;
19582 		/* heuristic to determine whether this state is beneficial
19583 		 * to keep checking from state equivalence point of view.
19584 		 * Higher numbers increase max_states_per_insn and verification time,
19585 		 * but do not meaningfully decrease insn_processed.
19586 		 * 'n' controls how many times state could miss before eviction.
19587 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
19588 		 * too early would hinder iterator convergence.
19589 		 */
19590 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
19591 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
19592 			/* the state is unlikely to be useful. Remove it to
19593 			 * speed up verification
19594 			 */
19595 			sl->in_free_list = true;
19596 			list_del(&sl->node);
19597 			list_add(&sl->node, &env->free_list);
19598 			env->free_list_size++;
19599 			env->explored_states_size--;
19600 			maybe_free_verifier_state(env, sl);
19601 		}
19602 	}
19603 
19604 	if (env->max_states_per_insn < states_cnt)
19605 		env->max_states_per_insn = states_cnt;
19606 
19607 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
19608 		return 0;
19609 
19610 	if (!add_new_state)
19611 		return 0;
19612 
19613 	/* There were no equivalent states, remember the current one.
19614 	 * Technically the current state is not proven to be safe yet,
19615 	 * but it will either reach outer most bpf_exit (which means it's safe)
19616 	 * or it will be rejected. When there are no loops the verifier won't be
19617 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
19618 	 * again on the way to bpf_exit.
19619 	 * When looping the sl->state.branches will be > 0 and this state
19620 	 * will not be considered for equivalence until branches == 0.
19621 	 */
19622 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL_ACCOUNT);
19623 	if (!new_sl)
19624 		return -ENOMEM;
19625 	env->total_states++;
19626 	env->explored_states_size++;
19627 	update_peak_states(env);
19628 	env->prev_jmps_processed = env->jmps_processed;
19629 	env->prev_insn_processed = env->insn_processed;
19630 
19631 	/* forget precise markings we inherited, see __mark_chain_precision */
19632 	if (env->bpf_capable)
19633 		mark_all_scalars_imprecise(env, cur);
19634 
19635 	/* add new state to the head of linked list */
19636 	new = &new_sl->state;
19637 	err = copy_verifier_state(new, cur);
19638 	if (err) {
19639 		free_verifier_state(new, false);
19640 		kfree(new_sl);
19641 		return err;
19642 	}
19643 	new->insn_idx = insn_idx;
19644 	verifier_bug_if(new->branches != 1, env,
19645 			"%s:branches_to_explore=%d insn %d",
19646 			__func__, new->branches, insn_idx);
19647 	err = maybe_enter_scc(env, new);
19648 	if (err) {
19649 		free_verifier_state(new, false);
19650 		kvfree(new_sl);
19651 		return err;
19652 	}
19653 
19654 	cur->parent = new;
19655 	cur->first_insn_idx = insn_idx;
19656 	cur->dfs_depth = new->dfs_depth + 1;
19657 	clear_jmp_history(cur);
19658 	list_add(&new_sl->node, head);
19659 
19660 	/* connect new state to parentage chain. Current frame needs all
19661 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
19662 	 * to the stack implicitly by JITs) so in callers' frames connect just
19663 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
19664 	 * the state of the call instruction (with WRITTEN set), and r0 comes
19665 	 * from callee with its full parentage chain, anyway.
19666 	 */
19667 	/* clear write marks in current state: the writes we did are not writes
19668 	 * our child did, so they don't screen off its reads from us.
19669 	 * (There are no read marks in current state, because reads always mark
19670 	 * their parent and current state never has children yet.  Only
19671 	 * explored_states can get read marks.)
19672 	 */
19673 	for (j = 0; j <= cur->curframe; j++) {
19674 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
19675 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
19676 		for (i = 0; i < BPF_REG_FP; i++)
19677 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
19678 	}
19679 
19680 	/* all stack frames are accessible from callee, clear them all */
19681 	for (j = 0; j <= cur->curframe; j++) {
19682 		struct bpf_func_state *frame = cur->frame[j];
19683 		struct bpf_func_state *newframe = new->frame[j];
19684 
19685 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
19686 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
19687 			frame->stack[i].spilled_ptr.parent =
19688 						&newframe->stack[i].spilled_ptr;
19689 		}
19690 	}
19691 	return 0;
19692 }
19693 
19694 /* Return true if it's OK to have the same insn return a different type. */
19695 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
19696 {
19697 	switch (base_type(type)) {
19698 	case PTR_TO_CTX:
19699 	case PTR_TO_SOCKET:
19700 	case PTR_TO_SOCK_COMMON:
19701 	case PTR_TO_TCP_SOCK:
19702 	case PTR_TO_XDP_SOCK:
19703 	case PTR_TO_BTF_ID:
19704 	case PTR_TO_ARENA:
19705 		return false;
19706 	default:
19707 		return true;
19708 	}
19709 }
19710 
19711 /* If an instruction was previously used with particular pointer types, then we
19712  * need to be careful to avoid cases such as the below, where it may be ok
19713  * for one branch accessing the pointer, but not ok for the other branch:
19714  *
19715  * R1 = sock_ptr
19716  * goto X;
19717  * ...
19718  * R1 = some_other_valid_ptr;
19719  * goto X;
19720  * ...
19721  * R2 = *(u32 *)(R1 + 0);
19722  */
19723 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
19724 {
19725 	return src != prev && (!reg_type_mismatch_ok(src) ||
19726 			       !reg_type_mismatch_ok(prev));
19727 }
19728 
19729 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
19730 {
19731 	switch (base_type(type)) {
19732 	case PTR_TO_MEM:
19733 	case PTR_TO_BTF_ID:
19734 		return true;
19735 	default:
19736 		return false;
19737 	}
19738 }
19739 
19740 static bool is_ptr_to_mem(enum bpf_reg_type type)
19741 {
19742 	return base_type(type) == PTR_TO_MEM;
19743 }
19744 
19745 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
19746 			     bool allow_trust_mismatch)
19747 {
19748 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
19749 	enum bpf_reg_type merged_type;
19750 
19751 	if (*prev_type == NOT_INIT) {
19752 		/* Saw a valid insn
19753 		 * dst_reg = *(u32 *)(src_reg + off)
19754 		 * save type to validate intersecting paths
19755 		 */
19756 		*prev_type = type;
19757 	} else if (reg_type_mismatch(type, *prev_type)) {
19758 		/* Abuser program is trying to use the same insn
19759 		 * dst_reg = *(u32*) (src_reg + off)
19760 		 * with different pointer types:
19761 		 * src_reg == ctx in one branch and
19762 		 * src_reg == stack|map in some other branch.
19763 		 * Reject it.
19764 		 */
19765 		if (allow_trust_mismatch &&
19766 		    is_ptr_to_mem_or_btf_id(type) &&
19767 		    is_ptr_to_mem_or_btf_id(*prev_type)) {
19768 			/*
19769 			 * Have to support a use case when one path through
19770 			 * the program yields TRUSTED pointer while another
19771 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
19772 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
19773 			 * Same behavior of MEM_RDONLY flag.
19774 			 */
19775 			if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type))
19776 				merged_type = PTR_TO_MEM;
19777 			else
19778 				merged_type = PTR_TO_BTF_ID;
19779 			if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED))
19780 				merged_type |= PTR_UNTRUSTED;
19781 			if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY))
19782 				merged_type |= MEM_RDONLY;
19783 			*prev_type = merged_type;
19784 		} else {
19785 			verbose(env, "same insn cannot be used with different pointers\n");
19786 			return -EINVAL;
19787 		}
19788 	}
19789 
19790 	return 0;
19791 }
19792 
19793 enum {
19794 	PROCESS_BPF_EXIT = 1
19795 };
19796 
19797 static int process_bpf_exit_full(struct bpf_verifier_env *env,
19798 				 bool *do_print_state,
19799 				 bool exception_exit)
19800 {
19801 	/* We must do check_reference_leak here before
19802 	 * prepare_func_exit to handle the case when
19803 	 * state->curframe > 0, it may be a callback function,
19804 	 * for which reference_state must match caller reference
19805 	 * state when it exits.
19806 	 */
19807 	int err = check_resource_leak(env, exception_exit,
19808 				      !env->cur_state->curframe,
19809 				      "BPF_EXIT instruction in main prog");
19810 	if (err)
19811 		return err;
19812 
19813 	/* The side effect of the prepare_func_exit which is
19814 	 * being skipped is that it frees bpf_func_state.
19815 	 * Typically, process_bpf_exit will only be hit with
19816 	 * outermost exit. copy_verifier_state in pop_stack will
19817 	 * handle freeing of any extra bpf_func_state left over
19818 	 * from not processing all nested function exits. We
19819 	 * also skip return code checks as they are not needed
19820 	 * for exceptional exits.
19821 	 */
19822 	if (exception_exit)
19823 		return PROCESS_BPF_EXIT;
19824 
19825 	if (env->cur_state->curframe) {
19826 		/* exit from nested function */
19827 		err = prepare_func_exit(env, &env->insn_idx);
19828 		if (err)
19829 			return err;
19830 		*do_print_state = true;
19831 		return 0;
19832 	}
19833 
19834 	err = check_return_code(env, BPF_REG_0, "R0");
19835 	if (err)
19836 		return err;
19837 	return PROCESS_BPF_EXIT;
19838 }
19839 
19840 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
19841 {
19842 	int err;
19843 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
19844 	u8 class = BPF_CLASS(insn->code);
19845 
19846 	if (class == BPF_ALU || class == BPF_ALU64) {
19847 		err = check_alu_op(env, insn);
19848 		if (err)
19849 			return err;
19850 
19851 	} else if (class == BPF_LDX) {
19852 		bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX;
19853 
19854 		/* Check for reserved fields is already done in
19855 		 * resolve_pseudo_ldimm64().
19856 		 */
19857 		err = check_load_mem(env, insn, false, is_ldsx, true, "ldx");
19858 		if (err)
19859 			return err;
19860 	} else if (class == BPF_STX) {
19861 		if (BPF_MODE(insn->code) == BPF_ATOMIC) {
19862 			err = check_atomic(env, insn);
19863 			if (err)
19864 				return err;
19865 			env->insn_idx++;
19866 			return 0;
19867 		}
19868 
19869 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
19870 			verbose(env, "BPF_STX uses reserved fields\n");
19871 			return -EINVAL;
19872 		}
19873 
19874 		err = check_store_reg(env, insn, false);
19875 		if (err)
19876 			return err;
19877 	} else if (class == BPF_ST) {
19878 		enum bpf_reg_type dst_reg_type;
19879 
19880 		if (BPF_MODE(insn->code) != BPF_MEM ||
19881 		    insn->src_reg != BPF_REG_0) {
19882 			verbose(env, "BPF_ST uses reserved fields\n");
19883 			return -EINVAL;
19884 		}
19885 		/* check src operand */
19886 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
19887 		if (err)
19888 			return err;
19889 
19890 		dst_reg_type = cur_regs(env)[insn->dst_reg].type;
19891 
19892 		/* check that memory (dst_reg + off) is writeable */
19893 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
19894 				       insn->off, BPF_SIZE(insn->code),
19895 				       BPF_WRITE, -1, false, false);
19896 		if (err)
19897 			return err;
19898 
19899 		err = save_aux_ptr_type(env, dst_reg_type, false);
19900 		if (err)
19901 			return err;
19902 	} else if (class == BPF_JMP || class == BPF_JMP32) {
19903 		u8 opcode = BPF_OP(insn->code);
19904 
19905 		env->jmps_processed++;
19906 		if (opcode == BPF_CALL) {
19907 			if (BPF_SRC(insn->code) != BPF_K ||
19908 			    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL &&
19909 			     insn->off != 0) ||
19910 			    (insn->src_reg != BPF_REG_0 &&
19911 			     insn->src_reg != BPF_PSEUDO_CALL &&
19912 			     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
19913 			    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
19914 				verbose(env, "BPF_CALL uses reserved fields\n");
19915 				return -EINVAL;
19916 			}
19917 
19918 			if (env->cur_state->active_locks) {
19919 				if ((insn->src_reg == BPF_REG_0 &&
19920 				     insn->imm != BPF_FUNC_spin_unlock) ||
19921 				    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
19922 				     (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
19923 					verbose(env,
19924 						"function calls are not allowed while holding a lock\n");
19925 					return -EINVAL;
19926 				}
19927 			}
19928 			if (insn->src_reg == BPF_PSEUDO_CALL) {
19929 				err = check_func_call(env, insn, &env->insn_idx);
19930 			} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19931 				err = check_kfunc_call(env, insn, &env->insn_idx);
19932 				if (!err && is_bpf_throw_kfunc(insn))
19933 					return process_bpf_exit_full(env, do_print_state, true);
19934 			} else {
19935 				err = check_helper_call(env, insn, &env->insn_idx);
19936 			}
19937 			if (err)
19938 				return err;
19939 
19940 			mark_reg_scratched(env, BPF_REG_0);
19941 		} else if (opcode == BPF_JA) {
19942 			if (BPF_SRC(insn->code) != BPF_K ||
19943 			    insn->src_reg != BPF_REG_0 ||
19944 			    insn->dst_reg != BPF_REG_0 ||
19945 			    (class == BPF_JMP && insn->imm != 0) ||
19946 			    (class == BPF_JMP32 && insn->off != 0)) {
19947 				verbose(env, "BPF_JA uses reserved fields\n");
19948 				return -EINVAL;
19949 			}
19950 
19951 			if (class == BPF_JMP)
19952 				env->insn_idx += insn->off + 1;
19953 			else
19954 				env->insn_idx += insn->imm + 1;
19955 			return 0;
19956 		} else if (opcode == BPF_EXIT) {
19957 			if (BPF_SRC(insn->code) != BPF_K ||
19958 			    insn->imm != 0 ||
19959 			    insn->src_reg != BPF_REG_0 ||
19960 			    insn->dst_reg != BPF_REG_0 ||
19961 			    class == BPF_JMP32) {
19962 				verbose(env, "BPF_EXIT uses reserved fields\n");
19963 				return -EINVAL;
19964 			}
19965 			return process_bpf_exit_full(env, do_print_state, false);
19966 		} else {
19967 			err = check_cond_jmp_op(env, insn, &env->insn_idx);
19968 			if (err)
19969 				return err;
19970 		}
19971 	} else if (class == BPF_LD) {
19972 		u8 mode = BPF_MODE(insn->code);
19973 
19974 		if (mode == BPF_ABS || mode == BPF_IND) {
19975 			err = check_ld_abs(env, insn);
19976 			if (err)
19977 				return err;
19978 
19979 		} else if (mode == BPF_IMM) {
19980 			err = check_ld_imm(env, insn);
19981 			if (err)
19982 				return err;
19983 
19984 			env->insn_idx++;
19985 			sanitize_mark_insn_seen(env);
19986 		} else {
19987 			verbose(env, "invalid BPF_LD mode\n");
19988 			return -EINVAL;
19989 		}
19990 	} else {
19991 		verbose(env, "unknown insn class %d\n", class);
19992 		return -EINVAL;
19993 	}
19994 
19995 	env->insn_idx++;
19996 	return 0;
19997 }
19998 
19999 static int do_check(struct bpf_verifier_env *env)
20000 {
20001 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20002 	struct bpf_verifier_state *state = env->cur_state;
20003 	struct bpf_insn *insns = env->prog->insnsi;
20004 	int insn_cnt = env->prog->len;
20005 	bool do_print_state = false;
20006 	int prev_insn_idx = -1;
20007 
20008 	for (;;) {
20009 		struct bpf_insn *insn;
20010 		struct bpf_insn_aux_data *insn_aux;
20011 		int err;
20012 
20013 		/* reset current history entry on each new instruction */
20014 		env->cur_hist_ent = NULL;
20015 
20016 		env->prev_insn_idx = prev_insn_idx;
20017 		if (env->insn_idx >= insn_cnt) {
20018 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
20019 				env->insn_idx, insn_cnt);
20020 			return -EFAULT;
20021 		}
20022 
20023 		insn = &insns[env->insn_idx];
20024 		insn_aux = &env->insn_aux_data[env->insn_idx];
20025 
20026 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
20027 			verbose(env,
20028 				"BPF program is too large. Processed %d insn\n",
20029 				env->insn_processed);
20030 			return -E2BIG;
20031 		}
20032 
20033 		state->last_insn_idx = env->prev_insn_idx;
20034 		state->insn_idx = env->insn_idx;
20035 
20036 		if (is_prune_point(env, env->insn_idx)) {
20037 			err = is_state_visited(env, env->insn_idx);
20038 			if (err < 0)
20039 				return err;
20040 			if (err == 1) {
20041 				/* found equivalent state, can prune the search */
20042 				if (env->log.level & BPF_LOG_LEVEL) {
20043 					if (do_print_state)
20044 						verbose(env, "\nfrom %d to %d%s: safe\n",
20045 							env->prev_insn_idx, env->insn_idx,
20046 							env->cur_state->speculative ?
20047 							" (speculative execution)" : "");
20048 					else
20049 						verbose(env, "%d: safe\n", env->insn_idx);
20050 				}
20051 				goto process_bpf_exit;
20052 			}
20053 		}
20054 
20055 		if (is_jmp_point(env, env->insn_idx)) {
20056 			err = push_jmp_history(env, state, 0, 0);
20057 			if (err)
20058 				return err;
20059 		}
20060 
20061 		if (signal_pending(current))
20062 			return -EAGAIN;
20063 
20064 		if (need_resched())
20065 			cond_resched();
20066 
20067 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
20068 			verbose(env, "\nfrom %d to %d%s:",
20069 				env->prev_insn_idx, env->insn_idx,
20070 				env->cur_state->speculative ?
20071 				" (speculative execution)" : "");
20072 			print_verifier_state(env, state, state->curframe, true);
20073 			do_print_state = false;
20074 		}
20075 
20076 		if (env->log.level & BPF_LOG_LEVEL) {
20077 			if (verifier_state_scratched(env))
20078 				print_insn_state(env, state, state->curframe);
20079 
20080 			verbose_linfo(env, env->insn_idx, "; ");
20081 			env->prev_log_pos = env->log.end_pos;
20082 			verbose(env, "%d: ", env->insn_idx);
20083 			verbose_insn(env, insn);
20084 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
20085 			env->prev_log_pos = env->log.end_pos;
20086 		}
20087 
20088 		if (bpf_prog_is_offloaded(env->prog->aux)) {
20089 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
20090 							   env->prev_insn_idx);
20091 			if (err)
20092 				return err;
20093 		}
20094 
20095 		sanitize_mark_insn_seen(env);
20096 		prev_insn_idx = env->insn_idx;
20097 
20098 		/* Reduce verification complexity by stopping speculative path
20099 		 * verification when a nospec is encountered.
20100 		 */
20101 		if (state->speculative && insn_aux->nospec)
20102 			goto process_bpf_exit;
20103 
20104 		err = do_check_insn(env, &do_print_state);
20105 		if (error_recoverable_with_nospec(err) && state->speculative) {
20106 			/* Prevent this speculative path from ever reaching the
20107 			 * insn that would have been unsafe to execute.
20108 			 */
20109 			insn_aux->nospec = true;
20110 			/* If it was an ADD/SUB insn, potentially remove any
20111 			 * markings for alu sanitization.
20112 			 */
20113 			insn_aux->alu_state = 0;
20114 			goto process_bpf_exit;
20115 		} else if (err < 0) {
20116 			return err;
20117 		} else if (err == PROCESS_BPF_EXIT) {
20118 			goto process_bpf_exit;
20119 		}
20120 		WARN_ON_ONCE(err);
20121 
20122 		if (state->speculative && insn_aux->nospec_result) {
20123 			/* If we are on a path that performed a jump-op, this
20124 			 * may skip a nospec patched-in after the jump. This can
20125 			 * currently never happen because nospec_result is only
20126 			 * used for the write-ops
20127 			 * `*(size*)(dst_reg+off)=src_reg|imm32` which must
20128 			 * never skip the following insn. Still, add a warning
20129 			 * to document this in case nospec_result is used
20130 			 * elsewhere in the future.
20131 			 *
20132 			 * All non-branch instructions have a single
20133 			 * fall-through edge. For these, nospec_result should
20134 			 * already work.
20135 			 */
20136 			if (verifier_bug_if(BPF_CLASS(insn->code) == BPF_JMP ||
20137 					    BPF_CLASS(insn->code) == BPF_JMP32, env,
20138 					    "speculation barrier after jump instruction may not have the desired effect"))
20139 				return -EFAULT;
20140 process_bpf_exit:
20141 			mark_verifier_state_scratched(env);
20142 			err = update_branch_counts(env, env->cur_state);
20143 			if (err)
20144 				return err;
20145 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
20146 					pop_log);
20147 			if (err < 0) {
20148 				if (err != -ENOENT)
20149 					return err;
20150 				break;
20151 			} else {
20152 				do_print_state = true;
20153 				continue;
20154 			}
20155 		}
20156 	}
20157 
20158 	return 0;
20159 }
20160 
20161 static int find_btf_percpu_datasec(struct btf *btf)
20162 {
20163 	const struct btf_type *t;
20164 	const char *tname;
20165 	int i, n;
20166 
20167 	/*
20168 	 * Both vmlinux and module each have their own ".data..percpu"
20169 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
20170 	 * types to look at only module's own BTF types.
20171 	 */
20172 	n = btf_nr_types(btf);
20173 	if (btf_is_module(btf))
20174 		i = btf_nr_types(btf_vmlinux);
20175 	else
20176 		i = 1;
20177 
20178 	for(; i < n; i++) {
20179 		t = btf_type_by_id(btf, i);
20180 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
20181 			continue;
20182 
20183 		tname = btf_name_by_offset(btf, t->name_off);
20184 		if (!strcmp(tname, ".data..percpu"))
20185 			return i;
20186 	}
20187 
20188 	return -ENOENT;
20189 }
20190 
20191 /*
20192  * Add btf to the used_btfs array and return the index. (If the btf was
20193  * already added, then just return the index.) Upon successful insertion
20194  * increase btf refcnt, and, if present, also refcount the corresponding
20195  * kernel module.
20196  */
20197 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
20198 {
20199 	struct btf_mod_pair *btf_mod;
20200 	int i;
20201 
20202 	/* check whether we recorded this BTF (and maybe module) already */
20203 	for (i = 0; i < env->used_btf_cnt; i++)
20204 		if (env->used_btfs[i].btf == btf)
20205 			return i;
20206 
20207 	if (env->used_btf_cnt >= MAX_USED_BTFS)
20208 		return -E2BIG;
20209 
20210 	btf_get(btf);
20211 
20212 	btf_mod = &env->used_btfs[env->used_btf_cnt];
20213 	btf_mod->btf = btf;
20214 	btf_mod->module = NULL;
20215 
20216 	/* if we reference variables from kernel module, bump its refcount */
20217 	if (btf_is_module(btf)) {
20218 		btf_mod->module = btf_try_get_module(btf);
20219 		if (!btf_mod->module) {
20220 			btf_put(btf);
20221 			return -ENXIO;
20222 		}
20223 	}
20224 
20225 	return env->used_btf_cnt++;
20226 }
20227 
20228 /* replace pseudo btf_id with kernel symbol address */
20229 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
20230 				 struct bpf_insn *insn,
20231 				 struct bpf_insn_aux_data *aux,
20232 				 struct btf *btf)
20233 {
20234 	const struct btf_var_secinfo *vsi;
20235 	const struct btf_type *datasec;
20236 	const struct btf_type *t;
20237 	const char *sym_name;
20238 	bool percpu = false;
20239 	u32 type, id = insn->imm;
20240 	s32 datasec_id;
20241 	u64 addr;
20242 	int i;
20243 
20244 	t = btf_type_by_id(btf, id);
20245 	if (!t) {
20246 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
20247 		return -ENOENT;
20248 	}
20249 
20250 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
20251 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
20252 		return -EINVAL;
20253 	}
20254 
20255 	sym_name = btf_name_by_offset(btf, t->name_off);
20256 	addr = kallsyms_lookup_name(sym_name);
20257 	if (!addr) {
20258 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
20259 			sym_name);
20260 		return -ENOENT;
20261 	}
20262 	insn[0].imm = (u32)addr;
20263 	insn[1].imm = addr >> 32;
20264 
20265 	if (btf_type_is_func(t)) {
20266 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20267 		aux->btf_var.mem_size = 0;
20268 		return 0;
20269 	}
20270 
20271 	datasec_id = find_btf_percpu_datasec(btf);
20272 	if (datasec_id > 0) {
20273 		datasec = btf_type_by_id(btf, datasec_id);
20274 		for_each_vsi(i, datasec, vsi) {
20275 			if (vsi->type == id) {
20276 				percpu = true;
20277 				break;
20278 			}
20279 		}
20280 	}
20281 
20282 	type = t->type;
20283 	t = btf_type_skip_modifiers(btf, type, NULL);
20284 	if (percpu) {
20285 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
20286 		aux->btf_var.btf = btf;
20287 		aux->btf_var.btf_id = type;
20288 	} else if (!btf_type_is_struct(t)) {
20289 		const struct btf_type *ret;
20290 		const char *tname;
20291 		u32 tsize;
20292 
20293 		/* resolve the type size of ksym. */
20294 		ret = btf_resolve_size(btf, t, &tsize);
20295 		if (IS_ERR(ret)) {
20296 			tname = btf_name_by_offset(btf, t->name_off);
20297 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
20298 				tname, PTR_ERR(ret));
20299 			return -EINVAL;
20300 		}
20301 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20302 		aux->btf_var.mem_size = tsize;
20303 	} else {
20304 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
20305 		aux->btf_var.btf = btf;
20306 		aux->btf_var.btf_id = type;
20307 	}
20308 
20309 	return 0;
20310 }
20311 
20312 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
20313 			       struct bpf_insn *insn,
20314 			       struct bpf_insn_aux_data *aux)
20315 {
20316 	struct btf *btf;
20317 	int btf_fd;
20318 	int err;
20319 
20320 	btf_fd = insn[1].imm;
20321 	if (btf_fd) {
20322 		CLASS(fd, f)(btf_fd);
20323 
20324 		btf = __btf_get_by_fd(f);
20325 		if (IS_ERR(btf)) {
20326 			verbose(env, "invalid module BTF object FD specified.\n");
20327 			return -EINVAL;
20328 		}
20329 	} else {
20330 		if (!btf_vmlinux) {
20331 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
20332 			return -EINVAL;
20333 		}
20334 		btf = btf_vmlinux;
20335 	}
20336 
20337 	err = __check_pseudo_btf_id(env, insn, aux, btf);
20338 	if (err)
20339 		return err;
20340 
20341 	err = __add_used_btf(env, btf);
20342 	if (err < 0)
20343 		return err;
20344 	return 0;
20345 }
20346 
20347 static bool is_tracing_prog_type(enum bpf_prog_type type)
20348 {
20349 	switch (type) {
20350 	case BPF_PROG_TYPE_KPROBE:
20351 	case BPF_PROG_TYPE_TRACEPOINT:
20352 	case BPF_PROG_TYPE_PERF_EVENT:
20353 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
20354 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
20355 		return true;
20356 	default:
20357 		return false;
20358 	}
20359 }
20360 
20361 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
20362 {
20363 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
20364 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
20365 }
20366 
20367 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
20368 					struct bpf_map *map,
20369 					struct bpf_prog *prog)
20370 
20371 {
20372 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
20373 
20374 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
20375 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
20376 		if (is_tracing_prog_type(prog_type)) {
20377 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
20378 			return -EINVAL;
20379 		}
20380 	}
20381 
20382 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
20383 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
20384 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
20385 			return -EINVAL;
20386 		}
20387 
20388 		if (is_tracing_prog_type(prog_type)) {
20389 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
20390 			return -EINVAL;
20391 		}
20392 	}
20393 
20394 	if (btf_record_has_field(map->record, BPF_TIMER)) {
20395 		if (is_tracing_prog_type(prog_type)) {
20396 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
20397 			return -EINVAL;
20398 		}
20399 	}
20400 
20401 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
20402 		if (is_tracing_prog_type(prog_type)) {
20403 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
20404 			return -EINVAL;
20405 		}
20406 	}
20407 
20408 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
20409 	    !bpf_offload_prog_map_match(prog, map)) {
20410 		verbose(env, "offload device mismatch between prog and map\n");
20411 		return -EINVAL;
20412 	}
20413 
20414 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
20415 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
20416 		return -EINVAL;
20417 	}
20418 
20419 	if (prog->sleepable)
20420 		switch (map->map_type) {
20421 		case BPF_MAP_TYPE_HASH:
20422 		case BPF_MAP_TYPE_LRU_HASH:
20423 		case BPF_MAP_TYPE_ARRAY:
20424 		case BPF_MAP_TYPE_PERCPU_HASH:
20425 		case BPF_MAP_TYPE_PERCPU_ARRAY:
20426 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
20427 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
20428 		case BPF_MAP_TYPE_HASH_OF_MAPS:
20429 		case BPF_MAP_TYPE_RINGBUF:
20430 		case BPF_MAP_TYPE_USER_RINGBUF:
20431 		case BPF_MAP_TYPE_INODE_STORAGE:
20432 		case BPF_MAP_TYPE_SK_STORAGE:
20433 		case BPF_MAP_TYPE_TASK_STORAGE:
20434 		case BPF_MAP_TYPE_CGRP_STORAGE:
20435 		case BPF_MAP_TYPE_QUEUE:
20436 		case BPF_MAP_TYPE_STACK:
20437 		case BPF_MAP_TYPE_ARENA:
20438 			break;
20439 		default:
20440 			verbose(env,
20441 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
20442 			return -EINVAL;
20443 		}
20444 
20445 	if (bpf_map_is_cgroup_storage(map) &&
20446 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
20447 		verbose(env, "only one cgroup storage of each type is allowed\n");
20448 		return -EBUSY;
20449 	}
20450 
20451 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
20452 		if (env->prog->aux->arena) {
20453 			verbose(env, "Only one arena per program\n");
20454 			return -EBUSY;
20455 		}
20456 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
20457 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
20458 			return -EPERM;
20459 		}
20460 		if (!env->prog->jit_requested) {
20461 			verbose(env, "JIT is required to use arena\n");
20462 			return -EOPNOTSUPP;
20463 		}
20464 		if (!bpf_jit_supports_arena()) {
20465 			verbose(env, "JIT doesn't support arena\n");
20466 			return -EOPNOTSUPP;
20467 		}
20468 		env->prog->aux->arena = (void *)map;
20469 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
20470 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
20471 			return -EINVAL;
20472 		}
20473 	}
20474 
20475 	return 0;
20476 }
20477 
20478 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
20479 {
20480 	int i, err;
20481 
20482 	/* check whether we recorded this map already */
20483 	for (i = 0; i < env->used_map_cnt; i++)
20484 		if (env->used_maps[i] == map)
20485 			return i;
20486 
20487 	if (env->used_map_cnt >= MAX_USED_MAPS) {
20488 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
20489 			MAX_USED_MAPS);
20490 		return -E2BIG;
20491 	}
20492 
20493 	err = check_map_prog_compatibility(env, map, env->prog);
20494 	if (err)
20495 		return err;
20496 
20497 	if (env->prog->sleepable)
20498 		atomic64_inc(&map->sleepable_refcnt);
20499 
20500 	/* hold the map. If the program is rejected by verifier,
20501 	 * the map will be released by release_maps() or it
20502 	 * will be used by the valid program until it's unloaded
20503 	 * and all maps are released in bpf_free_used_maps()
20504 	 */
20505 	bpf_map_inc(map);
20506 
20507 	env->used_maps[env->used_map_cnt++] = map;
20508 
20509 	return env->used_map_cnt - 1;
20510 }
20511 
20512 /* Add map behind fd to used maps list, if it's not already there, and return
20513  * its index.
20514  * Returns <0 on error, or >= 0 index, on success.
20515  */
20516 static int add_used_map(struct bpf_verifier_env *env, int fd)
20517 {
20518 	struct bpf_map *map;
20519 	CLASS(fd, f)(fd);
20520 
20521 	map = __bpf_map_get(f);
20522 	if (IS_ERR(map)) {
20523 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
20524 		return PTR_ERR(map);
20525 	}
20526 
20527 	return __add_used_map(env, map);
20528 }
20529 
20530 /* find and rewrite pseudo imm in ld_imm64 instructions:
20531  *
20532  * 1. if it accesses map FD, replace it with actual map pointer.
20533  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
20534  *
20535  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
20536  */
20537 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
20538 {
20539 	struct bpf_insn *insn = env->prog->insnsi;
20540 	int insn_cnt = env->prog->len;
20541 	int i, err;
20542 
20543 	err = bpf_prog_calc_tag(env->prog);
20544 	if (err)
20545 		return err;
20546 
20547 	for (i = 0; i < insn_cnt; i++, insn++) {
20548 		if (BPF_CLASS(insn->code) == BPF_LDX &&
20549 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
20550 		    insn->imm != 0)) {
20551 			verbose(env, "BPF_LDX uses reserved fields\n");
20552 			return -EINVAL;
20553 		}
20554 
20555 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
20556 			struct bpf_insn_aux_data *aux;
20557 			struct bpf_map *map;
20558 			int map_idx;
20559 			u64 addr;
20560 			u32 fd;
20561 
20562 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
20563 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
20564 			    insn[1].off != 0) {
20565 				verbose(env, "invalid bpf_ld_imm64 insn\n");
20566 				return -EINVAL;
20567 			}
20568 
20569 			if (insn[0].src_reg == 0)
20570 				/* valid generic load 64-bit imm */
20571 				goto next_insn;
20572 
20573 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
20574 				aux = &env->insn_aux_data[i];
20575 				err = check_pseudo_btf_id(env, insn, aux);
20576 				if (err)
20577 					return err;
20578 				goto next_insn;
20579 			}
20580 
20581 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
20582 				aux = &env->insn_aux_data[i];
20583 				aux->ptr_type = PTR_TO_FUNC;
20584 				goto next_insn;
20585 			}
20586 
20587 			/* In final convert_pseudo_ld_imm64() step, this is
20588 			 * converted into regular 64-bit imm load insn.
20589 			 */
20590 			switch (insn[0].src_reg) {
20591 			case BPF_PSEUDO_MAP_VALUE:
20592 			case BPF_PSEUDO_MAP_IDX_VALUE:
20593 				break;
20594 			case BPF_PSEUDO_MAP_FD:
20595 			case BPF_PSEUDO_MAP_IDX:
20596 				if (insn[1].imm == 0)
20597 					break;
20598 				fallthrough;
20599 			default:
20600 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
20601 				return -EINVAL;
20602 			}
20603 
20604 			switch (insn[0].src_reg) {
20605 			case BPF_PSEUDO_MAP_IDX_VALUE:
20606 			case BPF_PSEUDO_MAP_IDX:
20607 				if (bpfptr_is_null(env->fd_array)) {
20608 					verbose(env, "fd_idx without fd_array is invalid\n");
20609 					return -EPROTO;
20610 				}
20611 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
20612 							    insn[0].imm * sizeof(fd),
20613 							    sizeof(fd)))
20614 					return -EFAULT;
20615 				break;
20616 			default:
20617 				fd = insn[0].imm;
20618 				break;
20619 			}
20620 
20621 			map_idx = add_used_map(env, fd);
20622 			if (map_idx < 0)
20623 				return map_idx;
20624 			map = env->used_maps[map_idx];
20625 
20626 			aux = &env->insn_aux_data[i];
20627 			aux->map_index = map_idx;
20628 
20629 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
20630 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
20631 				addr = (unsigned long)map;
20632 			} else {
20633 				u32 off = insn[1].imm;
20634 
20635 				if (off >= BPF_MAX_VAR_OFF) {
20636 					verbose(env, "direct value offset of %u is not allowed\n", off);
20637 					return -EINVAL;
20638 				}
20639 
20640 				if (!map->ops->map_direct_value_addr) {
20641 					verbose(env, "no direct value access support for this map type\n");
20642 					return -EINVAL;
20643 				}
20644 
20645 				err = map->ops->map_direct_value_addr(map, &addr, off);
20646 				if (err) {
20647 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
20648 						map->value_size, off);
20649 					return err;
20650 				}
20651 
20652 				aux->map_off = off;
20653 				addr += off;
20654 			}
20655 
20656 			insn[0].imm = (u32)addr;
20657 			insn[1].imm = addr >> 32;
20658 
20659 next_insn:
20660 			insn++;
20661 			i++;
20662 			continue;
20663 		}
20664 
20665 		/* Basic sanity check before we invest more work here. */
20666 		if (!bpf_opcode_in_insntable(insn->code)) {
20667 			verbose(env, "unknown opcode %02x\n", insn->code);
20668 			return -EINVAL;
20669 		}
20670 	}
20671 
20672 	/* now all pseudo BPF_LD_IMM64 instructions load valid
20673 	 * 'struct bpf_map *' into a register instead of user map_fd.
20674 	 * These pointers will be used later by verifier to validate map access.
20675 	 */
20676 	return 0;
20677 }
20678 
20679 /* drop refcnt of maps used by the rejected program */
20680 static void release_maps(struct bpf_verifier_env *env)
20681 {
20682 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
20683 			     env->used_map_cnt);
20684 }
20685 
20686 /* drop refcnt of maps used by the rejected program */
20687 static void release_btfs(struct bpf_verifier_env *env)
20688 {
20689 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
20690 }
20691 
20692 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
20693 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
20694 {
20695 	struct bpf_insn *insn = env->prog->insnsi;
20696 	int insn_cnt = env->prog->len;
20697 	int i;
20698 
20699 	for (i = 0; i < insn_cnt; i++, insn++) {
20700 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
20701 			continue;
20702 		if (insn->src_reg == BPF_PSEUDO_FUNC)
20703 			continue;
20704 		insn->src_reg = 0;
20705 	}
20706 }
20707 
20708 /* single env->prog->insni[off] instruction was replaced with the range
20709  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
20710  * [0, off) and [off, end) to new locations, so the patched range stays zero
20711  */
20712 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
20713 				 struct bpf_insn_aux_data *new_data,
20714 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
20715 {
20716 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
20717 	struct bpf_insn *insn = new_prog->insnsi;
20718 	u32 old_seen = old_data[off].seen;
20719 	u32 prog_len;
20720 	int i;
20721 
20722 	/* aux info at OFF always needs adjustment, no matter fast path
20723 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
20724 	 * original insn at old prog.
20725 	 */
20726 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
20727 
20728 	if (cnt == 1)
20729 		return;
20730 	prog_len = new_prog->len;
20731 
20732 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
20733 	memcpy(new_data + off + cnt - 1, old_data + off,
20734 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
20735 	for (i = off; i < off + cnt - 1; i++) {
20736 		/* Expand insni[off]'s seen count to the patched range. */
20737 		new_data[i].seen = old_seen;
20738 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
20739 	}
20740 	env->insn_aux_data = new_data;
20741 	vfree(old_data);
20742 }
20743 
20744 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
20745 {
20746 	int i;
20747 
20748 	if (len == 1)
20749 		return;
20750 	/* NOTE: fake 'exit' subprog should be updated as well. */
20751 	for (i = 0; i <= env->subprog_cnt; i++) {
20752 		if (env->subprog_info[i].start <= off)
20753 			continue;
20754 		env->subprog_info[i].start += len - 1;
20755 	}
20756 }
20757 
20758 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
20759 {
20760 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
20761 	int i, sz = prog->aux->size_poke_tab;
20762 	struct bpf_jit_poke_descriptor *desc;
20763 
20764 	for (i = 0; i < sz; i++) {
20765 		desc = &tab[i];
20766 		if (desc->insn_idx <= off)
20767 			continue;
20768 		desc->insn_idx += len - 1;
20769 	}
20770 }
20771 
20772 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
20773 					    const struct bpf_insn *patch, u32 len)
20774 {
20775 	struct bpf_prog *new_prog;
20776 	struct bpf_insn_aux_data *new_data = NULL;
20777 
20778 	if (len > 1) {
20779 		new_data = vzalloc(array_size(env->prog->len + len - 1,
20780 					      sizeof(struct bpf_insn_aux_data)));
20781 		if (!new_data)
20782 			return NULL;
20783 	}
20784 
20785 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
20786 	if (IS_ERR(new_prog)) {
20787 		if (PTR_ERR(new_prog) == -ERANGE)
20788 			verbose(env,
20789 				"insn %d cannot be patched due to 16-bit range\n",
20790 				env->insn_aux_data[off].orig_idx);
20791 		vfree(new_data);
20792 		return NULL;
20793 	}
20794 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
20795 	adjust_subprog_starts(env, off, len);
20796 	adjust_poke_descs(new_prog, off, len);
20797 	return new_prog;
20798 }
20799 
20800 /*
20801  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
20802  * jump offset by 'delta'.
20803  */
20804 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
20805 {
20806 	struct bpf_insn *insn = prog->insnsi;
20807 	u32 insn_cnt = prog->len, i;
20808 	s32 imm;
20809 	s16 off;
20810 
20811 	for (i = 0; i < insn_cnt; i++, insn++) {
20812 		u8 code = insn->code;
20813 
20814 		if (tgt_idx <= i && i < tgt_idx + delta)
20815 			continue;
20816 
20817 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
20818 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
20819 			continue;
20820 
20821 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
20822 			if (i + 1 + insn->imm != tgt_idx)
20823 				continue;
20824 			if (check_add_overflow(insn->imm, delta, &imm))
20825 				return -ERANGE;
20826 			insn->imm = imm;
20827 		} else {
20828 			if (i + 1 + insn->off != tgt_idx)
20829 				continue;
20830 			if (check_add_overflow(insn->off, delta, &off))
20831 				return -ERANGE;
20832 			insn->off = off;
20833 		}
20834 	}
20835 	return 0;
20836 }
20837 
20838 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
20839 					      u32 off, u32 cnt)
20840 {
20841 	int i, j;
20842 
20843 	/* find first prog starting at or after off (first to remove) */
20844 	for (i = 0; i < env->subprog_cnt; i++)
20845 		if (env->subprog_info[i].start >= off)
20846 			break;
20847 	/* find first prog starting at or after off + cnt (first to stay) */
20848 	for (j = i; j < env->subprog_cnt; j++)
20849 		if (env->subprog_info[j].start >= off + cnt)
20850 			break;
20851 	/* if j doesn't start exactly at off + cnt, we are just removing
20852 	 * the front of previous prog
20853 	 */
20854 	if (env->subprog_info[j].start != off + cnt)
20855 		j--;
20856 
20857 	if (j > i) {
20858 		struct bpf_prog_aux *aux = env->prog->aux;
20859 		int move;
20860 
20861 		/* move fake 'exit' subprog as well */
20862 		move = env->subprog_cnt + 1 - j;
20863 
20864 		memmove(env->subprog_info + i,
20865 			env->subprog_info + j,
20866 			sizeof(*env->subprog_info) * move);
20867 		env->subprog_cnt -= j - i;
20868 
20869 		/* remove func_info */
20870 		if (aux->func_info) {
20871 			move = aux->func_info_cnt - j;
20872 
20873 			memmove(aux->func_info + i,
20874 				aux->func_info + j,
20875 				sizeof(*aux->func_info) * move);
20876 			aux->func_info_cnt -= j - i;
20877 			/* func_info->insn_off is set after all code rewrites,
20878 			 * in adjust_btf_func() - no need to adjust
20879 			 */
20880 		}
20881 	} else {
20882 		/* convert i from "first prog to remove" to "first to adjust" */
20883 		if (env->subprog_info[i].start == off)
20884 			i++;
20885 	}
20886 
20887 	/* update fake 'exit' subprog as well */
20888 	for (; i <= env->subprog_cnt; i++)
20889 		env->subprog_info[i].start -= cnt;
20890 
20891 	return 0;
20892 }
20893 
20894 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
20895 				      u32 cnt)
20896 {
20897 	struct bpf_prog *prog = env->prog;
20898 	u32 i, l_off, l_cnt, nr_linfo;
20899 	struct bpf_line_info *linfo;
20900 
20901 	nr_linfo = prog->aux->nr_linfo;
20902 	if (!nr_linfo)
20903 		return 0;
20904 
20905 	linfo = prog->aux->linfo;
20906 
20907 	/* find first line info to remove, count lines to be removed */
20908 	for (i = 0; i < nr_linfo; i++)
20909 		if (linfo[i].insn_off >= off)
20910 			break;
20911 
20912 	l_off = i;
20913 	l_cnt = 0;
20914 	for (; i < nr_linfo; i++)
20915 		if (linfo[i].insn_off < off + cnt)
20916 			l_cnt++;
20917 		else
20918 			break;
20919 
20920 	/* First live insn doesn't match first live linfo, it needs to "inherit"
20921 	 * last removed linfo.  prog is already modified, so prog->len == off
20922 	 * means no live instructions after (tail of the program was removed).
20923 	 */
20924 	if (prog->len != off && l_cnt &&
20925 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
20926 		l_cnt--;
20927 		linfo[--i].insn_off = off + cnt;
20928 	}
20929 
20930 	/* remove the line info which refer to the removed instructions */
20931 	if (l_cnt) {
20932 		memmove(linfo + l_off, linfo + i,
20933 			sizeof(*linfo) * (nr_linfo - i));
20934 
20935 		prog->aux->nr_linfo -= l_cnt;
20936 		nr_linfo = prog->aux->nr_linfo;
20937 	}
20938 
20939 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
20940 	for (i = l_off; i < nr_linfo; i++)
20941 		linfo[i].insn_off -= cnt;
20942 
20943 	/* fix up all subprogs (incl. 'exit') which start >= off */
20944 	for (i = 0; i <= env->subprog_cnt; i++)
20945 		if (env->subprog_info[i].linfo_idx > l_off) {
20946 			/* program may have started in the removed region but
20947 			 * may not be fully removed
20948 			 */
20949 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
20950 				env->subprog_info[i].linfo_idx -= l_cnt;
20951 			else
20952 				env->subprog_info[i].linfo_idx = l_off;
20953 		}
20954 
20955 	return 0;
20956 }
20957 
20958 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
20959 {
20960 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20961 	unsigned int orig_prog_len = env->prog->len;
20962 	int err;
20963 
20964 	if (bpf_prog_is_offloaded(env->prog->aux))
20965 		bpf_prog_offload_remove_insns(env, off, cnt);
20966 
20967 	err = bpf_remove_insns(env->prog, off, cnt);
20968 	if (err)
20969 		return err;
20970 
20971 	err = adjust_subprog_starts_after_remove(env, off, cnt);
20972 	if (err)
20973 		return err;
20974 
20975 	err = bpf_adj_linfo_after_remove(env, off, cnt);
20976 	if (err)
20977 		return err;
20978 
20979 	memmove(aux_data + off,	aux_data + off + cnt,
20980 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
20981 
20982 	return 0;
20983 }
20984 
20985 /* The verifier does more data flow analysis than llvm and will not
20986  * explore branches that are dead at run time. Malicious programs can
20987  * have dead code too. Therefore replace all dead at-run-time code
20988  * with 'ja -1'.
20989  *
20990  * Just nops are not optimal, e.g. if they would sit at the end of the
20991  * program and through another bug we would manage to jump there, then
20992  * we'd execute beyond program memory otherwise. Returning exception
20993  * code also wouldn't work since we can have subprogs where the dead
20994  * code could be located.
20995  */
20996 static void sanitize_dead_code(struct bpf_verifier_env *env)
20997 {
20998 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20999 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
21000 	struct bpf_insn *insn = env->prog->insnsi;
21001 	const int insn_cnt = env->prog->len;
21002 	int i;
21003 
21004 	for (i = 0; i < insn_cnt; i++) {
21005 		if (aux_data[i].seen)
21006 			continue;
21007 		memcpy(insn + i, &trap, sizeof(trap));
21008 		aux_data[i].zext_dst = false;
21009 	}
21010 }
21011 
21012 static bool insn_is_cond_jump(u8 code)
21013 {
21014 	u8 op;
21015 
21016 	op = BPF_OP(code);
21017 	if (BPF_CLASS(code) == BPF_JMP32)
21018 		return op != BPF_JA;
21019 
21020 	if (BPF_CLASS(code) != BPF_JMP)
21021 		return false;
21022 
21023 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
21024 }
21025 
21026 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
21027 {
21028 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21029 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21030 	struct bpf_insn *insn = env->prog->insnsi;
21031 	const int insn_cnt = env->prog->len;
21032 	int i;
21033 
21034 	for (i = 0; i < insn_cnt; i++, insn++) {
21035 		if (!insn_is_cond_jump(insn->code))
21036 			continue;
21037 
21038 		if (!aux_data[i + 1].seen)
21039 			ja.off = insn->off;
21040 		else if (!aux_data[i + 1 + insn->off].seen)
21041 			ja.off = 0;
21042 		else
21043 			continue;
21044 
21045 		if (bpf_prog_is_offloaded(env->prog->aux))
21046 			bpf_prog_offload_replace_insn(env, i, &ja);
21047 
21048 		memcpy(insn, &ja, sizeof(ja));
21049 	}
21050 }
21051 
21052 static int opt_remove_dead_code(struct bpf_verifier_env *env)
21053 {
21054 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21055 	int insn_cnt = env->prog->len;
21056 	int i, err;
21057 
21058 	for (i = 0; i < insn_cnt; i++) {
21059 		int j;
21060 
21061 		j = 0;
21062 		while (i + j < insn_cnt && !aux_data[i + j].seen)
21063 			j++;
21064 		if (!j)
21065 			continue;
21066 
21067 		err = verifier_remove_insns(env, i, j);
21068 		if (err)
21069 			return err;
21070 		insn_cnt = env->prog->len;
21071 	}
21072 
21073 	return 0;
21074 }
21075 
21076 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21077 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0);
21078 
21079 static int opt_remove_nops(struct bpf_verifier_env *env)
21080 {
21081 	struct bpf_insn *insn = env->prog->insnsi;
21082 	int insn_cnt = env->prog->len;
21083 	bool is_may_goto_0, is_ja;
21084 	int i, err;
21085 
21086 	for (i = 0; i < insn_cnt; i++) {
21087 		is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
21088 		is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP));
21089 
21090 		if (!is_may_goto_0 && !is_ja)
21091 			continue;
21092 
21093 		err = verifier_remove_insns(env, i, 1);
21094 		if (err)
21095 			return err;
21096 		insn_cnt--;
21097 		/* Go back one insn to catch may_goto +1; may_goto +0 sequence */
21098 		i -= (is_may_goto_0 && i > 0) ? 2 : 1;
21099 	}
21100 
21101 	return 0;
21102 }
21103 
21104 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
21105 					 const union bpf_attr *attr)
21106 {
21107 	struct bpf_insn *patch;
21108 	/* use env->insn_buf as two independent buffers */
21109 	struct bpf_insn *zext_patch = env->insn_buf;
21110 	struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2];
21111 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
21112 	int i, patch_len, delta = 0, len = env->prog->len;
21113 	struct bpf_insn *insns = env->prog->insnsi;
21114 	struct bpf_prog *new_prog;
21115 	bool rnd_hi32;
21116 
21117 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
21118 	zext_patch[1] = BPF_ZEXT_REG(0);
21119 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
21120 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
21121 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
21122 	for (i = 0; i < len; i++) {
21123 		int adj_idx = i + delta;
21124 		struct bpf_insn insn;
21125 		int load_reg;
21126 
21127 		insn = insns[adj_idx];
21128 		load_reg = insn_def_regno(&insn);
21129 		if (!aux[adj_idx].zext_dst) {
21130 			u8 code, class;
21131 			u32 imm_rnd;
21132 
21133 			if (!rnd_hi32)
21134 				continue;
21135 
21136 			code = insn.code;
21137 			class = BPF_CLASS(code);
21138 			if (load_reg == -1)
21139 				continue;
21140 
21141 			/* NOTE: arg "reg" (the fourth one) is only used for
21142 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
21143 			 *       here.
21144 			 */
21145 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
21146 				if (class == BPF_LD &&
21147 				    BPF_MODE(code) == BPF_IMM)
21148 					i++;
21149 				continue;
21150 			}
21151 
21152 			/* ctx load could be transformed into wider load. */
21153 			if (class == BPF_LDX &&
21154 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
21155 				continue;
21156 
21157 			imm_rnd = get_random_u32();
21158 			rnd_hi32_patch[0] = insn;
21159 			rnd_hi32_patch[1].imm = imm_rnd;
21160 			rnd_hi32_patch[3].dst_reg = load_reg;
21161 			patch = rnd_hi32_patch;
21162 			patch_len = 4;
21163 			goto apply_patch_buffer;
21164 		}
21165 
21166 		/* Add in an zero-extend instruction if a) the JIT has requested
21167 		 * it or b) it's a CMPXCHG.
21168 		 *
21169 		 * The latter is because: BPF_CMPXCHG always loads a value into
21170 		 * R0, therefore always zero-extends. However some archs'
21171 		 * equivalent instruction only does this load when the
21172 		 * comparison is successful. This detail of CMPXCHG is
21173 		 * orthogonal to the general zero-extension behaviour of the
21174 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
21175 		 */
21176 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
21177 			continue;
21178 
21179 		/* Zero-extension is done by the caller. */
21180 		if (bpf_pseudo_kfunc_call(&insn))
21181 			continue;
21182 
21183 		if (verifier_bug_if(load_reg == -1, env,
21184 				    "zext_dst is set, but no reg is defined"))
21185 			return -EFAULT;
21186 
21187 		zext_patch[0] = insn;
21188 		zext_patch[1].dst_reg = load_reg;
21189 		zext_patch[1].src_reg = load_reg;
21190 		patch = zext_patch;
21191 		patch_len = 2;
21192 apply_patch_buffer:
21193 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
21194 		if (!new_prog)
21195 			return -ENOMEM;
21196 		env->prog = new_prog;
21197 		insns = new_prog->insnsi;
21198 		aux = env->insn_aux_data;
21199 		delta += patch_len - 1;
21200 	}
21201 
21202 	return 0;
21203 }
21204 
21205 /* convert load instructions that access fields of a context type into a
21206  * sequence of instructions that access fields of the underlying structure:
21207  *     struct __sk_buff    -> struct sk_buff
21208  *     struct bpf_sock_ops -> struct sock
21209  */
21210 static int convert_ctx_accesses(struct bpf_verifier_env *env)
21211 {
21212 	struct bpf_subprog_info *subprogs = env->subprog_info;
21213 	const struct bpf_verifier_ops *ops = env->ops;
21214 	int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
21215 	const int insn_cnt = env->prog->len;
21216 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
21217 	struct bpf_insn *insn_buf = env->insn_buf;
21218 	struct bpf_insn *insn;
21219 	u32 target_size, size_default, off;
21220 	struct bpf_prog *new_prog;
21221 	enum bpf_access_type type;
21222 	bool is_narrower_load;
21223 	int epilogue_idx = 0;
21224 
21225 	if (ops->gen_epilogue) {
21226 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
21227 						 -(subprogs[0].stack_depth + 8));
21228 		if (epilogue_cnt >= INSN_BUF_SIZE) {
21229 			verifier_bug(env, "epilogue is too long");
21230 			return -EFAULT;
21231 		} else if (epilogue_cnt) {
21232 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
21233 			cnt = 0;
21234 			subprogs[0].stack_depth += 8;
21235 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
21236 						      -subprogs[0].stack_depth);
21237 			insn_buf[cnt++] = env->prog->insnsi[0];
21238 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21239 			if (!new_prog)
21240 				return -ENOMEM;
21241 			env->prog = new_prog;
21242 			delta += cnt - 1;
21243 
21244 			ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
21245 			if (ret < 0)
21246 				return ret;
21247 		}
21248 	}
21249 
21250 	if (ops->gen_prologue || env->seen_direct_write) {
21251 		if (!ops->gen_prologue) {
21252 			verifier_bug(env, "gen_prologue is null");
21253 			return -EFAULT;
21254 		}
21255 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
21256 					env->prog);
21257 		if (cnt >= INSN_BUF_SIZE) {
21258 			verifier_bug(env, "prologue is too long");
21259 			return -EFAULT;
21260 		} else if (cnt) {
21261 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21262 			if (!new_prog)
21263 				return -ENOMEM;
21264 
21265 			env->prog = new_prog;
21266 			delta += cnt - 1;
21267 
21268 			ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
21269 			if (ret < 0)
21270 				return ret;
21271 		}
21272 	}
21273 
21274 	if (delta)
21275 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
21276 
21277 	if (bpf_prog_is_offloaded(env->prog->aux))
21278 		return 0;
21279 
21280 	insn = env->prog->insnsi + delta;
21281 
21282 	for (i = 0; i < insn_cnt; i++, insn++) {
21283 		bpf_convert_ctx_access_t convert_ctx_access;
21284 		u8 mode;
21285 
21286 		if (env->insn_aux_data[i + delta].nospec) {
21287 			WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state);
21288 			struct bpf_insn *patch = insn_buf;
21289 
21290 			*patch++ = BPF_ST_NOSPEC();
21291 			*patch++ = *insn;
21292 			cnt = patch - insn_buf;
21293 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21294 			if (!new_prog)
21295 				return -ENOMEM;
21296 
21297 			delta    += cnt - 1;
21298 			env->prog = new_prog;
21299 			insn      = new_prog->insnsi + i + delta;
21300 			/* This can not be easily merged with the
21301 			 * nospec_result-case, because an insn may require a
21302 			 * nospec before and after itself. Therefore also do not
21303 			 * 'continue' here but potentially apply further
21304 			 * patching to insn. *insn should equal patch[1] now.
21305 			 */
21306 		}
21307 
21308 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
21309 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
21310 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
21311 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
21312 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
21313 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
21314 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
21315 			type = BPF_READ;
21316 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
21317 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
21318 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
21319 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
21320 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
21321 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
21322 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
21323 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
21324 			type = BPF_WRITE;
21325 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) ||
21326 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) ||
21327 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
21328 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
21329 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
21330 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
21331 			env->prog->aux->num_exentries++;
21332 			continue;
21333 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
21334 			   epilogue_cnt &&
21335 			   i + delta < subprogs[1].start) {
21336 			/* Generate epilogue for the main prog */
21337 			if (epilogue_idx) {
21338 				/* jump back to the earlier generated epilogue */
21339 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
21340 				cnt = 1;
21341 			} else {
21342 				memcpy(insn_buf, epilogue_buf,
21343 				       epilogue_cnt * sizeof(*epilogue_buf));
21344 				cnt = epilogue_cnt;
21345 				/* epilogue_idx cannot be 0. It must have at
21346 				 * least one ctx ptr saving insn before the
21347 				 * epilogue.
21348 				 */
21349 				epilogue_idx = i + delta;
21350 			}
21351 			goto patch_insn_buf;
21352 		} else {
21353 			continue;
21354 		}
21355 
21356 		if (type == BPF_WRITE &&
21357 		    env->insn_aux_data[i + delta].nospec_result) {
21358 			/* nospec_result is only used to mitigate Spectre v4 and
21359 			 * to limit verification-time for Spectre v1.
21360 			 */
21361 			struct bpf_insn *patch = insn_buf;
21362 
21363 			*patch++ = *insn;
21364 			*patch++ = BPF_ST_NOSPEC();
21365 			cnt = patch - insn_buf;
21366 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21367 			if (!new_prog)
21368 				return -ENOMEM;
21369 
21370 			delta    += cnt - 1;
21371 			env->prog = new_prog;
21372 			insn      = new_prog->insnsi + i + delta;
21373 			continue;
21374 		}
21375 
21376 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
21377 		case PTR_TO_CTX:
21378 			if (!ops->convert_ctx_access)
21379 				continue;
21380 			convert_ctx_access = ops->convert_ctx_access;
21381 			break;
21382 		case PTR_TO_SOCKET:
21383 		case PTR_TO_SOCK_COMMON:
21384 			convert_ctx_access = bpf_sock_convert_ctx_access;
21385 			break;
21386 		case PTR_TO_TCP_SOCK:
21387 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
21388 			break;
21389 		case PTR_TO_XDP_SOCK:
21390 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
21391 			break;
21392 		case PTR_TO_BTF_ID:
21393 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
21394 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
21395 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
21396 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
21397 		 * any faults for loads into such types. BPF_WRITE is disallowed
21398 		 * for this case.
21399 		 */
21400 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
21401 		case PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED:
21402 			if (type == BPF_READ) {
21403 				if (BPF_MODE(insn->code) == BPF_MEM)
21404 					insn->code = BPF_LDX | BPF_PROBE_MEM |
21405 						     BPF_SIZE((insn)->code);
21406 				else
21407 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
21408 						     BPF_SIZE((insn)->code);
21409 				env->prog->aux->num_exentries++;
21410 			}
21411 			continue;
21412 		case PTR_TO_ARENA:
21413 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
21414 				verbose(env, "sign extending loads from arena are not supported yet\n");
21415 				return -EOPNOTSUPP;
21416 			}
21417 			insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
21418 			env->prog->aux->num_exentries++;
21419 			continue;
21420 		default:
21421 			continue;
21422 		}
21423 
21424 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
21425 		size = BPF_LDST_BYTES(insn);
21426 		mode = BPF_MODE(insn->code);
21427 
21428 		/* If the read access is a narrower load of the field,
21429 		 * convert to a 4/8-byte load, to minimum program type specific
21430 		 * convert_ctx_access changes. If conversion is successful,
21431 		 * we will apply proper mask to the result.
21432 		 */
21433 		is_narrower_load = size < ctx_field_size;
21434 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
21435 		off = insn->off;
21436 		if (is_narrower_load) {
21437 			u8 size_code;
21438 
21439 			if (type == BPF_WRITE) {
21440 				verifier_bug(env, "narrow ctx access misconfigured");
21441 				return -EFAULT;
21442 			}
21443 
21444 			size_code = BPF_H;
21445 			if (ctx_field_size == 4)
21446 				size_code = BPF_W;
21447 			else if (ctx_field_size == 8)
21448 				size_code = BPF_DW;
21449 
21450 			insn->off = off & ~(size_default - 1);
21451 			insn->code = BPF_LDX | BPF_MEM | size_code;
21452 		}
21453 
21454 		target_size = 0;
21455 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
21456 					 &target_size);
21457 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
21458 		    (ctx_field_size && !target_size)) {
21459 			verifier_bug(env, "error during ctx access conversion (%d)", cnt);
21460 			return -EFAULT;
21461 		}
21462 
21463 		if (is_narrower_load && size < target_size) {
21464 			u8 shift = bpf_ctx_narrow_access_offset(
21465 				off, size, size_default) * 8;
21466 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
21467 				verifier_bug(env, "narrow ctx load misconfigured");
21468 				return -EFAULT;
21469 			}
21470 			if (ctx_field_size <= 4) {
21471 				if (shift)
21472 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
21473 									insn->dst_reg,
21474 									shift);
21475 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
21476 								(1 << size * 8) - 1);
21477 			} else {
21478 				if (shift)
21479 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
21480 									insn->dst_reg,
21481 									shift);
21482 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
21483 								(1ULL << size * 8) - 1);
21484 			}
21485 		}
21486 		if (mode == BPF_MEMSX)
21487 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
21488 						       insn->dst_reg, insn->dst_reg,
21489 						       size * 8, 0);
21490 
21491 patch_insn_buf:
21492 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21493 		if (!new_prog)
21494 			return -ENOMEM;
21495 
21496 		delta += cnt - 1;
21497 
21498 		/* keep walking new program and skip insns we just inserted */
21499 		env->prog = new_prog;
21500 		insn      = new_prog->insnsi + i + delta;
21501 	}
21502 
21503 	return 0;
21504 }
21505 
21506 static int jit_subprogs(struct bpf_verifier_env *env)
21507 {
21508 	struct bpf_prog *prog = env->prog, **func, *tmp;
21509 	int i, j, subprog_start, subprog_end = 0, len, subprog;
21510 	struct bpf_map *map_ptr;
21511 	struct bpf_insn *insn;
21512 	void *old_bpf_func;
21513 	int err, num_exentries;
21514 
21515 	if (env->subprog_cnt <= 1)
21516 		return 0;
21517 
21518 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21519 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
21520 			continue;
21521 
21522 		/* Upon error here we cannot fall back to interpreter but
21523 		 * need a hard reject of the program. Thus -EFAULT is
21524 		 * propagated in any case.
21525 		 */
21526 		subprog = find_subprog(env, i + insn->imm + 1);
21527 		if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d",
21528 				    i + insn->imm + 1))
21529 			return -EFAULT;
21530 		/* temporarily remember subprog id inside insn instead of
21531 		 * aux_data, since next loop will split up all insns into funcs
21532 		 */
21533 		insn->off = subprog;
21534 		/* remember original imm in case JIT fails and fallback
21535 		 * to interpreter will be needed
21536 		 */
21537 		env->insn_aux_data[i].call_imm = insn->imm;
21538 		/* point imm to __bpf_call_base+1 from JITs point of view */
21539 		insn->imm = 1;
21540 		if (bpf_pseudo_func(insn)) {
21541 #if defined(MODULES_VADDR)
21542 			u64 addr = MODULES_VADDR;
21543 #else
21544 			u64 addr = VMALLOC_START;
21545 #endif
21546 			/* jit (e.g. x86_64) may emit fewer instructions
21547 			 * if it learns a u32 imm is the same as a u64 imm.
21548 			 * Set close enough to possible prog address.
21549 			 */
21550 			insn[0].imm = (u32)addr;
21551 			insn[1].imm = addr >> 32;
21552 		}
21553 	}
21554 
21555 	err = bpf_prog_alloc_jited_linfo(prog);
21556 	if (err)
21557 		goto out_undo_insn;
21558 
21559 	err = -ENOMEM;
21560 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
21561 	if (!func)
21562 		goto out_undo_insn;
21563 
21564 	for (i = 0; i < env->subprog_cnt; i++) {
21565 		subprog_start = subprog_end;
21566 		subprog_end = env->subprog_info[i + 1].start;
21567 
21568 		len = subprog_end - subprog_start;
21569 		/* bpf_prog_run() doesn't call subprogs directly,
21570 		 * hence main prog stats include the runtime of subprogs.
21571 		 * subprogs don't have IDs and not reachable via prog_get_next_id
21572 		 * func[i]->stats will never be accessed and stays NULL
21573 		 */
21574 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
21575 		if (!func[i])
21576 			goto out_free;
21577 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
21578 		       len * sizeof(struct bpf_insn));
21579 		func[i]->type = prog->type;
21580 		func[i]->len = len;
21581 		if (bpf_prog_calc_tag(func[i]))
21582 			goto out_free;
21583 		func[i]->is_func = 1;
21584 		func[i]->sleepable = prog->sleepable;
21585 		func[i]->aux->func_idx = i;
21586 		/* Below members will be freed only at prog->aux */
21587 		func[i]->aux->btf = prog->aux->btf;
21588 		func[i]->aux->func_info = prog->aux->func_info;
21589 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
21590 		func[i]->aux->poke_tab = prog->aux->poke_tab;
21591 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
21592 
21593 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
21594 			struct bpf_jit_poke_descriptor *poke;
21595 
21596 			poke = &prog->aux->poke_tab[j];
21597 			if (poke->insn_idx < subprog_end &&
21598 			    poke->insn_idx >= subprog_start)
21599 				poke->aux = func[i]->aux;
21600 		}
21601 
21602 		func[i]->aux->name[0] = 'F';
21603 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
21604 		if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
21605 			func[i]->aux->jits_use_priv_stack = true;
21606 
21607 		func[i]->jit_requested = 1;
21608 		func[i]->blinding_requested = prog->blinding_requested;
21609 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
21610 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
21611 		func[i]->aux->linfo = prog->aux->linfo;
21612 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
21613 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
21614 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
21615 		func[i]->aux->arena = prog->aux->arena;
21616 		num_exentries = 0;
21617 		insn = func[i]->insnsi;
21618 		for (j = 0; j < func[i]->len; j++, insn++) {
21619 			if (BPF_CLASS(insn->code) == BPF_LDX &&
21620 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
21621 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
21622 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
21623 				num_exentries++;
21624 			if ((BPF_CLASS(insn->code) == BPF_STX ||
21625 			     BPF_CLASS(insn->code) == BPF_ST) &&
21626 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
21627 				num_exentries++;
21628 			if (BPF_CLASS(insn->code) == BPF_STX &&
21629 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
21630 				num_exentries++;
21631 		}
21632 		func[i]->aux->num_exentries = num_exentries;
21633 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
21634 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
21635 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
21636 		func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
21637 		if (!i)
21638 			func[i]->aux->exception_boundary = env->seen_exception;
21639 		func[i] = bpf_int_jit_compile(func[i]);
21640 		if (!func[i]->jited) {
21641 			err = -ENOTSUPP;
21642 			goto out_free;
21643 		}
21644 		cond_resched();
21645 	}
21646 
21647 	/* at this point all bpf functions were successfully JITed
21648 	 * now populate all bpf_calls with correct addresses and
21649 	 * run last pass of JIT
21650 	 */
21651 	for (i = 0; i < env->subprog_cnt; i++) {
21652 		insn = func[i]->insnsi;
21653 		for (j = 0; j < func[i]->len; j++, insn++) {
21654 			if (bpf_pseudo_func(insn)) {
21655 				subprog = insn->off;
21656 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
21657 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
21658 				continue;
21659 			}
21660 			if (!bpf_pseudo_call(insn))
21661 				continue;
21662 			subprog = insn->off;
21663 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
21664 		}
21665 
21666 		/* we use the aux data to keep a list of the start addresses
21667 		 * of the JITed images for each function in the program
21668 		 *
21669 		 * for some architectures, such as powerpc64, the imm field
21670 		 * might not be large enough to hold the offset of the start
21671 		 * address of the callee's JITed image from __bpf_call_base
21672 		 *
21673 		 * in such cases, we can lookup the start address of a callee
21674 		 * by using its subprog id, available from the off field of
21675 		 * the call instruction, as an index for this list
21676 		 */
21677 		func[i]->aux->func = func;
21678 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
21679 		func[i]->aux->real_func_cnt = env->subprog_cnt;
21680 	}
21681 	for (i = 0; i < env->subprog_cnt; i++) {
21682 		old_bpf_func = func[i]->bpf_func;
21683 		tmp = bpf_int_jit_compile(func[i]);
21684 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
21685 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
21686 			err = -ENOTSUPP;
21687 			goto out_free;
21688 		}
21689 		cond_resched();
21690 	}
21691 
21692 	/* finally lock prog and jit images for all functions and
21693 	 * populate kallsysm. Begin at the first subprogram, since
21694 	 * bpf_prog_load will add the kallsyms for the main program.
21695 	 */
21696 	for (i = 1; i < env->subprog_cnt; i++) {
21697 		err = bpf_prog_lock_ro(func[i]);
21698 		if (err)
21699 			goto out_free;
21700 	}
21701 
21702 	for (i = 1; i < env->subprog_cnt; i++)
21703 		bpf_prog_kallsyms_add(func[i]);
21704 
21705 	/* Last step: make now unused interpreter insns from main
21706 	 * prog consistent for later dump requests, so they can
21707 	 * later look the same as if they were interpreted only.
21708 	 */
21709 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21710 		if (bpf_pseudo_func(insn)) {
21711 			insn[0].imm = env->insn_aux_data[i].call_imm;
21712 			insn[1].imm = insn->off;
21713 			insn->off = 0;
21714 			continue;
21715 		}
21716 		if (!bpf_pseudo_call(insn))
21717 			continue;
21718 		insn->off = env->insn_aux_data[i].call_imm;
21719 		subprog = find_subprog(env, i + insn->off + 1);
21720 		insn->imm = subprog;
21721 	}
21722 
21723 	prog->jited = 1;
21724 	prog->bpf_func = func[0]->bpf_func;
21725 	prog->jited_len = func[0]->jited_len;
21726 	prog->aux->extable = func[0]->aux->extable;
21727 	prog->aux->num_exentries = func[0]->aux->num_exentries;
21728 	prog->aux->func = func;
21729 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
21730 	prog->aux->real_func_cnt = env->subprog_cnt;
21731 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
21732 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
21733 	bpf_prog_jit_attempt_done(prog);
21734 	return 0;
21735 out_free:
21736 	/* We failed JIT'ing, so at this point we need to unregister poke
21737 	 * descriptors from subprogs, so that kernel is not attempting to
21738 	 * patch it anymore as we're freeing the subprog JIT memory.
21739 	 */
21740 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
21741 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
21742 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
21743 	}
21744 	/* At this point we're guaranteed that poke descriptors are not
21745 	 * live anymore. We can just unlink its descriptor table as it's
21746 	 * released with the main prog.
21747 	 */
21748 	for (i = 0; i < env->subprog_cnt; i++) {
21749 		if (!func[i])
21750 			continue;
21751 		func[i]->aux->poke_tab = NULL;
21752 		bpf_jit_free(func[i]);
21753 	}
21754 	kfree(func);
21755 out_undo_insn:
21756 	/* cleanup main prog to be interpreted */
21757 	prog->jit_requested = 0;
21758 	prog->blinding_requested = 0;
21759 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21760 		if (!bpf_pseudo_call(insn))
21761 			continue;
21762 		insn->off = 0;
21763 		insn->imm = env->insn_aux_data[i].call_imm;
21764 	}
21765 	bpf_prog_jit_attempt_done(prog);
21766 	return err;
21767 }
21768 
21769 static int fixup_call_args(struct bpf_verifier_env *env)
21770 {
21771 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
21772 	struct bpf_prog *prog = env->prog;
21773 	struct bpf_insn *insn = prog->insnsi;
21774 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
21775 	int i, depth;
21776 #endif
21777 	int err = 0;
21778 
21779 	if (env->prog->jit_requested &&
21780 	    !bpf_prog_is_offloaded(env->prog->aux)) {
21781 		err = jit_subprogs(env);
21782 		if (err == 0)
21783 			return 0;
21784 		if (err == -EFAULT)
21785 			return err;
21786 	}
21787 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
21788 	if (has_kfunc_call) {
21789 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
21790 		return -EINVAL;
21791 	}
21792 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
21793 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
21794 		 * have to be rejected, since interpreter doesn't support them yet.
21795 		 */
21796 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
21797 		return -EINVAL;
21798 	}
21799 	for (i = 0; i < prog->len; i++, insn++) {
21800 		if (bpf_pseudo_func(insn)) {
21801 			/* When JIT fails the progs with callback calls
21802 			 * have to be rejected, since interpreter doesn't support them yet.
21803 			 */
21804 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
21805 			return -EINVAL;
21806 		}
21807 
21808 		if (!bpf_pseudo_call(insn))
21809 			continue;
21810 		depth = get_callee_stack_depth(env, insn, i);
21811 		if (depth < 0)
21812 			return depth;
21813 		bpf_patch_call_args(insn, depth);
21814 	}
21815 	err = 0;
21816 #endif
21817 	return err;
21818 }
21819 
21820 /* replace a generic kfunc with a specialized version if necessary */
21821 static void specialize_kfunc(struct bpf_verifier_env *env,
21822 			     u32 func_id, u16 offset, unsigned long *addr)
21823 {
21824 	struct bpf_prog *prog = env->prog;
21825 	bool seen_direct_write;
21826 	void *xdp_kfunc;
21827 	bool is_rdonly;
21828 
21829 	if (bpf_dev_bound_kfunc_id(func_id)) {
21830 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
21831 		if (xdp_kfunc) {
21832 			*addr = (unsigned long)xdp_kfunc;
21833 			return;
21834 		}
21835 		/* fallback to default kfunc when not supported by netdev */
21836 	}
21837 
21838 	if (offset)
21839 		return;
21840 
21841 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
21842 		seen_direct_write = env->seen_direct_write;
21843 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
21844 
21845 		if (is_rdonly)
21846 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
21847 
21848 		/* restore env->seen_direct_write to its original value, since
21849 		 * may_access_direct_pkt_data mutates it
21850 		 */
21851 		env->seen_direct_write = seen_direct_write;
21852 	}
21853 
21854 	if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr] &&
21855 	    bpf_lsm_has_d_inode_locked(prog))
21856 		*addr = (unsigned long)bpf_set_dentry_xattr_locked;
21857 
21858 	if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr] &&
21859 	    bpf_lsm_has_d_inode_locked(prog))
21860 		*addr = (unsigned long)bpf_remove_dentry_xattr_locked;
21861 }
21862 
21863 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
21864 					    u16 struct_meta_reg,
21865 					    u16 node_offset_reg,
21866 					    struct bpf_insn *insn,
21867 					    struct bpf_insn *insn_buf,
21868 					    int *cnt)
21869 {
21870 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
21871 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
21872 
21873 	insn_buf[0] = addr[0];
21874 	insn_buf[1] = addr[1];
21875 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
21876 	insn_buf[3] = *insn;
21877 	*cnt = 4;
21878 }
21879 
21880 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
21881 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
21882 {
21883 	const struct bpf_kfunc_desc *desc;
21884 
21885 	if (!insn->imm) {
21886 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
21887 		return -EINVAL;
21888 	}
21889 
21890 	*cnt = 0;
21891 
21892 	/* insn->imm has the btf func_id. Replace it with an offset relative to
21893 	 * __bpf_call_base, unless the JIT needs to call functions that are
21894 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
21895 	 */
21896 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
21897 	if (!desc) {
21898 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
21899 			     insn->imm);
21900 		return -EFAULT;
21901 	}
21902 
21903 	if (!bpf_jit_supports_far_kfunc_call())
21904 		insn->imm = BPF_CALL_IMM(desc->addr);
21905 	if (insn->off)
21906 		return 0;
21907 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
21908 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
21909 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21910 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
21911 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
21912 
21913 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
21914 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
21915 				     insn_idx);
21916 			return -EFAULT;
21917 		}
21918 
21919 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
21920 		insn_buf[1] = addr[0];
21921 		insn_buf[2] = addr[1];
21922 		insn_buf[3] = *insn;
21923 		*cnt = 4;
21924 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
21925 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
21926 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
21927 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21928 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
21929 
21930 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
21931 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
21932 				     insn_idx);
21933 			return -EFAULT;
21934 		}
21935 
21936 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
21937 		    !kptr_struct_meta) {
21938 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
21939 				     insn_idx);
21940 			return -EFAULT;
21941 		}
21942 
21943 		insn_buf[0] = addr[0];
21944 		insn_buf[1] = addr[1];
21945 		insn_buf[2] = *insn;
21946 		*cnt = 3;
21947 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
21948 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
21949 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
21950 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21951 		int struct_meta_reg = BPF_REG_3;
21952 		int node_offset_reg = BPF_REG_4;
21953 
21954 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
21955 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
21956 			struct_meta_reg = BPF_REG_4;
21957 			node_offset_reg = BPF_REG_5;
21958 		}
21959 
21960 		if (!kptr_struct_meta) {
21961 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
21962 				     insn_idx);
21963 			return -EFAULT;
21964 		}
21965 
21966 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
21967 						node_offset_reg, insn, insn_buf, cnt);
21968 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
21969 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
21970 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
21971 		*cnt = 1;
21972 	}
21973 
21974 	if (env->insn_aux_data[insn_idx].arg_prog) {
21975 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
21976 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
21977 		int idx = *cnt;
21978 
21979 		insn_buf[idx++] = ld_addrs[0];
21980 		insn_buf[idx++] = ld_addrs[1];
21981 		insn_buf[idx++] = *insn;
21982 		*cnt = idx;
21983 	}
21984 	return 0;
21985 }
21986 
21987 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
21988 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
21989 {
21990 	struct bpf_subprog_info *info = env->subprog_info;
21991 	int cnt = env->subprog_cnt;
21992 	struct bpf_prog *prog;
21993 
21994 	/* We only reserve one slot for hidden subprogs in subprog_info. */
21995 	if (env->hidden_subprog_cnt) {
21996 		verifier_bug(env, "only one hidden subprog supported");
21997 		return -EFAULT;
21998 	}
21999 	/* We're not patching any existing instruction, just appending the new
22000 	 * ones for the hidden subprog. Hence all of the adjustment operations
22001 	 * in bpf_patch_insn_data are no-ops.
22002 	 */
22003 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
22004 	if (!prog)
22005 		return -ENOMEM;
22006 	env->prog = prog;
22007 	info[cnt + 1].start = info[cnt].start;
22008 	info[cnt].start = prog->len - len + 1;
22009 	env->subprog_cnt++;
22010 	env->hidden_subprog_cnt++;
22011 	return 0;
22012 }
22013 
22014 /* Do various post-verification rewrites in a single program pass.
22015  * These rewrites simplify JIT and interpreter implementations.
22016  */
22017 static int do_misc_fixups(struct bpf_verifier_env *env)
22018 {
22019 	struct bpf_prog *prog = env->prog;
22020 	enum bpf_attach_type eatype = prog->expected_attach_type;
22021 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
22022 	struct bpf_insn *insn = prog->insnsi;
22023 	const struct bpf_func_proto *fn;
22024 	const int insn_cnt = prog->len;
22025 	const struct bpf_map_ops *ops;
22026 	struct bpf_insn_aux_data *aux;
22027 	struct bpf_insn *insn_buf = env->insn_buf;
22028 	struct bpf_prog *new_prog;
22029 	struct bpf_map *map_ptr;
22030 	int i, ret, cnt, delta = 0, cur_subprog = 0;
22031 	struct bpf_subprog_info *subprogs = env->subprog_info;
22032 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
22033 	u16 stack_depth_extra = 0;
22034 
22035 	if (env->seen_exception && !env->exception_callback_subprog) {
22036 		struct bpf_insn *patch = insn_buf;
22037 
22038 		*patch++ = env->prog->insnsi[insn_cnt - 1];
22039 		*patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
22040 		*patch++ = BPF_EXIT_INSN();
22041 		ret = add_hidden_subprog(env, insn_buf, patch - insn_buf);
22042 		if (ret < 0)
22043 			return ret;
22044 		prog = env->prog;
22045 		insn = prog->insnsi;
22046 
22047 		env->exception_callback_subprog = env->subprog_cnt - 1;
22048 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
22049 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
22050 	}
22051 
22052 	for (i = 0; i < insn_cnt;) {
22053 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
22054 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
22055 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
22056 				/* convert to 32-bit mov that clears upper 32-bit */
22057 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
22058 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
22059 				insn->off = 0;
22060 				insn->imm = 0;
22061 			} /* cast from as(0) to as(1) should be handled by JIT */
22062 			goto next_insn;
22063 		}
22064 
22065 		if (env->insn_aux_data[i + delta].needs_zext)
22066 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
22067 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
22068 
22069 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
22070 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
22071 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
22072 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
22073 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
22074 		    insn->off == 1 && insn->imm == -1) {
22075 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22076 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22077 			struct bpf_insn *patch = insn_buf;
22078 
22079 			if (isdiv)
22080 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22081 							BPF_NEG | BPF_K, insn->dst_reg,
22082 							0, 0, 0);
22083 			else
22084 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22085 
22086 			cnt = patch - insn_buf;
22087 
22088 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22089 			if (!new_prog)
22090 				return -ENOMEM;
22091 
22092 			delta    += cnt - 1;
22093 			env->prog = prog = new_prog;
22094 			insn      = new_prog->insnsi + i + delta;
22095 			goto next_insn;
22096 		}
22097 
22098 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
22099 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
22100 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
22101 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
22102 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
22103 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22104 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22105 			bool is_sdiv = isdiv && insn->off == 1;
22106 			bool is_smod = !isdiv && insn->off == 1;
22107 			struct bpf_insn *patch = insn_buf;
22108 
22109 			if (is_sdiv) {
22110 				/* [R,W]x sdiv 0 -> 0
22111 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
22112 				 * INT_MIN sdiv -1 -> INT_MIN
22113 				 */
22114 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22115 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22116 							BPF_ADD | BPF_K, BPF_REG_AX,
22117 							0, 0, 1);
22118 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22119 							BPF_JGT | BPF_K, BPF_REG_AX,
22120 							0, 4, 1);
22121 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22122 							BPF_JEQ | BPF_K, BPF_REG_AX,
22123 							0, 1, 0);
22124 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22125 							BPF_MOV | BPF_K, insn->dst_reg,
22126 							0, 0, 0);
22127 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
22128 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22129 							BPF_NEG | BPF_K, insn->dst_reg,
22130 							0, 0, 0);
22131 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22132 				*patch++ = *insn;
22133 				cnt = patch - insn_buf;
22134 			} else if (is_smod) {
22135 				/* [R,W]x mod 0 -> [R,W]x */
22136 				/* [R,W]x mod -1 -> 0 */
22137 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22138 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22139 							BPF_ADD | BPF_K, BPF_REG_AX,
22140 							0, 0, 1);
22141 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22142 							BPF_JGT | BPF_K, BPF_REG_AX,
22143 							0, 3, 1);
22144 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22145 							BPF_JEQ | BPF_K, BPF_REG_AX,
22146 							0, 3 + (is64 ? 0 : 1), 1);
22147 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22148 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22149 				*patch++ = *insn;
22150 
22151 				if (!is64) {
22152 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22153 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22154 				}
22155 				cnt = patch - insn_buf;
22156 			} else if (isdiv) {
22157 				/* [R,W]x div 0 -> 0 */
22158 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22159 							BPF_JNE | BPF_K, insn->src_reg,
22160 							0, 2, 0);
22161 				*patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg);
22162 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22163 				*patch++ = *insn;
22164 				cnt = patch - insn_buf;
22165 			} else {
22166 				/* [R,W]x mod 0 -> [R,W]x */
22167 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22168 							BPF_JEQ | BPF_K, insn->src_reg,
22169 							0, 1 + (is64 ? 0 : 1), 0);
22170 				*patch++ = *insn;
22171 
22172 				if (!is64) {
22173 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22174 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22175 				}
22176 				cnt = patch - insn_buf;
22177 			}
22178 
22179 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22180 			if (!new_prog)
22181 				return -ENOMEM;
22182 
22183 			delta    += cnt - 1;
22184 			env->prog = prog = new_prog;
22185 			insn      = new_prog->insnsi + i + delta;
22186 			goto next_insn;
22187 		}
22188 
22189 		/* Make it impossible to de-reference a userspace address */
22190 		if (BPF_CLASS(insn->code) == BPF_LDX &&
22191 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22192 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
22193 			struct bpf_insn *patch = insn_buf;
22194 			u64 uaddress_limit = bpf_arch_uaddress_limit();
22195 
22196 			if (!uaddress_limit)
22197 				goto next_insn;
22198 
22199 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22200 			if (insn->off)
22201 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
22202 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
22203 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
22204 			*patch++ = *insn;
22205 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22206 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
22207 
22208 			cnt = patch - insn_buf;
22209 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22210 			if (!new_prog)
22211 				return -ENOMEM;
22212 
22213 			delta    += cnt - 1;
22214 			env->prog = prog = new_prog;
22215 			insn      = new_prog->insnsi + i + delta;
22216 			goto next_insn;
22217 		}
22218 
22219 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
22220 		if (BPF_CLASS(insn->code) == BPF_LD &&
22221 		    (BPF_MODE(insn->code) == BPF_ABS ||
22222 		     BPF_MODE(insn->code) == BPF_IND)) {
22223 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
22224 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
22225 				verifier_bug(env, "%d insns generated for ld_abs", cnt);
22226 				return -EFAULT;
22227 			}
22228 
22229 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22230 			if (!new_prog)
22231 				return -ENOMEM;
22232 
22233 			delta    += cnt - 1;
22234 			env->prog = prog = new_prog;
22235 			insn      = new_prog->insnsi + i + delta;
22236 			goto next_insn;
22237 		}
22238 
22239 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
22240 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
22241 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
22242 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
22243 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
22244 			struct bpf_insn *patch = insn_buf;
22245 			bool issrc, isneg, isimm;
22246 			u32 off_reg;
22247 
22248 			aux = &env->insn_aux_data[i + delta];
22249 			if (!aux->alu_state ||
22250 			    aux->alu_state == BPF_ALU_NON_POINTER)
22251 				goto next_insn;
22252 
22253 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
22254 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
22255 				BPF_ALU_SANITIZE_SRC;
22256 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
22257 
22258 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
22259 			if (isimm) {
22260 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22261 			} else {
22262 				if (isneg)
22263 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22264 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22265 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
22266 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
22267 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
22268 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
22269 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
22270 			}
22271 			if (!issrc)
22272 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
22273 			insn->src_reg = BPF_REG_AX;
22274 			if (isneg)
22275 				insn->code = insn->code == code_add ?
22276 					     code_sub : code_add;
22277 			*patch++ = *insn;
22278 			if (issrc && isneg && !isimm)
22279 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22280 			cnt = patch - insn_buf;
22281 
22282 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22283 			if (!new_prog)
22284 				return -ENOMEM;
22285 
22286 			delta    += cnt - 1;
22287 			env->prog = prog = new_prog;
22288 			insn      = new_prog->insnsi + i + delta;
22289 			goto next_insn;
22290 		}
22291 
22292 		if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) {
22293 			int stack_off_cnt = -stack_depth - 16;
22294 
22295 			/*
22296 			 * Two 8 byte slots, depth-16 stores the count, and
22297 			 * depth-8 stores the start timestamp of the loop.
22298 			 *
22299 			 * The starting value of count is BPF_MAX_TIMED_LOOPS
22300 			 * (0xffff).  Every iteration loads it and subs it by 1,
22301 			 * until the value becomes 0 in AX (thus, 1 in stack),
22302 			 * after which we call arch_bpf_timed_may_goto, which
22303 			 * either sets AX to 0xffff to keep looping, or to 0
22304 			 * upon timeout. AX is then stored into the stack. In
22305 			 * the next iteration, we either see 0 and break out, or
22306 			 * continue iterating until the next time value is 0
22307 			 * after subtraction, rinse and repeat.
22308 			 */
22309 			stack_depth_extra = 16;
22310 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt);
22311 			if (insn->off >= 0)
22312 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5);
22313 			else
22314 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22315 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22316 			insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
22317 			/*
22318 			 * AX is used as an argument to pass in stack_off_cnt
22319 			 * (to add to r10/fp), and also as the return value of
22320 			 * the call to arch_bpf_timed_may_goto.
22321 			 */
22322 			insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt);
22323 			insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
22324 			insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt);
22325 			cnt = 7;
22326 
22327 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22328 			if (!new_prog)
22329 				return -ENOMEM;
22330 
22331 			delta += cnt - 1;
22332 			env->prog = prog = new_prog;
22333 			insn = new_prog->insnsi + i + delta;
22334 			goto next_insn;
22335 		} else if (is_may_goto_insn(insn)) {
22336 			int stack_off = -stack_depth - 8;
22337 
22338 			stack_depth_extra = 8;
22339 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
22340 			if (insn->off >= 0)
22341 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
22342 			else
22343 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22344 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22345 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
22346 			cnt = 4;
22347 
22348 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22349 			if (!new_prog)
22350 				return -ENOMEM;
22351 
22352 			delta += cnt - 1;
22353 			env->prog = prog = new_prog;
22354 			insn = new_prog->insnsi + i + delta;
22355 			goto next_insn;
22356 		}
22357 
22358 		if (insn->code != (BPF_JMP | BPF_CALL))
22359 			goto next_insn;
22360 		if (insn->src_reg == BPF_PSEUDO_CALL)
22361 			goto next_insn;
22362 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
22363 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
22364 			if (ret)
22365 				return ret;
22366 			if (cnt == 0)
22367 				goto next_insn;
22368 
22369 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22370 			if (!new_prog)
22371 				return -ENOMEM;
22372 
22373 			delta	 += cnt - 1;
22374 			env->prog = prog = new_prog;
22375 			insn	  = new_prog->insnsi + i + delta;
22376 			goto next_insn;
22377 		}
22378 
22379 		/* Skip inlining the helper call if the JIT does it. */
22380 		if (bpf_jit_inlines_helper_call(insn->imm))
22381 			goto next_insn;
22382 
22383 		if (insn->imm == BPF_FUNC_get_route_realm)
22384 			prog->dst_needed = 1;
22385 		if (insn->imm == BPF_FUNC_get_prandom_u32)
22386 			bpf_user_rnd_init_once();
22387 		if (insn->imm == BPF_FUNC_override_return)
22388 			prog->kprobe_override = 1;
22389 		if (insn->imm == BPF_FUNC_tail_call) {
22390 			/* If we tail call into other programs, we
22391 			 * cannot make any assumptions since they can
22392 			 * be replaced dynamically during runtime in
22393 			 * the program array.
22394 			 */
22395 			prog->cb_access = 1;
22396 			if (!allow_tail_call_in_subprogs(env))
22397 				prog->aux->stack_depth = MAX_BPF_STACK;
22398 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
22399 
22400 			/* mark bpf_tail_call as different opcode to avoid
22401 			 * conditional branch in the interpreter for every normal
22402 			 * call and to prevent accidental JITing by JIT compiler
22403 			 * that doesn't support bpf_tail_call yet
22404 			 */
22405 			insn->imm = 0;
22406 			insn->code = BPF_JMP | BPF_TAIL_CALL;
22407 
22408 			aux = &env->insn_aux_data[i + delta];
22409 			if (env->bpf_capable && !prog->blinding_requested &&
22410 			    prog->jit_requested &&
22411 			    !bpf_map_key_poisoned(aux) &&
22412 			    !bpf_map_ptr_poisoned(aux) &&
22413 			    !bpf_map_ptr_unpriv(aux)) {
22414 				struct bpf_jit_poke_descriptor desc = {
22415 					.reason = BPF_POKE_REASON_TAIL_CALL,
22416 					.tail_call.map = aux->map_ptr_state.map_ptr,
22417 					.tail_call.key = bpf_map_key_immediate(aux),
22418 					.insn_idx = i + delta,
22419 				};
22420 
22421 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
22422 				if (ret < 0) {
22423 					verbose(env, "adding tail call poke descriptor failed\n");
22424 					return ret;
22425 				}
22426 
22427 				insn->imm = ret + 1;
22428 				goto next_insn;
22429 			}
22430 
22431 			if (!bpf_map_ptr_unpriv(aux))
22432 				goto next_insn;
22433 
22434 			/* instead of changing every JIT dealing with tail_call
22435 			 * emit two extra insns:
22436 			 * if (index >= max_entries) goto out;
22437 			 * index &= array->index_mask;
22438 			 * to avoid out-of-bounds cpu speculation
22439 			 */
22440 			if (bpf_map_ptr_poisoned(aux)) {
22441 				verbose(env, "tail_call abusing map_ptr\n");
22442 				return -EINVAL;
22443 			}
22444 
22445 			map_ptr = aux->map_ptr_state.map_ptr;
22446 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
22447 						  map_ptr->max_entries, 2);
22448 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
22449 						    container_of(map_ptr,
22450 								 struct bpf_array,
22451 								 map)->index_mask);
22452 			insn_buf[2] = *insn;
22453 			cnt = 3;
22454 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22455 			if (!new_prog)
22456 				return -ENOMEM;
22457 
22458 			delta    += cnt - 1;
22459 			env->prog = prog = new_prog;
22460 			insn      = new_prog->insnsi + i + delta;
22461 			goto next_insn;
22462 		}
22463 
22464 		if (insn->imm == BPF_FUNC_timer_set_callback) {
22465 			/* The verifier will process callback_fn as many times as necessary
22466 			 * with different maps and the register states prepared by
22467 			 * set_timer_callback_state will be accurate.
22468 			 *
22469 			 * The following use case is valid:
22470 			 *   map1 is shared by prog1, prog2, prog3.
22471 			 *   prog1 calls bpf_timer_init for some map1 elements
22472 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
22473 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
22474 			 *   prog3 calls bpf_timer_start for some map1 elements.
22475 			 *     Those that were not both bpf_timer_init-ed and
22476 			 *     bpf_timer_set_callback-ed will return -EINVAL.
22477 			 */
22478 			struct bpf_insn ld_addrs[2] = {
22479 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
22480 			};
22481 
22482 			insn_buf[0] = ld_addrs[0];
22483 			insn_buf[1] = ld_addrs[1];
22484 			insn_buf[2] = *insn;
22485 			cnt = 3;
22486 
22487 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22488 			if (!new_prog)
22489 				return -ENOMEM;
22490 
22491 			delta    += cnt - 1;
22492 			env->prog = prog = new_prog;
22493 			insn      = new_prog->insnsi + i + delta;
22494 			goto patch_call_imm;
22495 		}
22496 
22497 		if (is_storage_get_function(insn->imm)) {
22498 			if (!in_sleepable(env) ||
22499 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
22500 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
22501 			else
22502 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
22503 			insn_buf[1] = *insn;
22504 			cnt = 2;
22505 
22506 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22507 			if (!new_prog)
22508 				return -ENOMEM;
22509 
22510 			delta += cnt - 1;
22511 			env->prog = prog = new_prog;
22512 			insn = new_prog->insnsi + i + delta;
22513 			goto patch_call_imm;
22514 		}
22515 
22516 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
22517 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
22518 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
22519 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
22520 			 */
22521 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
22522 			insn_buf[1] = *insn;
22523 			cnt = 2;
22524 
22525 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22526 			if (!new_prog)
22527 				return -ENOMEM;
22528 
22529 			delta += cnt - 1;
22530 			env->prog = prog = new_prog;
22531 			insn = new_prog->insnsi + i + delta;
22532 			goto patch_call_imm;
22533 		}
22534 
22535 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
22536 		 * and other inlining handlers are currently limited to 64 bit
22537 		 * only.
22538 		 */
22539 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22540 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
22541 		     insn->imm == BPF_FUNC_map_update_elem ||
22542 		     insn->imm == BPF_FUNC_map_delete_elem ||
22543 		     insn->imm == BPF_FUNC_map_push_elem   ||
22544 		     insn->imm == BPF_FUNC_map_pop_elem    ||
22545 		     insn->imm == BPF_FUNC_map_peek_elem   ||
22546 		     insn->imm == BPF_FUNC_redirect_map    ||
22547 		     insn->imm == BPF_FUNC_for_each_map_elem ||
22548 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
22549 			aux = &env->insn_aux_data[i + delta];
22550 			if (bpf_map_ptr_poisoned(aux))
22551 				goto patch_call_imm;
22552 
22553 			map_ptr = aux->map_ptr_state.map_ptr;
22554 			ops = map_ptr->ops;
22555 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
22556 			    ops->map_gen_lookup) {
22557 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
22558 				if (cnt == -EOPNOTSUPP)
22559 					goto patch_map_ops_generic;
22560 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
22561 					verifier_bug(env, "%d insns generated for map lookup", cnt);
22562 					return -EFAULT;
22563 				}
22564 
22565 				new_prog = bpf_patch_insn_data(env, i + delta,
22566 							       insn_buf, cnt);
22567 				if (!new_prog)
22568 					return -ENOMEM;
22569 
22570 				delta    += cnt - 1;
22571 				env->prog = prog = new_prog;
22572 				insn      = new_prog->insnsi + i + delta;
22573 				goto next_insn;
22574 			}
22575 
22576 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
22577 				     (void *(*)(struct bpf_map *map, void *key))NULL));
22578 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
22579 				     (long (*)(struct bpf_map *map, void *key))NULL));
22580 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
22581 				     (long (*)(struct bpf_map *map, void *key, void *value,
22582 					      u64 flags))NULL));
22583 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
22584 				     (long (*)(struct bpf_map *map, void *value,
22585 					      u64 flags))NULL));
22586 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
22587 				     (long (*)(struct bpf_map *map, void *value))NULL));
22588 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
22589 				     (long (*)(struct bpf_map *map, void *value))NULL));
22590 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
22591 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
22592 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
22593 				     (long (*)(struct bpf_map *map,
22594 					      bpf_callback_t callback_fn,
22595 					      void *callback_ctx,
22596 					      u64 flags))NULL));
22597 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
22598 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
22599 
22600 patch_map_ops_generic:
22601 			switch (insn->imm) {
22602 			case BPF_FUNC_map_lookup_elem:
22603 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
22604 				goto next_insn;
22605 			case BPF_FUNC_map_update_elem:
22606 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
22607 				goto next_insn;
22608 			case BPF_FUNC_map_delete_elem:
22609 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
22610 				goto next_insn;
22611 			case BPF_FUNC_map_push_elem:
22612 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
22613 				goto next_insn;
22614 			case BPF_FUNC_map_pop_elem:
22615 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
22616 				goto next_insn;
22617 			case BPF_FUNC_map_peek_elem:
22618 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
22619 				goto next_insn;
22620 			case BPF_FUNC_redirect_map:
22621 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
22622 				goto next_insn;
22623 			case BPF_FUNC_for_each_map_elem:
22624 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
22625 				goto next_insn;
22626 			case BPF_FUNC_map_lookup_percpu_elem:
22627 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
22628 				goto next_insn;
22629 			}
22630 
22631 			goto patch_call_imm;
22632 		}
22633 
22634 		/* Implement bpf_jiffies64 inline. */
22635 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22636 		    insn->imm == BPF_FUNC_jiffies64) {
22637 			struct bpf_insn ld_jiffies_addr[2] = {
22638 				BPF_LD_IMM64(BPF_REG_0,
22639 					     (unsigned long)&jiffies),
22640 			};
22641 
22642 			insn_buf[0] = ld_jiffies_addr[0];
22643 			insn_buf[1] = ld_jiffies_addr[1];
22644 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
22645 						  BPF_REG_0, 0);
22646 			cnt = 3;
22647 
22648 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
22649 						       cnt);
22650 			if (!new_prog)
22651 				return -ENOMEM;
22652 
22653 			delta    += cnt - 1;
22654 			env->prog = prog = new_prog;
22655 			insn      = new_prog->insnsi + i + delta;
22656 			goto next_insn;
22657 		}
22658 
22659 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
22660 		/* Implement bpf_get_smp_processor_id() inline. */
22661 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
22662 		    verifier_inlines_helper_call(env, insn->imm)) {
22663 			/* BPF_FUNC_get_smp_processor_id inlining is an
22664 			 * optimization, so if cpu_number is ever
22665 			 * changed in some incompatible and hard to support
22666 			 * way, it's fine to back out this inlining logic
22667 			 */
22668 #ifdef CONFIG_SMP
22669 			insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number);
22670 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
22671 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
22672 			cnt = 3;
22673 #else
22674 			insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
22675 			cnt = 1;
22676 #endif
22677 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22678 			if (!new_prog)
22679 				return -ENOMEM;
22680 
22681 			delta    += cnt - 1;
22682 			env->prog = prog = new_prog;
22683 			insn      = new_prog->insnsi + i + delta;
22684 			goto next_insn;
22685 		}
22686 #endif
22687 		/* Implement bpf_get_func_arg inline. */
22688 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22689 		    insn->imm == BPF_FUNC_get_func_arg) {
22690 			/* Load nr_args from ctx - 8 */
22691 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22692 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
22693 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
22694 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
22695 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
22696 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
22697 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
22698 			insn_buf[7] = BPF_JMP_A(1);
22699 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
22700 			cnt = 9;
22701 
22702 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22703 			if (!new_prog)
22704 				return -ENOMEM;
22705 
22706 			delta    += cnt - 1;
22707 			env->prog = prog = new_prog;
22708 			insn      = new_prog->insnsi + i + delta;
22709 			goto next_insn;
22710 		}
22711 
22712 		/* Implement bpf_get_func_ret inline. */
22713 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22714 		    insn->imm == BPF_FUNC_get_func_ret) {
22715 			if (eatype == BPF_TRACE_FEXIT ||
22716 			    eatype == BPF_MODIFY_RETURN) {
22717 				/* Load nr_args from ctx - 8 */
22718 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22719 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
22720 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
22721 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
22722 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
22723 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
22724 				cnt = 6;
22725 			} else {
22726 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
22727 				cnt = 1;
22728 			}
22729 
22730 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22731 			if (!new_prog)
22732 				return -ENOMEM;
22733 
22734 			delta    += cnt - 1;
22735 			env->prog = prog = new_prog;
22736 			insn      = new_prog->insnsi + i + delta;
22737 			goto next_insn;
22738 		}
22739 
22740 		/* Implement get_func_arg_cnt inline. */
22741 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22742 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
22743 			/* Load nr_args from ctx - 8 */
22744 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22745 
22746 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
22747 			if (!new_prog)
22748 				return -ENOMEM;
22749 
22750 			env->prog = prog = new_prog;
22751 			insn      = new_prog->insnsi + i + delta;
22752 			goto next_insn;
22753 		}
22754 
22755 		/* Implement bpf_get_func_ip inline. */
22756 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22757 		    insn->imm == BPF_FUNC_get_func_ip) {
22758 			/* Load IP address from ctx - 16 */
22759 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
22760 
22761 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
22762 			if (!new_prog)
22763 				return -ENOMEM;
22764 
22765 			env->prog = prog = new_prog;
22766 			insn      = new_prog->insnsi + i + delta;
22767 			goto next_insn;
22768 		}
22769 
22770 		/* Implement bpf_get_branch_snapshot inline. */
22771 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
22772 		    prog->jit_requested && BITS_PER_LONG == 64 &&
22773 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
22774 			/* We are dealing with the following func protos:
22775 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
22776 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
22777 			 */
22778 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
22779 
22780 			/* struct perf_branch_entry is part of UAPI and is
22781 			 * used as an array element, so extremely unlikely to
22782 			 * ever grow or shrink
22783 			 */
22784 			BUILD_BUG_ON(br_entry_size != 24);
22785 
22786 			/* if (unlikely(flags)) return -EINVAL */
22787 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
22788 
22789 			/* Transform size (bytes) into number of entries (cnt = size / 24).
22790 			 * But to avoid expensive division instruction, we implement
22791 			 * divide-by-3 through multiplication, followed by further
22792 			 * division by 8 through 3-bit right shift.
22793 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
22794 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
22795 			 *
22796 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
22797 			 */
22798 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
22799 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
22800 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
22801 
22802 			/* call perf_snapshot_branch_stack implementation */
22803 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
22804 			/* if (entry_cnt == 0) return -ENOENT */
22805 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
22806 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
22807 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
22808 			insn_buf[7] = BPF_JMP_A(3);
22809 			/* return -EINVAL; */
22810 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
22811 			insn_buf[9] = BPF_JMP_A(1);
22812 			/* return -ENOENT; */
22813 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
22814 			cnt = 11;
22815 
22816 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22817 			if (!new_prog)
22818 				return -ENOMEM;
22819 
22820 			delta    += cnt - 1;
22821 			env->prog = prog = new_prog;
22822 			insn      = new_prog->insnsi + i + delta;
22823 			goto next_insn;
22824 		}
22825 
22826 		/* Implement bpf_kptr_xchg inline */
22827 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22828 		    insn->imm == BPF_FUNC_kptr_xchg &&
22829 		    bpf_jit_supports_ptr_xchg()) {
22830 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
22831 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
22832 			cnt = 2;
22833 
22834 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22835 			if (!new_prog)
22836 				return -ENOMEM;
22837 
22838 			delta    += cnt - 1;
22839 			env->prog = prog = new_prog;
22840 			insn      = new_prog->insnsi + i + delta;
22841 			goto next_insn;
22842 		}
22843 patch_call_imm:
22844 		fn = env->ops->get_func_proto(insn->imm, env->prog);
22845 		/* all functions that have prototype and verifier allowed
22846 		 * programs to call them, must be real in-kernel functions
22847 		 */
22848 		if (!fn->func) {
22849 			verifier_bug(env,
22850 				     "not inlined functions %s#%d is missing func",
22851 				     func_id_name(insn->imm), insn->imm);
22852 			return -EFAULT;
22853 		}
22854 		insn->imm = fn->func - __bpf_call_base;
22855 next_insn:
22856 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
22857 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
22858 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
22859 
22860 			stack_depth = subprogs[cur_subprog].stack_depth;
22861 			if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) {
22862 				verbose(env, "stack size %d(extra %d) is too large\n",
22863 					stack_depth, stack_depth_extra);
22864 				return -EINVAL;
22865 			}
22866 			cur_subprog++;
22867 			stack_depth = subprogs[cur_subprog].stack_depth;
22868 			stack_depth_extra = 0;
22869 		}
22870 		i++;
22871 		insn++;
22872 	}
22873 
22874 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
22875 	for (i = 0; i < env->subprog_cnt; i++) {
22876 		int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1;
22877 		int subprog_start = subprogs[i].start;
22878 		int stack_slots = subprogs[i].stack_extra / 8;
22879 		int slots = delta, cnt = 0;
22880 
22881 		if (!stack_slots)
22882 			continue;
22883 		/* We need two slots in case timed may_goto is supported. */
22884 		if (stack_slots > slots) {
22885 			verifier_bug(env, "stack_slots supports may_goto only");
22886 			return -EFAULT;
22887 		}
22888 
22889 		stack_depth = subprogs[i].stack_depth;
22890 		if (bpf_jit_supports_timed_may_goto()) {
22891 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
22892 						     BPF_MAX_TIMED_LOOPS);
22893 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0);
22894 		} else {
22895 			/* Add ST insn to subprog prologue to init extra stack */
22896 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
22897 						     BPF_MAX_LOOPS);
22898 		}
22899 		/* Copy first actual insn to preserve it */
22900 		insn_buf[cnt++] = env->prog->insnsi[subprog_start];
22901 
22902 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt);
22903 		if (!new_prog)
22904 			return -ENOMEM;
22905 		env->prog = prog = new_prog;
22906 		/*
22907 		 * If may_goto is a first insn of a prog there could be a jmp
22908 		 * insn that points to it, hence adjust all such jmps to point
22909 		 * to insn after BPF_ST that inits may_goto count.
22910 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
22911 		 */
22912 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta));
22913 	}
22914 
22915 	/* Since poke tab is now finalized, publish aux to tracker. */
22916 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
22917 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
22918 		if (!map_ptr->ops->map_poke_track ||
22919 		    !map_ptr->ops->map_poke_untrack ||
22920 		    !map_ptr->ops->map_poke_run) {
22921 			verifier_bug(env, "poke tab is misconfigured");
22922 			return -EFAULT;
22923 		}
22924 
22925 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
22926 		if (ret < 0) {
22927 			verbose(env, "tracking tail call prog failed\n");
22928 			return ret;
22929 		}
22930 	}
22931 
22932 	sort_kfunc_descs_by_imm_off(env->prog);
22933 
22934 	return 0;
22935 }
22936 
22937 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
22938 					int position,
22939 					s32 stack_base,
22940 					u32 callback_subprogno,
22941 					u32 *total_cnt)
22942 {
22943 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
22944 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
22945 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
22946 	int reg_loop_max = BPF_REG_6;
22947 	int reg_loop_cnt = BPF_REG_7;
22948 	int reg_loop_ctx = BPF_REG_8;
22949 
22950 	struct bpf_insn *insn_buf = env->insn_buf;
22951 	struct bpf_prog *new_prog;
22952 	u32 callback_start;
22953 	u32 call_insn_offset;
22954 	s32 callback_offset;
22955 	u32 cnt = 0;
22956 
22957 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
22958 	 * be careful to modify this code in sync.
22959 	 */
22960 
22961 	/* Return error and jump to the end of the patch if
22962 	 * expected number of iterations is too big.
22963 	 */
22964 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
22965 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
22966 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
22967 	/* spill R6, R7, R8 to use these as loop vars */
22968 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
22969 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
22970 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
22971 	/* initialize loop vars */
22972 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
22973 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
22974 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
22975 	/* loop header,
22976 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
22977 	 */
22978 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
22979 	/* callback call,
22980 	 * correct callback offset would be set after patching
22981 	 */
22982 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
22983 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
22984 	insn_buf[cnt++] = BPF_CALL_REL(0);
22985 	/* increment loop counter */
22986 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
22987 	/* jump to loop header if callback returned 0 */
22988 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
22989 	/* return value of bpf_loop,
22990 	 * set R0 to the number of iterations
22991 	 */
22992 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
22993 	/* restore original values of R6, R7, R8 */
22994 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
22995 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
22996 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
22997 
22998 	*total_cnt = cnt;
22999 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
23000 	if (!new_prog)
23001 		return new_prog;
23002 
23003 	/* callback start is known only after patching */
23004 	callback_start = env->subprog_info[callback_subprogno].start;
23005 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
23006 	call_insn_offset = position + 12;
23007 	callback_offset = callback_start - call_insn_offset - 1;
23008 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
23009 
23010 	return new_prog;
23011 }
23012 
23013 static bool is_bpf_loop_call(struct bpf_insn *insn)
23014 {
23015 	return insn->code == (BPF_JMP | BPF_CALL) &&
23016 		insn->src_reg == 0 &&
23017 		insn->imm == BPF_FUNC_loop;
23018 }
23019 
23020 /* For all sub-programs in the program (including main) check
23021  * insn_aux_data to see if there are bpf_loop calls that require
23022  * inlining. If such calls are found the calls are replaced with a
23023  * sequence of instructions produced by `inline_bpf_loop` function and
23024  * subprog stack_depth is increased by the size of 3 registers.
23025  * This stack space is used to spill values of the R6, R7, R8.  These
23026  * registers are used to store the loop bound, counter and context
23027  * variables.
23028  */
23029 static int optimize_bpf_loop(struct bpf_verifier_env *env)
23030 {
23031 	struct bpf_subprog_info *subprogs = env->subprog_info;
23032 	int i, cur_subprog = 0, cnt, delta = 0;
23033 	struct bpf_insn *insn = env->prog->insnsi;
23034 	int insn_cnt = env->prog->len;
23035 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
23036 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23037 	u16 stack_depth_extra = 0;
23038 
23039 	for (i = 0; i < insn_cnt; i++, insn++) {
23040 		struct bpf_loop_inline_state *inline_state =
23041 			&env->insn_aux_data[i + delta].loop_inline_state;
23042 
23043 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
23044 			struct bpf_prog *new_prog;
23045 
23046 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
23047 			new_prog = inline_bpf_loop(env,
23048 						   i + delta,
23049 						   -(stack_depth + stack_depth_extra),
23050 						   inline_state->callback_subprogno,
23051 						   &cnt);
23052 			if (!new_prog)
23053 				return -ENOMEM;
23054 
23055 			delta     += cnt - 1;
23056 			env->prog  = new_prog;
23057 			insn       = new_prog->insnsi + i + delta;
23058 		}
23059 
23060 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
23061 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
23062 			cur_subprog++;
23063 			stack_depth = subprogs[cur_subprog].stack_depth;
23064 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23065 			stack_depth_extra = 0;
23066 		}
23067 	}
23068 
23069 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23070 
23071 	return 0;
23072 }
23073 
23074 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
23075  * adjust subprograms stack depth when possible.
23076  */
23077 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
23078 {
23079 	struct bpf_subprog_info *subprog = env->subprog_info;
23080 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
23081 	struct bpf_insn *insn = env->prog->insnsi;
23082 	int insn_cnt = env->prog->len;
23083 	u32 spills_num;
23084 	bool modified = false;
23085 	int i, j;
23086 
23087 	for (i = 0; i < insn_cnt; i++, insn++) {
23088 		if (aux[i].fastcall_spills_num > 0) {
23089 			spills_num = aux[i].fastcall_spills_num;
23090 			/* NOPs would be removed by opt_remove_nops() */
23091 			for (j = 1; j <= spills_num; ++j) {
23092 				*(insn - j) = NOP;
23093 				*(insn + j) = NOP;
23094 			}
23095 			modified = true;
23096 		}
23097 		if ((subprog + 1)->start == i + 1) {
23098 			if (modified && !subprog->keep_fastcall_stack)
23099 				subprog->stack_depth = -subprog->fastcall_stack_off;
23100 			subprog++;
23101 			modified = false;
23102 		}
23103 	}
23104 
23105 	return 0;
23106 }
23107 
23108 static void free_states(struct bpf_verifier_env *env)
23109 {
23110 	struct bpf_verifier_state_list *sl;
23111 	struct list_head *head, *pos, *tmp;
23112 	struct bpf_scc_info *info;
23113 	int i, j;
23114 
23115 	free_verifier_state(env->cur_state, true);
23116 	env->cur_state = NULL;
23117 	while (!pop_stack(env, NULL, NULL, false));
23118 
23119 	list_for_each_safe(pos, tmp, &env->free_list) {
23120 		sl = container_of(pos, struct bpf_verifier_state_list, node);
23121 		free_verifier_state(&sl->state, false);
23122 		kfree(sl);
23123 	}
23124 	INIT_LIST_HEAD(&env->free_list);
23125 
23126 	for (i = 0; i < env->scc_cnt; ++i) {
23127 		info = env->scc_info[i];
23128 		if (!info)
23129 			continue;
23130 		for (j = 0; j < info->num_visits; j++)
23131 			free_backedges(&info->visits[j]);
23132 		kvfree(info);
23133 		env->scc_info[i] = NULL;
23134 	}
23135 
23136 	if (!env->explored_states)
23137 		return;
23138 
23139 	for (i = 0; i < state_htab_size(env); i++) {
23140 		head = &env->explored_states[i];
23141 
23142 		list_for_each_safe(pos, tmp, head) {
23143 			sl = container_of(pos, struct bpf_verifier_state_list, node);
23144 			free_verifier_state(&sl->state, false);
23145 			kfree(sl);
23146 		}
23147 		INIT_LIST_HEAD(&env->explored_states[i]);
23148 	}
23149 }
23150 
23151 static int do_check_common(struct bpf_verifier_env *env, int subprog)
23152 {
23153 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
23154 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
23155 	struct bpf_prog_aux *aux = env->prog->aux;
23156 	struct bpf_verifier_state *state;
23157 	struct bpf_reg_state *regs;
23158 	int ret, i;
23159 
23160 	env->prev_linfo = NULL;
23161 	env->pass_cnt++;
23162 
23163 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL_ACCOUNT);
23164 	if (!state)
23165 		return -ENOMEM;
23166 	state->curframe = 0;
23167 	state->speculative = false;
23168 	state->branches = 1;
23169 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL_ACCOUNT);
23170 	if (!state->frame[0]) {
23171 		kfree(state);
23172 		return -ENOMEM;
23173 	}
23174 	env->cur_state = state;
23175 	init_func_state(env, state->frame[0],
23176 			BPF_MAIN_FUNC /* callsite */,
23177 			0 /* frameno */,
23178 			subprog);
23179 	state->first_insn_idx = env->subprog_info[subprog].start;
23180 	state->last_insn_idx = -1;
23181 
23182 	regs = state->frame[state->curframe]->regs;
23183 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
23184 		const char *sub_name = subprog_name(env, subprog);
23185 		struct bpf_subprog_arg_info *arg;
23186 		struct bpf_reg_state *reg;
23187 
23188 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
23189 		ret = btf_prepare_func_args(env, subprog);
23190 		if (ret)
23191 			goto out;
23192 
23193 		if (subprog_is_exc_cb(env, subprog)) {
23194 			state->frame[0]->in_exception_callback_fn = true;
23195 			/* We have already ensured that the callback returns an integer, just
23196 			 * like all global subprogs. We need to determine it only has a single
23197 			 * scalar argument.
23198 			 */
23199 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
23200 				verbose(env, "exception cb only supports single integer argument\n");
23201 				ret = -EINVAL;
23202 				goto out;
23203 			}
23204 		}
23205 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
23206 			arg = &sub->args[i - BPF_REG_1];
23207 			reg = &regs[i];
23208 
23209 			if (arg->arg_type == ARG_PTR_TO_CTX) {
23210 				reg->type = PTR_TO_CTX;
23211 				mark_reg_known_zero(env, regs, i);
23212 			} else if (arg->arg_type == ARG_ANYTHING) {
23213 				reg->type = SCALAR_VALUE;
23214 				mark_reg_unknown(env, regs, i);
23215 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
23216 				/* assume unspecial LOCAL dynptr type */
23217 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
23218 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
23219 				reg->type = PTR_TO_MEM;
23220 				reg->type |= arg->arg_type &
23221 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
23222 				mark_reg_known_zero(env, regs, i);
23223 				reg->mem_size = arg->mem_size;
23224 				if (arg->arg_type & PTR_MAYBE_NULL)
23225 					reg->id = ++env->id_gen;
23226 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
23227 				reg->type = PTR_TO_BTF_ID;
23228 				if (arg->arg_type & PTR_MAYBE_NULL)
23229 					reg->type |= PTR_MAYBE_NULL;
23230 				if (arg->arg_type & PTR_UNTRUSTED)
23231 					reg->type |= PTR_UNTRUSTED;
23232 				if (arg->arg_type & PTR_TRUSTED)
23233 					reg->type |= PTR_TRUSTED;
23234 				mark_reg_known_zero(env, regs, i);
23235 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
23236 				reg->btf_id = arg->btf_id;
23237 				reg->id = ++env->id_gen;
23238 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
23239 				/* caller can pass either PTR_TO_ARENA or SCALAR */
23240 				mark_reg_unknown(env, regs, i);
23241 			} else {
23242 				verifier_bug(env, "unhandled arg#%d type %d",
23243 					     i - BPF_REG_1, arg->arg_type);
23244 				ret = -EFAULT;
23245 				goto out;
23246 			}
23247 		}
23248 	} else {
23249 		/* if main BPF program has associated BTF info, validate that
23250 		 * it's matching expected signature, and otherwise mark BTF
23251 		 * info for main program as unreliable
23252 		 */
23253 		if (env->prog->aux->func_info_aux) {
23254 			ret = btf_prepare_func_args(env, 0);
23255 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
23256 				env->prog->aux->func_info_aux[0].unreliable = true;
23257 		}
23258 
23259 		/* 1st arg to a function */
23260 		regs[BPF_REG_1].type = PTR_TO_CTX;
23261 		mark_reg_known_zero(env, regs, BPF_REG_1);
23262 	}
23263 
23264 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
23265 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
23266 		for (i = 0; i < aux->ctx_arg_info_size; i++)
23267 			aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ?
23268 							  acquire_reference(env, 0) : 0;
23269 	}
23270 
23271 	ret = do_check(env);
23272 out:
23273 	if (!ret && pop_log)
23274 		bpf_vlog_reset(&env->log, 0);
23275 	free_states(env);
23276 	return ret;
23277 }
23278 
23279 /* Lazily verify all global functions based on their BTF, if they are called
23280  * from main BPF program or any of subprograms transitively.
23281  * BPF global subprogs called from dead code are not validated.
23282  * All callable global functions must pass verification.
23283  * Otherwise the whole program is rejected.
23284  * Consider:
23285  * int bar(int);
23286  * int foo(int f)
23287  * {
23288  *    return bar(f);
23289  * }
23290  * int bar(int b)
23291  * {
23292  *    ...
23293  * }
23294  * foo() will be verified first for R1=any_scalar_value. During verification it
23295  * will be assumed that bar() already verified successfully and call to bar()
23296  * from foo() will be checked for type match only. Later bar() will be verified
23297  * independently to check that it's safe for R1=any_scalar_value.
23298  */
23299 static int do_check_subprogs(struct bpf_verifier_env *env)
23300 {
23301 	struct bpf_prog_aux *aux = env->prog->aux;
23302 	struct bpf_func_info_aux *sub_aux;
23303 	int i, ret, new_cnt;
23304 
23305 	if (!aux->func_info)
23306 		return 0;
23307 
23308 	/* exception callback is presumed to be always called */
23309 	if (env->exception_callback_subprog)
23310 		subprog_aux(env, env->exception_callback_subprog)->called = true;
23311 
23312 again:
23313 	new_cnt = 0;
23314 	for (i = 1; i < env->subprog_cnt; i++) {
23315 		if (!subprog_is_global(env, i))
23316 			continue;
23317 
23318 		sub_aux = subprog_aux(env, i);
23319 		if (!sub_aux->called || sub_aux->verified)
23320 			continue;
23321 
23322 		env->insn_idx = env->subprog_info[i].start;
23323 		WARN_ON_ONCE(env->insn_idx == 0);
23324 		ret = do_check_common(env, i);
23325 		if (ret) {
23326 			return ret;
23327 		} else if (env->log.level & BPF_LOG_LEVEL) {
23328 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
23329 				i, subprog_name(env, i));
23330 		}
23331 
23332 		/* We verified new global subprog, it might have called some
23333 		 * more global subprogs that we haven't verified yet, so we
23334 		 * need to do another pass over subprogs to verify those.
23335 		 */
23336 		sub_aux->verified = true;
23337 		new_cnt++;
23338 	}
23339 
23340 	/* We can't loop forever as we verify at least one global subprog on
23341 	 * each pass.
23342 	 */
23343 	if (new_cnt)
23344 		goto again;
23345 
23346 	return 0;
23347 }
23348 
23349 static int do_check_main(struct bpf_verifier_env *env)
23350 {
23351 	int ret;
23352 
23353 	env->insn_idx = 0;
23354 	ret = do_check_common(env, 0);
23355 	if (!ret)
23356 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23357 	return ret;
23358 }
23359 
23360 
23361 static void print_verification_stats(struct bpf_verifier_env *env)
23362 {
23363 	int i;
23364 
23365 	if (env->log.level & BPF_LOG_STATS) {
23366 		verbose(env, "verification time %lld usec\n",
23367 			div_u64(env->verification_time, 1000));
23368 		verbose(env, "stack depth ");
23369 		for (i = 0; i < env->subprog_cnt; i++) {
23370 			u32 depth = env->subprog_info[i].stack_depth;
23371 
23372 			verbose(env, "%d", depth);
23373 			if (i + 1 < env->subprog_cnt)
23374 				verbose(env, "+");
23375 		}
23376 		verbose(env, "\n");
23377 	}
23378 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
23379 		"total_states %d peak_states %d mark_read %d\n",
23380 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
23381 		env->max_states_per_insn, env->total_states,
23382 		env->peak_states, env->longest_mark_read_walk);
23383 }
23384 
23385 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
23386 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
23387 {
23388 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
23389 	prog->aux->ctx_arg_info_size = cnt;
23390 
23391 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
23392 }
23393 
23394 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
23395 {
23396 	const struct btf_type *t, *func_proto;
23397 	const struct bpf_struct_ops_desc *st_ops_desc;
23398 	const struct bpf_struct_ops *st_ops;
23399 	const struct btf_member *member;
23400 	struct bpf_prog *prog = env->prog;
23401 	bool has_refcounted_arg = false;
23402 	u32 btf_id, member_idx, member_off;
23403 	struct btf *btf;
23404 	const char *mname;
23405 	int i, err;
23406 
23407 	if (!prog->gpl_compatible) {
23408 		verbose(env, "struct ops programs must have a GPL compatible license\n");
23409 		return -EINVAL;
23410 	}
23411 
23412 	if (!prog->aux->attach_btf_id)
23413 		return -ENOTSUPP;
23414 
23415 	btf = prog->aux->attach_btf;
23416 	if (btf_is_module(btf)) {
23417 		/* Make sure st_ops is valid through the lifetime of env */
23418 		env->attach_btf_mod = btf_try_get_module(btf);
23419 		if (!env->attach_btf_mod) {
23420 			verbose(env, "struct_ops module %s is not found\n",
23421 				btf_get_name(btf));
23422 			return -ENOTSUPP;
23423 		}
23424 	}
23425 
23426 	btf_id = prog->aux->attach_btf_id;
23427 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
23428 	if (!st_ops_desc) {
23429 		verbose(env, "attach_btf_id %u is not a supported struct\n",
23430 			btf_id);
23431 		return -ENOTSUPP;
23432 	}
23433 	st_ops = st_ops_desc->st_ops;
23434 
23435 	t = st_ops_desc->type;
23436 	member_idx = prog->expected_attach_type;
23437 	if (member_idx >= btf_type_vlen(t)) {
23438 		verbose(env, "attach to invalid member idx %u of struct %s\n",
23439 			member_idx, st_ops->name);
23440 		return -EINVAL;
23441 	}
23442 
23443 	member = &btf_type_member(t)[member_idx];
23444 	mname = btf_name_by_offset(btf, member->name_off);
23445 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
23446 					       NULL);
23447 	if (!func_proto) {
23448 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
23449 			mname, member_idx, st_ops->name);
23450 		return -EINVAL;
23451 	}
23452 
23453 	member_off = __btf_member_bit_offset(t, member) / 8;
23454 	err = bpf_struct_ops_supported(st_ops, member_off);
23455 	if (err) {
23456 		verbose(env, "attach to unsupported member %s of struct %s\n",
23457 			mname, st_ops->name);
23458 		return err;
23459 	}
23460 
23461 	if (st_ops->check_member) {
23462 		err = st_ops->check_member(t, member, prog);
23463 
23464 		if (err) {
23465 			verbose(env, "attach to unsupported member %s of struct %s\n",
23466 				mname, st_ops->name);
23467 			return err;
23468 		}
23469 	}
23470 
23471 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
23472 		verbose(env, "Private stack not supported by jit\n");
23473 		return -EACCES;
23474 	}
23475 
23476 	for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) {
23477 		if (st_ops_desc->arg_info[member_idx].info->refcounted) {
23478 			has_refcounted_arg = true;
23479 			break;
23480 		}
23481 	}
23482 
23483 	/* Tail call is not allowed for programs with refcounted arguments since we
23484 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
23485 	 */
23486 	for (i = 0; i < env->subprog_cnt; i++) {
23487 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
23488 			verbose(env, "program with __ref argument cannot tail call\n");
23489 			return -EINVAL;
23490 		}
23491 	}
23492 
23493 	prog->aux->st_ops = st_ops;
23494 	prog->aux->attach_st_ops_member_off = member_off;
23495 
23496 	prog->aux->attach_func_proto = func_proto;
23497 	prog->aux->attach_func_name = mname;
23498 	env->ops = st_ops->verifier_ops;
23499 
23500 	return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info,
23501 					  st_ops_desc->arg_info[member_idx].cnt);
23502 }
23503 #define SECURITY_PREFIX "security_"
23504 
23505 static int check_attach_modify_return(unsigned long addr, const char *func_name)
23506 {
23507 	if (within_error_injection_list(addr) ||
23508 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
23509 		return 0;
23510 
23511 	return -EINVAL;
23512 }
23513 
23514 /* list of non-sleepable functions that are otherwise on
23515  * ALLOW_ERROR_INJECTION list
23516  */
23517 BTF_SET_START(btf_non_sleepable_error_inject)
23518 /* Three functions below can be called from sleepable and non-sleepable context.
23519  * Assume non-sleepable from bpf safety point of view.
23520  */
23521 BTF_ID(func, __filemap_add_folio)
23522 #ifdef CONFIG_FAIL_PAGE_ALLOC
23523 BTF_ID(func, should_fail_alloc_page)
23524 #endif
23525 #ifdef CONFIG_FAILSLAB
23526 BTF_ID(func, should_failslab)
23527 #endif
23528 BTF_SET_END(btf_non_sleepable_error_inject)
23529 
23530 static int check_non_sleepable_error_inject(u32 btf_id)
23531 {
23532 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
23533 }
23534 
23535 int bpf_check_attach_target(struct bpf_verifier_log *log,
23536 			    const struct bpf_prog *prog,
23537 			    const struct bpf_prog *tgt_prog,
23538 			    u32 btf_id,
23539 			    struct bpf_attach_target_info *tgt_info)
23540 {
23541 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
23542 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
23543 	char trace_symbol[KSYM_SYMBOL_LEN];
23544 	const char prefix[] = "btf_trace_";
23545 	struct bpf_raw_event_map *btp;
23546 	int ret = 0, subprog = -1, i;
23547 	const struct btf_type *t;
23548 	bool conservative = true;
23549 	const char *tname, *fname;
23550 	struct btf *btf;
23551 	long addr = 0;
23552 	struct module *mod = NULL;
23553 
23554 	if (!btf_id) {
23555 		bpf_log(log, "Tracing programs must provide btf_id\n");
23556 		return -EINVAL;
23557 	}
23558 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
23559 	if (!btf) {
23560 		bpf_log(log,
23561 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
23562 		return -EINVAL;
23563 	}
23564 	t = btf_type_by_id(btf, btf_id);
23565 	if (!t) {
23566 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
23567 		return -EINVAL;
23568 	}
23569 	tname = btf_name_by_offset(btf, t->name_off);
23570 	if (!tname) {
23571 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
23572 		return -EINVAL;
23573 	}
23574 	if (tgt_prog) {
23575 		struct bpf_prog_aux *aux = tgt_prog->aux;
23576 		bool tgt_changes_pkt_data;
23577 		bool tgt_might_sleep;
23578 
23579 		if (bpf_prog_is_dev_bound(prog->aux) &&
23580 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
23581 			bpf_log(log, "Target program bound device mismatch");
23582 			return -EINVAL;
23583 		}
23584 
23585 		for (i = 0; i < aux->func_info_cnt; i++)
23586 			if (aux->func_info[i].type_id == btf_id) {
23587 				subprog = i;
23588 				break;
23589 			}
23590 		if (subprog == -1) {
23591 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
23592 			return -EINVAL;
23593 		}
23594 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
23595 			bpf_log(log,
23596 				"%s programs cannot attach to exception callback\n",
23597 				prog_extension ? "Extension" : "FENTRY/FEXIT");
23598 			return -EINVAL;
23599 		}
23600 		conservative = aux->func_info_aux[subprog].unreliable;
23601 		if (prog_extension) {
23602 			if (conservative) {
23603 				bpf_log(log,
23604 					"Cannot replace static functions\n");
23605 				return -EINVAL;
23606 			}
23607 			if (!prog->jit_requested) {
23608 				bpf_log(log,
23609 					"Extension programs should be JITed\n");
23610 				return -EINVAL;
23611 			}
23612 			tgt_changes_pkt_data = aux->func
23613 					       ? aux->func[subprog]->aux->changes_pkt_data
23614 					       : aux->changes_pkt_data;
23615 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
23616 				bpf_log(log,
23617 					"Extension program changes packet data, while original does not\n");
23618 				return -EINVAL;
23619 			}
23620 
23621 			tgt_might_sleep = aux->func
23622 					  ? aux->func[subprog]->aux->might_sleep
23623 					  : aux->might_sleep;
23624 			if (prog->aux->might_sleep && !tgt_might_sleep) {
23625 				bpf_log(log,
23626 					"Extension program may sleep, while original does not\n");
23627 				return -EINVAL;
23628 			}
23629 		}
23630 		if (!tgt_prog->jited) {
23631 			bpf_log(log, "Can attach to only JITed progs\n");
23632 			return -EINVAL;
23633 		}
23634 		if (prog_tracing) {
23635 			if (aux->attach_tracing_prog) {
23636 				/*
23637 				 * Target program is an fentry/fexit which is already attached
23638 				 * to another tracing program. More levels of nesting
23639 				 * attachment are not allowed.
23640 				 */
23641 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
23642 				return -EINVAL;
23643 			}
23644 		} else if (tgt_prog->type == prog->type) {
23645 			/*
23646 			 * To avoid potential call chain cycles, prevent attaching of a
23647 			 * program extension to another extension. It's ok to attach
23648 			 * fentry/fexit to extension program.
23649 			 */
23650 			bpf_log(log, "Cannot recursively attach\n");
23651 			return -EINVAL;
23652 		}
23653 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
23654 		    prog_extension &&
23655 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
23656 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
23657 			/* Program extensions can extend all program types
23658 			 * except fentry/fexit. The reason is the following.
23659 			 * The fentry/fexit programs are used for performance
23660 			 * analysis, stats and can be attached to any program
23661 			 * type. When extension program is replacing XDP function
23662 			 * it is necessary to allow performance analysis of all
23663 			 * functions. Both original XDP program and its program
23664 			 * extension. Hence attaching fentry/fexit to
23665 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
23666 			 * fentry/fexit was allowed it would be possible to create
23667 			 * long call chain fentry->extension->fentry->extension
23668 			 * beyond reasonable stack size. Hence extending fentry
23669 			 * is not allowed.
23670 			 */
23671 			bpf_log(log, "Cannot extend fentry/fexit\n");
23672 			return -EINVAL;
23673 		}
23674 	} else {
23675 		if (prog_extension) {
23676 			bpf_log(log, "Cannot replace kernel functions\n");
23677 			return -EINVAL;
23678 		}
23679 	}
23680 
23681 	switch (prog->expected_attach_type) {
23682 	case BPF_TRACE_RAW_TP:
23683 		if (tgt_prog) {
23684 			bpf_log(log,
23685 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
23686 			return -EINVAL;
23687 		}
23688 		if (!btf_type_is_typedef(t)) {
23689 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
23690 				btf_id);
23691 			return -EINVAL;
23692 		}
23693 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
23694 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
23695 				btf_id, tname);
23696 			return -EINVAL;
23697 		}
23698 		tname += sizeof(prefix) - 1;
23699 
23700 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
23701 		 * names. Thus using bpf_raw_event_map to get argument names.
23702 		 */
23703 		btp = bpf_get_raw_tracepoint(tname);
23704 		if (!btp)
23705 			return -EINVAL;
23706 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
23707 					trace_symbol);
23708 		bpf_put_raw_tracepoint(btp);
23709 
23710 		if (fname)
23711 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
23712 
23713 		if (!fname || ret < 0) {
23714 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
23715 				prefix, tname);
23716 			t = btf_type_by_id(btf, t->type);
23717 			if (!btf_type_is_ptr(t))
23718 				/* should never happen in valid vmlinux build */
23719 				return -EINVAL;
23720 		} else {
23721 			t = btf_type_by_id(btf, ret);
23722 			if (!btf_type_is_func(t))
23723 				/* should never happen in valid vmlinux build */
23724 				return -EINVAL;
23725 		}
23726 
23727 		t = btf_type_by_id(btf, t->type);
23728 		if (!btf_type_is_func_proto(t))
23729 			/* should never happen in valid vmlinux build */
23730 			return -EINVAL;
23731 
23732 		break;
23733 	case BPF_TRACE_ITER:
23734 		if (!btf_type_is_func(t)) {
23735 			bpf_log(log, "attach_btf_id %u is not a function\n",
23736 				btf_id);
23737 			return -EINVAL;
23738 		}
23739 		t = btf_type_by_id(btf, t->type);
23740 		if (!btf_type_is_func_proto(t))
23741 			return -EINVAL;
23742 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
23743 		if (ret)
23744 			return ret;
23745 		break;
23746 	default:
23747 		if (!prog_extension)
23748 			return -EINVAL;
23749 		fallthrough;
23750 	case BPF_MODIFY_RETURN:
23751 	case BPF_LSM_MAC:
23752 	case BPF_LSM_CGROUP:
23753 	case BPF_TRACE_FENTRY:
23754 	case BPF_TRACE_FEXIT:
23755 		if (!btf_type_is_func(t)) {
23756 			bpf_log(log, "attach_btf_id %u is not a function\n",
23757 				btf_id);
23758 			return -EINVAL;
23759 		}
23760 		if (prog_extension &&
23761 		    btf_check_type_match(log, prog, btf, t))
23762 			return -EINVAL;
23763 		t = btf_type_by_id(btf, t->type);
23764 		if (!btf_type_is_func_proto(t))
23765 			return -EINVAL;
23766 
23767 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
23768 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
23769 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
23770 			return -EINVAL;
23771 
23772 		if (tgt_prog && conservative)
23773 			t = NULL;
23774 
23775 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
23776 		if (ret < 0)
23777 			return ret;
23778 
23779 		if (tgt_prog) {
23780 			if (subprog == 0)
23781 				addr = (long) tgt_prog->bpf_func;
23782 			else
23783 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
23784 		} else {
23785 			if (btf_is_module(btf)) {
23786 				mod = btf_try_get_module(btf);
23787 				if (mod)
23788 					addr = find_kallsyms_symbol_value(mod, tname);
23789 				else
23790 					addr = 0;
23791 			} else {
23792 				addr = kallsyms_lookup_name(tname);
23793 			}
23794 			if (!addr) {
23795 				module_put(mod);
23796 				bpf_log(log,
23797 					"The address of function %s cannot be found\n",
23798 					tname);
23799 				return -ENOENT;
23800 			}
23801 		}
23802 
23803 		if (prog->sleepable) {
23804 			ret = -EINVAL;
23805 			switch (prog->type) {
23806 			case BPF_PROG_TYPE_TRACING:
23807 
23808 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
23809 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
23810 				 */
23811 				if (!check_non_sleepable_error_inject(btf_id) &&
23812 				    within_error_injection_list(addr))
23813 					ret = 0;
23814 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
23815 				 * in the fmodret id set with the KF_SLEEPABLE flag.
23816 				 */
23817 				else {
23818 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
23819 										prog);
23820 
23821 					if (flags && (*flags & KF_SLEEPABLE))
23822 						ret = 0;
23823 				}
23824 				break;
23825 			case BPF_PROG_TYPE_LSM:
23826 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
23827 				 * Only some of them are sleepable.
23828 				 */
23829 				if (bpf_lsm_is_sleepable_hook(btf_id))
23830 					ret = 0;
23831 				break;
23832 			default:
23833 				break;
23834 			}
23835 			if (ret) {
23836 				module_put(mod);
23837 				bpf_log(log, "%s is not sleepable\n", tname);
23838 				return ret;
23839 			}
23840 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
23841 			if (tgt_prog) {
23842 				module_put(mod);
23843 				bpf_log(log, "can't modify return codes of BPF programs\n");
23844 				return -EINVAL;
23845 			}
23846 			ret = -EINVAL;
23847 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
23848 			    !check_attach_modify_return(addr, tname))
23849 				ret = 0;
23850 			if (ret) {
23851 				module_put(mod);
23852 				bpf_log(log, "%s() is not modifiable\n", tname);
23853 				return ret;
23854 			}
23855 		}
23856 
23857 		break;
23858 	}
23859 	tgt_info->tgt_addr = addr;
23860 	tgt_info->tgt_name = tname;
23861 	tgt_info->tgt_type = t;
23862 	tgt_info->tgt_mod = mod;
23863 	return 0;
23864 }
23865 
23866 BTF_SET_START(btf_id_deny)
23867 BTF_ID_UNUSED
23868 #ifdef CONFIG_SMP
23869 BTF_ID(func, migrate_disable)
23870 BTF_ID(func, migrate_enable)
23871 #endif
23872 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
23873 BTF_ID(func, rcu_read_unlock_strict)
23874 #endif
23875 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
23876 BTF_ID(func, preempt_count_add)
23877 BTF_ID(func, preempt_count_sub)
23878 #endif
23879 #ifdef CONFIG_PREEMPT_RCU
23880 BTF_ID(func, __rcu_read_lock)
23881 BTF_ID(func, __rcu_read_unlock)
23882 #endif
23883 BTF_SET_END(btf_id_deny)
23884 
23885 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
23886  * Currently, we must manually list all __noreturn functions here. Once a more
23887  * robust solution is implemented, this workaround can be removed.
23888  */
23889 BTF_SET_START(noreturn_deny)
23890 #ifdef CONFIG_IA32_EMULATION
23891 BTF_ID(func, __ia32_sys_exit)
23892 BTF_ID(func, __ia32_sys_exit_group)
23893 #endif
23894 #ifdef CONFIG_KUNIT
23895 BTF_ID(func, __kunit_abort)
23896 BTF_ID(func, kunit_try_catch_throw)
23897 #endif
23898 #ifdef CONFIG_MODULES
23899 BTF_ID(func, __module_put_and_kthread_exit)
23900 #endif
23901 #ifdef CONFIG_X86_64
23902 BTF_ID(func, __x64_sys_exit)
23903 BTF_ID(func, __x64_sys_exit_group)
23904 #endif
23905 BTF_ID(func, do_exit)
23906 BTF_ID(func, do_group_exit)
23907 BTF_ID(func, kthread_complete_and_exit)
23908 BTF_ID(func, kthread_exit)
23909 BTF_ID(func, make_task_dead)
23910 BTF_SET_END(noreturn_deny)
23911 
23912 static bool can_be_sleepable(struct bpf_prog *prog)
23913 {
23914 	if (prog->type == BPF_PROG_TYPE_TRACING) {
23915 		switch (prog->expected_attach_type) {
23916 		case BPF_TRACE_FENTRY:
23917 		case BPF_TRACE_FEXIT:
23918 		case BPF_MODIFY_RETURN:
23919 		case BPF_TRACE_ITER:
23920 			return true;
23921 		default:
23922 			return false;
23923 		}
23924 	}
23925 	return prog->type == BPF_PROG_TYPE_LSM ||
23926 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
23927 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
23928 }
23929 
23930 static int check_attach_btf_id(struct bpf_verifier_env *env)
23931 {
23932 	struct bpf_prog *prog = env->prog;
23933 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
23934 	struct bpf_attach_target_info tgt_info = {};
23935 	u32 btf_id = prog->aux->attach_btf_id;
23936 	struct bpf_trampoline *tr;
23937 	int ret;
23938 	u64 key;
23939 
23940 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
23941 		if (prog->sleepable)
23942 			/* attach_btf_id checked to be zero already */
23943 			return 0;
23944 		verbose(env, "Syscall programs can only be sleepable\n");
23945 		return -EINVAL;
23946 	}
23947 
23948 	if (prog->sleepable && !can_be_sleepable(prog)) {
23949 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
23950 		return -EINVAL;
23951 	}
23952 
23953 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
23954 		return check_struct_ops_btf_id(env);
23955 
23956 	if (prog->type != BPF_PROG_TYPE_TRACING &&
23957 	    prog->type != BPF_PROG_TYPE_LSM &&
23958 	    prog->type != BPF_PROG_TYPE_EXT)
23959 		return 0;
23960 
23961 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
23962 	if (ret)
23963 		return ret;
23964 
23965 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
23966 		/* to make freplace equivalent to their targets, they need to
23967 		 * inherit env->ops and expected_attach_type for the rest of the
23968 		 * verification
23969 		 */
23970 		env->ops = bpf_verifier_ops[tgt_prog->type];
23971 		prog->expected_attach_type = tgt_prog->expected_attach_type;
23972 	}
23973 
23974 	/* store info about the attachment target that will be used later */
23975 	prog->aux->attach_func_proto = tgt_info.tgt_type;
23976 	prog->aux->attach_func_name = tgt_info.tgt_name;
23977 	prog->aux->mod = tgt_info.tgt_mod;
23978 
23979 	if (tgt_prog) {
23980 		prog->aux->saved_dst_prog_type = tgt_prog->type;
23981 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
23982 	}
23983 
23984 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
23985 		prog->aux->attach_btf_trace = true;
23986 		return 0;
23987 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
23988 		return bpf_iter_prog_supported(prog);
23989 	}
23990 
23991 	if (prog->type == BPF_PROG_TYPE_LSM) {
23992 		ret = bpf_lsm_verify_prog(&env->log, prog);
23993 		if (ret < 0)
23994 			return ret;
23995 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
23996 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
23997 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
23998 			tgt_info.tgt_name);
23999 		return -EINVAL;
24000 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
24001 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
24002 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
24003 		verbose(env, "Attaching fexit/fmod_ret to __noreturn function '%s' is rejected.\n",
24004 			tgt_info.tgt_name);
24005 		return -EINVAL;
24006 	}
24007 
24008 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
24009 	tr = bpf_trampoline_get(key, &tgt_info);
24010 	if (!tr)
24011 		return -ENOMEM;
24012 
24013 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
24014 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
24015 
24016 	prog->aux->dst_trampoline = tr;
24017 	return 0;
24018 }
24019 
24020 struct btf *bpf_get_btf_vmlinux(void)
24021 {
24022 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
24023 		mutex_lock(&bpf_verifier_lock);
24024 		if (!btf_vmlinux)
24025 			btf_vmlinux = btf_parse_vmlinux();
24026 		mutex_unlock(&bpf_verifier_lock);
24027 	}
24028 	return btf_vmlinux;
24029 }
24030 
24031 /*
24032  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
24033  * this case expect that every file descriptor in the array is either a map or
24034  * a BTF. Everything else is considered to be trash.
24035  */
24036 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
24037 {
24038 	struct bpf_map *map;
24039 	struct btf *btf;
24040 	CLASS(fd, f)(fd);
24041 	int err;
24042 
24043 	map = __bpf_map_get(f);
24044 	if (!IS_ERR(map)) {
24045 		err = __add_used_map(env, map);
24046 		if (err < 0)
24047 			return err;
24048 		return 0;
24049 	}
24050 
24051 	btf = __btf_get_by_fd(f);
24052 	if (!IS_ERR(btf)) {
24053 		err = __add_used_btf(env, btf);
24054 		if (err < 0)
24055 			return err;
24056 		return 0;
24057 	}
24058 
24059 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
24060 	return PTR_ERR(map);
24061 }
24062 
24063 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
24064 {
24065 	size_t size = sizeof(int);
24066 	int ret;
24067 	int fd;
24068 	u32 i;
24069 
24070 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
24071 
24072 	/*
24073 	 * The only difference between old (no fd_array_cnt is given) and new
24074 	 * APIs is that in the latter case the fd_array is expected to be
24075 	 * continuous and is scanned for map fds right away
24076 	 */
24077 	if (!attr->fd_array_cnt)
24078 		return 0;
24079 
24080 	/* Check for integer overflow */
24081 	if (attr->fd_array_cnt >= (U32_MAX / size)) {
24082 		verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
24083 		return -EINVAL;
24084 	}
24085 
24086 	for (i = 0; i < attr->fd_array_cnt; i++) {
24087 		if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
24088 			return -EFAULT;
24089 
24090 		ret = add_fd_from_fd_array(env, fd);
24091 		if (ret)
24092 			return ret;
24093 	}
24094 
24095 	return 0;
24096 }
24097 
24098 static bool can_fallthrough(struct bpf_insn *insn)
24099 {
24100 	u8 class = BPF_CLASS(insn->code);
24101 	u8 opcode = BPF_OP(insn->code);
24102 
24103 	if (class != BPF_JMP && class != BPF_JMP32)
24104 		return true;
24105 
24106 	if (opcode == BPF_EXIT || opcode == BPF_JA)
24107 		return false;
24108 
24109 	return true;
24110 }
24111 
24112 static bool can_jump(struct bpf_insn *insn)
24113 {
24114 	u8 class = BPF_CLASS(insn->code);
24115 	u8 opcode = BPF_OP(insn->code);
24116 
24117 	if (class != BPF_JMP && class != BPF_JMP32)
24118 		return false;
24119 
24120 	switch (opcode) {
24121 	case BPF_JA:
24122 	case BPF_JEQ:
24123 	case BPF_JNE:
24124 	case BPF_JLT:
24125 	case BPF_JLE:
24126 	case BPF_JGT:
24127 	case BPF_JGE:
24128 	case BPF_JSGT:
24129 	case BPF_JSGE:
24130 	case BPF_JSLT:
24131 	case BPF_JSLE:
24132 	case BPF_JCOND:
24133 	case BPF_JSET:
24134 		return true;
24135 	}
24136 
24137 	return false;
24138 }
24139 
24140 static int insn_successors(struct bpf_prog *prog, u32 idx, u32 succ[2])
24141 {
24142 	struct bpf_insn *insn = &prog->insnsi[idx];
24143 	int i = 0, insn_sz;
24144 	u32 dst;
24145 
24146 	insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
24147 	if (can_fallthrough(insn) && idx + 1 < prog->len)
24148 		succ[i++] = idx + insn_sz;
24149 
24150 	if (can_jump(insn)) {
24151 		dst = idx + jmp_offset(insn) + 1;
24152 		if (i == 0 || succ[0] != dst)
24153 			succ[i++] = dst;
24154 	}
24155 
24156 	return i;
24157 }
24158 
24159 /* Each field is a register bitmask */
24160 struct insn_live_regs {
24161 	u16 use;	/* registers read by instruction */
24162 	u16 def;	/* registers written by instruction */
24163 	u16 in;		/* registers that may be alive before instruction */
24164 	u16 out;	/* registers that may be alive after instruction */
24165 };
24166 
24167 /* Bitmask with 1s for all caller saved registers */
24168 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
24169 
24170 /* Compute info->{use,def} fields for the instruction */
24171 static void compute_insn_live_regs(struct bpf_verifier_env *env,
24172 				   struct bpf_insn *insn,
24173 				   struct insn_live_regs *info)
24174 {
24175 	struct call_summary cs;
24176 	u8 class = BPF_CLASS(insn->code);
24177 	u8 code = BPF_OP(insn->code);
24178 	u8 mode = BPF_MODE(insn->code);
24179 	u16 src = BIT(insn->src_reg);
24180 	u16 dst = BIT(insn->dst_reg);
24181 	u16 r0  = BIT(0);
24182 	u16 def = 0;
24183 	u16 use = 0xffff;
24184 
24185 	switch (class) {
24186 	case BPF_LD:
24187 		switch (mode) {
24188 		case BPF_IMM:
24189 			if (BPF_SIZE(insn->code) == BPF_DW) {
24190 				def = dst;
24191 				use = 0;
24192 			}
24193 			break;
24194 		case BPF_LD | BPF_ABS:
24195 		case BPF_LD | BPF_IND:
24196 			/* stick with defaults */
24197 			break;
24198 		}
24199 		break;
24200 	case BPF_LDX:
24201 		switch (mode) {
24202 		case BPF_MEM:
24203 		case BPF_MEMSX:
24204 			def = dst;
24205 			use = src;
24206 			break;
24207 		}
24208 		break;
24209 	case BPF_ST:
24210 		switch (mode) {
24211 		case BPF_MEM:
24212 			def = 0;
24213 			use = dst;
24214 			break;
24215 		}
24216 		break;
24217 	case BPF_STX:
24218 		switch (mode) {
24219 		case BPF_MEM:
24220 			def = 0;
24221 			use = dst | src;
24222 			break;
24223 		case BPF_ATOMIC:
24224 			switch (insn->imm) {
24225 			case BPF_CMPXCHG:
24226 				use = r0 | dst | src;
24227 				def = r0;
24228 				break;
24229 			case BPF_LOAD_ACQ:
24230 				def = dst;
24231 				use = src;
24232 				break;
24233 			case BPF_STORE_REL:
24234 				def = 0;
24235 				use = dst | src;
24236 				break;
24237 			default:
24238 				use = dst | src;
24239 				if (insn->imm & BPF_FETCH)
24240 					def = src;
24241 				else
24242 					def = 0;
24243 			}
24244 			break;
24245 		}
24246 		break;
24247 	case BPF_ALU:
24248 	case BPF_ALU64:
24249 		switch (code) {
24250 		case BPF_END:
24251 			use = dst;
24252 			def = dst;
24253 			break;
24254 		case BPF_MOV:
24255 			def = dst;
24256 			if (BPF_SRC(insn->code) == BPF_K)
24257 				use = 0;
24258 			else
24259 				use = src;
24260 			break;
24261 		default:
24262 			def = dst;
24263 			if (BPF_SRC(insn->code) == BPF_K)
24264 				use = dst;
24265 			else
24266 				use = dst | src;
24267 		}
24268 		break;
24269 	case BPF_JMP:
24270 	case BPF_JMP32:
24271 		switch (code) {
24272 		case BPF_JA:
24273 		case BPF_JCOND:
24274 			def = 0;
24275 			use = 0;
24276 			break;
24277 		case BPF_EXIT:
24278 			def = 0;
24279 			use = r0;
24280 			break;
24281 		case BPF_CALL:
24282 			def = ALL_CALLER_SAVED_REGS;
24283 			use = def & ~BIT(BPF_REG_0);
24284 			if (get_call_summary(env, insn, &cs))
24285 				use = GENMASK(cs.num_params, 1);
24286 			break;
24287 		default:
24288 			def = 0;
24289 			if (BPF_SRC(insn->code) == BPF_K)
24290 				use = dst;
24291 			else
24292 				use = dst | src;
24293 		}
24294 		break;
24295 	}
24296 
24297 	info->def = def;
24298 	info->use = use;
24299 }
24300 
24301 /* Compute may-live registers after each instruction in the program.
24302  * The register is live after the instruction I if it is read by some
24303  * instruction S following I during program execution and is not
24304  * overwritten between I and S.
24305  *
24306  * Store result in env->insn_aux_data[i].live_regs.
24307  */
24308 static int compute_live_registers(struct bpf_verifier_env *env)
24309 {
24310 	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
24311 	struct bpf_insn *insns = env->prog->insnsi;
24312 	struct insn_live_regs *state;
24313 	int insn_cnt = env->prog->len;
24314 	int err = 0, i, j;
24315 	bool changed;
24316 
24317 	/* Use the following algorithm:
24318 	 * - define the following:
24319 	 *   - I.use : a set of all registers read by instruction I;
24320 	 *   - I.def : a set of all registers written by instruction I;
24321 	 *   - I.in  : a set of all registers that may be alive before I execution;
24322 	 *   - I.out : a set of all registers that may be alive after I execution;
24323 	 *   - insn_successors(I): a set of instructions S that might immediately
24324 	 *                         follow I for some program execution;
24325 	 * - associate separate empty sets 'I.in' and 'I.out' with each instruction;
24326 	 * - visit each instruction in a postorder and update
24327 	 *   state[i].in, state[i].out as follows:
24328 	 *
24329 	 *       state[i].out = U [state[s].in for S in insn_successors(i)]
24330 	 *       state[i].in  = (state[i].out / state[i].def) U state[i].use
24331 	 *
24332 	 *   (where U stands for set union, / stands for set difference)
24333 	 * - repeat the computation while {in,out} fields changes for
24334 	 *   any instruction.
24335 	 */
24336 	state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL_ACCOUNT);
24337 	if (!state) {
24338 		err = -ENOMEM;
24339 		goto out;
24340 	}
24341 
24342 	for (i = 0; i < insn_cnt; ++i)
24343 		compute_insn_live_regs(env, &insns[i], &state[i]);
24344 
24345 	changed = true;
24346 	while (changed) {
24347 		changed = false;
24348 		for (i = 0; i < env->cfg.cur_postorder; ++i) {
24349 			int insn_idx = env->cfg.insn_postorder[i];
24350 			struct insn_live_regs *live = &state[insn_idx];
24351 			int succ_num;
24352 			u32 succ[2];
24353 			u16 new_out = 0;
24354 			u16 new_in = 0;
24355 
24356 			succ_num = insn_successors(env->prog, insn_idx, succ);
24357 			for (int s = 0; s < succ_num; ++s)
24358 				new_out |= state[succ[s]].in;
24359 			new_in = (new_out & ~live->def) | live->use;
24360 			if (new_out != live->out || new_in != live->in) {
24361 				live->in = new_in;
24362 				live->out = new_out;
24363 				changed = true;
24364 			}
24365 		}
24366 	}
24367 
24368 	for (i = 0; i < insn_cnt; ++i)
24369 		insn_aux[i].live_regs_before = state[i].in;
24370 
24371 	if (env->log.level & BPF_LOG_LEVEL2) {
24372 		verbose(env, "Live regs before insn:\n");
24373 		for (i = 0; i < insn_cnt; ++i) {
24374 			if (env->insn_aux_data[i].scc)
24375 				verbose(env, "%3d ", env->insn_aux_data[i].scc);
24376 			else
24377 				verbose(env, "    ");
24378 			verbose(env, "%3d: ", i);
24379 			for (j = BPF_REG_0; j < BPF_REG_10; ++j)
24380 				if (insn_aux[i].live_regs_before & BIT(j))
24381 					verbose(env, "%d", j);
24382 				else
24383 					verbose(env, ".");
24384 			verbose(env, " ");
24385 			verbose_insn(env, &insns[i]);
24386 			if (bpf_is_ldimm64(&insns[i]))
24387 				i++;
24388 		}
24389 	}
24390 
24391 out:
24392 	kvfree(state);
24393 	kvfree(env->cfg.insn_postorder);
24394 	env->cfg.insn_postorder = NULL;
24395 	env->cfg.cur_postorder = 0;
24396 	return err;
24397 }
24398 
24399 /*
24400  * Compute strongly connected components (SCCs) on the CFG.
24401  * Assign an SCC number to each instruction, recorded in env->insn_aux[*].scc.
24402  * If instruction is a sole member of its SCC and there are no self edges,
24403  * assign it SCC number of zero.
24404  * Uses a non-recursive adaptation of Tarjan's algorithm for SCC computation.
24405  */
24406 static int compute_scc(struct bpf_verifier_env *env)
24407 {
24408 	const u32 NOT_ON_STACK = U32_MAX;
24409 
24410 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
24411 	const u32 insn_cnt = env->prog->len;
24412 	int stack_sz, dfs_sz, err = 0;
24413 	u32 *stack, *pre, *low, *dfs;
24414 	u32 succ_cnt, i, j, t, w;
24415 	u32 next_preorder_num;
24416 	u32 next_scc_id;
24417 	bool assign_scc;
24418 	u32 succ[2];
24419 
24420 	next_preorder_num = 1;
24421 	next_scc_id = 1;
24422 	/*
24423 	 * - 'stack' accumulates vertices in DFS order, see invariant comment below;
24424 	 * - 'pre[t] == p' => preorder number of vertex 't' is 'p';
24425 	 * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n';
24426 	 * - 'dfs' DFS traversal stack, used to emulate explicit recursion.
24427 	 */
24428 	stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24429 	pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24430 	low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24431 	dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT);
24432 	if (!stack || !pre || !low || !dfs) {
24433 		err = -ENOMEM;
24434 		goto exit;
24435 	}
24436 	/*
24437 	 * References:
24438 	 * [1] R. Tarjan "Depth-First Search and Linear Graph Algorithms"
24439 	 * [2] D. J. Pearce "A Space-Efficient Algorithm for Finding Strongly Connected Components"
24440 	 *
24441 	 * The algorithm maintains the following invariant:
24442 	 * - suppose there is a path 'u' ~> 'v', such that 'pre[v] < pre[u]';
24443 	 * - then, vertex 'u' remains on stack while vertex 'v' is on stack.
24444 	 *
24445 	 * Consequently:
24446 	 * - If 'low[v] < pre[v]', there is a path from 'v' to some vertex 'u',
24447 	 *   such that 'pre[u] == low[v]'; vertex 'u' is currently on the stack,
24448 	 *   and thus there is an SCC (loop) containing both 'u' and 'v'.
24449 	 * - If 'low[v] == pre[v]', loops containing 'v' have been explored,
24450 	 *   and 'v' can be considered the root of some SCC.
24451 	 *
24452 	 * Here is a pseudo-code for an explicitly recursive version of the algorithm:
24453 	 *
24454 	 *    NOT_ON_STACK = insn_cnt + 1
24455 	 *    pre = [0] * insn_cnt
24456 	 *    low = [0] * insn_cnt
24457 	 *    scc = [0] * insn_cnt
24458 	 *    stack = []
24459 	 *
24460 	 *    next_preorder_num = 1
24461 	 *    next_scc_id = 1
24462 	 *
24463 	 *    def recur(w):
24464 	 *        nonlocal next_preorder_num
24465 	 *        nonlocal next_scc_id
24466 	 *
24467 	 *        pre[w] = next_preorder_num
24468 	 *        low[w] = next_preorder_num
24469 	 *        next_preorder_num += 1
24470 	 *        stack.append(w)
24471 	 *        for s in successors(w):
24472 	 *            # Note: for classic algorithm the block below should look as:
24473 	 *            #
24474 	 *            # if pre[s] == 0:
24475 	 *            #     recur(s)
24476 	 *            #	    low[w] = min(low[w], low[s])
24477 	 *            # elif low[s] != NOT_ON_STACK:
24478 	 *            #     low[w] = min(low[w], pre[s])
24479 	 *            #
24480 	 *            # But replacing both 'min' instructions with 'low[w] = min(low[w], low[s])'
24481 	 *            # does not break the invariant and makes itartive version of the algorithm
24482 	 *            # simpler. See 'Algorithm #3' from [2].
24483 	 *
24484 	 *            # 's' not yet visited
24485 	 *            if pre[s] == 0:
24486 	 *                recur(s)
24487 	 *            # if 's' is on stack, pick lowest reachable preorder number from it;
24488 	 *            # if 's' is not on stack 'low[s] == NOT_ON_STACK > low[w]',
24489 	 *            # so 'min' would be a noop.
24490 	 *            low[w] = min(low[w], low[s])
24491 	 *
24492 	 *        if low[w] == pre[w]:
24493 	 *            # 'w' is the root of an SCC, pop all vertices
24494 	 *            # below 'w' on stack and assign same SCC to them.
24495 	 *            while True:
24496 	 *                t = stack.pop()
24497 	 *                low[t] = NOT_ON_STACK
24498 	 *                scc[t] = next_scc_id
24499 	 *                if t == w:
24500 	 *                    break
24501 	 *            next_scc_id += 1
24502 	 *
24503 	 *    for i in range(0, insn_cnt):
24504 	 *        if pre[i] == 0:
24505 	 *            recur(i)
24506 	 *
24507 	 * Below implementation replaces explicit recursion with array 'dfs'.
24508 	 */
24509 	for (i = 0; i < insn_cnt; i++) {
24510 		if (pre[i])
24511 			continue;
24512 		stack_sz = 0;
24513 		dfs_sz = 1;
24514 		dfs[0] = i;
24515 dfs_continue:
24516 		while (dfs_sz) {
24517 			w = dfs[dfs_sz - 1];
24518 			if (pre[w] == 0) {
24519 				low[w] = next_preorder_num;
24520 				pre[w] = next_preorder_num;
24521 				next_preorder_num++;
24522 				stack[stack_sz++] = w;
24523 			}
24524 			/* Visit 'w' successors */
24525 			succ_cnt = insn_successors(env->prog, w, succ);
24526 			for (j = 0; j < succ_cnt; ++j) {
24527 				if (pre[succ[j]]) {
24528 					low[w] = min(low[w], low[succ[j]]);
24529 				} else {
24530 					dfs[dfs_sz++] = succ[j];
24531 					goto dfs_continue;
24532 				}
24533 			}
24534 			/*
24535 			 * Preserve the invariant: if some vertex above in the stack
24536 			 * is reachable from 'w', keep 'w' on the stack.
24537 			 */
24538 			if (low[w] < pre[w]) {
24539 				dfs_sz--;
24540 				goto dfs_continue;
24541 			}
24542 			/*
24543 			 * Assign SCC number only if component has two or more elements,
24544 			 * or if component has a self reference.
24545 			 */
24546 			assign_scc = stack[stack_sz - 1] != w;
24547 			for (j = 0; j < succ_cnt; ++j) {
24548 				if (succ[j] == w) {
24549 					assign_scc = true;
24550 					break;
24551 				}
24552 			}
24553 			/* Pop component elements from stack */
24554 			do {
24555 				t = stack[--stack_sz];
24556 				low[t] = NOT_ON_STACK;
24557 				if (assign_scc)
24558 					aux[t].scc = next_scc_id;
24559 			} while (t != w);
24560 			if (assign_scc)
24561 				next_scc_id++;
24562 			dfs_sz--;
24563 		}
24564 	}
24565 	env->scc_info = kvcalloc(next_scc_id, sizeof(*env->scc_info), GFP_KERNEL_ACCOUNT);
24566 	if (!env->scc_info) {
24567 		err = -ENOMEM;
24568 		goto exit;
24569 	}
24570 	env->scc_cnt = next_scc_id;
24571 exit:
24572 	kvfree(stack);
24573 	kvfree(pre);
24574 	kvfree(low);
24575 	kvfree(dfs);
24576 	return err;
24577 }
24578 
24579 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
24580 {
24581 	u64 start_time = ktime_get_ns();
24582 	struct bpf_verifier_env *env;
24583 	int i, len, ret = -EINVAL, err;
24584 	u32 log_true_size;
24585 	bool is_priv;
24586 
24587 	BTF_TYPE_EMIT(enum bpf_features);
24588 
24589 	/* no program is valid */
24590 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
24591 		return -EINVAL;
24592 
24593 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
24594 	 * allocate/free it every time bpf_check() is called
24595 	 */
24596 	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL_ACCOUNT);
24597 	if (!env)
24598 		return -ENOMEM;
24599 
24600 	env->bt.env = env;
24601 
24602 	len = (*prog)->len;
24603 	env->insn_aux_data =
24604 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
24605 	ret = -ENOMEM;
24606 	if (!env->insn_aux_data)
24607 		goto err_free_env;
24608 	for (i = 0; i < len; i++)
24609 		env->insn_aux_data[i].orig_idx = i;
24610 	env->prog = *prog;
24611 	env->ops = bpf_verifier_ops[env->prog->type];
24612 
24613 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
24614 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
24615 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
24616 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
24617 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
24618 
24619 	bpf_get_btf_vmlinux();
24620 
24621 	/* grab the mutex to protect few globals used by verifier */
24622 	if (!is_priv)
24623 		mutex_lock(&bpf_verifier_lock);
24624 
24625 	/* user could have requested verbose verifier output
24626 	 * and supplied buffer to store the verification trace
24627 	 */
24628 	ret = bpf_vlog_init(&env->log, attr->log_level,
24629 			    (char __user *) (unsigned long) attr->log_buf,
24630 			    attr->log_size);
24631 	if (ret)
24632 		goto err_unlock;
24633 
24634 	ret = process_fd_array(env, attr, uattr);
24635 	if (ret)
24636 		goto skip_full_check;
24637 
24638 	mark_verifier_state_clean(env);
24639 
24640 	if (IS_ERR(btf_vmlinux)) {
24641 		/* Either gcc or pahole or kernel are broken. */
24642 		verbose(env, "in-kernel BTF is malformed\n");
24643 		ret = PTR_ERR(btf_vmlinux);
24644 		goto skip_full_check;
24645 	}
24646 
24647 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
24648 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
24649 		env->strict_alignment = true;
24650 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
24651 		env->strict_alignment = false;
24652 
24653 	if (is_priv)
24654 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
24655 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
24656 
24657 	env->explored_states = kvcalloc(state_htab_size(env),
24658 				       sizeof(struct list_head),
24659 				       GFP_KERNEL_ACCOUNT);
24660 	ret = -ENOMEM;
24661 	if (!env->explored_states)
24662 		goto skip_full_check;
24663 
24664 	for (i = 0; i < state_htab_size(env); i++)
24665 		INIT_LIST_HEAD(&env->explored_states[i]);
24666 	INIT_LIST_HEAD(&env->free_list);
24667 
24668 	ret = check_btf_info_early(env, attr, uattr);
24669 	if (ret < 0)
24670 		goto skip_full_check;
24671 
24672 	ret = add_subprog_and_kfunc(env);
24673 	if (ret < 0)
24674 		goto skip_full_check;
24675 
24676 	ret = check_subprogs(env);
24677 	if (ret < 0)
24678 		goto skip_full_check;
24679 
24680 	ret = check_btf_info(env, attr, uattr);
24681 	if (ret < 0)
24682 		goto skip_full_check;
24683 
24684 	ret = resolve_pseudo_ldimm64(env);
24685 	if (ret < 0)
24686 		goto skip_full_check;
24687 
24688 	if (bpf_prog_is_offloaded(env->prog->aux)) {
24689 		ret = bpf_prog_offload_verifier_prep(env->prog);
24690 		if (ret)
24691 			goto skip_full_check;
24692 	}
24693 
24694 	ret = check_cfg(env);
24695 	if (ret < 0)
24696 		goto skip_full_check;
24697 
24698 	ret = check_attach_btf_id(env);
24699 	if (ret)
24700 		goto skip_full_check;
24701 
24702 	ret = compute_scc(env);
24703 	if (ret < 0)
24704 		goto skip_full_check;
24705 
24706 	ret = compute_live_registers(env);
24707 	if (ret < 0)
24708 		goto skip_full_check;
24709 
24710 	ret = mark_fastcall_patterns(env);
24711 	if (ret < 0)
24712 		goto skip_full_check;
24713 
24714 	ret = do_check_main(env);
24715 	ret = ret ?: do_check_subprogs(env);
24716 
24717 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
24718 		ret = bpf_prog_offload_finalize(env);
24719 
24720 skip_full_check:
24721 	kvfree(env->explored_states);
24722 
24723 	/* might decrease stack depth, keep it before passes that
24724 	 * allocate additional slots.
24725 	 */
24726 	if (ret == 0)
24727 		ret = remove_fastcall_spills_fills(env);
24728 
24729 	if (ret == 0)
24730 		ret = check_max_stack_depth(env);
24731 
24732 	/* instruction rewrites happen after this point */
24733 	if (ret == 0)
24734 		ret = optimize_bpf_loop(env);
24735 
24736 	if (is_priv) {
24737 		if (ret == 0)
24738 			opt_hard_wire_dead_code_branches(env);
24739 		if (ret == 0)
24740 			ret = opt_remove_dead_code(env);
24741 		if (ret == 0)
24742 			ret = opt_remove_nops(env);
24743 	} else {
24744 		if (ret == 0)
24745 			sanitize_dead_code(env);
24746 	}
24747 
24748 	if (ret == 0)
24749 		/* program is valid, convert *(u32*)(ctx + off) accesses */
24750 		ret = convert_ctx_accesses(env);
24751 
24752 	if (ret == 0)
24753 		ret = do_misc_fixups(env);
24754 
24755 	/* do 32-bit optimization after insn patching has done so those patched
24756 	 * insns could be handled correctly.
24757 	 */
24758 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
24759 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
24760 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
24761 								     : false;
24762 	}
24763 
24764 	if (ret == 0)
24765 		ret = fixup_call_args(env);
24766 
24767 	env->verification_time = ktime_get_ns() - start_time;
24768 	print_verification_stats(env);
24769 	env->prog->aux->verified_insns = env->insn_processed;
24770 
24771 	/* preserve original error even if log finalization is successful */
24772 	err = bpf_vlog_finalize(&env->log, &log_true_size);
24773 	if (err)
24774 		ret = err;
24775 
24776 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
24777 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
24778 				  &log_true_size, sizeof(log_true_size))) {
24779 		ret = -EFAULT;
24780 		goto err_release_maps;
24781 	}
24782 
24783 	if (ret)
24784 		goto err_release_maps;
24785 
24786 	if (env->used_map_cnt) {
24787 		/* if program passed verifier, update used_maps in bpf_prog_info */
24788 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
24789 							  sizeof(env->used_maps[0]),
24790 							  GFP_KERNEL_ACCOUNT);
24791 
24792 		if (!env->prog->aux->used_maps) {
24793 			ret = -ENOMEM;
24794 			goto err_release_maps;
24795 		}
24796 
24797 		memcpy(env->prog->aux->used_maps, env->used_maps,
24798 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
24799 		env->prog->aux->used_map_cnt = env->used_map_cnt;
24800 	}
24801 	if (env->used_btf_cnt) {
24802 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
24803 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
24804 							  sizeof(env->used_btfs[0]),
24805 							  GFP_KERNEL_ACCOUNT);
24806 		if (!env->prog->aux->used_btfs) {
24807 			ret = -ENOMEM;
24808 			goto err_release_maps;
24809 		}
24810 
24811 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
24812 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
24813 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
24814 	}
24815 	if (env->used_map_cnt || env->used_btf_cnt) {
24816 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
24817 		 * bpf_ld_imm64 instructions
24818 		 */
24819 		convert_pseudo_ld_imm64(env);
24820 	}
24821 
24822 	adjust_btf_func(env);
24823 
24824 err_release_maps:
24825 	if (!env->prog->aux->used_maps)
24826 		/* if we didn't copy map pointers into bpf_prog_info, release
24827 		 * them now. Otherwise free_used_maps() will release them.
24828 		 */
24829 		release_maps(env);
24830 	if (!env->prog->aux->used_btfs)
24831 		release_btfs(env);
24832 
24833 	/* extension progs temporarily inherit the attach_type of their targets
24834 	   for verification purposes, so set it back to zero before returning
24835 	 */
24836 	if (env->prog->type == BPF_PROG_TYPE_EXT)
24837 		env->prog->expected_attach_type = 0;
24838 
24839 	*prog = env->prog;
24840 
24841 	module_put(env->attach_btf_mod);
24842 err_unlock:
24843 	if (!is_priv)
24844 		mutex_unlock(&bpf_verifier_lock);
24845 	vfree(env->insn_aux_data);
24846 err_free_env:
24847 	kvfree(env->cfg.insn_postorder);
24848 	kvfree(env->scc_info);
24849 	kvfree(env);
24850 	return ret;
24851 }
24852