xref: /linux/kernel/bpf/verifier.c (revision 47c9214dcbea9043ac20441a285c7bb5486b8b2d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <linux/bpf_mem_alloc.h>
30 #include <net/xdp.h>
31 #include <linux/trace_events.h>
32 #include <linux/kallsyms.h>
33 
34 #include "disasm.h"
35 
36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
38 	[_id] = & _name ## _verifier_ops,
39 #define BPF_MAP_TYPE(_id, _ops)
40 #define BPF_LINK_TYPE(_id, _name)
41 #include <linux/bpf_types.h>
42 #undef BPF_PROG_TYPE
43 #undef BPF_MAP_TYPE
44 #undef BPF_LINK_TYPE
45 };
46 
47 enum bpf_features {
48 	BPF_FEAT_RDONLY_CAST_TO_VOID = 0,
49 	BPF_FEAT_STREAMS	     = 1,
50 	__MAX_BPF_FEAT,
51 };
52 
53 struct bpf_mem_alloc bpf_global_percpu_ma;
54 static bool bpf_global_percpu_ma_set;
55 
56 /* bpf_check() is a static code analyzer that walks eBPF program
57  * instruction by instruction and updates register/stack state.
58  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
59  *
60  * The first pass is depth-first-search to check that the program is a DAG.
61  * It rejects the following programs:
62  * - larger than BPF_MAXINSNS insns
63  * - if loop is present (detected via back-edge)
64  * - unreachable insns exist (shouldn't be a forest. program = one function)
65  * - out of bounds or malformed jumps
66  * The second pass is all possible path descent from the 1st insn.
67  * Since it's analyzing all paths through the program, the length of the
68  * analysis is limited to 64k insn, which may be hit even if total number of
69  * insn is less then 4K, but there are too many branches that change stack/regs.
70  * Number of 'branches to be analyzed' is limited to 1k
71  *
72  * On entry to each instruction, each register has a type, and the instruction
73  * changes the types of the registers depending on instruction semantics.
74  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
75  * copied to R1.
76  *
77  * All registers are 64-bit.
78  * R0 - return register
79  * R1-R5 argument passing registers
80  * R6-R9 callee saved registers
81  * R10 - frame pointer read-only
82  *
83  * At the start of BPF program the register R1 contains a pointer to bpf_context
84  * and has type PTR_TO_CTX.
85  *
86  * Verifier tracks arithmetic operations on pointers in case:
87  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
88  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
89  * 1st insn copies R10 (which has FRAME_PTR) type into R1
90  * and 2nd arithmetic instruction is pattern matched to recognize
91  * that it wants to construct a pointer to some element within stack.
92  * So after 2nd insn, the register R1 has type PTR_TO_STACK
93  * (and -20 constant is saved for further stack bounds checking).
94  * Meaning that this reg is a pointer to stack plus known immediate constant.
95  *
96  * Most of the time the registers have SCALAR_VALUE type, which
97  * means the register has some value, but it's not a valid pointer.
98  * (like pointer plus pointer becomes SCALAR_VALUE type)
99  *
100  * When verifier sees load or store instructions the type of base register
101  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
102  * four pointer types recognized by check_mem_access() function.
103  *
104  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
105  * and the range of [ptr, ptr + map's value_size) is accessible.
106  *
107  * registers used to pass values to function calls are checked against
108  * function argument constraints.
109  *
110  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
111  * It means that the register type passed to this function must be
112  * PTR_TO_STACK and it will be used inside the function as
113  * 'pointer to map element key'
114  *
115  * For example the argument constraints for bpf_map_lookup_elem():
116  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
117  *   .arg1_type = ARG_CONST_MAP_PTR,
118  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
119  *
120  * ret_type says that this function returns 'pointer to map elem value or null'
121  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
122  * 2nd argument should be a pointer to stack, which will be used inside
123  * the helper function as a pointer to map element key.
124  *
125  * On the kernel side the helper function looks like:
126  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
127  * {
128  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
129  *    void *key = (void *) (unsigned long) r2;
130  *    void *value;
131  *
132  *    here kernel can access 'key' and 'map' pointers safely, knowing that
133  *    [key, key + map->key_size) bytes are valid and were initialized on
134  *    the stack of eBPF program.
135  * }
136  *
137  * Corresponding eBPF program may look like:
138  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
139  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
140  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
141  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
142  * here verifier looks at prototype of map_lookup_elem() and sees:
143  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
144  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
145  *
146  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
147  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
148  * and were initialized prior to this call.
149  * If it's ok, then verifier allows this BPF_CALL insn and looks at
150  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
151  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
152  * returns either pointer to map value or NULL.
153  *
154  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
155  * insn, the register holding that pointer in the true branch changes state to
156  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
157  * branch. See check_cond_jmp_op().
158  *
159  * After the call R0 is set to return type of the function and registers R1-R5
160  * are set to NOT_INIT to indicate that they are no longer readable.
161  *
162  * The following reference types represent a potential reference to a kernel
163  * resource which, after first being allocated, must be checked and freed by
164  * the BPF program:
165  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
166  *
167  * When the verifier sees a helper call return a reference type, it allocates a
168  * pointer id for the reference and stores it in the current function state.
169  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
170  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
171  * passes through a NULL-check conditional. For the branch wherein the state is
172  * changed to CONST_IMM, the verifier releases the reference.
173  *
174  * For each helper function that allocates a reference, such as
175  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
176  * bpf_sk_release(). When a reference type passes into the release function,
177  * the verifier also releases the reference. If any unchecked or unreleased
178  * reference remains at the end of the program, the verifier rejects it.
179  */
180 
181 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
182 struct bpf_verifier_stack_elem {
183 	/* verifier state is 'st'
184 	 * before processing instruction 'insn_idx'
185 	 * and after processing instruction 'prev_insn_idx'
186 	 */
187 	struct bpf_verifier_state st;
188 	int insn_idx;
189 	int prev_insn_idx;
190 	struct bpf_verifier_stack_elem *next;
191 	/* length of verifier log at the time this state was pushed on stack */
192 	u32 log_pos;
193 };
194 
195 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
196 #define BPF_COMPLEXITY_LIMIT_STATES	64
197 
198 #define BPF_MAP_KEY_POISON	(1ULL << 63)
199 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
200 
201 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
202 
203 #define BPF_PRIV_STACK_MIN_SIZE		64
204 
205 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx);
206 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id);
207 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
208 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
209 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
210 static int ref_set_non_owning(struct bpf_verifier_env *env,
211 			      struct bpf_reg_state *reg);
212 static bool is_trusted_reg(const struct bpf_reg_state *reg);
213 
214 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
215 {
216 	return aux->map_ptr_state.poison;
217 }
218 
219 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
220 {
221 	return aux->map_ptr_state.unpriv;
222 }
223 
224 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
225 			      struct bpf_map *map,
226 			      bool unpriv, bool poison)
227 {
228 	unpriv |= bpf_map_ptr_unpriv(aux);
229 	aux->map_ptr_state.unpriv = unpriv;
230 	aux->map_ptr_state.poison = poison;
231 	aux->map_ptr_state.map_ptr = map;
232 }
233 
234 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
235 {
236 	return aux->map_key_state & BPF_MAP_KEY_POISON;
237 }
238 
239 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
240 {
241 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
242 }
243 
244 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
245 {
246 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
247 }
248 
249 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
250 {
251 	bool poisoned = bpf_map_key_poisoned(aux);
252 
253 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
254 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
255 }
256 
257 static bool bpf_helper_call(const struct bpf_insn *insn)
258 {
259 	return insn->code == (BPF_JMP | BPF_CALL) &&
260 	       insn->src_reg == 0;
261 }
262 
263 static bool bpf_pseudo_call(const struct bpf_insn *insn)
264 {
265 	return insn->code == (BPF_JMP | BPF_CALL) &&
266 	       insn->src_reg == BPF_PSEUDO_CALL;
267 }
268 
269 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
270 {
271 	return insn->code == (BPF_JMP | BPF_CALL) &&
272 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
273 }
274 
275 struct bpf_call_arg_meta {
276 	struct bpf_map *map_ptr;
277 	bool raw_mode;
278 	bool pkt_access;
279 	u8 release_regno;
280 	int regno;
281 	int access_size;
282 	int mem_size;
283 	u64 msize_max_value;
284 	int ref_obj_id;
285 	int dynptr_id;
286 	int map_uid;
287 	int func_id;
288 	struct btf *btf;
289 	u32 btf_id;
290 	struct btf *ret_btf;
291 	u32 ret_btf_id;
292 	u32 subprogno;
293 	struct btf_field *kptr_field;
294 	s64 const_map_key;
295 };
296 
297 struct bpf_kfunc_call_arg_meta {
298 	/* In parameters */
299 	struct btf *btf;
300 	u32 func_id;
301 	u32 kfunc_flags;
302 	const struct btf_type *func_proto;
303 	const char *func_name;
304 	/* Out parameters */
305 	u32 ref_obj_id;
306 	u8 release_regno;
307 	bool r0_rdonly;
308 	u32 ret_btf_id;
309 	u64 r0_size;
310 	u32 subprogno;
311 	struct {
312 		u64 value;
313 		bool found;
314 	} arg_constant;
315 
316 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
317 	 * generally to pass info about user-defined local kptr types to later
318 	 * verification logic
319 	 *   bpf_obj_drop/bpf_percpu_obj_drop
320 	 *     Record the local kptr type to be drop'd
321 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
322 	 *     Record the local kptr type to be refcount_incr'd and use
323 	 *     arg_owning_ref to determine whether refcount_acquire should be
324 	 *     fallible
325 	 */
326 	struct btf *arg_btf;
327 	u32 arg_btf_id;
328 	bool arg_owning_ref;
329 	bool arg_prog;
330 
331 	struct {
332 		struct btf_field *field;
333 	} arg_list_head;
334 	struct {
335 		struct btf_field *field;
336 	} arg_rbtree_root;
337 	struct {
338 		enum bpf_dynptr_type type;
339 		u32 id;
340 		u32 ref_obj_id;
341 	} initialized_dynptr;
342 	struct {
343 		u8 spi;
344 		u8 frameno;
345 	} iter;
346 	struct {
347 		struct bpf_map *ptr;
348 		int uid;
349 	} map;
350 	u64 mem_size;
351 };
352 
353 struct btf *btf_vmlinux;
354 
355 static const char *btf_type_name(const struct btf *btf, u32 id)
356 {
357 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
358 }
359 
360 static DEFINE_MUTEX(bpf_verifier_lock);
361 static DEFINE_MUTEX(bpf_percpu_ma_lock);
362 
363 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
364 {
365 	struct bpf_verifier_env *env = private_data;
366 	va_list args;
367 
368 	if (!bpf_verifier_log_needed(&env->log))
369 		return;
370 
371 	va_start(args, fmt);
372 	bpf_verifier_vlog(&env->log, fmt, args);
373 	va_end(args);
374 }
375 
376 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
377 				   struct bpf_reg_state *reg,
378 				   struct bpf_retval_range range, const char *ctx,
379 				   const char *reg_name)
380 {
381 	bool unknown = true;
382 
383 	verbose(env, "%s the register %s has", ctx, reg_name);
384 	if (reg->smin_value > S64_MIN) {
385 		verbose(env, " smin=%lld", reg->smin_value);
386 		unknown = false;
387 	}
388 	if (reg->smax_value < S64_MAX) {
389 		verbose(env, " smax=%lld", reg->smax_value);
390 		unknown = false;
391 	}
392 	if (unknown)
393 		verbose(env, " unknown scalar value");
394 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
395 }
396 
397 static bool reg_not_null(const struct bpf_reg_state *reg)
398 {
399 	enum bpf_reg_type type;
400 
401 	type = reg->type;
402 	if (type_may_be_null(type))
403 		return false;
404 
405 	type = base_type(type);
406 	return type == PTR_TO_SOCKET ||
407 		type == PTR_TO_TCP_SOCK ||
408 		type == PTR_TO_MAP_VALUE ||
409 		type == PTR_TO_MAP_KEY ||
410 		type == PTR_TO_SOCK_COMMON ||
411 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
412 		(type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) ||
413 		type == CONST_PTR_TO_MAP;
414 }
415 
416 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
417 {
418 	struct btf_record *rec = NULL;
419 	struct btf_struct_meta *meta;
420 
421 	if (reg->type == PTR_TO_MAP_VALUE) {
422 		rec = reg->map_ptr->record;
423 	} else if (type_is_ptr_alloc_obj(reg->type)) {
424 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
425 		if (meta)
426 			rec = meta->record;
427 	}
428 	return rec;
429 }
430 
431 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
432 {
433 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
434 
435 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
436 }
437 
438 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
439 {
440 	struct bpf_func_info *info;
441 
442 	if (!env->prog->aux->func_info)
443 		return "";
444 
445 	info = &env->prog->aux->func_info[subprog];
446 	return btf_type_name(env->prog->aux->btf, info->type_id);
447 }
448 
449 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
450 {
451 	struct bpf_subprog_info *info = subprog_info(env, subprog);
452 
453 	info->is_cb = true;
454 	info->is_async_cb = true;
455 	info->is_exception_cb = true;
456 }
457 
458 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
459 {
460 	return subprog_info(env, subprog)->is_exception_cb;
461 }
462 
463 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
464 {
465 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
466 }
467 
468 static bool type_is_rdonly_mem(u32 type)
469 {
470 	return type & MEM_RDONLY;
471 }
472 
473 static bool is_acquire_function(enum bpf_func_id func_id,
474 				const struct bpf_map *map)
475 {
476 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
477 
478 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
479 	    func_id == BPF_FUNC_sk_lookup_udp ||
480 	    func_id == BPF_FUNC_skc_lookup_tcp ||
481 	    func_id == BPF_FUNC_ringbuf_reserve ||
482 	    func_id == BPF_FUNC_kptr_xchg)
483 		return true;
484 
485 	if (func_id == BPF_FUNC_map_lookup_elem &&
486 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
487 	     map_type == BPF_MAP_TYPE_SOCKHASH))
488 		return true;
489 
490 	return false;
491 }
492 
493 static bool is_ptr_cast_function(enum bpf_func_id func_id)
494 {
495 	return func_id == BPF_FUNC_tcp_sock ||
496 		func_id == BPF_FUNC_sk_fullsock ||
497 		func_id == BPF_FUNC_skc_to_tcp_sock ||
498 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
499 		func_id == BPF_FUNC_skc_to_udp6_sock ||
500 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
501 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
502 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
503 }
504 
505 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
506 {
507 	return func_id == BPF_FUNC_dynptr_data;
508 }
509 
510 static bool is_sync_callback_calling_kfunc(u32 btf_id);
511 static bool is_async_callback_calling_kfunc(u32 btf_id);
512 static bool is_callback_calling_kfunc(u32 btf_id);
513 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
514 
515 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
516 static bool is_task_work_add_kfunc(u32 func_id);
517 
518 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
519 {
520 	return func_id == BPF_FUNC_for_each_map_elem ||
521 	       func_id == BPF_FUNC_find_vma ||
522 	       func_id == BPF_FUNC_loop ||
523 	       func_id == BPF_FUNC_user_ringbuf_drain;
524 }
525 
526 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
527 {
528 	return func_id == BPF_FUNC_timer_set_callback;
529 }
530 
531 static bool is_callback_calling_function(enum bpf_func_id func_id)
532 {
533 	return is_sync_callback_calling_function(func_id) ||
534 	       is_async_callback_calling_function(func_id);
535 }
536 
537 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
538 {
539 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
540 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
541 }
542 
543 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
544 {
545 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
546 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
547 }
548 
549 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn)
550 {
551 	/* bpf_timer callbacks are never sleepable. */
552 	if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback)
553 		return false;
554 
555 	/* bpf_wq and bpf_task_work callbacks are always sleepable. */
556 	if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
557 	    (is_bpf_wq_set_callback_impl_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm)))
558 		return true;
559 
560 	verifier_bug(env, "unhandled async callback in is_async_cb_sleepable");
561 	return false;
562 }
563 
564 static bool is_may_goto_insn(struct bpf_insn *insn)
565 {
566 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
567 }
568 
569 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
570 {
571 	return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
572 }
573 
574 static bool is_storage_get_function(enum bpf_func_id func_id)
575 {
576 	return func_id == BPF_FUNC_sk_storage_get ||
577 	       func_id == BPF_FUNC_inode_storage_get ||
578 	       func_id == BPF_FUNC_task_storage_get ||
579 	       func_id == BPF_FUNC_cgrp_storage_get;
580 }
581 
582 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
583 					const struct bpf_map *map)
584 {
585 	int ref_obj_uses = 0;
586 
587 	if (is_ptr_cast_function(func_id))
588 		ref_obj_uses++;
589 	if (is_acquire_function(func_id, map))
590 		ref_obj_uses++;
591 	if (is_dynptr_ref_function(func_id))
592 		ref_obj_uses++;
593 
594 	return ref_obj_uses > 1;
595 }
596 
597 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
598 {
599 	return BPF_CLASS(insn->code) == BPF_STX &&
600 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
601 	       insn->imm == BPF_CMPXCHG;
602 }
603 
604 static bool is_atomic_load_insn(const struct bpf_insn *insn)
605 {
606 	return BPF_CLASS(insn->code) == BPF_STX &&
607 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
608 	       insn->imm == BPF_LOAD_ACQ;
609 }
610 
611 static int __get_spi(s32 off)
612 {
613 	return (-off - 1) / BPF_REG_SIZE;
614 }
615 
616 static struct bpf_func_state *func(struct bpf_verifier_env *env,
617 				   const struct bpf_reg_state *reg)
618 {
619 	struct bpf_verifier_state *cur = env->cur_state;
620 
621 	return cur->frame[reg->frameno];
622 }
623 
624 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
625 {
626        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
627 
628        /* We need to check that slots between [spi - nr_slots + 1, spi] are
629 	* within [0, allocated_stack).
630 	*
631 	* Please note that the spi grows downwards. For example, a dynptr
632 	* takes the size of two stack slots; the first slot will be at
633 	* spi and the second slot will be at spi - 1.
634 	*/
635        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
636 }
637 
638 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
639 			          const char *obj_kind, int nr_slots)
640 {
641 	int off, spi;
642 
643 	if (!tnum_is_const(reg->var_off)) {
644 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
645 		return -EINVAL;
646 	}
647 
648 	off = reg->off + reg->var_off.value;
649 	if (off % BPF_REG_SIZE) {
650 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
651 		return -EINVAL;
652 	}
653 
654 	spi = __get_spi(off);
655 	if (spi + 1 < nr_slots) {
656 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
657 		return -EINVAL;
658 	}
659 
660 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
661 		return -ERANGE;
662 	return spi;
663 }
664 
665 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
666 {
667 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
668 }
669 
670 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
671 {
672 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
673 }
674 
675 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
676 {
677 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
678 }
679 
680 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
681 {
682 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
683 	case DYNPTR_TYPE_LOCAL:
684 		return BPF_DYNPTR_TYPE_LOCAL;
685 	case DYNPTR_TYPE_RINGBUF:
686 		return BPF_DYNPTR_TYPE_RINGBUF;
687 	case DYNPTR_TYPE_SKB:
688 		return BPF_DYNPTR_TYPE_SKB;
689 	case DYNPTR_TYPE_XDP:
690 		return BPF_DYNPTR_TYPE_XDP;
691 	case DYNPTR_TYPE_SKB_META:
692 		return BPF_DYNPTR_TYPE_SKB_META;
693 	case DYNPTR_TYPE_FILE:
694 		return BPF_DYNPTR_TYPE_FILE;
695 	default:
696 		return BPF_DYNPTR_TYPE_INVALID;
697 	}
698 }
699 
700 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
701 {
702 	switch (type) {
703 	case BPF_DYNPTR_TYPE_LOCAL:
704 		return DYNPTR_TYPE_LOCAL;
705 	case BPF_DYNPTR_TYPE_RINGBUF:
706 		return DYNPTR_TYPE_RINGBUF;
707 	case BPF_DYNPTR_TYPE_SKB:
708 		return DYNPTR_TYPE_SKB;
709 	case BPF_DYNPTR_TYPE_XDP:
710 		return DYNPTR_TYPE_XDP;
711 	case BPF_DYNPTR_TYPE_SKB_META:
712 		return DYNPTR_TYPE_SKB_META;
713 	case BPF_DYNPTR_TYPE_FILE:
714 		return DYNPTR_TYPE_FILE;
715 	default:
716 		return 0;
717 	}
718 }
719 
720 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
721 {
722 	return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE;
723 }
724 
725 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
726 			      enum bpf_dynptr_type type,
727 			      bool first_slot, int dynptr_id);
728 
729 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
730 				struct bpf_reg_state *reg);
731 
732 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
733 				   struct bpf_reg_state *sreg1,
734 				   struct bpf_reg_state *sreg2,
735 				   enum bpf_dynptr_type type)
736 {
737 	int id = ++env->id_gen;
738 
739 	__mark_dynptr_reg(sreg1, type, true, id);
740 	__mark_dynptr_reg(sreg2, type, false, id);
741 }
742 
743 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
744 			       struct bpf_reg_state *reg,
745 			       enum bpf_dynptr_type type)
746 {
747 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
748 }
749 
750 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
751 				        struct bpf_func_state *state, int spi);
752 
753 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
754 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
755 {
756 	struct bpf_func_state *state = func(env, reg);
757 	enum bpf_dynptr_type type;
758 	int spi, i, err;
759 
760 	spi = dynptr_get_spi(env, reg);
761 	if (spi < 0)
762 		return spi;
763 
764 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
765 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
766 	 * to ensure that for the following example:
767 	 *	[d1][d1][d2][d2]
768 	 * spi    3   2   1   0
769 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
770 	 * case they do belong to same dynptr, second call won't see slot_type
771 	 * as STACK_DYNPTR and will simply skip destruction.
772 	 */
773 	err = destroy_if_dynptr_stack_slot(env, state, spi);
774 	if (err)
775 		return err;
776 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
777 	if (err)
778 		return err;
779 
780 	for (i = 0; i < BPF_REG_SIZE; i++) {
781 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
782 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
783 	}
784 
785 	type = arg_to_dynptr_type(arg_type);
786 	if (type == BPF_DYNPTR_TYPE_INVALID)
787 		return -EINVAL;
788 
789 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
790 			       &state->stack[spi - 1].spilled_ptr, type);
791 
792 	if (dynptr_type_refcounted(type)) {
793 		/* The id is used to track proper releasing */
794 		int id;
795 
796 		if (clone_ref_obj_id)
797 			id = clone_ref_obj_id;
798 		else
799 			id = acquire_reference(env, insn_idx);
800 
801 		if (id < 0)
802 			return id;
803 
804 		state->stack[spi].spilled_ptr.ref_obj_id = id;
805 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
806 	}
807 
808 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
809 
810 	return 0;
811 }
812 
813 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
814 {
815 	int i;
816 
817 	for (i = 0; i < BPF_REG_SIZE; i++) {
818 		state->stack[spi].slot_type[i] = STACK_INVALID;
819 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
820 	}
821 
822 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
823 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
824 
825 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
826 }
827 
828 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
829 {
830 	struct bpf_func_state *state = func(env, reg);
831 	int spi, ref_obj_id, i;
832 
833 	/*
834 	 * This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
835 	 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
836 	 * is safe to do directly.
837 	 */
838 	if (reg->type == CONST_PTR_TO_DYNPTR) {
839 		verifier_bug(env, "CONST_PTR_TO_DYNPTR cannot be released");
840 		return -EFAULT;
841 	}
842 	spi = dynptr_get_spi(env, reg);
843 	if (spi < 0)
844 		return spi;
845 
846 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
847 		invalidate_dynptr(env, state, spi);
848 		return 0;
849 	}
850 
851 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
852 
853 	/* If the dynptr has a ref_obj_id, then we need to invalidate
854 	 * two things:
855 	 *
856 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
857 	 * 2) Any slices derived from this dynptr.
858 	 */
859 
860 	/* Invalidate any slices associated with this dynptr */
861 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
862 
863 	/* Invalidate any dynptr clones */
864 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
865 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
866 			continue;
867 
868 		/* it should always be the case that if the ref obj id
869 		 * matches then the stack slot also belongs to a
870 		 * dynptr
871 		 */
872 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
873 			verifier_bug(env, "misconfigured ref_obj_id");
874 			return -EFAULT;
875 		}
876 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
877 			invalidate_dynptr(env, state, i);
878 	}
879 
880 	return 0;
881 }
882 
883 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
884 			       struct bpf_reg_state *reg);
885 
886 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
887 {
888 	if (!env->allow_ptr_leaks)
889 		__mark_reg_not_init(env, reg);
890 	else
891 		__mark_reg_unknown(env, reg);
892 }
893 
894 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
895 				        struct bpf_func_state *state, int spi)
896 {
897 	struct bpf_func_state *fstate;
898 	struct bpf_reg_state *dreg;
899 	int i, dynptr_id;
900 
901 	/* We always ensure that STACK_DYNPTR is never set partially,
902 	 * hence just checking for slot_type[0] is enough. This is
903 	 * different for STACK_SPILL, where it may be only set for
904 	 * 1 byte, so code has to use is_spilled_reg.
905 	 */
906 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
907 		return 0;
908 
909 	/* Reposition spi to first slot */
910 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
911 		spi = spi + 1;
912 
913 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
914 		verbose(env, "cannot overwrite referenced dynptr\n");
915 		return -EINVAL;
916 	}
917 
918 	mark_stack_slot_scratched(env, spi);
919 	mark_stack_slot_scratched(env, spi - 1);
920 
921 	/* Writing partially to one dynptr stack slot destroys both. */
922 	for (i = 0; i < BPF_REG_SIZE; i++) {
923 		state->stack[spi].slot_type[i] = STACK_INVALID;
924 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
925 	}
926 
927 	dynptr_id = state->stack[spi].spilled_ptr.id;
928 	/* Invalidate any slices associated with this dynptr */
929 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
930 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
931 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
932 			continue;
933 		if (dreg->dynptr_id == dynptr_id)
934 			mark_reg_invalid(env, dreg);
935 	}));
936 
937 	/* Do not release reference state, we are destroying dynptr on stack,
938 	 * not using some helper to release it. Just reset register.
939 	 */
940 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
941 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
942 
943 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
944 
945 	return 0;
946 }
947 
948 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
949 {
950 	int spi;
951 
952 	if (reg->type == CONST_PTR_TO_DYNPTR)
953 		return false;
954 
955 	spi = dynptr_get_spi(env, reg);
956 
957 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
958 	 * error because this just means the stack state hasn't been updated yet.
959 	 * We will do check_mem_access to check and update stack bounds later.
960 	 */
961 	if (spi < 0 && spi != -ERANGE)
962 		return false;
963 
964 	/* We don't need to check if the stack slots are marked by previous
965 	 * dynptr initializations because we allow overwriting existing unreferenced
966 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
967 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
968 	 * touching are completely destructed before we reinitialize them for a new
969 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
970 	 * instead of delaying it until the end where the user will get "Unreleased
971 	 * reference" error.
972 	 */
973 	return true;
974 }
975 
976 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
977 {
978 	struct bpf_func_state *state = func(env, reg);
979 	int i, spi;
980 
981 	/* This already represents first slot of initialized bpf_dynptr.
982 	 *
983 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
984 	 * check_func_arg_reg_off's logic, so we don't need to check its
985 	 * offset and alignment.
986 	 */
987 	if (reg->type == CONST_PTR_TO_DYNPTR)
988 		return true;
989 
990 	spi = dynptr_get_spi(env, reg);
991 	if (spi < 0)
992 		return false;
993 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
994 		return false;
995 
996 	for (i = 0; i < BPF_REG_SIZE; i++) {
997 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
998 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
999 			return false;
1000 	}
1001 
1002 	return true;
1003 }
1004 
1005 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1006 				    enum bpf_arg_type arg_type)
1007 {
1008 	struct bpf_func_state *state = func(env, reg);
1009 	enum bpf_dynptr_type dynptr_type;
1010 	int spi;
1011 
1012 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1013 	if (arg_type == ARG_PTR_TO_DYNPTR)
1014 		return true;
1015 
1016 	dynptr_type = arg_to_dynptr_type(arg_type);
1017 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1018 		return reg->dynptr.type == dynptr_type;
1019 	} else {
1020 		spi = dynptr_get_spi(env, reg);
1021 		if (spi < 0)
1022 			return false;
1023 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1024 	}
1025 }
1026 
1027 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1028 
1029 static bool in_rcu_cs(struct bpf_verifier_env *env);
1030 
1031 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1032 
1033 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1034 				 struct bpf_kfunc_call_arg_meta *meta,
1035 				 struct bpf_reg_state *reg, int insn_idx,
1036 				 struct btf *btf, u32 btf_id, int nr_slots)
1037 {
1038 	struct bpf_func_state *state = func(env, reg);
1039 	int spi, i, j, id;
1040 
1041 	spi = iter_get_spi(env, reg, nr_slots);
1042 	if (spi < 0)
1043 		return spi;
1044 
1045 	id = acquire_reference(env, insn_idx);
1046 	if (id < 0)
1047 		return id;
1048 
1049 	for (i = 0; i < nr_slots; i++) {
1050 		struct bpf_stack_state *slot = &state->stack[spi - i];
1051 		struct bpf_reg_state *st = &slot->spilled_ptr;
1052 
1053 		__mark_reg_known_zero(st);
1054 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1055 		if (is_kfunc_rcu_protected(meta)) {
1056 			if (in_rcu_cs(env))
1057 				st->type |= MEM_RCU;
1058 			else
1059 				st->type |= PTR_UNTRUSTED;
1060 		}
1061 		st->ref_obj_id = i == 0 ? id : 0;
1062 		st->iter.btf = btf;
1063 		st->iter.btf_id = btf_id;
1064 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1065 		st->iter.depth = 0;
1066 
1067 		for (j = 0; j < BPF_REG_SIZE; j++)
1068 			slot->slot_type[j] = STACK_ITER;
1069 
1070 		bpf_mark_stack_write(env, state->frameno, BIT(spi - i));
1071 		mark_stack_slot_scratched(env, spi - i);
1072 	}
1073 
1074 	return 0;
1075 }
1076 
1077 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1078 				   struct bpf_reg_state *reg, int nr_slots)
1079 {
1080 	struct bpf_func_state *state = func(env, reg);
1081 	int spi, i, j;
1082 
1083 	spi = iter_get_spi(env, reg, nr_slots);
1084 	if (spi < 0)
1085 		return spi;
1086 
1087 	for (i = 0; i < nr_slots; i++) {
1088 		struct bpf_stack_state *slot = &state->stack[spi - i];
1089 		struct bpf_reg_state *st = &slot->spilled_ptr;
1090 
1091 		if (i == 0)
1092 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1093 
1094 		__mark_reg_not_init(env, st);
1095 
1096 		for (j = 0; j < BPF_REG_SIZE; j++)
1097 			slot->slot_type[j] = STACK_INVALID;
1098 
1099 		bpf_mark_stack_write(env, state->frameno, BIT(spi - i));
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 	bpf_mark_stack_write(env, reg->frameno, BIT(spi));
1190 	__mark_reg_known_zero(st);
1191 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
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 	bpf_mark_stack_write(env, reg->frameno, BIT(spi));
1246 
1247 	for (i = 0; i < BPF_REG_SIZE; i++)
1248 		slot->slot_type[i] = STACK_INVALID;
1249 
1250 	mark_stack_slot_scratched(env, spi);
1251 	return 0;
1252 }
1253 
1254 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1255 {
1256 	struct bpf_func_state *state = func(env, reg);
1257 	struct bpf_stack_state *slot;
1258 	int spi, i;
1259 
1260 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1261 	 * will do check_mem_access to check and update stack bounds later, so
1262 	 * return true for that case.
1263 	 */
1264 	spi = irq_flag_get_spi(env, reg);
1265 	if (spi == -ERANGE)
1266 		return true;
1267 	if (spi < 0)
1268 		return false;
1269 
1270 	slot = &state->stack[spi];
1271 
1272 	for (i = 0; i < BPF_REG_SIZE; i++)
1273 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1274 			return false;
1275 	return true;
1276 }
1277 
1278 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1279 {
1280 	struct bpf_func_state *state = func(env, reg);
1281 	struct bpf_stack_state *slot;
1282 	struct bpf_reg_state *st;
1283 	int spi, i;
1284 
1285 	spi = irq_flag_get_spi(env, reg);
1286 	if (spi < 0)
1287 		return -EINVAL;
1288 
1289 	slot = &state->stack[spi];
1290 	st = &slot->spilled_ptr;
1291 
1292 	if (!st->ref_obj_id)
1293 		return -EINVAL;
1294 
1295 	for (i = 0; i < BPF_REG_SIZE; i++)
1296 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1297 			return -EINVAL;
1298 	return 0;
1299 }
1300 
1301 /* Check if given stack slot is "special":
1302  *   - spilled register state (STACK_SPILL);
1303  *   - dynptr state (STACK_DYNPTR);
1304  *   - iter state (STACK_ITER).
1305  *   - irq flag state (STACK_IRQ_FLAG)
1306  */
1307 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1308 {
1309 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1310 
1311 	switch (type) {
1312 	case STACK_SPILL:
1313 	case STACK_DYNPTR:
1314 	case STACK_ITER:
1315 	case STACK_IRQ_FLAG:
1316 		return true;
1317 	case STACK_INVALID:
1318 	case STACK_MISC:
1319 	case STACK_ZERO:
1320 		return false;
1321 	default:
1322 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1323 		return true;
1324 	}
1325 }
1326 
1327 /* The reg state of a pointer or a bounded scalar was saved when
1328  * it was spilled to the stack.
1329  */
1330 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1331 {
1332 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1333 }
1334 
1335 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1336 {
1337 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1338 	       stack->spilled_ptr.type == SCALAR_VALUE;
1339 }
1340 
1341 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1342 {
1343 	return stack->slot_type[0] == STACK_SPILL &&
1344 	       stack->spilled_ptr.type == SCALAR_VALUE;
1345 }
1346 
1347 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1348  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1349  * more precise STACK_ZERO.
1350  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1351  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1352  * unnecessary as both are considered equivalent when loading data and pruning,
1353  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1354  * slots.
1355  */
1356 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1357 {
1358 	if (*stype == STACK_ZERO)
1359 		return;
1360 	if (*stype == STACK_INVALID)
1361 		return;
1362 	*stype = STACK_MISC;
1363 }
1364 
1365 static void scrub_spilled_slot(u8 *stype)
1366 {
1367 	if (*stype != STACK_INVALID)
1368 		*stype = STACK_MISC;
1369 }
1370 
1371 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1372  * small to hold src. This is different from krealloc since we don't want to preserve
1373  * the contents of dst.
1374  *
1375  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1376  * not be allocated.
1377  */
1378 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1379 {
1380 	size_t alloc_bytes;
1381 	void *orig = dst;
1382 	size_t bytes;
1383 
1384 	if (ZERO_OR_NULL_PTR(src))
1385 		goto out;
1386 
1387 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1388 		return NULL;
1389 
1390 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1391 	dst = krealloc(orig, alloc_bytes, flags);
1392 	if (!dst) {
1393 		kfree(orig);
1394 		return NULL;
1395 	}
1396 
1397 	memcpy(dst, src, bytes);
1398 out:
1399 	return dst ? dst : ZERO_SIZE_PTR;
1400 }
1401 
1402 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1403  * small to hold new_n items. new items are zeroed out if the array grows.
1404  *
1405  * Contrary to krealloc_array, does not free arr if new_n is zero.
1406  */
1407 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1408 {
1409 	size_t alloc_size;
1410 	void *new_arr;
1411 
1412 	if (!new_n || old_n == new_n)
1413 		goto out;
1414 
1415 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1416 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1417 	if (!new_arr) {
1418 		kfree(arr);
1419 		return NULL;
1420 	}
1421 	arr = new_arr;
1422 
1423 	if (new_n > old_n)
1424 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1425 
1426 out:
1427 	return arr ? arr : ZERO_SIZE_PTR;
1428 }
1429 
1430 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1431 {
1432 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1433 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1434 	if (!dst->refs)
1435 		return -ENOMEM;
1436 
1437 	dst->acquired_refs = src->acquired_refs;
1438 	dst->active_locks = src->active_locks;
1439 	dst->active_preempt_locks = src->active_preempt_locks;
1440 	dst->active_rcu_locks = src->active_rcu_locks;
1441 	dst->active_irq_id = src->active_irq_id;
1442 	dst->active_lock_id = src->active_lock_id;
1443 	dst->active_lock_ptr = src->active_lock_ptr;
1444 	return 0;
1445 }
1446 
1447 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1448 {
1449 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1450 
1451 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1452 				GFP_KERNEL_ACCOUNT);
1453 	if (!dst->stack)
1454 		return -ENOMEM;
1455 
1456 	dst->allocated_stack = src->allocated_stack;
1457 	return 0;
1458 }
1459 
1460 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1461 {
1462 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1463 				    sizeof(struct bpf_reference_state));
1464 	if (!state->refs)
1465 		return -ENOMEM;
1466 
1467 	state->acquired_refs = n;
1468 	return 0;
1469 }
1470 
1471 /* Possibly update state->allocated_stack to be at least size bytes. Also
1472  * possibly update the function's high-water mark in its bpf_subprog_info.
1473  */
1474 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1475 {
1476 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1477 
1478 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1479 	size = round_up(size, BPF_REG_SIZE);
1480 	n = size / BPF_REG_SIZE;
1481 
1482 	if (old_n >= n)
1483 		return 0;
1484 
1485 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1486 	if (!state->stack)
1487 		return -ENOMEM;
1488 
1489 	state->allocated_stack = size;
1490 
1491 	/* update known max for given subprogram */
1492 	if (env->subprog_info[state->subprogno].stack_depth < size)
1493 		env->subprog_info[state->subprogno].stack_depth = size;
1494 
1495 	return 0;
1496 }
1497 
1498 /* Acquire a pointer id from the env and update the state->refs to include
1499  * this new pointer reference.
1500  * On success, returns a valid pointer id to associate with the register
1501  * On failure, returns a negative errno.
1502  */
1503 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1504 {
1505 	struct bpf_verifier_state *state = env->cur_state;
1506 	int new_ofs = state->acquired_refs;
1507 	int err;
1508 
1509 	err = resize_reference_state(state, state->acquired_refs + 1);
1510 	if (err)
1511 		return NULL;
1512 	state->refs[new_ofs].insn_idx = insn_idx;
1513 
1514 	return &state->refs[new_ofs];
1515 }
1516 
1517 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx)
1518 {
1519 	struct bpf_reference_state *s;
1520 
1521 	s = acquire_reference_state(env, insn_idx);
1522 	if (!s)
1523 		return -ENOMEM;
1524 	s->type = REF_TYPE_PTR;
1525 	s->id = ++env->id_gen;
1526 	return s->id;
1527 }
1528 
1529 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1530 			      int id, void *ptr)
1531 {
1532 	struct bpf_verifier_state *state = env->cur_state;
1533 	struct bpf_reference_state *s;
1534 
1535 	s = acquire_reference_state(env, insn_idx);
1536 	if (!s)
1537 		return -ENOMEM;
1538 	s->type = type;
1539 	s->id = id;
1540 	s->ptr = ptr;
1541 
1542 	state->active_locks++;
1543 	state->active_lock_id = id;
1544 	state->active_lock_ptr = ptr;
1545 	return 0;
1546 }
1547 
1548 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1549 {
1550 	struct bpf_verifier_state *state = env->cur_state;
1551 	struct bpf_reference_state *s;
1552 
1553 	s = acquire_reference_state(env, insn_idx);
1554 	if (!s)
1555 		return -ENOMEM;
1556 	s->type = REF_TYPE_IRQ;
1557 	s->id = ++env->id_gen;
1558 
1559 	state->active_irq_id = s->id;
1560 	return s->id;
1561 }
1562 
1563 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1564 {
1565 	int last_idx;
1566 	size_t rem;
1567 
1568 	/* IRQ state requires the relative ordering of elements remaining the
1569 	 * same, since it relies on the refs array to behave as a stack, so that
1570 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1571 	 * the array instead of swapping the final element into the deleted idx.
1572 	 */
1573 	last_idx = state->acquired_refs - 1;
1574 	rem = state->acquired_refs - idx - 1;
1575 	if (last_idx && idx != last_idx)
1576 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1577 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1578 	state->acquired_refs--;
1579 	return;
1580 }
1581 
1582 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id)
1583 {
1584 	int i;
1585 
1586 	for (i = 0; i < state->acquired_refs; i++)
1587 		if (state->refs[i].id == ptr_id)
1588 			return true;
1589 
1590 	return false;
1591 }
1592 
1593 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
1594 {
1595 	void *prev_ptr = NULL;
1596 	u32 prev_id = 0;
1597 	int i;
1598 
1599 	for (i = 0; i < state->acquired_refs; i++) {
1600 		if (state->refs[i].type == type && state->refs[i].id == id &&
1601 		    state->refs[i].ptr == ptr) {
1602 			release_reference_state(state, i);
1603 			state->active_locks--;
1604 			/* Reassign active lock (id, ptr). */
1605 			state->active_lock_id = prev_id;
1606 			state->active_lock_ptr = prev_ptr;
1607 			return 0;
1608 		}
1609 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1610 			prev_id = state->refs[i].id;
1611 			prev_ptr = state->refs[i].ptr;
1612 		}
1613 	}
1614 	return -EINVAL;
1615 }
1616 
1617 static int release_irq_state(struct bpf_verifier_state *state, int id)
1618 {
1619 	u32 prev_id = 0;
1620 	int i;
1621 
1622 	if (id != state->active_irq_id)
1623 		return -EACCES;
1624 
1625 	for (i = 0; i < state->acquired_refs; i++) {
1626 		if (state->refs[i].type != REF_TYPE_IRQ)
1627 			continue;
1628 		if (state->refs[i].id == id) {
1629 			release_reference_state(state, i);
1630 			state->active_irq_id = prev_id;
1631 			return 0;
1632 		} else {
1633 			prev_id = state->refs[i].id;
1634 		}
1635 	}
1636 	return -EINVAL;
1637 }
1638 
1639 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1640 						   int id, void *ptr)
1641 {
1642 	int i;
1643 
1644 	for (i = 0; i < state->acquired_refs; i++) {
1645 		struct bpf_reference_state *s = &state->refs[i];
1646 
1647 		if (!(s->type & type))
1648 			continue;
1649 
1650 		if (s->id == id && s->ptr == ptr)
1651 			return s;
1652 	}
1653 	return NULL;
1654 }
1655 
1656 static void update_peak_states(struct bpf_verifier_env *env)
1657 {
1658 	u32 cur_states;
1659 
1660 	cur_states = env->explored_states_size + env->free_list_size + env->num_backedges;
1661 	env->peak_states = max(env->peak_states, cur_states);
1662 }
1663 
1664 static void free_func_state(struct bpf_func_state *state)
1665 {
1666 	if (!state)
1667 		return;
1668 	kfree(state->stack);
1669 	kfree(state);
1670 }
1671 
1672 static void clear_jmp_history(struct bpf_verifier_state *state)
1673 {
1674 	kfree(state->jmp_history);
1675 	state->jmp_history = NULL;
1676 	state->jmp_history_cnt = 0;
1677 }
1678 
1679 static void free_verifier_state(struct bpf_verifier_state *state,
1680 				bool free_self)
1681 {
1682 	int i;
1683 
1684 	for (i = 0; i <= state->curframe; i++) {
1685 		free_func_state(state->frame[i]);
1686 		state->frame[i] = NULL;
1687 	}
1688 	kfree(state->refs);
1689 	clear_jmp_history(state);
1690 	if (free_self)
1691 		kfree(state);
1692 }
1693 
1694 /* struct bpf_verifier_state->parent refers to states
1695  * that are in either of env->{expored_states,free_list}.
1696  * In both cases the state is contained in struct bpf_verifier_state_list.
1697  */
1698 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st)
1699 {
1700 	if (st->parent)
1701 		return container_of(st->parent, struct bpf_verifier_state_list, state);
1702 	return NULL;
1703 }
1704 
1705 static bool incomplete_read_marks(struct bpf_verifier_env *env,
1706 				  struct bpf_verifier_state *st);
1707 
1708 /* A state can be freed if it is no longer referenced:
1709  * - is in the env->free_list;
1710  * - has no children states;
1711  */
1712 static void maybe_free_verifier_state(struct bpf_verifier_env *env,
1713 				      struct bpf_verifier_state_list *sl)
1714 {
1715 	if (!sl->in_free_list
1716 	    || sl->state.branches != 0
1717 	    || incomplete_read_marks(env, &sl->state))
1718 		return;
1719 	list_del(&sl->node);
1720 	free_verifier_state(&sl->state, false);
1721 	kfree(sl);
1722 	env->free_list_size--;
1723 }
1724 
1725 /* copy verifier state from src to dst growing dst stack space
1726  * when necessary to accommodate larger src stack
1727  */
1728 static int copy_func_state(struct bpf_func_state *dst,
1729 			   const struct bpf_func_state *src)
1730 {
1731 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1732 	return copy_stack_state(dst, src);
1733 }
1734 
1735 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1736 			       const struct bpf_verifier_state *src)
1737 {
1738 	struct bpf_func_state *dst;
1739 	int i, err;
1740 
1741 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1742 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1743 					  GFP_KERNEL_ACCOUNT);
1744 	if (!dst_state->jmp_history)
1745 		return -ENOMEM;
1746 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1747 
1748 	/* if dst has more stack frames then src frame, free them, this is also
1749 	 * necessary in case of exceptional exits using bpf_throw.
1750 	 */
1751 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1752 		free_func_state(dst_state->frame[i]);
1753 		dst_state->frame[i] = NULL;
1754 	}
1755 	err = copy_reference_state(dst_state, src);
1756 	if (err)
1757 		return err;
1758 	dst_state->speculative = src->speculative;
1759 	dst_state->in_sleepable = src->in_sleepable;
1760 	dst_state->cleaned = src->cleaned;
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 		/*
1954 		 * If path traversal stops inside an SCC, corresponding bpf_scc_visit
1955 		 * must exist for non-speculative paths. For non-speculative paths
1956 		 * traversal stops when:
1957 		 * a. Verification error is found, maybe_exit_scc() is not called.
1958 		 * b. Top level BPF_EXIT is reached. Top level BPF_EXIT is not a member
1959 		 *    of any SCC.
1960 		 * c. A checkpoint is reached and matched. Checkpoints are created by
1961 		 *    is_state_visited(), which calls maybe_enter_scc(), which allocates
1962 		 *    bpf_scc_visit instances for checkpoints within SCCs.
1963 		 * (c) is the only case that can reach this point.
1964 		 */
1965 		if (!st->speculative) {
1966 			verifier_bug(env, "scc exit: no visit info for call chain %s",
1967 				     format_callchain(env, callchain));
1968 			return -EFAULT;
1969 		}
1970 		return 0;
1971 	}
1972 	if (visit->entry_state != st)
1973 		return 0;
1974 	if (env->log.level & BPF_LOG_LEVEL2)
1975 		verbose(env, "SCC exit %s\n", format_callchain(env, callchain));
1976 	visit->entry_state = NULL;
1977 	env->num_backedges -= visit->num_backedges;
1978 	visit->num_backedges = 0;
1979 	update_peak_states(env);
1980 	return propagate_backedges(env, visit);
1981 }
1982 
1983 /* Lookup an bpf_scc_visit instance corresponding to @st callchain
1984  * and add @backedge to visit->backedges. @st callchain must exist.
1985  */
1986 static int add_scc_backedge(struct bpf_verifier_env *env,
1987 			    struct bpf_verifier_state *st,
1988 			    struct bpf_scc_backedge *backedge)
1989 {
1990 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1991 	struct bpf_scc_visit *visit;
1992 
1993 	if (!compute_scc_callchain(env, st, callchain)) {
1994 		verifier_bug(env, "add backedge: no SCC in verification path, insn_idx %d",
1995 			     st->insn_idx);
1996 		return -EFAULT;
1997 	}
1998 	visit = scc_visit_lookup(env, callchain);
1999 	if (!visit) {
2000 		verifier_bug(env, "add backedge: no visit info for call chain %s",
2001 			     format_callchain(env, callchain));
2002 		return -EFAULT;
2003 	}
2004 	if (env->log.level & BPF_LOG_LEVEL2)
2005 		verbose(env, "SCC backedge %s\n", format_callchain(env, callchain));
2006 	backedge->next = visit->backedges;
2007 	visit->backedges = backedge;
2008 	visit->num_backedges++;
2009 	env->num_backedges++;
2010 	update_peak_states(env);
2011 	return 0;
2012 }
2013 
2014 /* bpf_reg_state->live marks for registers in a state @st are incomplete,
2015  * if state @st is in some SCC and not all execution paths starting at this
2016  * SCC are fully explored.
2017  */
2018 static bool incomplete_read_marks(struct bpf_verifier_env *env,
2019 				  struct bpf_verifier_state *st)
2020 {
2021 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
2022 	struct bpf_scc_visit *visit;
2023 
2024 	if (!compute_scc_callchain(env, st, callchain))
2025 		return false;
2026 	visit = scc_visit_lookup(env, callchain);
2027 	if (!visit)
2028 		return false;
2029 	return !!visit->backedges;
2030 }
2031 
2032 static void free_backedges(struct bpf_scc_visit *visit)
2033 {
2034 	struct bpf_scc_backedge *backedge, *next;
2035 
2036 	for (backedge = visit->backedges; backedge; backedge = next) {
2037 		free_verifier_state(&backedge->state, false);
2038 		next = backedge->next;
2039 		kfree(backedge);
2040 	}
2041 	visit->backedges = NULL;
2042 }
2043 
2044 static int update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2045 {
2046 	struct bpf_verifier_state_list *sl = NULL, *parent_sl;
2047 	struct bpf_verifier_state *parent;
2048 	int err;
2049 
2050 	while (st) {
2051 		u32 br = --st->branches;
2052 
2053 		/* verifier_bug_if(br > 1, ...) technically makes sense here,
2054 		 * but see comment in push_stack(), hence:
2055 		 */
2056 		verifier_bug_if((int)br < 0, env, "%s:branches_to_explore=%d", __func__, br);
2057 		if (br)
2058 			break;
2059 		err = maybe_exit_scc(env, st);
2060 		if (err)
2061 			return err;
2062 		parent = st->parent;
2063 		parent_sl = state_parent_as_list(st);
2064 		if (sl)
2065 			maybe_free_verifier_state(env, sl);
2066 		st = parent;
2067 		sl = parent_sl;
2068 	}
2069 	return 0;
2070 }
2071 
2072 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2073 		     int *insn_idx, bool pop_log)
2074 {
2075 	struct bpf_verifier_state *cur = env->cur_state;
2076 	struct bpf_verifier_stack_elem *elem, *head = env->head;
2077 	int err;
2078 
2079 	if (env->head == NULL)
2080 		return -ENOENT;
2081 
2082 	if (cur) {
2083 		err = copy_verifier_state(cur, &head->st);
2084 		if (err)
2085 			return err;
2086 	}
2087 	if (pop_log)
2088 		bpf_vlog_reset(&env->log, head->log_pos);
2089 	if (insn_idx)
2090 		*insn_idx = head->insn_idx;
2091 	if (prev_insn_idx)
2092 		*prev_insn_idx = head->prev_insn_idx;
2093 	elem = head->next;
2094 	free_verifier_state(&head->st, false);
2095 	kfree(head);
2096 	env->head = elem;
2097 	env->stack_size--;
2098 	return 0;
2099 }
2100 
2101 static bool error_recoverable_with_nospec(int err)
2102 {
2103 	/* Should only return true for non-fatal errors that are allowed to
2104 	 * occur during speculative verification. For these we can insert a
2105 	 * nospec and the program might still be accepted. Do not include
2106 	 * something like ENOMEM because it is likely to re-occur for the next
2107 	 * architectural path once it has been recovered-from in all speculative
2108 	 * paths.
2109 	 */
2110 	return err == -EPERM || err == -EACCES || err == -EINVAL;
2111 }
2112 
2113 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2114 					     int insn_idx, int prev_insn_idx,
2115 					     bool speculative)
2116 {
2117 	struct bpf_verifier_state *cur = env->cur_state;
2118 	struct bpf_verifier_stack_elem *elem;
2119 	int err;
2120 
2121 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2122 	if (!elem)
2123 		return ERR_PTR(-ENOMEM);
2124 
2125 	elem->insn_idx = insn_idx;
2126 	elem->prev_insn_idx = prev_insn_idx;
2127 	elem->next = env->head;
2128 	elem->log_pos = env->log.end_pos;
2129 	env->head = elem;
2130 	env->stack_size++;
2131 	err = copy_verifier_state(&elem->st, cur);
2132 	if (err)
2133 		return ERR_PTR(-ENOMEM);
2134 	elem->st.speculative |= speculative;
2135 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2136 		verbose(env, "The sequence of %d jumps is too complex.\n",
2137 			env->stack_size);
2138 		return ERR_PTR(-E2BIG);
2139 	}
2140 	if (elem->st.parent) {
2141 		++elem->st.parent->branches;
2142 		/* WARN_ON(branches > 2) technically makes sense here,
2143 		 * but
2144 		 * 1. speculative states will bump 'branches' for non-branch
2145 		 * instructions
2146 		 * 2. is_state_visited() heuristics may decide not to create
2147 		 * a new state for a sequence of branches and all such current
2148 		 * and cloned states will be pointing to a single parent state
2149 		 * which might have large 'branches' count.
2150 		 */
2151 	}
2152 	return &elem->st;
2153 }
2154 
2155 #define CALLER_SAVED_REGS 6
2156 static const int caller_saved[CALLER_SAVED_REGS] = {
2157 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2158 };
2159 
2160 /* This helper doesn't clear reg->id */
2161 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2162 {
2163 	reg->var_off = tnum_const(imm);
2164 	reg->smin_value = (s64)imm;
2165 	reg->smax_value = (s64)imm;
2166 	reg->umin_value = imm;
2167 	reg->umax_value = imm;
2168 
2169 	reg->s32_min_value = (s32)imm;
2170 	reg->s32_max_value = (s32)imm;
2171 	reg->u32_min_value = (u32)imm;
2172 	reg->u32_max_value = (u32)imm;
2173 }
2174 
2175 /* Mark the unknown part of a register (variable offset or scalar value) as
2176  * known to have the value @imm.
2177  */
2178 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2179 {
2180 	/* Clear off and union(map_ptr, range) */
2181 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2182 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2183 	reg->id = 0;
2184 	reg->ref_obj_id = 0;
2185 	___mark_reg_known(reg, imm);
2186 }
2187 
2188 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2189 {
2190 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2191 	reg->s32_min_value = (s32)imm;
2192 	reg->s32_max_value = (s32)imm;
2193 	reg->u32_min_value = (u32)imm;
2194 	reg->u32_max_value = (u32)imm;
2195 }
2196 
2197 /* Mark the 'variable offset' part of a register as zero.  This should be
2198  * used only on registers holding a pointer type.
2199  */
2200 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2201 {
2202 	__mark_reg_known(reg, 0);
2203 }
2204 
2205 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2206 {
2207 	__mark_reg_known(reg, 0);
2208 	reg->type = SCALAR_VALUE;
2209 	/* all scalars are assumed imprecise initially (unless unprivileged,
2210 	 * in which case everything is forced to be precise)
2211 	 */
2212 	reg->precise = !env->bpf_capable;
2213 }
2214 
2215 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2216 				struct bpf_reg_state *regs, u32 regno)
2217 {
2218 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2219 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2220 		/* Something bad happened, let's kill all regs */
2221 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2222 			__mark_reg_not_init(env, regs + regno);
2223 		return;
2224 	}
2225 	__mark_reg_known_zero(regs + regno);
2226 }
2227 
2228 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2229 			      bool first_slot, int dynptr_id)
2230 {
2231 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2232 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2233 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2234 	 */
2235 	__mark_reg_known_zero(reg);
2236 	reg->type = CONST_PTR_TO_DYNPTR;
2237 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2238 	reg->id = dynptr_id;
2239 	reg->dynptr.type = type;
2240 	reg->dynptr.first_slot = first_slot;
2241 }
2242 
2243 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2244 {
2245 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2246 		const struct bpf_map *map = reg->map_ptr;
2247 
2248 		if (map->inner_map_meta) {
2249 			reg->type = CONST_PTR_TO_MAP;
2250 			reg->map_ptr = map->inner_map_meta;
2251 			/* transfer reg's id which is unique for every map_lookup_elem
2252 			 * as UID of the inner map.
2253 			 */
2254 			if (btf_record_has_field(map->inner_map_meta->record,
2255 						 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) {
2256 				reg->map_uid = reg->id;
2257 			}
2258 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2259 			reg->type = PTR_TO_XDP_SOCK;
2260 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2261 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2262 			reg->type = PTR_TO_SOCKET;
2263 		} else {
2264 			reg->type = PTR_TO_MAP_VALUE;
2265 		}
2266 		return;
2267 	}
2268 
2269 	reg->type &= ~PTR_MAYBE_NULL;
2270 }
2271 
2272 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2273 				struct btf_field_graph_root *ds_head)
2274 {
2275 	__mark_reg_known_zero(&regs[regno]);
2276 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2277 	regs[regno].btf = ds_head->btf;
2278 	regs[regno].btf_id = ds_head->value_btf_id;
2279 	regs[regno].off = ds_head->node_offset;
2280 }
2281 
2282 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2283 {
2284 	return type_is_pkt_pointer(reg->type);
2285 }
2286 
2287 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2288 {
2289 	return reg_is_pkt_pointer(reg) ||
2290 	       reg->type == PTR_TO_PACKET_END;
2291 }
2292 
2293 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2294 {
2295 	return base_type(reg->type) == PTR_TO_MEM &&
2296 	       (reg->type &
2297 		(DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META));
2298 }
2299 
2300 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2301 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2302 				    enum bpf_reg_type which)
2303 {
2304 	/* The register can already have a range from prior markings.
2305 	 * This is fine as long as it hasn't been advanced from its
2306 	 * origin.
2307 	 */
2308 	return reg->type == which &&
2309 	       reg->id == 0 &&
2310 	       reg->off == 0 &&
2311 	       tnum_equals_const(reg->var_off, 0);
2312 }
2313 
2314 /* Reset the min/max bounds of a register */
2315 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2316 {
2317 	reg->smin_value = S64_MIN;
2318 	reg->smax_value = S64_MAX;
2319 	reg->umin_value = 0;
2320 	reg->umax_value = U64_MAX;
2321 
2322 	reg->s32_min_value = S32_MIN;
2323 	reg->s32_max_value = S32_MAX;
2324 	reg->u32_min_value = 0;
2325 	reg->u32_max_value = U32_MAX;
2326 }
2327 
2328 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2329 {
2330 	reg->smin_value = S64_MIN;
2331 	reg->smax_value = S64_MAX;
2332 	reg->umin_value = 0;
2333 	reg->umax_value = U64_MAX;
2334 }
2335 
2336 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2337 {
2338 	reg->s32_min_value = S32_MIN;
2339 	reg->s32_max_value = S32_MAX;
2340 	reg->u32_min_value = 0;
2341 	reg->u32_max_value = U32_MAX;
2342 }
2343 
2344 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2345 {
2346 	struct tnum var32_off = tnum_subreg(reg->var_off);
2347 
2348 	/* min signed is max(sign bit) | min(other bits) */
2349 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2350 			var32_off.value | (var32_off.mask & S32_MIN));
2351 	/* max signed is min(sign bit) | max(other bits) */
2352 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2353 			var32_off.value | (var32_off.mask & S32_MAX));
2354 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2355 	reg->u32_max_value = min(reg->u32_max_value,
2356 				 (u32)(var32_off.value | var32_off.mask));
2357 }
2358 
2359 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2360 {
2361 	/* min signed is max(sign bit) | min(other bits) */
2362 	reg->smin_value = max_t(s64, reg->smin_value,
2363 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2364 	/* max signed is min(sign bit) | max(other bits) */
2365 	reg->smax_value = min_t(s64, reg->smax_value,
2366 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2367 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2368 	reg->umax_value = min(reg->umax_value,
2369 			      reg->var_off.value | reg->var_off.mask);
2370 }
2371 
2372 static void __update_reg_bounds(struct bpf_reg_state *reg)
2373 {
2374 	__update_reg32_bounds(reg);
2375 	__update_reg64_bounds(reg);
2376 }
2377 
2378 /* Uses signed min/max values to inform unsigned, and vice-versa */
2379 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2380 {
2381 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
2382 	 * bits to improve our u32/s32 boundaries.
2383 	 *
2384 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
2385 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
2386 	 * [10, 20] range. But this property holds for any 64-bit range as
2387 	 * long as upper 32 bits in that entire range of values stay the same.
2388 	 *
2389 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
2390 	 * in decimal) has the same upper 32 bits throughout all the values in
2391 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
2392 	 * range.
2393 	 *
2394 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
2395 	 * following the rules outlined below about u64/s64 correspondence
2396 	 * (which equally applies to u32 vs s32 correspondence). In general it
2397 	 * depends on actual hexadecimal values of 32-bit range. They can form
2398 	 * only valid u32, or only valid s32 ranges in some cases.
2399 	 *
2400 	 * So we use all these insights to derive bounds for subregisters here.
2401 	 */
2402 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
2403 		/* u64 to u32 casting preserves validity of low 32 bits as
2404 		 * a range, if upper 32 bits are the same
2405 		 */
2406 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2407 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2408 
2409 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2410 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2411 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2412 		}
2413 	}
2414 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2415 		/* low 32 bits should form a proper u32 range */
2416 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2417 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2418 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2419 		}
2420 		/* low 32 bits should form a proper s32 range */
2421 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2422 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2423 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2424 		}
2425 	}
2426 	/* Special case where upper bits form a small sequence of two
2427 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2428 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2429 	 * going from negative numbers to positive numbers. E.g., let's say we
2430 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2431 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2432 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2433 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2434 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2435 	 * upper 32 bits. As a random example, s64 range
2436 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2437 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2438 	 */
2439 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2440 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2441 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2442 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2443 	}
2444 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2445 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2446 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2447 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2448 	}
2449 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2450 	 * try to learn from that
2451 	 */
2452 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2453 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2454 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2455 	}
2456 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2457 	 * are the same, so combine.  This works even in the negative case, e.g.
2458 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2459 	 */
2460 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2461 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2462 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2463 	}
2464 }
2465 
2466 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2467 {
2468 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2469 	 * try to learn from that. Let's do a bit of ASCII art to see when
2470 	 * this is happening. Let's take u64 range first:
2471 	 *
2472 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2473 	 * |-------------------------------|--------------------------------|
2474 	 *
2475 	 * Valid u64 range is formed when umin and umax are anywhere in the
2476 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2477 	 * straightforward. Let's see how s64 range maps onto the same range
2478 	 * of values, annotated below the line for comparison:
2479 	 *
2480 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2481 	 * |-------------------------------|--------------------------------|
2482 	 * 0                        S64_MAX S64_MIN                        -1
2483 	 *
2484 	 * So s64 values basically start in the middle and they are logically
2485 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2486 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2487 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2488 	 * more visually as mapped to sign-agnostic range of hex values.
2489 	 *
2490 	 *  u64 start                                               u64 end
2491 	 *  _______________________________________________________________
2492 	 * /                                                               \
2493 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2494 	 * |-------------------------------|--------------------------------|
2495 	 * 0                        S64_MAX S64_MIN                        -1
2496 	 *                                / \
2497 	 * >------------------------------   ------------------------------->
2498 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2499 	 *
2500 	 * What this means is that, in general, we can't always derive
2501 	 * something new about u64 from any random s64 range, and vice versa.
2502 	 *
2503 	 * But we can do that in two particular cases. One is when entire
2504 	 * u64/s64 range is *entirely* contained within left half of the above
2505 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2506 	 *
2507 	 * |-------------------------------|--------------------------------|
2508 	 *     ^                   ^            ^                 ^
2509 	 *     A                   B            C                 D
2510 	 *
2511 	 * [A, B] and [C, D] are contained entirely in their respective halves
2512 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2513 	 * will be non-negative both as u64 and s64 (and in fact it will be
2514 	 * identical ranges no matter the signedness). [C, D] treated as s64
2515 	 * will be a range of negative values, while in u64 it will be
2516 	 * non-negative range of values larger than 0x8000000000000000.
2517 	 *
2518 	 * Now, any other range here can't be represented in both u64 and s64
2519 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2520 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2521 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2522 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2523 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2524 	 * ranges as u64. Currently reg_state can't represent two segments per
2525 	 * numeric domain, so in such situations we can only derive maximal
2526 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2527 	 *
2528 	 * So we use these facts to derive umin/umax from smin/smax and vice
2529 	 * versa only if they stay within the same "half". This is equivalent
2530 	 * to checking sign bit: lower half will have sign bit as zero, upper
2531 	 * half have sign bit 1. Below in code we simplify this by just
2532 	 * casting umin/umax as smin/smax and checking if they form valid
2533 	 * range, and vice versa. Those are equivalent checks.
2534 	 */
2535 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2536 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2537 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2538 	}
2539 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2540 	 * are the same, so combine.  This works even in the negative case, e.g.
2541 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2542 	 */
2543 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2544 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2545 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2546 	} else {
2547 		/* If the s64 range crosses the sign boundary, then it's split
2548 		 * between the beginning and end of the U64 domain. In that
2549 		 * case, we can derive new bounds if the u64 range overlaps
2550 		 * with only one end of the s64 range.
2551 		 *
2552 		 * In the following example, the u64 range overlaps only with
2553 		 * positive portion of the s64 range.
2554 		 *
2555 		 * 0                                                   U64_MAX
2556 		 * |  [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]              |
2557 		 * |----------------------------|----------------------------|
2558 		 * |xxxxx s64 range xxxxxxxxx]                       [xxxxxxx|
2559 		 * 0                     S64_MAX S64_MIN                    -1
2560 		 *
2561 		 * We can thus derive the following new s64 and u64 ranges.
2562 		 *
2563 		 * 0                                                   U64_MAX
2564 		 * |  [xxxxxx u64 range xxxxx]                               |
2565 		 * |----------------------------|----------------------------|
2566 		 * |  [xxxxxx s64 range xxxxx]                               |
2567 		 * 0                     S64_MAX S64_MIN                    -1
2568 		 *
2569 		 * If they overlap in two places, we can't derive anything
2570 		 * because reg_state can't represent two ranges per numeric
2571 		 * domain.
2572 		 *
2573 		 * 0                                                   U64_MAX
2574 		 * |  [xxxxxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxxxxx]        |
2575 		 * |----------------------------|----------------------------|
2576 		 * |xxxxx s64 range xxxxxxxxx]                    [xxxxxxxxxx|
2577 		 * 0                     S64_MAX S64_MIN                    -1
2578 		 *
2579 		 * The first condition below corresponds to the first diagram
2580 		 * above.
2581 		 */
2582 		if (reg->umax_value < (u64)reg->smin_value) {
2583 			reg->smin_value = (s64)reg->umin_value;
2584 			reg->umax_value = min_t(u64, reg->umax_value, reg->smax_value);
2585 		} else if ((u64)reg->smax_value < reg->umin_value) {
2586 			/* This second condition considers the case where the u64 range
2587 			 * overlaps with the negative portion of the s64 range:
2588 			 *
2589 			 * 0                                                   U64_MAX
2590 			 * |              [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]  |
2591 			 * |----------------------------|----------------------------|
2592 			 * |xxxxxxxxx]                       [xxxxxxxxxxxx s64 range |
2593 			 * 0                     S64_MAX S64_MIN                    -1
2594 			 */
2595 			reg->smax_value = (s64)reg->umax_value;
2596 			reg->umin_value = max_t(u64, reg->umin_value, reg->smin_value);
2597 		}
2598 	}
2599 }
2600 
2601 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2602 {
2603 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2604 	 * values on both sides of 64-bit range in hope to have tighter range.
2605 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2606 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2607 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2608 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2609 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2610 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2611 	 * We just need to make sure that derived bounds we are intersecting
2612 	 * with are well-formed ranges in respective s64 or u64 domain, just
2613 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2614 	 */
2615 	__u64 new_umin, new_umax;
2616 	__s64 new_smin, new_smax;
2617 
2618 	/* u32 -> u64 tightening, it's always well-formed */
2619 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2620 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2621 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2622 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2623 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2624 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2625 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2626 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2627 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2628 
2629 	/* Here we would like to handle a special case after sign extending load,
2630 	 * when upper bits for a 64-bit range are all 1s or all 0s.
2631 	 *
2632 	 * Upper bits are all 1s when register is in a range:
2633 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2634 	 * Upper bits are all 0s when register is in a range:
2635 	 *   [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2636 	 * Together this forms are continuous range:
2637 	 *   [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2638 	 *
2639 	 * Now, suppose that register range is in fact tighter:
2640 	 *   [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2641 	 * Also suppose that it's 32-bit range is positive,
2642 	 * meaning that lower 32-bits of the full 64-bit register
2643 	 * are in the range:
2644 	 *   [0x0000_0000, 0x7fff_ffff] (W)
2645 	 *
2646 	 * If this happens, then any value in a range:
2647 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2648 	 * is smaller than a lowest bound of the range (R):
2649 	 *   0xffff_ffff_8000_0000
2650 	 * which means that upper bits of the full 64-bit register
2651 	 * can't be all 1s, when lower bits are in range (W).
2652 	 *
2653 	 * Note that:
2654 	 *  - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2655 	 *  - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2656 	 * These relations are used in the conditions below.
2657 	 */
2658 	if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2659 		reg->smin_value = reg->s32_min_value;
2660 		reg->smax_value = reg->s32_max_value;
2661 		reg->umin_value = reg->s32_min_value;
2662 		reg->umax_value = reg->s32_max_value;
2663 		reg->var_off = tnum_intersect(reg->var_off,
2664 					      tnum_range(reg->smin_value, reg->smax_value));
2665 	}
2666 }
2667 
2668 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2669 {
2670 	__reg32_deduce_bounds(reg);
2671 	__reg64_deduce_bounds(reg);
2672 	__reg_deduce_mixed_bounds(reg);
2673 }
2674 
2675 /* Attempts to improve var_off based on unsigned min/max information */
2676 static void __reg_bound_offset(struct bpf_reg_state *reg)
2677 {
2678 	struct tnum var64_off = tnum_intersect(reg->var_off,
2679 					       tnum_range(reg->umin_value,
2680 							  reg->umax_value));
2681 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2682 					       tnum_range(reg->u32_min_value,
2683 							  reg->u32_max_value));
2684 
2685 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2686 }
2687 
2688 static void reg_bounds_sync(struct bpf_reg_state *reg)
2689 {
2690 	/* We might have learned new bounds from the var_off. */
2691 	__update_reg_bounds(reg);
2692 	/* We might have learned something about the sign bit. */
2693 	__reg_deduce_bounds(reg);
2694 	__reg_deduce_bounds(reg);
2695 	__reg_deduce_bounds(reg);
2696 	/* We might have learned some bits from the bounds. */
2697 	__reg_bound_offset(reg);
2698 	/* Intersecting with the old var_off might have improved our bounds
2699 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2700 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2701 	 */
2702 	__update_reg_bounds(reg);
2703 }
2704 
2705 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2706 				   struct bpf_reg_state *reg, const char *ctx)
2707 {
2708 	const char *msg;
2709 
2710 	if (reg->umin_value > reg->umax_value ||
2711 	    reg->smin_value > reg->smax_value ||
2712 	    reg->u32_min_value > reg->u32_max_value ||
2713 	    reg->s32_min_value > reg->s32_max_value) {
2714 		    msg = "range bounds violation";
2715 		    goto out;
2716 	}
2717 
2718 	if (tnum_is_const(reg->var_off)) {
2719 		u64 uval = reg->var_off.value;
2720 		s64 sval = (s64)uval;
2721 
2722 		if (reg->umin_value != uval || reg->umax_value != uval ||
2723 		    reg->smin_value != sval || reg->smax_value != sval) {
2724 			msg = "const tnum out of sync with range bounds";
2725 			goto out;
2726 		}
2727 	}
2728 
2729 	if (tnum_subreg_is_const(reg->var_off)) {
2730 		u32 uval32 = tnum_subreg(reg->var_off).value;
2731 		s32 sval32 = (s32)uval32;
2732 
2733 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2734 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2735 			msg = "const subreg tnum out of sync with range bounds";
2736 			goto out;
2737 		}
2738 	}
2739 
2740 	return 0;
2741 out:
2742 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2743 		     "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)",
2744 		     ctx, msg, reg->umin_value, reg->umax_value,
2745 		     reg->smin_value, reg->smax_value,
2746 		     reg->u32_min_value, reg->u32_max_value,
2747 		     reg->s32_min_value, reg->s32_max_value,
2748 		     reg->var_off.value, reg->var_off.mask);
2749 	if (env->test_reg_invariants)
2750 		return -EFAULT;
2751 	__mark_reg_unbounded(reg);
2752 	return 0;
2753 }
2754 
2755 static bool __reg32_bound_s64(s32 a)
2756 {
2757 	return a >= 0 && a <= S32_MAX;
2758 }
2759 
2760 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2761 {
2762 	reg->umin_value = reg->u32_min_value;
2763 	reg->umax_value = reg->u32_max_value;
2764 
2765 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2766 	 * be positive otherwise set to worse case bounds and refine later
2767 	 * from tnum.
2768 	 */
2769 	if (__reg32_bound_s64(reg->s32_min_value) &&
2770 	    __reg32_bound_s64(reg->s32_max_value)) {
2771 		reg->smin_value = reg->s32_min_value;
2772 		reg->smax_value = reg->s32_max_value;
2773 	} else {
2774 		reg->smin_value = 0;
2775 		reg->smax_value = U32_MAX;
2776 	}
2777 }
2778 
2779 /* Mark a register as having a completely unknown (scalar) value. */
2780 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2781 {
2782 	/*
2783 	 * Clear type, off, and union(map_ptr, range) and
2784 	 * padding between 'type' and union
2785 	 */
2786 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2787 	reg->type = SCALAR_VALUE;
2788 	reg->id = 0;
2789 	reg->ref_obj_id = 0;
2790 	reg->var_off = tnum_unknown;
2791 	reg->frameno = 0;
2792 	reg->precise = false;
2793 	__mark_reg_unbounded(reg);
2794 }
2795 
2796 /* Mark a register as having a completely unknown (scalar) value,
2797  * initialize .precise as true when not bpf capable.
2798  */
2799 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2800 			       struct bpf_reg_state *reg)
2801 {
2802 	__mark_reg_unknown_imprecise(reg);
2803 	reg->precise = !env->bpf_capable;
2804 }
2805 
2806 static void mark_reg_unknown(struct bpf_verifier_env *env,
2807 			     struct bpf_reg_state *regs, u32 regno)
2808 {
2809 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2810 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2811 		/* Something bad happened, let's kill all regs except FP */
2812 		for (regno = 0; regno < BPF_REG_FP; regno++)
2813 			__mark_reg_not_init(env, regs + regno);
2814 		return;
2815 	}
2816 	__mark_reg_unknown(env, regs + regno);
2817 }
2818 
2819 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2820 				struct bpf_reg_state *regs,
2821 				u32 regno,
2822 				s32 s32_min,
2823 				s32 s32_max)
2824 {
2825 	struct bpf_reg_state *reg = regs + regno;
2826 
2827 	reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2828 	reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2829 
2830 	reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2831 	reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2832 
2833 	reg_bounds_sync(reg);
2834 
2835 	return reg_bounds_sanity_check(env, reg, "s32_range");
2836 }
2837 
2838 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2839 				struct bpf_reg_state *reg)
2840 {
2841 	__mark_reg_unknown(env, reg);
2842 	reg->type = NOT_INIT;
2843 }
2844 
2845 static void mark_reg_not_init(struct bpf_verifier_env *env,
2846 			      struct bpf_reg_state *regs, u32 regno)
2847 {
2848 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2849 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2850 		/* Something bad happened, let's kill all regs except FP */
2851 		for (regno = 0; regno < BPF_REG_FP; regno++)
2852 			__mark_reg_not_init(env, regs + regno);
2853 		return;
2854 	}
2855 	__mark_reg_not_init(env, regs + regno);
2856 }
2857 
2858 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2859 			   struct bpf_reg_state *regs, u32 regno,
2860 			   enum bpf_reg_type reg_type,
2861 			   struct btf *btf, u32 btf_id,
2862 			   enum bpf_type_flag flag)
2863 {
2864 	switch (reg_type) {
2865 	case SCALAR_VALUE:
2866 		mark_reg_unknown(env, regs, regno);
2867 		return 0;
2868 	case PTR_TO_BTF_ID:
2869 		mark_reg_known_zero(env, regs, regno);
2870 		regs[regno].type = PTR_TO_BTF_ID | flag;
2871 		regs[regno].btf = btf;
2872 		regs[regno].btf_id = btf_id;
2873 		if (type_may_be_null(flag))
2874 			regs[regno].id = ++env->id_gen;
2875 		return 0;
2876 	case PTR_TO_MEM:
2877 		mark_reg_known_zero(env, regs, regno);
2878 		regs[regno].type = PTR_TO_MEM | flag;
2879 		regs[regno].mem_size = 0;
2880 		return 0;
2881 	default:
2882 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2883 		return -EFAULT;
2884 	}
2885 }
2886 
2887 #define DEF_NOT_SUBREG	(0)
2888 static void init_reg_state(struct bpf_verifier_env *env,
2889 			   struct bpf_func_state *state)
2890 {
2891 	struct bpf_reg_state *regs = state->regs;
2892 	int i;
2893 
2894 	for (i = 0; i < MAX_BPF_REG; i++) {
2895 		mark_reg_not_init(env, regs, i);
2896 		regs[i].subreg_def = DEF_NOT_SUBREG;
2897 	}
2898 
2899 	/* frame pointer */
2900 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2901 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2902 	regs[BPF_REG_FP].frameno = state->frameno;
2903 }
2904 
2905 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2906 {
2907 	return (struct bpf_retval_range){ minval, maxval };
2908 }
2909 
2910 #define BPF_MAIN_FUNC (-1)
2911 static void init_func_state(struct bpf_verifier_env *env,
2912 			    struct bpf_func_state *state,
2913 			    int callsite, int frameno, int subprogno)
2914 {
2915 	state->callsite = callsite;
2916 	state->frameno = frameno;
2917 	state->subprogno = subprogno;
2918 	state->callback_ret_range = retval_range(0, 0);
2919 	init_reg_state(env, state);
2920 	mark_verifier_state_scratched(env);
2921 }
2922 
2923 /* Similar to push_stack(), but for async callbacks */
2924 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2925 						int insn_idx, int prev_insn_idx,
2926 						int subprog, bool is_sleepable)
2927 {
2928 	struct bpf_verifier_stack_elem *elem;
2929 	struct bpf_func_state *frame;
2930 
2931 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2932 	if (!elem)
2933 		return ERR_PTR(-ENOMEM);
2934 
2935 	elem->insn_idx = insn_idx;
2936 	elem->prev_insn_idx = prev_insn_idx;
2937 	elem->next = env->head;
2938 	elem->log_pos = env->log.end_pos;
2939 	env->head = elem;
2940 	env->stack_size++;
2941 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2942 		verbose(env,
2943 			"The sequence of %d jumps is too complex for async cb.\n",
2944 			env->stack_size);
2945 		return ERR_PTR(-E2BIG);
2946 	}
2947 	/* Unlike push_stack() do not copy_verifier_state().
2948 	 * The caller state doesn't matter.
2949 	 * This is async callback. It starts in a fresh stack.
2950 	 * Initialize it similar to do_check_common().
2951 	 */
2952 	elem->st.branches = 1;
2953 	elem->st.in_sleepable = is_sleepable;
2954 	frame = kzalloc(sizeof(*frame), GFP_KERNEL_ACCOUNT);
2955 	if (!frame)
2956 		return ERR_PTR(-ENOMEM);
2957 	init_func_state(env, frame,
2958 			BPF_MAIN_FUNC /* callsite */,
2959 			0 /* frameno within this callchain */,
2960 			subprog /* subprog number within this prog */);
2961 	elem->st.frame[0] = frame;
2962 	return &elem->st;
2963 }
2964 
2965 
2966 enum reg_arg_type {
2967 	SRC_OP,		/* register is used as source operand */
2968 	DST_OP,		/* register is used as destination operand */
2969 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2970 };
2971 
2972 static int cmp_subprogs(const void *a, const void *b)
2973 {
2974 	return ((struct bpf_subprog_info *)a)->start -
2975 	       ((struct bpf_subprog_info *)b)->start;
2976 }
2977 
2978 /* Find subprogram that contains instruction at 'off' */
2979 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)
2980 {
2981 	struct bpf_subprog_info *vals = env->subprog_info;
2982 	int l, r, m;
2983 
2984 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2985 		return NULL;
2986 
2987 	l = 0;
2988 	r = env->subprog_cnt - 1;
2989 	while (l < r) {
2990 		m = l + (r - l + 1) / 2;
2991 		if (vals[m].start <= off)
2992 			l = m;
2993 		else
2994 			r = m - 1;
2995 	}
2996 	return &vals[l];
2997 }
2998 
2999 /* Find subprogram that starts exactly at 'off' */
3000 static int find_subprog(struct bpf_verifier_env *env, int off)
3001 {
3002 	struct bpf_subprog_info *p;
3003 
3004 	p = bpf_find_containing_subprog(env, off);
3005 	if (!p || p->start != off)
3006 		return -ENOENT;
3007 	return p - env->subprog_info;
3008 }
3009 
3010 static int add_subprog(struct bpf_verifier_env *env, int off)
3011 {
3012 	int insn_cnt = env->prog->len;
3013 	int ret;
3014 
3015 	if (off >= insn_cnt || off < 0) {
3016 		verbose(env, "call to invalid destination\n");
3017 		return -EINVAL;
3018 	}
3019 	ret = find_subprog(env, off);
3020 	if (ret >= 0)
3021 		return ret;
3022 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
3023 		verbose(env, "too many subprograms\n");
3024 		return -E2BIG;
3025 	}
3026 	/* determine subprog starts. The end is one before the next starts */
3027 	env->subprog_info[env->subprog_cnt++].start = off;
3028 	sort(env->subprog_info, env->subprog_cnt,
3029 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
3030 	return env->subprog_cnt - 1;
3031 }
3032 
3033 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
3034 {
3035 	struct bpf_prog_aux *aux = env->prog->aux;
3036 	struct btf *btf = aux->btf;
3037 	const struct btf_type *t;
3038 	u32 main_btf_id, id;
3039 	const char *name;
3040 	int ret, i;
3041 
3042 	/* Non-zero func_info_cnt implies valid btf */
3043 	if (!aux->func_info_cnt)
3044 		return 0;
3045 	main_btf_id = aux->func_info[0].type_id;
3046 
3047 	t = btf_type_by_id(btf, main_btf_id);
3048 	if (!t) {
3049 		verbose(env, "invalid btf id for main subprog in func_info\n");
3050 		return -EINVAL;
3051 	}
3052 
3053 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
3054 	if (IS_ERR(name)) {
3055 		ret = PTR_ERR(name);
3056 		/* If there is no tag present, there is no exception callback */
3057 		if (ret == -ENOENT)
3058 			ret = 0;
3059 		else if (ret == -EEXIST)
3060 			verbose(env, "multiple exception callback tags for main subprog\n");
3061 		return ret;
3062 	}
3063 
3064 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
3065 	if (ret < 0) {
3066 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
3067 		return ret;
3068 	}
3069 	id = ret;
3070 	t = btf_type_by_id(btf, id);
3071 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3072 		verbose(env, "exception callback '%s' must have global linkage\n", name);
3073 		return -EINVAL;
3074 	}
3075 	ret = 0;
3076 	for (i = 0; i < aux->func_info_cnt; i++) {
3077 		if (aux->func_info[i].type_id != id)
3078 			continue;
3079 		ret = aux->func_info[i].insn_off;
3080 		/* Further func_info and subprog checks will also happen
3081 		 * later, so assume this is the right insn_off for now.
3082 		 */
3083 		if (!ret) {
3084 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
3085 			ret = -EINVAL;
3086 		}
3087 	}
3088 	if (!ret) {
3089 		verbose(env, "exception callback type id not found in func_info\n");
3090 		ret = -EINVAL;
3091 	}
3092 	return ret;
3093 }
3094 
3095 #define MAX_KFUNC_DESCS 256
3096 #define MAX_KFUNC_BTFS	256
3097 
3098 struct bpf_kfunc_desc {
3099 	struct btf_func_model func_model;
3100 	u32 func_id;
3101 	s32 imm;
3102 	u16 offset;
3103 	unsigned long addr;
3104 };
3105 
3106 struct bpf_kfunc_btf {
3107 	struct btf *btf;
3108 	struct module *module;
3109 	u16 offset;
3110 };
3111 
3112 struct bpf_kfunc_desc_tab {
3113 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
3114 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
3115 	 * available, therefore at the end of verification do_misc_fixups()
3116 	 * sorts this by imm and offset.
3117 	 */
3118 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
3119 	u32 nr_descs;
3120 };
3121 
3122 struct bpf_kfunc_btf_tab {
3123 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
3124 	u32 nr_descs;
3125 };
3126 
3127 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc,
3128 			    int insn_idx);
3129 
3130 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
3131 {
3132 	const struct bpf_kfunc_desc *d0 = a;
3133 	const struct bpf_kfunc_desc *d1 = b;
3134 
3135 	/* func_id is not greater than BTF_MAX_TYPE */
3136 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
3137 }
3138 
3139 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
3140 {
3141 	const struct bpf_kfunc_btf *d0 = a;
3142 	const struct bpf_kfunc_btf *d1 = b;
3143 
3144 	return d0->offset - d1->offset;
3145 }
3146 
3147 static struct bpf_kfunc_desc *
3148 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
3149 {
3150 	struct bpf_kfunc_desc desc = {
3151 		.func_id = func_id,
3152 		.offset = offset,
3153 	};
3154 	struct bpf_kfunc_desc_tab *tab;
3155 
3156 	tab = prog->aux->kfunc_tab;
3157 	return bsearch(&desc, tab->descs, tab->nr_descs,
3158 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
3159 }
3160 
3161 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3162 		       u16 btf_fd_idx, u8 **func_addr)
3163 {
3164 	const struct bpf_kfunc_desc *desc;
3165 
3166 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
3167 	if (!desc)
3168 		return -EFAULT;
3169 
3170 	*func_addr = (u8 *)desc->addr;
3171 	return 0;
3172 }
3173 
3174 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
3175 					 s16 offset)
3176 {
3177 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
3178 	struct bpf_kfunc_btf_tab *tab;
3179 	struct bpf_kfunc_btf *b;
3180 	struct module *mod;
3181 	struct btf *btf;
3182 	int btf_fd;
3183 
3184 	tab = env->prog->aux->kfunc_btf_tab;
3185 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
3186 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
3187 	if (!b) {
3188 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
3189 			verbose(env, "too many different module BTFs\n");
3190 			return ERR_PTR(-E2BIG);
3191 		}
3192 
3193 		if (bpfptr_is_null(env->fd_array)) {
3194 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
3195 			return ERR_PTR(-EPROTO);
3196 		}
3197 
3198 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
3199 					    offset * sizeof(btf_fd),
3200 					    sizeof(btf_fd)))
3201 			return ERR_PTR(-EFAULT);
3202 
3203 		btf = btf_get_by_fd(btf_fd);
3204 		if (IS_ERR(btf)) {
3205 			verbose(env, "invalid module BTF fd specified\n");
3206 			return btf;
3207 		}
3208 
3209 		if (!btf_is_module(btf)) {
3210 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
3211 			btf_put(btf);
3212 			return ERR_PTR(-EINVAL);
3213 		}
3214 
3215 		mod = btf_try_get_module(btf);
3216 		if (!mod) {
3217 			btf_put(btf);
3218 			return ERR_PTR(-ENXIO);
3219 		}
3220 
3221 		b = &tab->descs[tab->nr_descs++];
3222 		b->btf = btf;
3223 		b->module = mod;
3224 		b->offset = offset;
3225 
3226 		/* sort() reorders entries by value, so b may no longer point
3227 		 * to the right entry after this
3228 		 */
3229 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3230 		     kfunc_btf_cmp_by_off, NULL);
3231 	} else {
3232 		btf = b->btf;
3233 	}
3234 
3235 	return btf;
3236 }
3237 
3238 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
3239 {
3240 	if (!tab)
3241 		return;
3242 
3243 	while (tab->nr_descs--) {
3244 		module_put(tab->descs[tab->nr_descs].module);
3245 		btf_put(tab->descs[tab->nr_descs].btf);
3246 	}
3247 	kfree(tab);
3248 }
3249 
3250 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
3251 {
3252 	if (offset) {
3253 		if (offset < 0) {
3254 			/* In the future, this can be allowed to increase limit
3255 			 * of fd index into fd_array, interpreted as u16.
3256 			 */
3257 			verbose(env, "negative offset disallowed for kernel module function call\n");
3258 			return ERR_PTR(-EINVAL);
3259 		}
3260 
3261 		return __find_kfunc_desc_btf(env, offset);
3262 	}
3263 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
3264 }
3265 
3266 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
3267 {
3268 	const struct btf_type *func, *func_proto;
3269 	struct bpf_kfunc_btf_tab *btf_tab;
3270 	struct btf_func_model func_model;
3271 	struct bpf_kfunc_desc_tab *tab;
3272 	struct bpf_prog_aux *prog_aux;
3273 	struct bpf_kfunc_desc *desc;
3274 	const char *func_name;
3275 	struct btf *desc_btf;
3276 	unsigned long addr;
3277 	int err;
3278 
3279 	prog_aux = env->prog->aux;
3280 	tab = prog_aux->kfunc_tab;
3281 	btf_tab = prog_aux->kfunc_btf_tab;
3282 	if (!tab) {
3283 		if (!btf_vmlinux) {
3284 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3285 			return -ENOTSUPP;
3286 		}
3287 
3288 		if (!env->prog->jit_requested) {
3289 			verbose(env, "JIT is required for calling kernel function\n");
3290 			return -ENOTSUPP;
3291 		}
3292 
3293 		if (!bpf_jit_supports_kfunc_call()) {
3294 			verbose(env, "JIT does not support calling kernel function\n");
3295 			return -ENOTSUPP;
3296 		}
3297 
3298 		if (!env->prog->gpl_compatible) {
3299 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3300 			return -EINVAL;
3301 		}
3302 
3303 		tab = kzalloc(sizeof(*tab), GFP_KERNEL_ACCOUNT);
3304 		if (!tab)
3305 			return -ENOMEM;
3306 		prog_aux->kfunc_tab = tab;
3307 	}
3308 
3309 	/* func_id == 0 is always invalid, but instead of returning an error, be
3310 	 * conservative and wait until the code elimination pass before returning
3311 	 * error, so that invalid calls that get pruned out can be in BPF programs
3312 	 * loaded from userspace.  It is also required that offset be untouched
3313 	 * for such calls.
3314 	 */
3315 	if (!func_id && !offset)
3316 		return 0;
3317 
3318 	if (!btf_tab && offset) {
3319 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL_ACCOUNT);
3320 		if (!btf_tab)
3321 			return -ENOMEM;
3322 		prog_aux->kfunc_btf_tab = btf_tab;
3323 	}
3324 
3325 	desc_btf = find_kfunc_desc_btf(env, offset);
3326 	if (IS_ERR(desc_btf)) {
3327 		verbose(env, "failed to find BTF for kernel function\n");
3328 		return PTR_ERR(desc_btf);
3329 	}
3330 
3331 	if (find_kfunc_desc(env->prog, func_id, offset))
3332 		return 0;
3333 
3334 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
3335 		verbose(env, "too many different kernel function calls\n");
3336 		return -E2BIG;
3337 	}
3338 
3339 	func = btf_type_by_id(desc_btf, func_id);
3340 	if (!func || !btf_type_is_func(func)) {
3341 		verbose(env, "kernel btf_id %u is not a function\n",
3342 			func_id);
3343 		return -EINVAL;
3344 	}
3345 	func_proto = btf_type_by_id(desc_btf, func->type);
3346 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3347 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
3348 			func_id);
3349 		return -EINVAL;
3350 	}
3351 
3352 	func_name = btf_name_by_offset(desc_btf, func->name_off);
3353 	addr = kallsyms_lookup_name(func_name);
3354 	if (!addr) {
3355 		verbose(env, "cannot find address for kernel function %s\n",
3356 			func_name);
3357 		return -EINVAL;
3358 	}
3359 
3360 	if (bpf_dev_bound_kfunc_id(func_id)) {
3361 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3362 		if (err)
3363 			return err;
3364 	}
3365 
3366 	err = btf_distill_func_proto(&env->log, desc_btf,
3367 				     func_proto, func_name,
3368 				     &func_model);
3369 	if (err)
3370 		return err;
3371 
3372 	desc = &tab->descs[tab->nr_descs++];
3373 	desc->func_id = func_id;
3374 	desc->offset = offset;
3375 	desc->addr = addr;
3376 	desc->func_model = func_model;
3377 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3378 	     kfunc_desc_cmp_by_id_off, NULL);
3379 	return 0;
3380 }
3381 
3382 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3383 {
3384 	const struct bpf_kfunc_desc *d0 = a;
3385 	const struct bpf_kfunc_desc *d1 = b;
3386 
3387 	if (d0->imm != d1->imm)
3388 		return d0->imm < d1->imm ? -1 : 1;
3389 	if (d0->offset != d1->offset)
3390 		return d0->offset < d1->offset ? -1 : 1;
3391 	return 0;
3392 }
3393 
3394 static int set_kfunc_desc_imm(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc)
3395 {
3396 	unsigned long call_imm;
3397 
3398 	if (bpf_jit_supports_far_kfunc_call()) {
3399 		call_imm = desc->func_id;
3400 	} else {
3401 		call_imm = BPF_CALL_IMM(desc->addr);
3402 		/* Check whether the relative offset overflows desc->imm */
3403 		if ((unsigned long)(s32)call_imm != call_imm) {
3404 			verbose(env, "address of kernel func_id %u is out of range\n",
3405 				desc->func_id);
3406 			return -EINVAL;
3407 		}
3408 	}
3409 	desc->imm = call_imm;
3410 	return 0;
3411 }
3412 
3413 static int sort_kfunc_descs_by_imm_off(struct bpf_verifier_env *env)
3414 {
3415 	struct bpf_kfunc_desc_tab *tab;
3416 	int i, err;
3417 
3418 	tab = env->prog->aux->kfunc_tab;
3419 	if (!tab)
3420 		return 0;
3421 
3422 	for (i = 0; i < tab->nr_descs; i++) {
3423 		err = set_kfunc_desc_imm(env, &tab->descs[i]);
3424 		if (err)
3425 			return err;
3426 	}
3427 
3428 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3429 	     kfunc_desc_cmp_by_imm_off, NULL);
3430 	return 0;
3431 }
3432 
3433 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3434 {
3435 	return !!prog->aux->kfunc_tab;
3436 }
3437 
3438 const struct btf_func_model *
3439 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3440 			 const struct bpf_insn *insn)
3441 {
3442 	const struct bpf_kfunc_desc desc = {
3443 		.imm = insn->imm,
3444 		.offset = insn->off,
3445 	};
3446 	const struct bpf_kfunc_desc *res;
3447 	struct bpf_kfunc_desc_tab *tab;
3448 
3449 	tab = prog->aux->kfunc_tab;
3450 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3451 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3452 
3453 	return res ? &res->func_model : NULL;
3454 }
3455 
3456 static int add_kfunc_in_insns(struct bpf_verifier_env *env,
3457 			      struct bpf_insn *insn, int cnt)
3458 {
3459 	int i, ret;
3460 
3461 	for (i = 0; i < cnt; i++, insn++) {
3462 		if (bpf_pseudo_kfunc_call(insn)) {
3463 			ret = add_kfunc_call(env, insn->imm, insn->off);
3464 			if (ret < 0)
3465 				return ret;
3466 		}
3467 	}
3468 	return 0;
3469 }
3470 
3471 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3472 {
3473 	struct bpf_subprog_info *subprog = env->subprog_info;
3474 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3475 	struct bpf_insn *insn = env->prog->insnsi;
3476 
3477 	/* Add entry function. */
3478 	ret = add_subprog(env, 0);
3479 	if (ret)
3480 		return ret;
3481 
3482 	for (i = 0; i < insn_cnt; i++, insn++) {
3483 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3484 		    !bpf_pseudo_kfunc_call(insn))
3485 			continue;
3486 
3487 		if (!env->bpf_capable) {
3488 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3489 			return -EPERM;
3490 		}
3491 
3492 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3493 			ret = add_subprog(env, i + insn->imm + 1);
3494 		else
3495 			ret = add_kfunc_call(env, insn->imm, insn->off);
3496 
3497 		if (ret < 0)
3498 			return ret;
3499 	}
3500 
3501 	ret = bpf_find_exception_callback_insn_off(env);
3502 	if (ret < 0)
3503 		return ret;
3504 	ex_cb_insn = ret;
3505 
3506 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3507 	 * marked using BTF decl tag to serve as the exception callback.
3508 	 */
3509 	if (ex_cb_insn) {
3510 		ret = add_subprog(env, ex_cb_insn);
3511 		if (ret < 0)
3512 			return ret;
3513 		for (i = 1; i < env->subprog_cnt; i++) {
3514 			if (env->subprog_info[i].start != ex_cb_insn)
3515 				continue;
3516 			env->exception_callback_subprog = i;
3517 			mark_subprog_exc_cb(env, i);
3518 			break;
3519 		}
3520 	}
3521 
3522 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3523 	 * logic. 'subprog_cnt' should not be increased.
3524 	 */
3525 	subprog[env->subprog_cnt].start = insn_cnt;
3526 
3527 	if (env->log.level & BPF_LOG_LEVEL2)
3528 		for (i = 0; i < env->subprog_cnt; i++)
3529 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3530 
3531 	return 0;
3532 }
3533 
3534 static int check_subprogs(struct bpf_verifier_env *env)
3535 {
3536 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3537 	struct bpf_subprog_info *subprog = env->subprog_info;
3538 	struct bpf_insn *insn = env->prog->insnsi;
3539 	int insn_cnt = env->prog->len;
3540 
3541 	/* now check that all jumps are within the same subprog */
3542 	subprog_start = subprog[cur_subprog].start;
3543 	subprog_end = subprog[cur_subprog + 1].start;
3544 	for (i = 0; i < insn_cnt; i++) {
3545 		u8 code = insn[i].code;
3546 
3547 		if (code == (BPF_JMP | BPF_CALL) &&
3548 		    insn[i].src_reg == 0 &&
3549 		    insn[i].imm == BPF_FUNC_tail_call) {
3550 			subprog[cur_subprog].has_tail_call = true;
3551 			subprog[cur_subprog].tail_call_reachable = true;
3552 		}
3553 		if (BPF_CLASS(code) == BPF_LD &&
3554 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3555 			subprog[cur_subprog].has_ld_abs = true;
3556 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3557 			goto next;
3558 		if (BPF_OP(code) == BPF_CALL)
3559 			goto next;
3560 		if (BPF_OP(code) == BPF_EXIT) {
3561 			subprog[cur_subprog].exit_idx = i;
3562 			goto next;
3563 		}
3564 		off = i + bpf_jmp_offset(&insn[i]) + 1;
3565 		if (off < subprog_start || off >= subprog_end) {
3566 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3567 			return -EINVAL;
3568 		}
3569 next:
3570 		if (i == subprog_end - 1) {
3571 			/* to avoid fall-through from one subprog into another
3572 			 * the last insn of the subprog should be either exit
3573 			 * or unconditional jump back or bpf_throw call
3574 			 */
3575 			if (code != (BPF_JMP | BPF_EXIT) &&
3576 			    code != (BPF_JMP32 | BPF_JA) &&
3577 			    code != (BPF_JMP | BPF_JA)) {
3578 				verbose(env, "last insn is not an exit or jmp\n");
3579 				return -EINVAL;
3580 			}
3581 			subprog_start = subprog_end;
3582 			cur_subprog++;
3583 			if (cur_subprog < env->subprog_cnt)
3584 				subprog_end = subprog[cur_subprog + 1].start;
3585 		}
3586 	}
3587 	return 0;
3588 }
3589 
3590 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3591 				    int spi, int nr_slots)
3592 {
3593 	int err, i;
3594 
3595 	for (i = 0; i < nr_slots; i++) {
3596 		err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi - i));
3597 		if (err)
3598 			return err;
3599 		mark_stack_slot_scratched(env, spi - i);
3600 	}
3601 	return 0;
3602 }
3603 
3604 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3605 {
3606 	int spi;
3607 
3608 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3609 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3610 	 * check_kfunc_call.
3611 	 */
3612 	if (reg->type == CONST_PTR_TO_DYNPTR)
3613 		return 0;
3614 	spi = dynptr_get_spi(env, reg);
3615 	if (spi < 0)
3616 		return spi;
3617 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3618 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3619 	 * read.
3620 	 */
3621 	return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS);
3622 }
3623 
3624 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3625 			  int spi, int nr_slots)
3626 {
3627 	return mark_stack_slot_obj_read(env, reg, spi, nr_slots);
3628 }
3629 
3630 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3631 {
3632 	int spi;
3633 
3634 	spi = irq_flag_get_spi(env, reg);
3635 	if (spi < 0)
3636 		return spi;
3637 	return mark_stack_slot_obj_read(env, reg, spi, 1);
3638 }
3639 
3640 /* This function is supposed to be used by the following 32-bit optimization
3641  * code only. It returns TRUE if the source or destination register operates
3642  * on 64-bit, otherwise return FALSE.
3643  */
3644 static bool is_reg64(struct bpf_insn *insn,
3645 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3646 {
3647 	u8 code, class, op;
3648 
3649 	code = insn->code;
3650 	class = BPF_CLASS(code);
3651 	op = BPF_OP(code);
3652 	if (class == BPF_JMP) {
3653 		/* BPF_EXIT for "main" will reach here. Return TRUE
3654 		 * conservatively.
3655 		 */
3656 		if (op == BPF_EXIT)
3657 			return true;
3658 		if (op == BPF_CALL) {
3659 			/* BPF to BPF call will reach here because of marking
3660 			 * caller saved clobber with DST_OP_NO_MARK for which we
3661 			 * don't care the register def because they are anyway
3662 			 * marked as NOT_INIT already.
3663 			 */
3664 			if (insn->src_reg == BPF_PSEUDO_CALL)
3665 				return false;
3666 			/* Helper call will reach here because of arg type
3667 			 * check, conservatively return TRUE.
3668 			 */
3669 			if (t == SRC_OP)
3670 				return true;
3671 
3672 			return false;
3673 		}
3674 	}
3675 
3676 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3677 		return false;
3678 
3679 	if (class == BPF_ALU64 || class == BPF_JMP ||
3680 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3681 		return true;
3682 
3683 	if (class == BPF_ALU || class == BPF_JMP32)
3684 		return false;
3685 
3686 	if (class == BPF_LDX) {
3687 		if (t != SRC_OP)
3688 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3689 		/* LDX source must be ptr. */
3690 		return true;
3691 	}
3692 
3693 	if (class == BPF_STX) {
3694 		/* BPF_STX (including atomic variants) has one or more source
3695 		 * operands, one of which is a ptr. Check whether the caller is
3696 		 * asking about it.
3697 		 */
3698 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3699 			return true;
3700 		return BPF_SIZE(code) == BPF_DW;
3701 	}
3702 
3703 	if (class == BPF_LD) {
3704 		u8 mode = BPF_MODE(code);
3705 
3706 		/* LD_IMM64 */
3707 		if (mode == BPF_IMM)
3708 			return true;
3709 
3710 		/* Both LD_IND and LD_ABS return 32-bit data. */
3711 		if (t != SRC_OP)
3712 			return  false;
3713 
3714 		/* Implicit ctx ptr. */
3715 		if (regno == BPF_REG_6)
3716 			return true;
3717 
3718 		/* Explicit source could be any width. */
3719 		return true;
3720 	}
3721 
3722 	if (class == BPF_ST)
3723 		/* The only source register for BPF_ST is a ptr. */
3724 		return true;
3725 
3726 	/* Conservatively return true at default. */
3727 	return true;
3728 }
3729 
3730 /* Return the regno defined by the insn, or -1. */
3731 static int insn_def_regno(const struct bpf_insn *insn)
3732 {
3733 	switch (BPF_CLASS(insn->code)) {
3734 	case BPF_JMP:
3735 	case BPF_JMP32:
3736 	case BPF_ST:
3737 		return -1;
3738 	case BPF_STX:
3739 		if (BPF_MODE(insn->code) == BPF_ATOMIC ||
3740 		    BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) {
3741 			if (insn->imm == BPF_CMPXCHG)
3742 				return BPF_REG_0;
3743 			else if (insn->imm == BPF_LOAD_ACQ)
3744 				return insn->dst_reg;
3745 			else if (insn->imm & BPF_FETCH)
3746 				return insn->src_reg;
3747 		}
3748 		return -1;
3749 	default:
3750 		return insn->dst_reg;
3751 	}
3752 }
3753 
3754 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3755 static bool insn_has_def32(struct bpf_insn *insn)
3756 {
3757 	int dst_reg = insn_def_regno(insn);
3758 
3759 	if (dst_reg == -1)
3760 		return false;
3761 
3762 	return !is_reg64(insn, dst_reg, NULL, DST_OP);
3763 }
3764 
3765 static void mark_insn_zext(struct bpf_verifier_env *env,
3766 			   struct bpf_reg_state *reg)
3767 {
3768 	s32 def_idx = reg->subreg_def;
3769 
3770 	if (def_idx == DEF_NOT_SUBREG)
3771 		return;
3772 
3773 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3774 	/* The dst will be zero extended, so won't be sub-register anymore. */
3775 	reg->subreg_def = DEF_NOT_SUBREG;
3776 }
3777 
3778 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3779 			   enum reg_arg_type t)
3780 {
3781 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3782 	struct bpf_reg_state *reg;
3783 	bool rw64;
3784 
3785 	if (regno >= MAX_BPF_REG) {
3786 		verbose(env, "R%d is invalid\n", regno);
3787 		return -EINVAL;
3788 	}
3789 
3790 	mark_reg_scratched(env, regno);
3791 
3792 	reg = &regs[regno];
3793 	rw64 = is_reg64(insn, regno, reg, t);
3794 	if (t == SRC_OP) {
3795 		/* check whether register used as source operand can be read */
3796 		if (reg->type == NOT_INIT) {
3797 			verbose(env, "R%d !read_ok\n", regno);
3798 			return -EACCES;
3799 		}
3800 		/* We don't need to worry about FP liveness because it's read-only */
3801 		if (regno == BPF_REG_FP)
3802 			return 0;
3803 
3804 		if (rw64)
3805 			mark_insn_zext(env, reg);
3806 
3807 		return 0;
3808 	} else {
3809 		/* check whether register used as dest operand can be written to */
3810 		if (regno == BPF_REG_FP) {
3811 			verbose(env, "frame pointer is read only\n");
3812 			return -EACCES;
3813 		}
3814 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3815 		if (t == DST_OP)
3816 			mark_reg_unknown(env, regs, regno);
3817 	}
3818 	return 0;
3819 }
3820 
3821 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3822 			 enum reg_arg_type t)
3823 {
3824 	struct bpf_verifier_state *vstate = env->cur_state;
3825 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3826 
3827 	return __check_reg_arg(env, state->regs, regno, t);
3828 }
3829 
3830 static int insn_stack_access_flags(int frameno, int spi)
3831 {
3832 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3833 }
3834 
3835 static int insn_stack_access_spi(int insn_flags)
3836 {
3837 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3838 }
3839 
3840 static int insn_stack_access_frameno(int insn_flags)
3841 {
3842 	return insn_flags & INSN_F_FRAMENO_MASK;
3843 }
3844 
3845 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3846 {
3847 	env->insn_aux_data[idx].jmp_point = true;
3848 }
3849 
3850 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3851 {
3852 	return env->insn_aux_data[insn_idx].jmp_point;
3853 }
3854 
3855 #define LR_FRAMENO_BITS	3
3856 #define LR_SPI_BITS	6
3857 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3858 #define LR_SIZE_BITS	4
3859 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3860 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3861 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3862 #define LR_SPI_OFF	LR_FRAMENO_BITS
3863 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3864 #define LINKED_REGS_MAX	6
3865 
3866 struct linked_reg {
3867 	u8 frameno;
3868 	union {
3869 		u8 spi;
3870 		u8 regno;
3871 	};
3872 	bool is_reg;
3873 };
3874 
3875 struct linked_regs {
3876 	int cnt;
3877 	struct linked_reg entries[LINKED_REGS_MAX];
3878 };
3879 
3880 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3881 {
3882 	if (s->cnt < LINKED_REGS_MAX)
3883 		return &s->entries[s->cnt++];
3884 
3885 	return NULL;
3886 }
3887 
3888 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3889  * number of elements currently in stack.
3890  * Pack one history entry for linked registers as 10 bits in the following format:
3891  * - 3-bits frameno
3892  * - 6-bits spi_or_reg
3893  * - 1-bit  is_reg
3894  */
3895 static u64 linked_regs_pack(struct linked_regs *s)
3896 {
3897 	u64 val = 0;
3898 	int i;
3899 
3900 	for (i = 0; i < s->cnt; ++i) {
3901 		struct linked_reg *e = &s->entries[i];
3902 		u64 tmp = 0;
3903 
3904 		tmp |= e->frameno;
3905 		tmp |= e->spi << LR_SPI_OFF;
3906 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3907 
3908 		val <<= LR_ENTRY_BITS;
3909 		val |= tmp;
3910 	}
3911 	val <<= LR_SIZE_BITS;
3912 	val |= s->cnt;
3913 	return val;
3914 }
3915 
3916 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3917 {
3918 	int i;
3919 
3920 	s->cnt = val & LR_SIZE_MASK;
3921 	val >>= LR_SIZE_BITS;
3922 
3923 	for (i = 0; i < s->cnt; ++i) {
3924 		struct linked_reg *e = &s->entries[i];
3925 
3926 		e->frameno =  val & LR_FRAMENO_MASK;
3927 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3928 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3929 		val >>= LR_ENTRY_BITS;
3930 	}
3931 }
3932 
3933 /* for any branch, call, exit record the history of jmps in the given state */
3934 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3935 			    int insn_flags, u64 linked_regs)
3936 {
3937 	u32 cnt = cur->jmp_history_cnt;
3938 	struct bpf_jmp_history_entry *p;
3939 	size_t alloc_size;
3940 
3941 	/* combine instruction flags if we already recorded this instruction */
3942 	if (env->cur_hist_ent) {
3943 		/* atomic instructions push insn_flags twice, for READ and
3944 		 * WRITE sides, but they should agree on stack slot
3945 		 */
3946 		verifier_bug_if((env->cur_hist_ent->flags & insn_flags) &&
3947 				(env->cur_hist_ent->flags & insn_flags) != insn_flags,
3948 				env, "insn history: insn_idx %d cur flags %x new flags %x",
3949 				env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3950 		env->cur_hist_ent->flags |= insn_flags;
3951 		verifier_bug_if(env->cur_hist_ent->linked_regs != 0, env,
3952 				"insn history: insn_idx %d linked_regs: %#llx",
3953 				env->insn_idx, env->cur_hist_ent->linked_regs);
3954 		env->cur_hist_ent->linked_regs = linked_regs;
3955 		return 0;
3956 	}
3957 
3958 	cnt++;
3959 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3960 	p = krealloc(cur->jmp_history, alloc_size, GFP_KERNEL_ACCOUNT);
3961 	if (!p)
3962 		return -ENOMEM;
3963 	cur->jmp_history = p;
3964 
3965 	p = &cur->jmp_history[cnt - 1];
3966 	p->idx = env->insn_idx;
3967 	p->prev_idx = env->prev_insn_idx;
3968 	p->flags = insn_flags;
3969 	p->linked_regs = linked_regs;
3970 	cur->jmp_history_cnt = cnt;
3971 	env->cur_hist_ent = p;
3972 
3973 	return 0;
3974 }
3975 
3976 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3977 						        u32 hist_end, int insn_idx)
3978 {
3979 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3980 		return &st->jmp_history[hist_end - 1];
3981 	return NULL;
3982 }
3983 
3984 /* Backtrack one insn at a time. If idx is not at the top of recorded
3985  * history then previous instruction came from straight line execution.
3986  * Return -ENOENT if we exhausted all instructions within given state.
3987  *
3988  * It's legal to have a bit of a looping with the same starting and ending
3989  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3990  * instruction index is the same as state's first_idx doesn't mean we are
3991  * done. If there is still some jump history left, we should keep going. We
3992  * need to take into account that we might have a jump history between given
3993  * state's parent and itself, due to checkpointing. In this case, we'll have
3994  * history entry recording a jump from last instruction of parent state and
3995  * first instruction of given state.
3996  */
3997 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3998 			     u32 *history)
3999 {
4000 	u32 cnt = *history;
4001 
4002 	if (i == st->first_insn_idx) {
4003 		if (cnt == 0)
4004 			return -ENOENT;
4005 		if (cnt == 1 && st->jmp_history[0].idx == i)
4006 			return -ENOENT;
4007 	}
4008 
4009 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
4010 		i = st->jmp_history[cnt - 1].prev_idx;
4011 		(*history)--;
4012 	} else {
4013 		i--;
4014 	}
4015 	return i;
4016 }
4017 
4018 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
4019 {
4020 	const struct btf_type *func;
4021 	struct btf *desc_btf;
4022 
4023 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
4024 		return NULL;
4025 
4026 	desc_btf = find_kfunc_desc_btf(data, insn->off);
4027 	if (IS_ERR(desc_btf))
4028 		return "<error>";
4029 
4030 	func = btf_type_by_id(desc_btf, insn->imm);
4031 	return btf_name_by_offset(desc_btf, func->name_off);
4032 }
4033 
4034 static void verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
4035 {
4036 	const struct bpf_insn_cbs cbs = {
4037 		.cb_call	= disasm_kfunc_name,
4038 		.cb_print	= verbose,
4039 		.private_data	= env,
4040 	};
4041 
4042 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
4043 }
4044 
4045 static inline void bt_init(struct backtrack_state *bt, u32 frame)
4046 {
4047 	bt->frame = frame;
4048 }
4049 
4050 static inline void bt_reset(struct backtrack_state *bt)
4051 {
4052 	struct bpf_verifier_env *env = bt->env;
4053 
4054 	memset(bt, 0, sizeof(*bt));
4055 	bt->env = env;
4056 }
4057 
4058 static inline u32 bt_empty(struct backtrack_state *bt)
4059 {
4060 	u64 mask = 0;
4061 	int i;
4062 
4063 	for (i = 0; i <= bt->frame; i++)
4064 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
4065 
4066 	return mask == 0;
4067 }
4068 
4069 static inline int bt_subprog_enter(struct backtrack_state *bt)
4070 {
4071 	if (bt->frame == MAX_CALL_FRAMES - 1) {
4072 		verifier_bug(bt->env, "subprog enter from frame %d", bt->frame);
4073 		return -EFAULT;
4074 	}
4075 	bt->frame++;
4076 	return 0;
4077 }
4078 
4079 static inline int bt_subprog_exit(struct backtrack_state *bt)
4080 {
4081 	if (bt->frame == 0) {
4082 		verifier_bug(bt->env, "subprog exit from frame 0");
4083 		return -EFAULT;
4084 	}
4085 	bt->frame--;
4086 	return 0;
4087 }
4088 
4089 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4090 {
4091 	bt->reg_masks[frame] |= 1 << reg;
4092 }
4093 
4094 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4095 {
4096 	bt->reg_masks[frame] &= ~(1 << reg);
4097 }
4098 
4099 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
4100 {
4101 	bt_set_frame_reg(bt, bt->frame, reg);
4102 }
4103 
4104 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
4105 {
4106 	bt_clear_frame_reg(bt, bt->frame, reg);
4107 }
4108 
4109 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4110 {
4111 	bt->stack_masks[frame] |= 1ull << slot;
4112 }
4113 
4114 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4115 {
4116 	bt->stack_masks[frame] &= ~(1ull << slot);
4117 }
4118 
4119 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
4120 {
4121 	return bt->reg_masks[frame];
4122 }
4123 
4124 static inline u32 bt_reg_mask(struct backtrack_state *bt)
4125 {
4126 	return bt->reg_masks[bt->frame];
4127 }
4128 
4129 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
4130 {
4131 	return bt->stack_masks[frame];
4132 }
4133 
4134 static inline u64 bt_stack_mask(struct backtrack_state *bt)
4135 {
4136 	return bt->stack_masks[bt->frame];
4137 }
4138 
4139 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
4140 {
4141 	return bt->reg_masks[bt->frame] & (1 << reg);
4142 }
4143 
4144 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
4145 {
4146 	return bt->reg_masks[frame] & (1 << reg);
4147 }
4148 
4149 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
4150 {
4151 	return bt->stack_masks[frame] & (1ull << slot);
4152 }
4153 
4154 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
4155 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
4156 {
4157 	DECLARE_BITMAP(mask, 64);
4158 	bool first = true;
4159 	int i, n;
4160 
4161 	buf[0] = '\0';
4162 
4163 	bitmap_from_u64(mask, reg_mask);
4164 	for_each_set_bit(i, mask, 32) {
4165 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
4166 		first = false;
4167 		buf += n;
4168 		buf_sz -= n;
4169 		if (buf_sz < 0)
4170 			break;
4171 	}
4172 }
4173 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
4174 void bpf_fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
4175 {
4176 	DECLARE_BITMAP(mask, 64);
4177 	bool first = true;
4178 	int i, n;
4179 
4180 	buf[0] = '\0';
4181 
4182 	bitmap_from_u64(mask, stack_mask);
4183 	for_each_set_bit(i, mask, 64) {
4184 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
4185 		first = false;
4186 		buf += n;
4187 		buf_sz -= n;
4188 		if (buf_sz < 0)
4189 			break;
4190 	}
4191 }
4192 
4193 /* If any register R in hist->linked_regs is marked as precise in bt,
4194  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
4195  */
4196 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
4197 {
4198 	struct linked_regs linked_regs;
4199 	bool some_precise = false;
4200 	int i;
4201 
4202 	if (!hist || hist->linked_regs == 0)
4203 		return;
4204 
4205 	linked_regs_unpack(hist->linked_regs, &linked_regs);
4206 	for (i = 0; i < linked_regs.cnt; ++i) {
4207 		struct linked_reg *e = &linked_regs.entries[i];
4208 
4209 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
4210 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
4211 			some_precise = true;
4212 			break;
4213 		}
4214 	}
4215 
4216 	if (!some_precise)
4217 		return;
4218 
4219 	for (i = 0; i < linked_regs.cnt; ++i) {
4220 		struct linked_reg *e = &linked_regs.entries[i];
4221 
4222 		if (e->is_reg)
4223 			bt_set_frame_reg(bt, e->frameno, e->regno);
4224 		else
4225 			bt_set_frame_slot(bt, e->frameno, e->spi);
4226 	}
4227 }
4228 
4229 /* For given verifier state backtrack_insn() is called from the last insn to
4230  * the first insn. Its purpose is to compute a bitmask of registers and
4231  * stack slots that needs precision in the parent verifier state.
4232  *
4233  * @idx is an index of the instruction we are currently processing;
4234  * @subseq_idx is an index of the subsequent instruction that:
4235  *   - *would be* executed next, if jump history is viewed in forward order;
4236  *   - *was* processed previously during backtracking.
4237  */
4238 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
4239 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
4240 {
4241 	struct bpf_insn *insn = env->prog->insnsi + idx;
4242 	u8 class = BPF_CLASS(insn->code);
4243 	u8 opcode = BPF_OP(insn->code);
4244 	u8 mode = BPF_MODE(insn->code);
4245 	u32 dreg = insn->dst_reg;
4246 	u32 sreg = insn->src_reg;
4247 	u32 spi, i, fr;
4248 
4249 	if (insn->code == 0)
4250 		return 0;
4251 	if (env->log.level & BPF_LOG_LEVEL2) {
4252 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
4253 		verbose(env, "mark_precise: frame%d: regs=%s ",
4254 			bt->frame, env->tmp_str_buf);
4255 		bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
4256 		verbose(env, "stack=%s before ", env->tmp_str_buf);
4257 		verbose(env, "%d: ", idx);
4258 		verbose_insn(env, insn);
4259 	}
4260 
4261 	/* If there is a history record that some registers gained range at this insn,
4262 	 * propagate precision marks to those registers, so that bt_is_reg_set()
4263 	 * accounts for these registers.
4264 	 */
4265 	bt_sync_linked_regs(bt, hist);
4266 
4267 	if (class == BPF_ALU || class == BPF_ALU64) {
4268 		if (!bt_is_reg_set(bt, dreg))
4269 			return 0;
4270 		if (opcode == BPF_END || opcode == BPF_NEG) {
4271 			/* sreg is reserved and unused
4272 			 * dreg still need precision before this insn
4273 			 */
4274 			return 0;
4275 		} else if (opcode == BPF_MOV) {
4276 			if (BPF_SRC(insn->code) == BPF_X) {
4277 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
4278 				 * dreg needs precision after this insn
4279 				 * sreg needs precision before this insn
4280 				 */
4281 				bt_clear_reg(bt, dreg);
4282 				if (sreg != BPF_REG_FP)
4283 					bt_set_reg(bt, sreg);
4284 			} else {
4285 				/* dreg = K
4286 				 * dreg needs precision after this insn.
4287 				 * Corresponding register is already marked
4288 				 * as precise=true in this verifier state.
4289 				 * No further markings in parent are necessary
4290 				 */
4291 				bt_clear_reg(bt, dreg);
4292 			}
4293 		} else {
4294 			if (BPF_SRC(insn->code) == BPF_X) {
4295 				/* dreg += sreg
4296 				 * both dreg and sreg need precision
4297 				 * before this insn
4298 				 */
4299 				if (sreg != BPF_REG_FP)
4300 					bt_set_reg(bt, sreg);
4301 			} /* else dreg += K
4302 			   * dreg still needs precision before this insn
4303 			   */
4304 		}
4305 	} else if (class == BPF_LDX || is_atomic_load_insn(insn)) {
4306 		if (!bt_is_reg_set(bt, dreg))
4307 			return 0;
4308 		bt_clear_reg(bt, dreg);
4309 
4310 		/* scalars can only be spilled into stack w/o losing precision.
4311 		 * Load from any other memory can be zero extended.
4312 		 * The desire to keep that precision is already indicated
4313 		 * by 'precise' mark in corresponding register of this state.
4314 		 * No further tracking necessary.
4315 		 */
4316 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4317 			return 0;
4318 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
4319 		 * that [fp - off] slot contains scalar that needs to be
4320 		 * tracked with precision
4321 		 */
4322 		spi = insn_stack_access_spi(hist->flags);
4323 		fr = insn_stack_access_frameno(hist->flags);
4324 		bt_set_frame_slot(bt, fr, spi);
4325 	} else if (class == BPF_STX || class == BPF_ST) {
4326 		if (bt_is_reg_set(bt, dreg))
4327 			/* stx & st shouldn't be using _scalar_ dst_reg
4328 			 * to access memory. It means backtracking
4329 			 * encountered a case of pointer subtraction.
4330 			 */
4331 			return -ENOTSUPP;
4332 		/* scalars can only be spilled into stack */
4333 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4334 			return 0;
4335 		spi = insn_stack_access_spi(hist->flags);
4336 		fr = insn_stack_access_frameno(hist->flags);
4337 		if (!bt_is_frame_slot_set(bt, fr, spi))
4338 			return 0;
4339 		bt_clear_frame_slot(bt, fr, spi);
4340 		if (class == BPF_STX)
4341 			bt_set_reg(bt, sreg);
4342 	} else if (class == BPF_JMP || class == BPF_JMP32) {
4343 		if (bpf_pseudo_call(insn)) {
4344 			int subprog_insn_idx, subprog;
4345 
4346 			subprog_insn_idx = idx + insn->imm + 1;
4347 			subprog = find_subprog(env, subprog_insn_idx);
4348 			if (subprog < 0)
4349 				return -EFAULT;
4350 
4351 			if (subprog_is_global(env, subprog)) {
4352 				/* check that jump history doesn't have any
4353 				 * extra instructions from subprog; the next
4354 				 * instruction after call to global subprog
4355 				 * should be literally next instruction in
4356 				 * caller program
4357 				 */
4358 				verifier_bug_if(idx + 1 != subseq_idx, env,
4359 						"extra insn from subprog");
4360 				/* r1-r5 are invalidated after subprog call,
4361 				 * so for global func call it shouldn't be set
4362 				 * anymore
4363 				 */
4364 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4365 					verifier_bug(env, "global subprog unexpected regs %x",
4366 						     bt_reg_mask(bt));
4367 					return -EFAULT;
4368 				}
4369 				/* global subprog always sets R0 */
4370 				bt_clear_reg(bt, BPF_REG_0);
4371 				return 0;
4372 			} else {
4373 				/* static subprog call instruction, which
4374 				 * means that we are exiting current subprog,
4375 				 * so only r1-r5 could be still requested as
4376 				 * precise, r0 and r6-r10 or any stack slot in
4377 				 * the current frame should be zero by now
4378 				 */
4379 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4380 					verifier_bug(env, "static subprog unexpected regs %x",
4381 						     bt_reg_mask(bt));
4382 					return -EFAULT;
4383 				}
4384 				/* we are now tracking register spills correctly,
4385 				 * so any instance of leftover slots is a bug
4386 				 */
4387 				if (bt_stack_mask(bt) != 0) {
4388 					verifier_bug(env,
4389 						     "static subprog leftover stack slots %llx",
4390 						     bt_stack_mask(bt));
4391 					return -EFAULT;
4392 				}
4393 				/* propagate r1-r5 to the caller */
4394 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
4395 					if (bt_is_reg_set(bt, i)) {
4396 						bt_clear_reg(bt, i);
4397 						bt_set_frame_reg(bt, bt->frame - 1, i);
4398 					}
4399 				}
4400 				if (bt_subprog_exit(bt))
4401 					return -EFAULT;
4402 				return 0;
4403 			}
4404 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
4405 			/* exit from callback subprog to callback-calling helper or
4406 			 * kfunc call. Use idx/subseq_idx check to discern it from
4407 			 * straight line code backtracking.
4408 			 * Unlike the subprog call handling above, we shouldn't
4409 			 * propagate precision of r1-r5 (if any requested), as they are
4410 			 * not actually arguments passed directly to callback subprogs
4411 			 */
4412 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4413 				verifier_bug(env, "callback unexpected regs %x",
4414 					     bt_reg_mask(bt));
4415 				return -EFAULT;
4416 			}
4417 			if (bt_stack_mask(bt) != 0) {
4418 				verifier_bug(env, "callback leftover stack slots %llx",
4419 					     bt_stack_mask(bt));
4420 				return -EFAULT;
4421 			}
4422 			/* clear r1-r5 in callback subprog's mask */
4423 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4424 				bt_clear_reg(bt, i);
4425 			if (bt_subprog_exit(bt))
4426 				return -EFAULT;
4427 			return 0;
4428 		} else if (opcode == BPF_CALL) {
4429 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
4430 			 * catch this error later. Make backtracking conservative
4431 			 * with ENOTSUPP.
4432 			 */
4433 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
4434 				return -ENOTSUPP;
4435 			/* regular helper call sets R0 */
4436 			bt_clear_reg(bt, BPF_REG_0);
4437 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4438 				/* if backtracking was looking for registers R1-R5
4439 				 * they should have been found already.
4440 				 */
4441 				verifier_bug(env, "backtracking call unexpected regs %x",
4442 					     bt_reg_mask(bt));
4443 				return -EFAULT;
4444 			}
4445 			if (insn->src_reg == BPF_REG_0 && insn->imm == BPF_FUNC_tail_call
4446 			    && subseq_idx - idx != 1) {
4447 				if (bt_subprog_enter(bt))
4448 					return -EFAULT;
4449 			}
4450 		} else if (opcode == BPF_EXIT) {
4451 			bool r0_precise;
4452 
4453 			/* Backtracking to a nested function call, 'idx' is a part of
4454 			 * the inner frame 'subseq_idx' is a part of the outer frame.
4455 			 * In case of a regular function call, instructions giving
4456 			 * precision to registers R1-R5 should have been found already.
4457 			 * In case of a callback, it is ok to have R1-R5 marked for
4458 			 * backtracking, as these registers are set by the function
4459 			 * invoking callback.
4460 			 */
4461 			if (subseq_idx >= 0 && bpf_calls_callback(env, subseq_idx))
4462 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4463 					bt_clear_reg(bt, i);
4464 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4465 				verifier_bug(env, "backtracking exit unexpected regs %x",
4466 					     bt_reg_mask(bt));
4467 				return -EFAULT;
4468 			}
4469 
4470 			/* BPF_EXIT in subprog or callback always returns
4471 			 * right after the call instruction, so by checking
4472 			 * whether the instruction at subseq_idx-1 is subprog
4473 			 * call or not we can distinguish actual exit from
4474 			 * *subprog* from exit from *callback*. In the former
4475 			 * case, we need to propagate r0 precision, if
4476 			 * necessary. In the former we never do that.
4477 			 */
4478 			r0_precise = subseq_idx - 1 >= 0 &&
4479 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4480 				     bt_is_reg_set(bt, BPF_REG_0);
4481 
4482 			bt_clear_reg(bt, BPF_REG_0);
4483 			if (bt_subprog_enter(bt))
4484 				return -EFAULT;
4485 
4486 			if (r0_precise)
4487 				bt_set_reg(bt, BPF_REG_0);
4488 			/* r6-r9 and stack slots will stay set in caller frame
4489 			 * bitmasks until we return back from callee(s)
4490 			 */
4491 			return 0;
4492 		} else if (BPF_SRC(insn->code) == BPF_X) {
4493 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4494 				return 0;
4495 			/* dreg <cond> sreg
4496 			 * Both dreg and sreg need precision before
4497 			 * this insn. If only sreg was marked precise
4498 			 * before it would be equally necessary to
4499 			 * propagate it to dreg.
4500 			 */
4501 			if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK))
4502 				bt_set_reg(bt, sreg);
4503 			if (!hist || !(hist->flags & INSN_F_DST_REG_STACK))
4504 				bt_set_reg(bt, dreg);
4505 		} else if (BPF_SRC(insn->code) == BPF_K) {
4506 			 /* dreg <cond> K
4507 			  * Only dreg still needs precision before
4508 			  * this insn, so for the K-based conditional
4509 			  * there is nothing new to be marked.
4510 			  */
4511 		}
4512 	} else if (class == BPF_LD) {
4513 		if (!bt_is_reg_set(bt, dreg))
4514 			return 0;
4515 		bt_clear_reg(bt, dreg);
4516 		/* It's ld_imm64 or ld_abs or ld_ind.
4517 		 * For ld_imm64 no further tracking of precision
4518 		 * into parent is necessary
4519 		 */
4520 		if (mode == BPF_IND || mode == BPF_ABS)
4521 			/* to be analyzed */
4522 			return -ENOTSUPP;
4523 	}
4524 	/* Propagate precision marks to linked registers, to account for
4525 	 * registers marked as precise in this function.
4526 	 */
4527 	bt_sync_linked_regs(bt, hist);
4528 	return 0;
4529 }
4530 
4531 /* the scalar precision tracking algorithm:
4532  * . at the start all registers have precise=false.
4533  * . scalar ranges are tracked as normal through alu and jmp insns.
4534  * . once precise value of the scalar register is used in:
4535  *   .  ptr + scalar alu
4536  *   . if (scalar cond K|scalar)
4537  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
4538  *   backtrack through the verifier states and mark all registers and
4539  *   stack slots with spilled constants that these scalar registers
4540  *   should be precise.
4541  * . during state pruning two registers (or spilled stack slots)
4542  *   are equivalent if both are not precise.
4543  *
4544  * Note the verifier cannot simply walk register parentage chain,
4545  * since many different registers and stack slots could have been
4546  * used to compute single precise scalar.
4547  *
4548  * The approach of starting with precise=true for all registers and then
4549  * backtrack to mark a register as not precise when the verifier detects
4550  * that program doesn't care about specific value (e.g., when helper
4551  * takes register as ARG_ANYTHING parameter) is not safe.
4552  *
4553  * It's ok to walk single parentage chain of the verifier states.
4554  * It's possible that this backtracking will go all the way till 1st insn.
4555  * All other branches will be explored for needing precision later.
4556  *
4557  * The backtracking needs to deal with cases like:
4558  *   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)
4559  * r9 -= r8
4560  * r5 = r9
4561  * if r5 > 0x79f goto pc+7
4562  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4563  * r5 += 1
4564  * ...
4565  * call bpf_perf_event_output#25
4566  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4567  *
4568  * and this case:
4569  * r6 = 1
4570  * call foo // uses callee's r6 inside to compute r0
4571  * r0 += r6
4572  * if r0 == 0 goto
4573  *
4574  * to track above reg_mask/stack_mask needs to be independent for each frame.
4575  *
4576  * Also if parent's curframe > frame where backtracking started,
4577  * the verifier need to mark registers in both frames, otherwise callees
4578  * may incorrectly prune callers. This is similar to
4579  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4580  *
4581  * For now backtracking falls back into conservative marking.
4582  */
4583 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4584 				     struct bpf_verifier_state *st)
4585 {
4586 	struct bpf_func_state *func;
4587 	struct bpf_reg_state *reg;
4588 	int i, j;
4589 
4590 	if (env->log.level & BPF_LOG_LEVEL2) {
4591 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4592 			st->curframe);
4593 	}
4594 
4595 	/* big hammer: mark all scalars precise in this path.
4596 	 * pop_stack may still get !precise scalars.
4597 	 * We also skip current state and go straight to first parent state,
4598 	 * because precision markings in current non-checkpointed state are
4599 	 * not needed. See why in the comment in __mark_chain_precision below.
4600 	 */
4601 	for (st = st->parent; st; st = st->parent) {
4602 		for (i = 0; i <= st->curframe; i++) {
4603 			func = st->frame[i];
4604 			for (j = 0; j < BPF_REG_FP; j++) {
4605 				reg = &func->regs[j];
4606 				if (reg->type != SCALAR_VALUE || reg->precise)
4607 					continue;
4608 				reg->precise = true;
4609 				if (env->log.level & BPF_LOG_LEVEL2) {
4610 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4611 						i, j);
4612 				}
4613 			}
4614 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4615 				if (!is_spilled_reg(&func->stack[j]))
4616 					continue;
4617 				reg = &func->stack[j].spilled_ptr;
4618 				if (reg->type != SCALAR_VALUE || reg->precise)
4619 					continue;
4620 				reg->precise = true;
4621 				if (env->log.level & BPF_LOG_LEVEL2) {
4622 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4623 						i, -(j + 1) * 8);
4624 				}
4625 			}
4626 		}
4627 	}
4628 }
4629 
4630 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4631 {
4632 	struct bpf_func_state *func;
4633 	struct bpf_reg_state *reg;
4634 	int i, j;
4635 
4636 	for (i = 0; i <= st->curframe; i++) {
4637 		func = st->frame[i];
4638 		for (j = 0; j < BPF_REG_FP; j++) {
4639 			reg = &func->regs[j];
4640 			if (reg->type != SCALAR_VALUE)
4641 				continue;
4642 			reg->precise = false;
4643 		}
4644 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4645 			if (!is_spilled_reg(&func->stack[j]))
4646 				continue;
4647 			reg = &func->stack[j].spilled_ptr;
4648 			if (reg->type != SCALAR_VALUE)
4649 				continue;
4650 			reg->precise = false;
4651 		}
4652 	}
4653 }
4654 
4655 /*
4656  * __mark_chain_precision() backtracks BPF program instruction sequence and
4657  * chain of verifier states making sure that register *regno* (if regno >= 0)
4658  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4659  * SCALARS, as well as any other registers and slots that contribute to
4660  * a tracked state of given registers/stack slots, depending on specific BPF
4661  * assembly instructions (see backtrack_insns() for exact instruction handling
4662  * logic). This backtracking relies on recorded jmp_history and is able to
4663  * traverse entire chain of parent states. This process ends only when all the
4664  * necessary registers/slots and their transitive dependencies are marked as
4665  * precise.
4666  *
4667  * One important and subtle aspect is that precise marks *do not matter* in
4668  * the currently verified state (current state). It is important to understand
4669  * why this is the case.
4670  *
4671  * First, note that current state is the state that is not yet "checkpointed",
4672  * i.e., it is not yet put into env->explored_states, and it has no children
4673  * states as well. It's ephemeral, and can end up either a) being discarded if
4674  * compatible explored state is found at some point or BPF_EXIT instruction is
4675  * reached or b) checkpointed and put into env->explored_states, branching out
4676  * into one or more children states.
4677  *
4678  * In the former case, precise markings in current state are completely
4679  * ignored by state comparison code (see regsafe() for details). Only
4680  * checkpointed ("old") state precise markings are important, and if old
4681  * state's register/slot is precise, regsafe() assumes current state's
4682  * register/slot as precise and checks value ranges exactly and precisely. If
4683  * states turn out to be compatible, current state's necessary precise
4684  * markings and any required parent states' precise markings are enforced
4685  * after the fact with propagate_precision() logic, after the fact. But it's
4686  * important to realize that in this case, even after marking current state
4687  * registers/slots as precise, we immediately discard current state. So what
4688  * actually matters is any of the precise markings propagated into current
4689  * state's parent states, which are always checkpointed (due to b) case above).
4690  * As such, for scenario a) it doesn't matter if current state has precise
4691  * markings set or not.
4692  *
4693  * Now, for the scenario b), checkpointing and forking into child(ren)
4694  * state(s). Note that before current state gets to checkpointing step, any
4695  * processed instruction always assumes precise SCALAR register/slot
4696  * knowledge: if precise value or range is useful to prune jump branch, BPF
4697  * verifier takes this opportunity enthusiastically. Similarly, when
4698  * register's value is used to calculate offset or memory address, exact
4699  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4700  * what we mentioned above about state comparison ignoring precise markings
4701  * during state comparison, BPF verifier ignores and also assumes precise
4702  * markings *at will* during instruction verification process. But as verifier
4703  * assumes precision, it also propagates any precision dependencies across
4704  * parent states, which are not yet finalized, so can be further restricted
4705  * based on new knowledge gained from restrictions enforced by their children
4706  * states. This is so that once those parent states are finalized, i.e., when
4707  * they have no more active children state, state comparison logic in
4708  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4709  * required for correctness.
4710  *
4711  * To build a bit more intuition, note also that once a state is checkpointed,
4712  * the path we took to get to that state is not important. This is crucial
4713  * property for state pruning. When state is checkpointed and finalized at
4714  * some instruction index, it can be correctly and safely used to "short
4715  * circuit" any *compatible* state that reaches exactly the same instruction
4716  * index. I.e., if we jumped to that instruction from a completely different
4717  * code path than original finalized state was derived from, it doesn't
4718  * matter, current state can be discarded because from that instruction
4719  * forward having a compatible state will ensure we will safely reach the
4720  * exit. States describe preconditions for further exploration, but completely
4721  * forget the history of how we got here.
4722  *
4723  * This also means that even if we needed precise SCALAR range to get to
4724  * finalized state, but from that point forward *that same* SCALAR register is
4725  * never used in a precise context (i.e., it's precise value is not needed for
4726  * correctness), it's correct and safe to mark such register as "imprecise"
4727  * (i.e., precise marking set to false). This is what we rely on when we do
4728  * not set precise marking in current state. If no child state requires
4729  * precision for any given SCALAR register, it's safe to dictate that it can
4730  * be imprecise. If any child state does require this register to be precise,
4731  * we'll mark it precise later retroactively during precise markings
4732  * propagation from child state to parent states.
4733  *
4734  * Skipping precise marking setting in current state is a mild version of
4735  * relying on the above observation. But we can utilize this property even
4736  * more aggressively by proactively forgetting any precise marking in the
4737  * current state (which we inherited from the parent state), right before we
4738  * checkpoint it and branch off into new child state. This is done by
4739  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4740  * finalized states which help in short circuiting more future states.
4741  */
4742 static int __mark_chain_precision(struct bpf_verifier_env *env,
4743 				  struct bpf_verifier_state *starting_state,
4744 				  int regno,
4745 				  bool *changed)
4746 {
4747 	struct bpf_verifier_state *st = starting_state;
4748 	struct backtrack_state *bt = &env->bt;
4749 	int first_idx = st->first_insn_idx;
4750 	int last_idx = starting_state->insn_idx;
4751 	int subseq_idx = -1;
4752 	struct bpf_func_state *func;
4753 	bool tmp, skip_first = true;
4754 	struct bpf_reg_state *reg;
4755 	int i, fr, err;
4756 
4757 	if (!env->bpf_capable)
4758 		return 0;
4759 
4760 	changed = changed ?: &tmp;
4761 	/* set frame number from which we are starting to backtrack */
4762 	bt_init(bt, starting_state->curframe);
4763 
4764 	/* Do sanity checks against current state of register and/or stack
4765 	 * slot, but don't set precise flag in current state, as precision
4766 	 * tracking in the current state is unnecessary.
4767 	 */
4768 	func = st->frame[bt->frame];
4769 	if (regno >= 0) {
4770 		reg = &func->regs[regno];
4771 		if (reg->type != SCALAR_VALUE) {
4772 			verifier_bug(env, "backtracking misuse");
4773 			return -EFAULT;
4774 		}
4775 		bt_set_reg(bt, regno);
4776 	}
4777 
4778 	if (bt_empty(bt))
4779 		return 0;
4780 
4781 	for (;;) {
4782 		DECLARE_BITMAP(mask, 64);
4783 		u32 history = st->jmp_history_cnt;
4784 		struct bpf_jmp_history_entry *hist;
4785 
4786 		if (env->log.level & BPF_LOG_LEVEL2) {
4787 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4788 				bt->frame, last_idx, first_idx, subseq_idx);
4789 		}
4790 
4791 		if (last_idx < 0) {
4792 			/* we are at the entry into subprog, which
4793 			 * is expected for global funcs, but only if
4794 			 * requested precise registers are R1-R5
4795 			 * (which are global func's input arguments)
4796 			 */
4797 			if (st->curframe == 0 &&
4798 			    st->frame[0]->subprogno > 0 &&
4799 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4800 			    bt_stack_mask(bt) == 0 &&
4801 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4802 				bitmap_from_u64(mask, bt_reg_mask(bt));
4803 				for_each_set_bit(i, mask, 32) {
4804 					reg = &st->frame[0]->regs[i];
4805 					bt_clear_reg(bt, i);
4806 					if (reg->type == SCALAR_VALUE) {
4807 						reg->precise = true;
4808 						*changed = true;
4809 					}
4810 				}
4811 				return 0;
4812 			}
4813 
4814 			verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %llx",
4815 				     st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4816 			return -EFAULT;
4817 		}
4818 
4819 		for (i = last_idx;;) {
4820 			if (skip_first) {
4821 				err = 0;
4822 				skip_first = false;
4823 			} else {
4824 				hist = get_jmp_hist_entry(st, history, i);
4825 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4826 			}
4827 			if (err == -ENOTSUPP) {
4828 				mark_all_scalars_precise(env, starting_state);
4829 				bt_reset(bt);
4830 				return 0;
4831 			} else if (err) {
4832 				return err;
4833 			}
4834 			if (bt_empty(bt))
4835 				/* Found assignment(s) into tracked register in this state.
4836 				 * Since this state is already marked, just return.
4837 				 * Nothing to be tracked further in the parent state.
4838 				 */
4839 				return 0;
4840 			subseq_idx = i;
4841 			i = get_prev_insn_idx(st, i, &history);
4842 			if (i == -ENOENT)
4843 				break;
4844 			if (i >= env->prog->len) {
4845 				/* This can happen if backtracking reached insn 0
4846 				 * and there are still reg_mask or stack_mask
4847 				 * to backtrack.
4848 				 * It means the backtracking missed the spot where
4849 				 * particular register was initialized with a constant.
4850 				 */
4851 				verifier_bug(env, "backtracking idx %d", i);
4852 				return -EFAULT;
4853 			}
4854 		}
4855 		st = st->parent;
4856 		if (!st)
4857 			break;
4858 
4859 		for (fr = bt->frame; fr >= 0; fr--) {
4860 			func = st->frame[fr];
4861 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4862 			for_each_set_bit(i, mask, 32) {
4863 				reg = &func->regs[i];
4864 				if (reg->type != SCALAR_VALUE) {
4865 					bt_clear_frame_reg(bt, fr, i);
4866 					continue;
4867 				}
4868 				if (reg->precise) {
4869 					bt_clear_frame_reg(bt, fr, i);
4870 				} else {
4871 					reg->precise = true;
4872 					*changed = true;
4873 				}
4874 			}
4875 
4876 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4877 			for_each_set_bit(i, mask, 64) {
4878 				if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE,
4879 						    env, "stack slot %d, total slots %d",
4880 						    i, func->allocated_stack / BPF_REG_SIZE))
4881 					return -EFAULT;
4882 
4883 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4884 					bt_clear_frame_slot(bt, fr, i);
4885 					continue;
4886 				}
4887 				reg = &func->stack[i].spilled_ptr;
4888 				if (reg->precise) {
4889 					bt_clear_frame_slot(bt, fr, i);
4890 				} else {
4891 					reg->precise = true;
4892 					*changed = true;
4893 				}
4894 			}
4895 			if (env->log.level & BPF_LOG_LEVEL2) {
4896 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4897 					     bt_frame_reg_mask(bt, fr));
4898 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4899 					fr, env->tmp_str_buf);
4900 				bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4901 					       bt_frame_stack_mask(bt, fr));
4902 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4903 				print_verifier_state(env, st, fr, true);
4904 			}
4905 		}
4906 
4907 		if (bt_empty(bt))
4908 			return 0;
4909 
4910 		subseq_idx = first_idx;
4911 		last_idx = st->last_insn_idx;
4912 		first_idx = st->first_insn_idx;
4913 	}
4914 
4915 	/* if we still have requested precise regs or slots, we missed
4916 	 * something (e.g., stack access through non-r10 register), so
4917 	 * fallback to marking all precise
4918 	 */
4919 	if (!bt_empty(bt)) {
4920 		mark_all_scalars_precise(env, starting_state);
4921 		bt_reset(bt);
4922 	}
4923 
4924 	return 0;
4925 }
4926 
4927 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4928 {
4929 	return __mark_chain_precision(env, env->cur_state, regno, NULL);
4930 }
4931 
4932 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4933  * desired reg and stack masks across all relevant frames
4934  */
4935 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
4936 				      struct bpf_verifier_state *starting_state)
4937 {
4938 	return __mark_chain_precision(env, starting_state, -1, NULL);
4939 }
4940 
4941 static bool is_spillable_regtype(enum bpf_reg_type type)
4942 {
4943 	switch (base_type(type)) {
4944 	case PTR_TO_MAP_VALUE:
4945 	case PTR_TO_STACK:
4946 	case PTR_TO_CTX:
4947 	case PTR_TO_PACKET:
4948 	case PTR_TO_PACKET_META:
4949 	case PTR_TO_PACKET_END:
4950 	case PTR_TO_FLOW_KEYS:
4951 	case CONST_PTR_TO_MAP:
4952 	case PTR_TO_SOCKET:
4953 	case PTR_TO_SOCK_COMMON:
4954 	case PTR_TO_TCP_SOCK:
4955 	case PTR_TO_XDP_SOCK:
4956 	case PTR_TO_BTF_ID:
4957 	case PTR_TO_BUF:
4958 	case PTR_TO_MEM:
4959 	case PTR_TO_FUNC:
4960 	case PTR_TO_MAP_KEY:
4961 	case PTR_TO_ARENA:
4962 		return true;
4963 	default:
4964 		return false;
4965 	}
4966 }
4967 
4968 /* Does this register contain a constant zero? */
4969 static bool register_is_null(struct bpf_reg_state *reg)
4970 {
4971 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4972 }
4973 
4974 /* check if register is a constant scalar value */
4975 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4976 {
4977 	return reg->type == SCALAR_VALUE &&
4978 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4979 }
4980 
4981 /* assuming is_reg_const() is true, return constant value of a register */
4982 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4983 {
4984 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4985 }
4986 
4987 static bool __is_pointer_value(bool allow_ptr_leaks,
4988 			       const struct bpf_reg_state *reg)
4989 {
4990 	if (allow_ptr_leaks)
4991 		return false;
4992 
4993 	return reg->type != SCALAR_VALUE;
4994 }
4995 
4996 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4997 					struct bpf_reg_state *src_reg)
4998 {
4999 	if (src_reg->type != SCALAR_VALUE)
5000 		return;
5001 
5002 	if (src_reg->id & BPF_ADD_CONST) {
5003 		/*
5004 		 * The verifier is processing rX = rY insn and
5005 		 * rY->id has special linked register already.
5006 		 * Cleared it, since multiple rX += const are not supported.
5007 		 */
5008 		src_reg->id = 0;
5009 		src_reg->off = 0;
5010 	}
5011 
5012 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
5013 		/* Ensure that src_reg has a valid ID that will be copied to
5014 		 * dst_reg and then will be used by sync_linked_regs() to
5015 		 * propagate min/max range.
5016 		 */
5017 		src_reg->id = ++env->id_gen;
5018 }
5019 
5020 /* Copy src state preserving dst->parent and dst->live fields */
5021 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
5022 {
5023 	*dst = *src;
5024 }
5025 
5026 static void save_register_state(struct bpf_verifier_env *env,
5027 				struct bpf_func_state *state,
5028 				int spi, struct bpf_reg_state *reg,
5029 				int size)
5030 {
5031 	int i;
5032 
5033 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
5034 
5035 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
5036 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
5037 
5038 	/* size < 8 bytes spill */
5039 	for (; i; i--)
5040 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
5041 }
5042 
5043 static bool is_bpf_st_mem(struct bpf_insn *insn)
5044 {
5045 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
5046 }
5047 
5048 static int get_reg_width(struct bpf_reg_state *reg)
5049 {
5050 	return fls64(reg->umax_value);
5051 }
5052 
5053 /* See comment for mark_fastcall_pattern_for_call() */
5054 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
5055 					  struct bpf_func_state *state, int insn_idx, int off)
5056 {
5057 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
5058 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
5059 	int i;
5060 
5061 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
5062 		return;
5063 	/* access to the region [max_stack_depth .. fastcall_stack_off)
5064 	 * from something that is not a part of the fastcall pattern,
5065 	 * disable fastcall rewrites for current subprogram by setting
5066 	 * fastcall_stack_off to a value smaller than any possible offset.
5067 	 */
5068 	subprog->fastcall_stack_off = S16_MIN;
5069 	/* reset fastcall aux flags within subprogram,
5070 	 * happens at most once per subprogram
5071 	 */
5072 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
5073 		aux[i].fastcall_spills_num = 0;
5074 		aux[i].fastcall_pattern = 0;
5075 	}
5076 }
5077 
5078 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
5079  * stack boundary and alignment are checked in check_mem_access()
5080  */
5081 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
5082 				       /* stack frame we're writing to */
5083 				       struct bpf_func_state *state,
5084 				       int off, int size, int value_regno,
5085 				       int insn_idx)
5086 {
5087 	struct bpf_func_state *cur; /* state of the current function */
5088 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
5089 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5090 	struct bpf_reg_state *reg = NULL;
5091 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
5092 
5093 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
5094 	 * so it's aligned access and [off, off + size) are within stack limits
5095 	 */
5096 	if (!env->allow_ptr_leaks &&
5097 	    is_spilled_reg(&state->stack[spi]) &&
5098 	    !is_spilled_scalar_reg(&state->stack[spi]) &&
5099 	    size != BPF_REG_SIZE) {
5100 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
5101 		return -EACCES;
5102 	}
5103 
5104 	cur = env->cur_state->frame[env->cur_state->curframe];
5105 	if (value_regno >= 0)
5106 		reg = &cur->regs[value_regno];
5107 	if (!env->bypass_spec_v4) {
5108 		bool sanitize = reg && is_spillable_regtype(reg->type);
5109 
5110 		for (i = 0; i < size; i++) {
5111 			u8 type = state->stack[spi].slot_type[i];
5112 
5113 			if (type != STACK_MISC && type != STACK_ZERO) {
5114 				sanitize = true;
5115 				break;
5116 			}
5117 		}
5118 
5119 		if (sanitize)
5120 			env->insn_aux_data[insn_idx].nospec_result = true;
5121 	}
5122 
5123 	err = destroy_if_dynptr_stack_slot(env, state, spi);
5124 	if (err)
5125 		return err;
5126 
5127 	if (!(off % BPF_REG_SIZE) && size == BPF_REG_SIZE) {
5128 		/* only mark the slot as written if all 8 bytes were written
5129 		 * otherwise read propagation may incorrectly stop too soon
5130 		 * when stack slots are partially written.
5131 		 * This heuristic means that read propagation will be
5132 		 * conservative, since it will add reg_live_read marks
5133 		 * to stack slots all the way to first state when programs
5134 		 * writes+reads less than 8 bytes
5135 		 */
5136 		bpf_mark_stack_write(env, state->frameno, BIT(spi));
5137 	}
5138 
5139 	check_fastcall_stack_contract(env, state, insn_idx, off);
5140 	mark_stack_slot_scratched(env, spi);
5141 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
5142 		bool reg_value_fits;
5143 
5144 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
5145 		/* Make sure that reg had an ID to build a relation on spill. */
5146 		if (reg_value_fits)
5147 			assign_scalar_id_before_mov(env, reg);
5148 		save_register_state(env, state, spi, reg, size);
5149 		/* Break the relation on a narrowing spill. */
5150 		if (!reg_value_fits)
5151 			state->stack[spi].spilled_ptr.id = 0;
5152 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
5153 		   env->bpf_capable) {
5154 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
5155 
5156 		memset(tmp_reg, 0, sizeof(*tmp_reg));
5157 		__mark_reg_known(tmp_reg, insn->imm);
5158 		tmp_reg->type = SCALAR_VALUE;
5159 		save_register_state(env, state, spi, tmp_reg, size);
5160 	} else if (reg && is_spillable_regtype(reg->type)) {
5161 		/* register containing pointer is being spilled into stack */
5162 		if (size != BPF_REG_SIZE) {
5163 			verbose_linfo(env, insn_idx, "; ");
5164 			verbose(env, "invalid size of register spill\n");
5165 			return -EACCES;
5166 		}
5167 		if (state != cur && reg->type == PTR_TO_STACK) {
5168 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
5169 			return -EINVAL;
5170 		}
5171 		save_register_state(env, state, spi, reg, size);
5172 	} else {
5173 		u8 type = STACK_MISC;
5174 
5175 		/* regular write of data into stack destroys any spilled ptr */
5176 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5177 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
5178 		if (is_stack_slot_special(&state->stack[spi]))
5179 			for (i = 0; i < BPF_REG_SIZE; i++)
5180 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
5181 
5182 		/* when we zero initialize stack slots mark them as such */
5183 		if ((reg && register_is_null(reg)) ||
5184 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
5185 			/* STACK_ZERO case happened because register spill
5186 			 * wasn't properly aligned at the stack slot boundary,
5187 			 * so it's not a register spill anymore; force
5188 			 * originating register to be precise to make
5189 			 * STACK_ZERO correct for subsequent states
5190 			 */
5191 			err = mark_chain_precision(env, value_regno);
5192 			if (err)
5193 				return err;
5194 			type = STACK_ZERO;
5195 		}
5196 
5197 		/* Mark slots affected by this stack write. */
5198 		for (i = 0; i < size; i++)
5199 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
5200 		insn_flags = 0; /* not a register spill */
5201 	}
5202 
5203 	if (insn_flags)
5204 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5205 	return 0;
5206 }
5207 
5208 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
5209  * known to contain a variable offset.
5210  * This function checks whether the write is permitted and conservatively
5211  * tracks the effects of the write, considering that each stack slot in the
5212  * dynamic range is potentially written to.
5213  *
5214  * 'off' includes 'regno->off'.
5215  * 'value_regno' can be -1, meaning that an unknown value is being written to
5216  * the stack.
5217  *
5218  * Spilled pointers in range are not marked as written because we don't know
5219  * what's going to be actually written. This means that read propagation for
5220  * future reads cannot be terminated by this write.
5221  *
5222  * For privileged programs, uninitialized stack slots are considered
5223  * initialized by this write (even though we don't know exactly what offsets
5224  * are going to be written to). The idea is that we don't want the verifier to
5225  * reject future reads that access slots written to through variable offsets.
5226  */
5227 static int check_stack_write_var_off(struct bpf_verifier_env *env,
5228 				     /* func where register points to */
5229 				     struct bpf_func_state *state,
5230 				     int ptr_regno, int off, int size,
5231 				     int value_regno, int insn_idx)
5232 {
5233 	struct bpf_func_state *cur; /* state of the current function */
5234 	int min_off, max_off;
5235 	int i, err;
5236 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
5237 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5238 	bool writing_zero = false;
5239 	/* set if the fact that we're writing a zero is used to let any
5240 	 * stack slots remain STACK_ZERO
5241 	 */
5242 	bool zero_used = false;
5243 
5244 	cur = env->cur_state->frame[env->cur_state->curframe];
5245 	ptr_reg = &cur->regs[ptr_regno];
5246 	min_off = ptr_reg->smin_value + off;
5247 	max_off = ptr_reg->smax_value + off + size;
5248 	if (value_regno >= 0)
5249 		value_reg = &cur->regs[value_regno];
5250 	if ((value_reg && register_is_null(value_reg)) ||
5251 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
5252 		writing_zero = true;
5253 
5254 	for (i = min_off; i < max_off; i++) {
5255 		int spi;
5256 
5257 		spi = __get_spi(i);
5258 		err = destroy_if_dynptr_stack_slot(env, state, spi);
5259 		if (err)
5260 			return err;
5261 	}
5262 
5263 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
5264 	/* Variable offset writes destroy any spilled pointers in range. */
5265 	for (i = min_off; i < max_off; i++) {
5266 		u8 new_type, *stype;
5267 		int slot, spi;
5268 
5269 		slot = -i - 1;
5270 		spi = slot / BPF_REG_SIZE;
5271 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5272 		mark_stack_slot_scratched(env, spi);
5273 
5274 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
5275 			/* Reject the write if range we may write to has not
5276 			 * been initialized beforehand. If we didn't reject
5277 			 * here, the ptr status would be erased below (even
5278 			 * though not all slots are actually overwritten),
5279 			 * possibly opening the door to leaks.
5280 			 *
5281 			 * We do however catch STACK_INVALID case below, and
5282 			 * only allow reading possibly uninitialized memory
5283 			 * later for CAP_PERFMON, as the write may not happen to
5284 			 * that slot.
5285 			 */
5286 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
5287 				insn_idx, i);
5288 			return -EINVAL;
5289 		}
5290 
5291 		/* If writing_zero and the spi slot contains a spill of value 0,
5292 		 * maintain the spill type.
5293 		 */
5294 		if (writing_zero && *stype == STACK_SPILL &&
5295 		    is_spilled_scalar_reg(&state->stack[spi])) {
5296 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
5297 
5298 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
5299 				zero_used = true;
5300 				continue;
5301 			}
5302 		}
5303 
5304 		/* Erase all other spilled pointers. */
5305 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5306 
5307 		/* Update the slot type. */
5308 		new_type = STACK_MISC;
5309 		if (writing_zero && *stype == STACK_ZERO) {
5310 			new_type = STACK_ZERO;
5311 			zero_used = true;
5312 		}
5313 		/* If the slot is STACK_INVALID, we check whether it's OK to
5314 		 * pretend that it will be initialized by this write. The slot
5315 		 * might not actually be written to, and so if we mark it as
5316 		 * initialized future reads might leak uninitialized memory.
5317 		 * For privileged programs, we will accept such reads to slots
5318 		 * that may or may not be written because, if we're reject
5319 		 * them, the error would be too confusing.
5320 		 */
5321 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
5322 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
5323 					insn_idx, i);
5324 			return -EINVAL;
5325 		}
5326 		*stype = new_type;
5327 	}
5328 	if (zero_used) {
5329 		/* backtracking doesn't work for STACK_ZERO yet. */
5330 		err = mark_chain_precision(env, value_regno);
5331 		if (err)
5332 			return err;
5333 	}
5334 	return 0;
5335 }
5336 
5337 /* When register 'dst_regno' is assigned some values from stack[min_off,
5338  * max_off), we set the register's type according to the types of the
5339  * respective stack slots. If all the stack values are known to be zeros, then
5340  * so is the destination reg. Otherwise, the register is considered to be
5341  * SCALAR. This function does not deal with register filling; the caller must
5342  * ensure that all spilled registers in the stack range have been marked as
5343  * read.
5344  */
5345 static void mark_reg_stack_read(struct bpf_verifier_env *env,
5346 				/* func where src register points to */
5347 				struct bpf_func_state *ptr_state,
5348 				int min_off, int max_off, int dst_regno)
5349 {
5350 	struct bpf_verifier_state *vstate = env->cur_state;
5351 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5352 	int i, slot, spi;
5353 	u8 *stype;
5354 	int zeros = 0;
5355 
5356 	for (i = min_off; i < max_off; i++) {
5357 		slot = -i - 1;
5358 		spi = slot / BPF_REG_SIZE;
5359 		mark_stack_slot_scratched(env, spi);
5360 		stype = ptr_state->stack[spi].slot_type;
5361 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
5362 			break;
5363 		zeros++;
5364 	}
5365 	if (zeros == max_off - min_off) {
5366 		/* Any access_size read into register is zero extended,
5367 		 * so the whole register == const_zero.
5368 		 */
5369 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
5370 	} else {
5371 		/* have read misc data from the stack */
5372 		mark_reg_unknown(env, state->regs, dst_regno);
5373 	}
5374 }
5375 
5376 /* Read the stack at 'off' and put the results into the register indicated by
5377  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
5378  * spilled reg.
5379  *
5380  * 'dst_regno' can be -1, meaning that the read value is not going to a
5381  * register.
5382  *
5383  * The access is assumed to be within the current stack bounds.
5384  */
5385 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
5386 				      /* func where src register points to */
5387 				      struct bpf_func_state *reg_state,
5388 				      int off, int size, int dst_regno)
5389 {
5390 	struct bpf_verifier_state *vstate = env->cur_state;
5391 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5392 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
5393 	struct bpf_reg_state *reg;
5394 	u8 *stype, type;
5395 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
5396 	int err;
5397 
5398 	stype = reg_state->stack[spi].slot_type;
5399 	reg = &reg_state->stack[spi].spilled_ptr;
5400 
5401 	mark_stack_slot_scratched(env, spi);
5402 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
5403 	err = bpf_mark_stack_read(env, reg_state->frameno, env->insn_idx, BIT(spi));
5404 	if (err)
5405 		return err;
5406 
5407 	if (is_spilled_reg(&reg_state->stack[spi])) {
5408 		u8 spill_size = 1;
5409 
5410 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
5411 			spill_size++;
5412 
5413 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
5414 			if (reg->type != SCALAR_VALUE) {
5415 				verbose_linfo(env, env->insn_idx, "; ");
5416 				verbose(env, "invalid size of register fill\n");
5417 				return -EACCES;
5418 			}
5419 
5420 			if (dst_regno < 0)
5421 				return 0;
5422 
5423 			if (size <= spill_size &&
5424 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
5425 				/* The earlier check_reg_arg() has decided the
5426 				 * subreg_def for this insn.  Save it first.
5427 				 */
5428 				s32 subreg_def = state->regs[dst_regno].subreg_def;
5429 
5430 				copy_register_state(&state->regs[dst_regno], reg);
5431 				state->regs[dst_regno].subreg_def = subreg_def;
5432 
5433 				/* Break the relation on a narrowing fill.
5434 				 * coerce_reg_to_size will adjust the boundaries.
5435 				 */
5436 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
5437 					state->regs[dst_regno].id = 0;
5438 			} else {
5439 				int spill_cnt = 0, zero_cnt = 0;
5440 
5441 				for (i = 0; i < size; i++) {
5442 					type = stype[(slot - i) % BPF_REG_SIZE];
5443 					if (type == STACK_SPILL) {
5444 						spill_cnt++;
5445 						continue;
5446 					}
5447 					if (type == STACK_MISC)
5448 						continue;
5449 					if (type == STACK_ZERO) {
5450 						zero_cnt++;
5451 						continue;
5452 					}
5453 					if (type == STACK_INVALID && env->allow_uninit_stack)
5454 						continue;
5455 					verbose(env, "invalid read from stack off %d+%d size %d\n",
5456 						off, i, size);
5457 					return -EACCES;
5458 				}
5459 
5460 				if (spill_cnt == size &&
5461 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
5462 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5463 					/* this IS register fill, so keep insn_flags */
5464 				} else if (zero_cnt == size) {
5465 					/* similarly to mark_reg_stack_read(), preserve zeroes */
5466 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5467 					insn_flags = 0; /* not restoring original register state */
5468 				} else {
5469 					mark_reg_unknown(env, state->regs, dst_regno);
5470 					insn_flags = 0; /* not restoring original register state */
5471 				}
5472 			}
5473 		} else if (dst_regno >= 0) {
5474 			/* restore register state from stack */
5475 			copy_register_state(&state->regs[dst_regno], reg);
5476 			/* mark reg as written since spilled pointer state likely
5477 			 * has its liveness marks cleared by is_state_visited()
5478 			 * which resets stack/reg liveness for state transitions
5479 			 */
5480 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5481 			/* If dst_regno==-1, the caller is asking us whether
5482 			 * it is acceptable to use this value as a SCALAR_VALUE
5483 			 * (e.g. for XADD).
5484 			 * We must not allow unprivileged callers to do that
5485 			 * with spilled pointers.
5486 			 */
5487 			verbose(env, "leaking pointer from stack off %d\n",
5488 				off);
5489 			return -EACCES;
5490 		}
5491 	} else {
5492 		for (i = 0; i < size; i++) {
5493 			type = stype[(slot - i) % BPF_REG_SIZE];
5494 			if (type == STACK_MISC)
5495 				continue;
5496 			if (type == STACK_ZERO)
5497 				continue;
5498 			if (type == STACK_INVALID && env->allow_uninit_stack)
5499 				continue;
5500 			verbose(env, "invalid read from stack off %d+%d size %d\n",
5501 				off, i, size);
5502 			return -EACCES;
5503 		}
5504 		if (dst_regno >= 0)
5505 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5506 		insn_flags = 0; /* we are not restoring spilled register */
5507 	}
5508 	if (insn_flags)
5509 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5510 	return 0;
5511 }
5512 
5513 enum bpf_access_src {
5514 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5515 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
5516 };
5517 
5518 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5519 					 int regno, int off, int access_size,
5520 					 bool zero_size_allowed,
5521 					 enum bpf_access_type type,
5522 					 struct bpf_call_arg_meta *meta);
5523 
5524 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5525 {
5526 	return cur_regs(env) + regno;
5527 }
5528 
5529 /* Read the stack at 'ptr_regno + off' and put the result into the register
5530  * 'dst_regno'.
5531  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5532  * but not its variable offset.
5533  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5534  *
5535  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5536  * filling registers (i.e. reads of spilled register cannot be detected when
5537  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5538  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5539  * offset; for a fixed offset check_stack_read_fixed_off should be used
5540  * instead.
5541  */
5542 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5543 				    int ptr_regno, int off, int size, int dst_regno)
5544 {
5545 	/* The state of the source register. */
5546 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5547 	struct bpf_func_state *ptr_state = func(env, reg);
5548 	int err;
5549 	int min_off, max_off;
5550 
5551 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5552 	 */
5553 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5554 					    false, BPF_READ, NULL);
5555 	if (err)
5556 		return err;
5557 
5558 	min_off = reg->smin_value + off;
5559 	max_off = reg->smax_value + off;
5560 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5561 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5562 	return 0;
5563 }
5564 
5565 /* check_stack_read dispatches to check_stack_read_fixed_off or
5566  * check_stack_read_var_off.
5567  *
5568  * The caller must ensure that the offset falls within the allocated stack
5569  * bounds.
5570  *
5571  * 'dst_regno' is a register which will receive the value from the stack. It
5572  * can be -1, meaning that the read value is not going to a register.
5573  */
5574 static int check_stack_read(struct bpf_verifier_env *env,
5575 			    int ptr_regno, int off, int size,
5576 			    int dst_regno)
5577 {
5578 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5579 	struct bpf_func_state *state = func(env, reg);
5580 	int err;
5581 	/* Some accesses are only permitted with a static offset. */
5582 	bool var_off = !tnum_is_const(reg->var_off);
5583 
5584 	/* The offset is required to be static when reads don't go to a
5585 	 * register, in order to not leak pointers (see
5586 	 * check_stack_read_fixed_off).
5587 	 */
5588 	if (dst_regno < 0 && var_off) {
5589 		char tn_buf[48];
5590 
5591 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5592 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5593 			tn_buf, off, size);
5594 		return -EACCES;
5595 	}
5596 	/* Variable offset is prohibited for unprivileged mode for simplicity
5597 	 * since it requires corresponding support in Spectre masking for stack
5598 	 * ALU. See also retrieve_ptr_limit(). The check in
5599 	 * check_stack_access_for_ptr_arithmetic() called by
5600 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5601 	 * with variable offsets, therefore no check is required here. Further,
5602 	 * just checking it here would be insufficient as speculative stack
5603 	 * writes could still lead to unsafe speculative behaviour.
5604 	 */
5605 	if (!var_off) {
5606 		off += reg->var_off.value;
5607 		err = check_stack_read_fixed_off(env, state, off, size,
5608 						 dst_regno);
5609 	} else {
5610 		/* Variable offset stack reads need more conservative handling
5611 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5612 		 * branch.
5613 		 */
5614 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5615 					       dst_regno);
5616 	}
5617 	return err;
5618 }
5619 
5620 
5621 /* check_stack_write dispatches to check_stack_write_fixed_off or
5622  * check_stack_write_var_off.
5623  *
5624  * 'ptr_regno' is the register used as a pointer into the stack.
5625  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5626  * 'value_regno' is the register whose value we're writing to the stack. It can
5627  * be -1, meaning that we're not writing from a register.
5628  *
5629  * The caller must ensure that the offset falls within the maximum stack size.
5630  */
5631 static int check_stack_write(struct bpf_verifier_env *env,
5632 			     int ptr_regno, int off, int size,
5633 			     int value_regno, int insn_idx)
5634 {
5635 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5636 	struct bpf_func_state *state = func(env, reg);
5637 	int err;
5638 
5639 	if (tnum_is_const(reg->var_off)) {
5640 		off += reg->var_off.value;
5641 		err = check_stack_write_fixed_off(env, state, off, size,
5642 						  value_regno, insn_idx);
5643 	} else {
5644 		/* Variable offset stack reads need more conservative handling
5645 		 * than fixed offset ones.
5646 		 */
5647 		err = check_stack_write_var_off(env, state,
5648 						ptr_regno, off, size,
5649 						value_regno, insn_idx);
5650 	}
5651 	return err;
5652 }
5653 
5654 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5655 				 int off, int size, enum bpf_access_type type)
5656 {
5657 	struct bpf_reg_state *regs = cur_regs(env);
5658 	struct bpf_map *map = regs[regno].map_ptr;
5659 	u32 cap = bpf_map_flags_to_cap(map);
5660 
5661 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5662 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5663 			map->value_size, off, size);
5664 		return -EACCES;
5665 	}
5666 
5667 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5668 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5669 			map->value_size, off, size);
5670 		return -EACCES;
5671 	}
5672 
5673 	return 0;
5674 }
5675 
5676 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5677 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5678 			      int off, int size, u32 mem_size,
5679 			      bool zero_size_allowed)
5680 {
5681 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5682 	struct bpf_reg_state *reg;
5683 
5684 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5685 		return 0;
5686 
5687 	reg = &cur_regs(env)[regno];
5688 	switch (reg->type) {
5689 	case PTR_TO_MAP_KEY:
5690 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5691 			mem_size, off, size);
5692 		break;
5693 	case PTR_TO_MAP_VALUE:
5694 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5695 			mem_size, off, size);
5696 		break;
5697 	case PTR_TO_PACKET:
5698 	case PTR_TO_PACKET_META:
5699 	case PTR_TO_PACKET_END:
5700 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5701 			off, size, regno, reg->id, off, mem_size);
5702 		break;
5703 	case PTR_TO_MEM:
5704 	default:
5705 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5706 			mem_size, off, size);
5707 	}
5708 
5709 	return -EACCES;
5710 }
5711 
5712 /* check read/write into a memory region with possible variable offset */
5713 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5714 				   int off, int size, u32 mem_size,
5715 				   bool zero_size_allowed)
5716 {
5717 	struct bpf_verifier_state *vstate = env->cur_state;
5718 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5719 	struct bpf_reg_state *reg = &state->regs[regno];
5720 	int err;
5721 
5722 	/* We may have adjusted the register pointing to memory region, so we
5723 	 * need to try adding each of min_value and max_value to off
5724 	 * to make sure our theoretical access will be safe.
5725 	 *
5726 	 * The minimum value is only important with signed
5727 	 * comparisons where we can't assume the floor of a
5728 	 * value is 0.  If we are using signed variables for our
5729 	 * index'es we need to make sure that whatever we use
5730 	 * will have a set floor within our range.
5731 	 */
5732 	if (reg->smin_value < 0 &&
5733 	    (reg->smin_value == S64_MIN ||
5734 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5735 	      reg->smin_value + off < 0)) {
5736 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5737 			regno);
5738 		return -EACCES;
5739 	}
5740 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5741 				 mem_size, zero_size_allowed);
5742 	if (err) {
5743 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5744 			regno);
5745 		return err;
5746 	}
5747 
5748 	/* If we haven't set a max value then we need to bail since we can't be
5749 	 * sure we won't do bad things.
5750 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5751 	 */
5752 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5753 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5754 			regno);
5755 		return -EACCES;
5756 	}
5757 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5758 				 mem_size, zero_size_allowed);
5759 	if (err) {
5760 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5761 			regno);
5762 		return err;
5763 	}
5764 
5765 	return 0;
5766 }
5767 
5768 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5769 			       const struct bpf_reg_state *reg, int regno,
5770 			       bool fixed_off_ok)
5771 {
5772 	/* Access to this pointer-typed register or passing it to a helper
5773 	 * is only allowed in its original, unmodified form.
5774 	 */
5775 
5776 	if (reg->off < 0) {
5777 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5778 			reg_type_str(env, reg->type), regno, reg->off);
5779 		return -EACCES;
5780 	}
5781 
5782 	if (!fixed_off_ok && reg->off) {
5783 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5784 			reg_type_str(env, reg->type), regno, reg->off);
5785 		return -EACCES;
5786 	}
5787 
5788 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5789 		char tn_buf[48];
5790 
5791 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5792 		verbose(env, "variable %s access var_off=%s disallowed\n",
5793 			reg_type_str(env, reg->type), tn_buf);
5794 		return -EACCES;
5795 	}
5796 
5797 	return 0;
5798 }
5799 
5800 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5801 		             const struct bpf_reg_state *reg, int regno)
5802 {
5803 	return __check_ptr_off_reg(env, reg, regno, false);
5804 }
5805 
5806 static int map_kptr_match_type(struct bpf_verifier_env *env,
5807 			       struct btf_field *kptr_field,
5808 			       struct bpf_reg_state *reg, u32 regno)
5809 {
5810 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5811 	int perm_flags;
5812 	const char *reg_name = "";
5813 
5814 	if (btf_is_kernel(reg->btf)) {
5815 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5816 
5817 		/* Only unreferenced case accepts untrusted pointers */
5818 		if (kptr_field->type == BPF_KPTR_UNREF)
5819 			perm_flags |= PTR_UNTRUSTED;
5820 	} else {
5821 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5822 		if (kptr_field->type == BPF_KPTR_PERCPU)
5823 			perm_flags |= MEM_PERCPU;
5824 	}
5825 
5826 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5827 		goto bad_type;
5828 
5829 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5830 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5831 
5832 	/* For ref_ptr case, release function check should ensure we get one
5833 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5834 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5835 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5836 	 * reg->off and reg->ref_obj_id are not needed here.
5837 	 */
5838 	if (__check_ptr_off_reg(env, reg, regno, true))
5839 		return -EACCES;
5840 
5841 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5842 	 * we also need to take into account the reg->off.
5843 	 *
5844 	 * We want to support cases like:
5845 	 *
5846 	 * struct foo {
5847 	 *         struct bar br;
5848 	 *         struct baz bz;
5849 	 * };
5850 	 *
5851 	 * struct foo *v;
5852 	 * v = func();	      // PTR_TO_BTF_ID
5853 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5854 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5855 	 *                    // first member type of struct after comparison fails
5856 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5857 	 *                    // to match type
5858 	 *
5859 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5860 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5861 	 * the struct to match type against first member of struct, i.e. reject
5862 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5863 	 * strict mode to true for type match.
5864 	 */
5865 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5866 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5867 				  kptr_field->type != BPF_KPTR_UNREF))
5868 		goto bad_type;
5869 	return 0;
5870 bad_type:
5871 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5872 		reg_type_str(env, reg->type), reg_name);
5873 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5874 	if (kptr_field->type == BPF_KPTR_UNREF)
5875 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5876 			targ_name);
5877 	else
5878 		verbose(env, "\n");
5879 	return -EINVAL;
5880 }
5881 
5882 static bool in_sleepable(struct bpf_verifier_env *env)
5883 {
5884 	return env->cur_state->in_sleepable;
5885 }
5886 
5887 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5888  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5889  */
5890 static bool in_rcu_cs(struct bpf_verifier_env *env)
5891 {
5892 	return env->cur_state->active_rcu_locks ||
5893 	       env->cur_state->active_locks ||
5894 	       !in_sleepable(env);
5895 }
5896 
5897 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5898 BTF_SET_START(rcu_protected_types)
5899 #ifdef CONFIG_NET
5900 BTF_ID(struct, prog_test_ref_kfunc)
5901 #endif
5902 #ifdef CONFIG_CGROUPS
5903 BTF_ID(struct, cgroup)
5904 #endif
5905 #ifdef CONFIG_BPF_JIT
5906 BTF_ID(struct, bpf_cpumask)
5907 #endif
5908 BTF_ID(struct, task_struct)
5909 #ifdef CONFIG_CRYPTO
5910 BTF_ID(struct, bpf_crypto_ctx)
5911 #endif
5912 BTF_SET_END(rcu_protected_types)
5913 
5914 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5915 {
5916 	if (!btf_is_kernel(btf))
5917 		return true;
5918 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5919 }
5920 
5921 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5922 {
5923 	struct btf_struct_meta *meta;
5924 
5925 	if (btf_is_kernel(kptr_field->kptr.btf))
5926 		return NULL;
5927 
5928 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5929 				    kptr_field->kptr.btf_id);
5930 
5931 	return meta ? meta->record : NULL;
5932 }
5933 
5934 static bool rcu_safe_kptr(const struct btf_field *field)
5935 {
5936 	const struct btf_field_kptr *kptr = &field->kptr;
5937 
5938 	return field->type == BPF_KPTR_PERCPU ||
5939 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5940 }
5941 
5942 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5943 {
5944 	struct btf_record *rec;
5945 	u32 ret;
5946 
5947 	ret = PTR_MAYBE_NULL;
5948 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5949 		ret |= MEM_RCU;
5950 		if (kptr_field->type == BPF_KPTR_PERCPU)
5951 			ret |= MEM_PERCPU;
5952 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5953 			ret |= MEM_ALLOC;
5954 
5955 		rec = kptr_pointee_btf_record(kptr_field);
5956 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5957 			ret |= NON_OWN_REF;
5958 	} else {
5959 		ret |= PTR_UNTRUSTED;
5960 	}
5961 
5962 	return ret;
5963 }
5964 
5965 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
5966 			    struct btf_field *field)
5967 {
5968 	struct bpf_reg_state *reg;
5969 	const struct btf_type *t;
5970 
5971 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
5972 	mark_reg_known_zero(env, cur_regs(env), regno);
5973 	reg = reg_state(env, regno);
5974 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5975 	reg->mem_size = t->size;
5976 	reg->id = ++env->id_gen;
5977 
5978 	return 0;
5979 }
5980 
5981 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5982 				 int value_regno, int insn_idx,
5983 				 struct btf_field *kptr_field)
5984 {
5985 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5986 	int class = BPF_CLASS(insn->code);
5987 	struct bpf_reg_state *val_reg;
5988 	int ret;
5989 
5990 	/* Things we already checked for in check_map_access and caller:
5991 	 *  - Reject cases where variable offset may touch kptr
5992 	 *  - size of access (must be BPF_DW)
5993 	 *  - tnum_is_const(reg->var_off)
5994 	 *  - kptr_field->offset == off + reg->var_off.value
5995 	 */
5996 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5997 	if (BPF_MODE(insn->code) != BPF_MEM) {
5998 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5999 		return -EACCES;
6000 	}
6001 
6002 	/* We only allow loading referenced kptr, since it will be marked as
6003 	 * untrusted, similar to unreferenced kptr.
6004 	 */
6005 	if (class != BPF_LDX &&
6006 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
6007 		verbose(env, "store to referenced kptr disallowed\n");
6008 		return -EACCES;
6009 	}
6010 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
6011 		verbose(env, "store to uptr disallowed\n");
6012 		return -EACCES;
6013 	}
6014 
6015 	if (class == BPF_LDX) {
6016 		if (kptr_field->type == BPF_UPTR)
6017 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
6018 
6019 		/* We can simply mark the value_regno receiving the pointer
6020 		 * value from map as PTR_TO_BTF_ID, with the correct type.
6021 		 */
6022 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
6023 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
6024 				      btf_ld_kptr_type(env, kptr_field));
6025 		if (ret < 0)
6026 			return ret;
6027 	} else if (class == BPF_STX) {
6028 		val_reg = reg_state(env, value_regno);
6029 		if (!register_is_null(val_reg) &&
6030 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
6031 			return -EACCES;
6032 	} else if (class == BPF_ST) {
6033 		if (insn->imm) {
6034 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
6035 				kptr_field->offset);
6036 			return -EACCES;
6037 		}
6038 	} else {
6039 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
6040 		return -EACCES;
6041 	}
6042 	return 0;
6043 }
6044 
6045 /*
6046  * Return the size of the memory region accessible from a pointer to map value.
6047  * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible.
6048  */
6049 static u32 map_mem_size(const struct bpf_map *map)
6050 {
6051 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY)
6052 		return map->max_entries * sizeof(long);
6053 
6054 	return map->value_size;
6055 }
6056 
6057 /* check read/write into a map element with possible variable offset */
6058 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
6059 			    int off, int size, bool zero_size_allowed,
6060 			    enum bpf_access_src src)
6061 {
6062 	struct bpf_verifier_state *vstate = env->cur_state;
6063 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6064 	struct bpf_reg_state *reg = &state->regs[regno];
6065 	struct bpf_map *map = reg->map_ptr;
6066 	u32 mem_size = map_mem_size(map);
6067 	struct btf_record *rec;
6068 	int err, i;
6069 
6070 	err = check_mem_region_access(env, regno, off, size, mem_size, zero_size_allowed);
6071 	if (err)
6072 		return err;
6073 
6074 	if (IS_ERR_OR_NULL(map->record))
6075 		return 0;
6076 	rec = map->record;
6077 	for (i = 0; i < rec->cnt; i++) {
6078 		struct btf_field *field = &rec->fields[i];
6079 		u32 p = field->offset;
6080 
6081 		/* If any part of a field  can be touched by load/store, reject
6082 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
6083 		 * it is sufficient to check x1 < y2 && y1 < x2.
6084 		 */
6085 		if (reg->smin_value + off < p + field->size &&
6086 		    p < reg->umax_value + off + size) {
6087 			switch (field->type) {
6088 			case BPF_KPTR_UNREF:
6089 			case BPF_KPTR_REF:
6090 			case BPF_KPTR_PERCPU:
6091 			case BPF_UPTR:
6092 				if (src != ACCESS_DIRECT) {
6093 					verbose(env, "%s cannot be accessed indirectly by helper\n",
6094 						btf_field_type_name(field->type));
6095 					return -EACCES;
6096 				}
6097 				if (!tnum_is_const(reg->var_off)) {
6098 					verbose(env, "%s access cannot have variable offset\n",
6099 						btf_field_type_name(field->type));
6100 					return -EACCES;
6101 				}
6102 				if (p != off + reg->var_off.value) {
6103 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
6104 						btf_field_type_name(field->type),
6105 						p, off + reg->var_off.value);
6106 					return -EACCES;
6107 				}
6108 				if (size != bpf_size_to_bytes(BPF_DW)) {
6109 					verbose(env, "%s access size must be BPF_DW\n",
6110 						btf_field_type_name(field->type));
6111 					return -EACCES;
6112 				}
6113 				break;
6114 			default:
6115 				verbose(env, "%s cannot be accessed directly by load/store\n",
6116 					btf_field_type_name(field->type));
6117 				return -EACCES;
6118 			}
6119 		}
6120 	}
6121 	return 0;
6122 }
6123 
6124 #define MAX_PACKET_OFF 0xffff
6125 
6126 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
6127 				       const struct bpf_call_arg_meta *meta,
6128 				       enum bpf_access_type t)
6129 {
6130 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6131 
6132 	switch (prog_type) {
6133 	/* Program types only with direct read access go here! */
6134 	case BPF_PROG_TYPE_LWT_IN:
6135 	case BPF_PROG_TYPE_LWT_OUT:
6136 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
6137 	case BPF_PROG_TYPE_SK_REUSEPORT:
6138 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6139 	case BPF_PROG_TYPE_CGROUP_SKB:
6140 		if (t == BPF_WRITE)
6141 			return false;
6142 		fallthrough;
6143 
6144 	/* Program types with direct read + write access go here! */
6145 	case BPF_PROG_TYPE_SCHED_CLS:
6146 	case BPF_PROG_TYPE_SCHED_ACT:
6147 	case BPF_PROG_TYPE_XDP:
6148 	case BPF_PROG_TYPE_LWT_XMIT:
6149 	case BPF_PROG_TYPE_SK_SKB:
6150 	case BPF_PROG_TYPE_SK_MSG:
6151 		if (meta)
6152 			return meta->pkt_access;
6153 
6154 		env->seen_direct_write = true;
6155 		return true;
6156 
6157 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
6158 		if (t == BPF_WRITE)
6159 			env->seen_direct_write = true;
6160 
6161 		return true;
6162 
6163 	default:
6164 		return false;
6165 	}
6166 }
6167 
6168 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
6169 			       int size, bool zero_size_allowed)
6170 {
6171 	struct bpf_reg_state *regs = cur_regs(env);
6172 	struct bpf_reg_state *reg = &regs[regno];
6173 	int err;
6174 
6175 	/* We may have added a variable offset to the packet pointer; but any
6176 	 * reg->range we have comes after that.  We are only checking the fixed
6177 	 * offset.
6178 	 */
6179 
6180 	/* We don't allow negative numbers, because we aren't tracking enough
6181 	 * detail to prove they're safe.
6182 	 */
6183 	if (reg->smin_value < 0) {
6184 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6185 			regno);
6186 		return -EACCES;
6187 	}
6188 
6189 	err = reg->range < 0 ? -EINVAL :
6190 	      __check_mem_access(env, regno, off, size, reg->range,
6191 				 zero_size_allowed);
6192 	if (err) {
6193 		verbose(env, "R%d offset is outside of the packet\n", regno);
6194 		return err;
6195 	}
6196 
6197 	/* __check_mem_access has made sure "off + size - 1" is within u16.
6198 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
6199 	 * otherwise find_good_pkt_pointers would have refused to set range info
6200 	 * that __check_mem_access would have rejected this pkt access.
6201 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
6202 	 */
6203 	env->prog->aux->max_pkt_offset =
6204 		max_t(u32, env->prog->aux->max_pkt_offset,
6205 		      off + reg->umax_value + size - 1);
6206 
6207 	return err;
6208 }
6209 
6210 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
6211 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
6212 			    enum bpf_access_type t, struct bpf_insn_access_aux *info)
6213 {
6214 	if (env->ops->is_valid_access &&
6215 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
6216 		/* A non zero info.ctx_field_size indicates that this field is a
6217 		 * candidate for later verifier transformation to load the whole
6218 		 * field and then apply a mask when accessed with a narrower
6219 		 * access than actual ctx access size. A zero info.ctx_field_size
6220 		 * will only allow for whole field access and rejects any other
6221 		 * type of narrower access.
6222 		 */
6223 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
6224 			if (info->ref_obj_id &&
6225 			    !find_reference_state(env->cur_state, info->ref_obj_id)) {
6226 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
6227 					off);
6228 				return -EACCES;
6229 			}
6230 		} else {
6231 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
6232 		}
6233 		/* remember the offset of last byte accessed in ctx */
6234 		if (env->prog->aux->max_ctx_offset < off + size)
6235 			env->prog->aux->max_ctx_offset = off + size;
6236 		return 0;
6237 	}
6238 
6239 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
6240 	return -EACCES;
6241 }
6242 
6243 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
6244 				  int size)
6245 {
6246 	if (size < 0 || off < 0 ||
6247 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
6248 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
6249 			off, size);
6250 		return -EACCES;
6251 	}
6252 	return 0;
6253 }
6254 
6255 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
6256 			     u32 regno, int off, int size,
6257 			     enum bpf_access_type t)
6258 {
6259 	struct bpf_reg_state *regs = cur_regs(env);
6260 	struct bpf_reg_state *reg = &regs[regno];
6261 	struct bpf_insn_access_aux info = {};
6262 	bool valid;
6263 
6264 	if (reg->smin_value < 0) {
6265 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6266 			regno);
6267 		return -EACCES;
6268 	}
6269 
6270 	switch (reg->type) {
6271 	case PTR_TO_SOCK_COMMON:
6272 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
6273 		break;
6274 	case PTR_TO_SOCKET:
6275 		valid = bpf_sock_is_valid_access(off, size, t, &info);
6276 		break;
6277 	case PTR_TO_TCP_SOCK:
6278 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
6279 		break;
6280 	case PTR_TO_XDP_SOCK:
6281 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
6282 		break;
6283 	default:
6284 		valid = false;
6285 	}
6286 
6287 
6288 	if (valid) {
6289 		env->insn_aux_data[insn_idx].ctx_field_size =
6290 			info.ctx_field_size;
6291 		return 0;
6292 	}
6293 
6294 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
6295 		regno, reg_type_str(env, reg->type), off, size);
6296 
6297 	return -EACCES;
6298 }
6299 
6300 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
6301 {
6302 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
6303 }
6304 
6305 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
6306 {
6307 	const struct bpf_reg_state *reg = reg_state(env, regno);
6308 
6309 	return reg->type == PTR_TO_CTX;
6310 }
6311 
6312 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
6313 {
6314 	const struct bpf_reg_state *reg = reg_state(env, regno);
6315 
6316 	return type_is_sk_pointer(reg->type);
6317 }
6318 
6319 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
6320 {
6321 	const struct bpf_reg_state *reg = reg_state(env, regno);
6322 
6323 	return type_is_pkt_pointer(reg->type);
6324 }
6325 
6326 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
6327 {
6328 	const struct bpf_reg_state *reg = reg_state(env, regno);
6329 
6330 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
6331 	return reg->type == PTR_TO_FLOW_KEYS;
6332 }
6333 
6334 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
6335 {
6336 	const struct bpf_reg_state *reg = reg_state(env, regno);
6337 
6338 	return reg->type == PTR_TO_ARENA;
6339 }
6340 
6341 /* Return false if @regno contains a pointer whose type isn't supported for
6342  * atomic instruction @insn.
6343  */
6344 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
6345 			       struct bpf_insn *insn)
6346 {
6347 	if (is_ctx_reg(env, regno))
6348 		return false;
6349 	if (is_pkt_reg(env, regno))
6350 		return false;
6351 	if (is_flow_key_reg(env, regno))
6352 		return false;
6353 	if (is_sk_reg(env, regno))
6354 		return false;
6355 	if (is_arena_reg(env, regno))
6356 		return bpf_jit_supports_insn(insn, true);
6357 
6358 	return true;
6359 }
6360 
6361 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
6362 #ifdef CONFIG_NET
6363 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
6364 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6365 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
6366 #endif
6367 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
6368 };
6369 
6370 static bool is_trusted_reg(const struct bpf_reg_state *reg)
6371 {
6372 	/* A referenced register is always trusted. */
6373 	if (reg->ref_obj_id)
6374 		return true;
6375 
6376 	/* Types listed in the reg2btf_ids are always trusted */
6377 	if (reg2btf_ids[base_type(reg->type)] &&
6378 	    !bpf_type_has_unsafe_modifiers(reg->type))
6379 		return true;
6380 
6381 	/* If a register is not referenced, it is trusted if it has the
6382 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
6383 	 * other type modifiers may be safe, but we elect to take an opt-in
6384 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
6385 	 * not.
6386 	 *
6387 	 * Eventually, we should make PTR_TRUSTED the single source of truth
6388 	 * for whether a register is trusted.
6389 	 */
6390 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
6391 	       !bpf_type_has_unsafe_modifiers(reg->type);
6392 }
6393 
6394 static bool is_rcu_reg(const struct bpf_reg_state *reg)
6395 {
6396 	return reg->type & MEM_RCU;
6397 }
6398 
6399 static void clear_trusted_flags(enum bpf_type_flag *flag)
6400 {
6401 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
6402 }
6403 
6404 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
6405 				   const struct bpf_reg_state *reg,
6406 				   int off, int size, bool strict)
6407 {
6408 	struct tnum reg_off;
6409 	int ip_align;
6410 
6411 	/* Byte size accesses are always allowed. */
6412 	if (!strict || size == 1)
6413 		return 0;
6414 
6415 	/* For platforms that do not have a Kconfig enabling
6416 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
6417 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
6418 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
6419 	 * to this code only in strict mode where we want to emulate
6420 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
6421 	 * unconditional IP align value of '2'.
6422 	 */
6423 	ip_align = 2;
6424 
6425 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
6426 	if (!tnum_is_aligned(reg_off, size)) {
6427 		char tn_buf[48];
6428 
6429 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6430 		verbose(env,
6431 			"misaligned packet access off %d+%s+%d+%d size %d\n",
6432 			ip_align, tn_buf, reg->off, off, size);
6433 		return -EACCES;
6434 	}
6435 
6436 	return 0;
6437 }
6438 
6439 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
6440 				       const struct bpf_reg_state *reg,
6441 				       const char *pointer_desc,
6442 				       int off, int size, bool strict)
6443 {
6444 	struct tnum reg_off;
6445 
6446 	/* Byte size accesses are always allowed. */
6447 	if (!strict || size == 1)
6448 		return 0;
6449 
6450 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
6451 	if (!tnum_is_aligned(reg_off, size)) {
6452 		char tn_buf[48];
6453 
6454 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6455 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
6456 			pointer_desc, tn_buf, reg->off, off, size);
6457 		return -EACCES;
6458 	}
6459 
6460 	return 0;
6461 }
6462 
6463 static int check_ptr_alignment(struct bpf_verifier_env *env,
6464 			       const struct bpf_reg_state *reg, int off,
6465 			       int size, bool strict_alignment_once)
6466 {
6467 	bool strict = env->strict_alignment || strict_alignment_once;
6468 	const char *pointer_desc = "";
6469 
6470 	switch (reg->type) {
6471 	case PTR_TO_PACKET:
6472 	case PTR_TO_PACKET_META:
6473 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
6474 		 * right in front, treat it the very same way.
6475 		 */
6476 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
6477 	case PTR_TO_FLOW_KEYS:
6478 		pointer_desc = "flow keys ";
6479 		break;
6480 	case PTR_TO_MAP_KEY:
6481 		pointer_desc = "key ";
6482 		break;
6483 	case PTR_TO_MAP_VALUE:
6484 		pointer_desc = "value ";
6485 		break;
6486 	case PTR_TO_CTX:
6487 		pointer_desc = "context ";
6488 		break;
6489 	case PTR_TO_STACK:
6490 		pointer_desc = "stack ";
6491 		/* The stack spill tracking logic in check_stack_write_fixed_off()
6492 		 * and check_stack_read_fixed_off() relies on stack accesses being
6493 		 * aligned.
6494 		 */
6495 		strict = true;
6496 		break;
6497 	case PTR_TO_SOCKET:
6498 		pointer_desc = "sock ";
6499 		break;
6500 	case PTR_TO_SOCK_COMMON:
6501 		pointer_desc = "sock_common ";
6502 		break;
6503 	case PTR_TO_TCP_SOCK:
6504 		pointer_desc = "tcp_sock ";
6505 		break;
6506 	case PTR_TO_XDP_SOCK:
6507 		pointer_desc = "xdp_sock ";
6508 		break;
6509 	case PTR_TO_ARENA:
6510 		return 0;
6511 	default:
6512 		break;
6513 	}
6514 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
6515 					   strict);
6516 }
6517 
6518 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
6519 {
6520 	if (!bpf_jit_supports_private_stack())
6521 		return NO_PRIV_STACK;
6522 
6523 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
6524 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
6525 	 * explicitly.
6526 	 */
6527 	switch (prog->type) {
6528 	case BPF_PROG_TYPE_KPROBE:
6529 	case BPF_PROG_TYPE_TRACEPOINT:
6530 	case BPF_PROG_TYPE_PERF_EVENT:
6531 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6532 		return PRIV_STACK_ADAPTIVE;
6533 	case BPF_PROG_TYPE_TRACING:
6534 	case BPF_PROG_TYPE_LSM:
6535 	case BPF_PROG_TYPE_STRUCT_OPS:
6536 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
6537 			return PRIV_STACK_ADAPTIVE;
6538 		fallthrough;
6539 	default:
6540 		break;
6541 	}
6542 
6543 	return NO_PRIV_STACK;
6544 }
6545 
6546 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
6547 {
6548 	if (env->prog->jit_requested)
6549 		return round_up(stack_depth, 16);
6550 
6551 	/* round up to 32-bytes, since this is granularity
6552 	 * of interpreter stack size
6553 	 */
6554 	return round_up(max_t(u32, stack_depth, 1), 32);
6555 }
6556 
6557 /* starting from main bpf function walk all instructions of the function
6558  * and recursively walk all callees that given function can call.
6559  * Ignore jump and exit insns.
6560  * Since recursion is prevented by check_cfg() this algorithm
6561  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6562  */
6563 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
6564 					 bool priv_stack_supported)
6565 {
6566 	struct bpf_subprog_info *subprog = env->subprog_info;
6567 	struct bpf_insn *insn = env->prog->insnsi;
6568 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
6569 	bool tail_call_reachable = false;
6570 	int ret_insn[MAX_CALL_FRAMES];
6571 	int ret_prog[MAX_CALL_FRAMES];
6572 	int j;
6573 
6574 	i = subprog[idx].start;
6575 	if (!priv_stack_supported)
6576 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6577 process_func:
6578 	/* protect against potential stack overflow that might happen when
6579 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6580 	 * depth for such case down to 256 so that the worst case scenario
6581 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
6582 	 * 8k).
6583 	 *
6584 	 * To get the idea what might happen, see an example:
6585 	 * func1 -> sub rsp, 128
6586 	 *  subfunc1 -> sub rsp, 256
6587 	 *  tailcall1 -> add rsp, 256
6588 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6589 	 *   subfunc2 -> sub rsp, 64
6590 	 *   subfunc22 -> sub rsp, 128
6591 	 *   tailcall2 -> add rsp, 128
6592 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6593 	 *
6594 	 * tailcall will unwind the current stack frame but it will not get rid
6595 	 * of caller's stack as shown on the example above.
6596 	 */
6597 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
6598 		verbose(env,
6599 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6600 			depth);
6601 		return -EACCES;
6602 	}
6603 
6604 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
6605 	if (priv_stack_supported) {
6606 		/* Request private stack support only if the subprog stack
6607 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
6608 		 * avoid jit penalty if the stack usage is small.
6609 		 */
6610 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
6611 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
6612 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
6613 	}
6614 
6615 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6616 		if (subprog_depth > MAX_BPF_STACK) {
6617 			verbose(env, "stack size of subprog %d is %d. Too large\n",
6618 				idx, subprog_depth);
6619 			return -EACCES;
6620 		}
6621 	} else {
6622 		depth += subprog_depth;
6623 		if (depth > MAX_BPF_STACK) {
6624 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
6625 				frame + 1, depth);
6626 			return -EACCES;
6627 		}
6628 	}
6629 continue_func:
6630 	subprog_end = subprog[idx + 1].start;
6631 	for (; i < subprog_end; i++) {
6632 		int next_insn, sidx;
6633 
6634 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6635 			bool err = false;
6636 
6637 			if (!is_bpf_throw_kfunc(insn + i))
6638 				continue;
6639 			if (subprog[idx].is_cb)
6640 				err = true;
6641 			for (int c = 0; c < frame && !err; c++) {
6642 				if (subprog[ret_prog[c]].is_cb) {
6643 					err = true;
6644 					break;
6645 				}
6646 			}
6647 			if (!err)
6648 				continue;
6649 			verbose(env,
6650 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6651 				i, idx);
6652 			return -EINVAL;
6653 		}
6654 
6655 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6656 			continue;
6657 		/* remember insn and function to return to */
6658 		ret_insn[frame] = i + 1;
6659 		ret_prog[frame] = idx;
6660 
6661 		/* find the callee */
6662 		next_insn = i + insn[i].imm + 1;
6663 		sidx = find_subprog(env, next_insn);
6664 		if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
6665 			return -EFAULT;
6666 		if (subprog[sidx].is_async_cb) {
6667 			if (subprog[sidx].has_tail_call) {
6668 				verifier_bug(env, "subprog has tail_call and async cb");
6669 				return -EFAULT;
6670 			}
6671 			/* async callbacks don't increase bpf prog stack size unless called directly */
6672 			if (!bpf_pseudo_call(insn + i))
6673 				continue;
6674 			if (subprog[sidx].is_exception_cb) {
6675 				verbose(env, "insn %d cannot call exception cb directly", i);
6676 				return -EINVAL;
6677 			}
6678 		}
6679 		i = next_insn;
6680 		idx = sidx;
6681 		if (!priv_stack_supported)
6682 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6683 
6684 		if (subprog[idx].has_tail_call)
6685 			tail_call_reachable = true;
6686 
6687 		frame++;
6688 		if (frame >= MAX_CALL_FRAMES) {
6689 			verbose(env, "the call stack of %d frames is too deep !\n",
6690 				frame);
6691 			return -E2BIG;
6692 		}
6693 		goto process_func;
6694 	}
6695 	/* if tail call got detected across bpf2bpf calls then mark each of the
6696 	 * currently present subprog frames as tail call reachable subprogs;
6697 	 * this info will be utilized by JIT so that we will be preserving the
6698 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6699 	 */
6700 	if (tail_call_reachable)
6701 		for (j = 0; j < frame; j++) {
6702 			if (subprog[ret_prog[j]].is_exception_cb) {
6703 				verbose(env, "cannot tail call within exception cb\n");
6704 				return -EINVAL;
6705 			}
6706 			subprog[ret_prog[j]].tail_call_reachable = true;
6707 		}
6708 	if (subprog[0].tail_call_reachable)
6709 		env->prog->aux->tail_call_reachable = true;
6710 
6711 	/* end of for() loop means the last insn of the 'subprog'
6712 	 * was reached. Doesn't matter whether it was JA or EXIT
6713 	 */
6714 	if (frame == 0)
6715 		return 0;
6716 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6717 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6718 	frame--;
6719 	i = ret_insn[frame];
6720 	idx = ret_prog[frame];
6721 	goto continue_func;
6722 }
6723 
6724 static int check_max_stack_depth(struct bpf_verifier_env *env)
6725 {
6726 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6727 	struct bpf_subprog_info *si = env->subprog_info;
6728 	bool priv_stack_supported;
6729 	int ret;
6730 
6731 	for (int i = 0; i < env->subprog_cnt; i++) {
6732 		if (si[i].has_tail_call) {
6733 			priv_stack_mode = NO_PRIV_STACK;
6734 			break;
6735 		}
6736 	}
6737 
6738 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6739 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6740 
6741 	/* All async_cb subprogs use normal kernel stack. If a particular
6742 	 * subprog appears in both main prog and async_cb subtree, that
6743 	 * subprog will use normal kernel stack to avoid potential nesting.
6744 	 * The reverse subprog traversal ensures when main prog subtree is
6745 	 * checked, the subprogs appearing in async_cb subtrees are already
6746 	 * marked as using normal kernel stack, so stack size checking can
6747 	 * be done properly.
6748 	 */
6749 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6750 		if (!i || si[i].is_async_cb) {
6751 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6752 			ret = check_max_stack_depth_subprog(env, i, priv_stack_supported);
6753 			if (ret < 0)
6754 				return ret;
6755 		}
6756 	}
6757 
6758 	for (int i = 0; i < env->subprog_cnt; i++) {
6759 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6760 			env->prog->aux->jits_use_priv_stack = true;
6761 			break;
6762 		}
6763 	}
6764 
6765 	return 0;
6766 }
6767 
6768 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6769 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6770 				  const struct bpf_insn *insn, int idx)
6771 {
6772 	int start = idx + insn->imm + 1, subprog;
6773 
6774 	subprog = find_subprog(env, start);
6775 	if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start))
6776 		return -EFAULT;
6777 	return env->subprog_info[subprog].stack_depth;
6778 }
6779 #endif
6780 
6781 static int __check_buffer_access(struct bpf_verifier_env *env,
6782 				 const char *buf_info,
6783 				 const struct bpf_reg_state *reg,
6784 				 int regno, int off, int size)
6785 {
6786 	if (off < 0) {
6787 		verbose(env,
6788 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6789 			regno, buf_info, off, size);
6790 		return -EACCES;
6791 	}
6792 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6793 		char tn_buf[48];
6794 
6795 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6796 		verbose(env,
6797 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6798 			regno, off, tn_buf);
6799 		return -EACCES;
6800 	}
6801 
6802 	return 0;
6803 }
6804 
6805 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6806 				  const struct bpf_reg_state *reg,
6807 				  int regno, int off, int size)
6808 {
6809 	int err;
6810 
6811 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6812 	if (err)
6813 		return err;
6814 
6815 	if (off + size > env->prog->aux->max_tp_access)
6816 		env->prog->aux->max_tp_access = off + size;
6817 
6818 	return 0;
6819 }
6820 
6821 static int check_buffer_access(struct bpf_verifier_env *env,
6822 			       const struct bpf_reg_state *reg,
6823 			       int regno, int off, int size,
6824 			       bool zero_size_allowed,
6825 			       u32 *max_access)
6826 {
6827 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6828 	int err;
6829 
6830 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6831 	if (err)
6832 		return err;
6833 
6834 	if (off + size > *max_access)
6835 		*max_access = off + size;
6836 
6837 	return 0;
6838 }
6839 
6840 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6841 static void zext_32_to_64(struct bpf_reg_state *reg)
6842 {
6843 	reg->var_off = tnum_subreg(reg->var_off);
6844 	__reg_assign_32_into_64(reg);
6845 }
6846 
6847 /* truncate register to smaller size (in bytes)
6848  * must be called with size < BPF_REG_SIZE
6849  */
6850 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6851 {
6852 	u64 mask;
6853 
6854 	/* clear high bits in bit representation */
6855 	reg->var_off = tnum_cast(reg->var_off, size);
6856 
6857 	/* fix arithmetic bounds */
6858 	mask = ((u64)1 << (size * 8)) - 1;
6859 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6860 		reg->umin_value &= mask;
6861 		reg->umax_value &= mask;
6862 	} else {
6863 		reg->umin_value = 0;
6864 		reg->umax_value = mask;
6865 	}
6866 	reg->smin_value = reg->umin_value;
6867 	reg->smax_value = reg->umax_value;
6868 
6869 	/* If size is smaller than 32bit register the 32bit register
6870 	 * values are also truncated so we push 64-bit bounds into
6871 	 * 32-bit bounds. Above were truncated < 32-bits already.
6872 	 */
6873 	if (size < 4)
6874 		__mark_reg32_unbounded(reg);
6875 
6876 	reg_bounds_sync(reg);
6877 }
6878 
6879 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6880 {
6881 	if (size == 1) {
6882 		reg->smin_value = reg->s32_min_value = S8_MIN;
6883 		reg->smax_value = reg->s32_max_value = S8_MAX;
6884 	} else if (size == 2) {
6885 		reg->smin_value = reg->s32_min_value = S16_MIN;
6886 		reg->smax_value = reg->s32_max_value = S16_MAX;
6887 	} else {
6888 		/* size == 4 */
6889 		reg->smin_value = reg->s32_min_value = S32_MIN;
6890 		reg->smax_value = reg->s32_max_value = S32_MAX;
6891 	}
6892 	reg->umin_value = reg->u32_min_value = 0;
6893 	reg->umax_value = U64_MAX;
6894 	reg->u32_max_value = U32_MAX;
6895 	reg->var_off = tnum_unknown;
6896 }
6897 
6898 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6899 {
6900 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6901 	u64 top_smax_value, top_smin_value;
6902 	u64 num_bits = size * 8;
6903 
6904 	if (tnum_is_const(reg->var_off)) {
6905 		u64_cval = reg->var_off.value;
6906 		if (size == 1)
6907 			reg->var_off = tnum_const((s8)u64_cval);
6908 		else if (size == 2)
6909 			reg->var_off = tnum_const((s16)u64_cval);
6910 		else
6911 			/* size == 4 */
6912 			reg->var_off = tnum_const((s32)u64_cval);
6913 
6914 		u64_cval = reg->var_off.value;
6915 		reg->smax_value = reg->smin_value = u64_cval;
6916 		reg->umax_value = reg->umin_value = u64_cval;
6917 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6918 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6919 		return;
6920 	}
6921 
6922 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6923 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6924 
6925 	if (top_smax_value != top_smin_value)
6926 		goto out;
6927 
6928 	/* find the s64_min and s64_min after sign extension */
6929 	if (size == 1) {
6930 		init_s64_max = (s8)reg->smax_value;
6931 		init_s64_min = (s8)reg->smin_value;
6932 	} else if (size == 2) {
6933 		init_s64_max = (s16)reg->smax_value;
6934 		init_s64_min = (s16)reg->smin_value;
6935 	} else {
6936 		init_s64_max = (s32)reg->smax_value;
6937 		init_s64_min = (s32)reg->smin_value;
6938 	}
6939 
6940 	s64_max = max(init_s64_max, init_s64_min);
6941 	s64_min = min(init_s64_max, init_s64_min);
6942 
6943 	/* both of s64_max/s64_min positive or negative */
6944 	if ((s64_max >= 0) == (s64_min >= 0)) {
6945 		reg->s32_min_value = reg->smin_value = s64_min;
6946 		reg->s32_max_value = reg->smax_value = s64_max;
6947 		reg->u32_min_value = reg->umin_value = s64_min;
6948 		reg->u32_max_value = reg->umax_value = s64_max;
6949 		reg->var_off = tnum_range(s64_min, s64_max);
6950 		return;
6951 	}
6952 
6953 out:
6954 	set_sext64_default_val(reg, size);
6955 }
6956 
6957 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6958 {
6959 	if (size == 1) {
6960 		reg->s32_min_value = S8_MIN;
6961 		reg->s32_max_value = S8_MAX;
6962 	} else {
6963 		/* size == 2 */
6964 		reg->s32_min_value = S16_MIN;
6965 		reg->s32_max_value = S16_MAX;
6966 	}
6967 	reg->u32_min_value = 0;
6968 	reg->u32_max_value = U32_MAX;
6969 	reg->var_off = tnum_subreg(tnum_unknown);
6970 }
6971 
6972 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6973 {
6974 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6975 	u32 top_smax_value, top_smin_value;
6976 	u32 num_bits = size * 8;
6977 
6978 	if (tnum_is_const(reg->var_off)) {
6979 		u32_val = reg->var_off.value;
6980 		if (size == 1)
6981 			reg->var_off = tnum_const((s8)u32_val);
6982 		else
6983 			reg->var_off = tnum_const((s16)u32_val);
6984 
6985 		u32_val = reg->var_off.value;
6986 		reg->s32_min_value = reg->s32_max_value = u32_val;
6987 		reg->u32_min_value = reg->u32_max_value = u32_val;
6988 		return;
6989 	}
6990 
6991 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6992 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6993 
6994 	if (top_smax_value != top_smin_value)
6995 		goto out;
6996 
6997 	/* find the s32_min and s32_min after sign extension */
6998 	if (size == 1) {
6999 		init_s32_max = (s8)reg->s32_max_value;
7000 		init_s32_min = (s8)reg->s32_min_value;
7001 	} else {
7002 		/* size == 2 */
7003 		init_s32_max = (s16)reg->s32_max_value;
7004 		init_s32_min = (s16)reg->s32_min_value;
7005 	}
7006 	s32_max = max(init_s32_max, init_s32_min);
7007 	s32_min = min(init_s32_max, init_s32_min);
7008 
7009 	if ((s32_min >= 0) == (s32_max >= 0)) {
7010 		reg->s32_min_value = s32_min;
7011 		reg->s32_max_value = s32_max;
7012 		reg->u32_min_value = (u32)s32_min;
7013 		reg->u32_max_value = (u32)s32_max;
7014 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
7015 		return;
7016 	}
7017 
7018 out:
7019 	set_sext32_default_val(reg, size);
7020 }
7021 
7022 static bool bpf_map_is_rdonly(const struct bpf_map *map)
7023 {
7024 	/* A map is considered read-only if the following condition are true:
7025 	 *
7026 	 * 1) BPF program side cannot change any of the map content. The
7027 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
7028 	 *    and was set at map creation time.
7029 	 * 2) The map value(s) have been initialized from user space by a
7030 	 *    loader and then "frozen", such that no new map update/delete
7031 	 *    operations from syscall side are possible for the rest of
7032 	 *    the map's lifetime from that point onwards.
7033 	 * 3) Any parallel/pending map update/delete operations from syscall
7034 	 *    side have been completed. Only after that point, it's safe to
7035 	 *    assume that map value(s) are immutable.
7036 	 */
7037 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
7038 	       READ_ONCE(map->frozen) &&
7039 	       !bpf_map_write_active(map);
7040 }
7041 
7042 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
7043 			       bool is_ldsx)
7044 {
7045 	void *ptr;
7046 	u64 addr;
7047 	int err;
7048 
7049 	err = map->ops->map_direct_value_addr(map, &addr, off);
7050 	if (err)
7051 		return err;
7052 	ptr = (void *)(long)addr + off;
7053 
7054 	switch (size) {
7055 	case sizeof(u8):
7056 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
7057 		break;
7058 	case sizeof(u16):
7059 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
7060 		break;
7061 	case sizeof(u32):
7062 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
7063 		break;
7064 	case sizeof(u64):
7065 		*val = *(u64 *)ptr;
7066 		break;
7067 	default:
7068 		return -EINVAL;
7069 	}
7070 	return 0;
7071 }
7072 
7073 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
7074 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
7075 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
7076 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
7077 
7078 /*
7079  * Allow list few fields as RCU trusted or full trusted.
7080  * This logic doesn't allow mix tagging and will be removed once GCC supports
7081  * btf_type_tag.
7082  */
7083 
7084 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
7085 BTF_TYPE_SAFE_RCU(struct task_struct) {
7086 	const cpumask_t *cpus_ptr;
7087 	struct css_set __rcu *cgroups;
7088 	struct task_struct __rcu *real_parent;
7089 	struct task_struct *group_leader;
7090 };
7091 
7092 BTF_TYPE_SAFE_RCU(struct cgroup) {
7093 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
7094 	struct kernfs_node *kn;
7095 };
7096 
7097 BTF_TYPE_SAFE_RCU(struct css_set) {
7098 	struct cgroup *dfl_cgrp;
7099 };
7100 
7101 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
7102 	struct cgroup *cgroup;
7103 };
7104 
7105 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
7106 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
7107 	struct file __rcu *exe_file;
7108 #ifdef CONFIG_MEMCG
7109 	struct task_struct __rcu *owner;
7110 #endif
7111 };
7112 
7113 /* skb->sk, req->sk are not RCU protected, but we mark them as such
7114  * because bpf prog accessible sockets are SOCK_RCU_FREE.
7115  */
7116 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
7117 	struct sock *sk;
7118 };
7119 
7120 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
7121 	struct sock *sk;
7122 };
7123 
7124 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
7125 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
7126 	struct seq_file *seq;
7127 };
7128 
7129 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
7130 	struct bpf_iter_meta *meta;
7131 	struct task_struct *task;
7132 };
7133 
7134 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
7135 	struct file *file;
7136 };
7137 
7138 BTF_TYPE_SAFE_TRUSTED(struct file) {
7139 	struct inode *f_inode;
7140 };
7141 
7142 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
7143 	struct inode *d_inode;
7144 };
7145 
7146 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
7147 	struct sock *sk;
7148 };
7149 
7150 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) {
7151 	struct mm_struct *vm_mm;
7152 	struct file *vm_file;
7153 };
7154 
7155 static bool type_is_rcu(struct bpf_verifier_env *env,
7156 			struct bpf_reg_state *reg,
7157 			const char *field_name, u32 btf_id)
7158 {
7159 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
7160 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
7161 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
7162 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
7163 
7164 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
7165 }
7166 
7167 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
7168 				struct bpf_reg_state *reg,
7169 				const char *field_name, u32 btf_id)
7170 {
7171 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
7172 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
7173 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
7174 
7175 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
7176 }
7177 
7178 static bool type_is_trusted(struct bpf_verifier_env *env,
7179 			    struct bpf_reg_state *reg,
7180 			    const char *field_name, u32 btf_id)
7181 {
7182 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
7183 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
7184 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
7185 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
7186 
7187 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
7188 }
7189 
7190 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
7191 				    struct bpf_reg_state *reg,
7192 				    const char *field_name, u32 btf_id)
7193 {
7194 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
7195 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
7196 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
7197 
7198 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
7199 					  "__safe_trusted_or_null");
7200 }
7201 
7202 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
7203 				   struct bpf_reg_state *regs,
7204 				   int regno, int off, int size,
7205 				   enum bpf_access_type atype,
7206 				   int value_regno)
7207 {
7208 	struct bpf_reg_state *reg = regs + regno;
7209 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
7210 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
7211 	const char *field_name = NULL;
7212 	enum bpf_type_flag flag = 0;
7213 	u32 btf_id = 0;
7214 	int ret;
7215 
7216 	if (!env->allow_ptr_leaks) {
7217 		verbose(env,
7218 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7219 			tname);
7220 		return -EPERM;
7221 	}
7222 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
7223 		verbose(env,
7224 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
7225 			tname);
7226 		return -EINVAL;
7227 	}
7228 	if (off < 0) {
7229 		verbose(env,
7230 			"R%d is ptr_%s invalid negative access: off=%d\n",
7231 			regno, tname, off);
7232 		return -EACCES;
7233 	}
7234 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
7235 		char tn_buf[48];
7236 
7237 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7238 		verbose(env,
7239 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
7240 			regno, tname, off, tn_buf);
7241 		return -EACCES;
7242 	}
7243 
7244 	if (reg->type & MEM_USER) {
7245 		verbose(env,
7246 			"R%d is ptr_%s access user memory: off=%d\n",
7247 			regno, tname, off);
7248 		return -EACCES;
7249 	}
7250 
7251 	if (reg->type & MEM_PERCPU) {
7252 		verbose(env,
7253 			"R%d is ptr_%s access percpu memory: off=%d\n",
7254 			regno, tname, off);
7255 		return -EACCES;
7256 	}
7257 
7258 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
7259 		if (!btf_is_kernel(reg->btf)) {
7260 			verifier_bug(env, "reg->btf must be kernel btf");
7261 			return -EFAULT;
7262 		}
7263 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
7264 	} else {
7265 		/* Writes are permitted with default btf_struct_access for
7266 		 * program allocated objects (which always have ref_obj_id > 0),
7267 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
7268 		 */
7269 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
7270 			verbose(env, "only read is supported\n");
7271 			return -EACCES;
7272 		}
7273 
7274 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
7275 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
7276 			verifier_bug(env, "ref_obj_id for allocated object must be non-zero");
7277 			return -EFAULT;
7278 		}
7279 
7280 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
7281 	}
7282 
7283 	if (ret < 0)
7284 		return ret;
7285 
7286 	if (ret != PTR_TO_BTF_ID) {
7287 		/* just mark; */
7288 
7289 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
7290 		/* If this is an untrusted pointer, all pointers formed by walking it
7291 		 * also inherit the untrusted flag.
7292 		 */
7293 		flag = PTR_UNTRUSTED;
7294 
7295 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
7296 		/* By default any pointer obtained from walking a trusted pointer is no
7297 		 * longer trusted, unless the field being accessed has explicitly been
7298 		 * marked as inheriting its parent's state of trust (either full or RCU).
7299 		 * For example:
7300 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
7301 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
7302 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
7303 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
7304 		 *
7305 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
7306 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
7307 		 */
7308 		if (type_is_trusted(env, reg, field_name, btf_id)) {
7309 			flag |= PTR_TRUSTED;
7310 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
7311 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
7312 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
7313 			if (type_is_rcu(env, reg, field_name, btf_id)) {
7314 				/* ignore __rcu tag and mark it MEM_RCU */
7315 				flag |= MEM_RCU;
7316 			} else if (flag & MEM_RCU ||
7317 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
7318 				/* __rcu tagged pointers can be NULL */
7319 				flag |= MEM_RCU | PTR_MAYBE_NULL;
7320 
7321 				/* We always trust them */
7322 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
7323 				    flag & PTR_UNTRUSTED)
7324 					flag &= ~PTR_UNTRUSTED;
7325 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
7326 				/* keep as-is */
7327 			} else {
7328 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
7329 				clear_trusted_flags(&flag);
7330 			}
7331 		} else {
7332 			/*
7333 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
7334 			 * aggressively mark as untrusted otherwise such
7335 			 * pointers will be plain PTR_TO_BTF_ID without flags
7336 			 * and will be allowed to be passed into helpers for
7337 			 * compat reasons.
7338 			 */
7339 			flag = PTR_UNTRUSTED;
7340 		}
7341 	} else {
7342 		/* Old compat. Deprecated */
7343 		clear_trusted_flags(&flag);
7344 	}
7345 
7346 	if (atype == BPF_READ && value_regno >= 0) {
7347 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
7348 		if (ret < 0)
7349 			return ret;
7350 	}
7351 
7352 	return 0;
7353 }
7354 
7355 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
7356 				   struct bpf_reg_state *regs,
7357 				   int regno, int off, int size,
7358 				   enum bpf_access_type atype,
7359 				   int value_regno)
7360 {
7361 	struct bpf_reg_state *reg = regs + regno;
7362 	struct bpf_map *map = reg->map_ptr;
7363 	struct bpf_reg_state map_reg;
7364 	enum bpf_type_flag flag = 0;
7365 	const struct btf_type *t;
7366 	const char *tname;
7367 	u32 btf_id;
7368 	int ret;
7369 
7370 	if (!btf_vmlinux) {
7371 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
7372 		return -ENOTSUPP;
7373 	}
7374 
7375 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
7376 		verbose(env, "map_ptr access not supported for map type %d\n",
7377 			map->map_type);
7378 		return -ENOTSUPP;
7379 	}
7380 
7381 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
7382 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
7383 
7384 	if (!env->allow_ptr_leaks) {
7385 		verbose(env,
7386 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7387 			tname);
7388 		return -EPERM;
7389 	}
7390 
7391 	if (off < 0) {
7392 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
7393 			regno, tname, off);
7394 		return -EACCES;
7395 	}
7396 
7397 	if (atype != BPF_READ) {
7398 		verbose(env, "only read from %s is supported\n", tname);
7399 		return -EACCES;
7400 	}
7401 
7402 	/* Simulate access to a PTR_TO_BTF_ID */
7403 	memset(&map_reg, 0, sizeof(map_reg));
7404 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
7405 			      btf_vmlinux, *map->ops->map_btf_id, 0);
7406 	if (ret < 0)
7407 		return ret;
7408 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
7409 	if (ret < 0)
7410 		return ret;
7411 
7412 	if (value_regno >= 0) {
7413 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
7414 		if (ret < 0)
7415 			return ret;
7416 	}
7417 
7418 	return 0;
7419 }
7420 
7421 /* Check that the stack access at the given offset is within bounds. The
7422  * maximum valid offset is -1.
7423  *
7424  * The minimum valid offset is -MAX_BPF_STACK for writes, and
7425  * -state->allocated_stack for reads.
7426  */
7427 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
7428                                           s64 off,
7429                                           struct bpf_func_state *state,
7430                                           enum bpf_access_type t)
7431 {
7432 	int min_valid_off;
7433 
7434 	if (t == BPF_WRITE || env->allow_uninit_stack)
7435 		min_valid_off = -MAX_BPF_STACK;
7436 	else
7437 		min_valid_off = -state->allocated_stack;
7438 
7439 	if (off < min_valid_off || off > -1)
7440 		return -EACCES;
7441 	return 0;
7442 }
7443 
7444 /* Check that the stack access at 'regno + off' falls within the maximum stack
7445  * bounds.
7446  *
7447  * 'off' includes `regno->offset`, but not its dynamic part (if any).
7448  */
7449 static int check_stack_access_within_bounds(
7450 		struct bpf_verifier_env *env,
7451 		int regno, int off, int access_size,
7452 		enum bpf_access_type type)
7453 {
7454 	struct bpf_reg_state *regs = cur_regs(env);
7455 	struct bpf_reg_state *reg = regs + regno;
7456 	struct bpf_func_state *state = func(env, reg);
7457 	s64 min_off, max_off;
7458 	int err;
7459 	char *err_extra;
7460 
7461 	if (type == BPF_READ)
7462 		err_extra = " read from";
7463 	else
7464 		err_extra = " write to";
7465 
7466 	if (tnum_is_const(reg->var_off)) {
7467 		min_off = (s64)reg->var_off.value + off;
7468 		max_off = min_off + access_size;
7469 	} else {
7470 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
7471 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
7472 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
7473 				err_extra, regno);
7474 			return -EACCES;
7475 		}
7476 		min_off = reg->smin_value + off;
7477 		max_off = reg->smax_value + off + access_size;
7478 	}
7479 
7480 	err = check_stack_slot_within_bounds(env, min_off, state, type);
7481 	if (!err && max_off > 0)
7482 		err = -EINVAL; /* out of stack access into non-negative offsets */
7483 	if (!err && access_size < 0)
7484 		/* access_size should not be negative (or overflow an int); others checks
7485 		 * along the way should have prevented such an access.
7486 		 */
7487 		err = -EFAULT; /* invalid negative access size; integer overflow? */
7488 
7489 	if (err) {
7490 		if (tnum_is_const(reg->var_off)) {
7491 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
7492 				err_extra, regno, off, access_size);
7493 		} else {
7494 			char tn_buf[48];
7495 
7496 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7497 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
7498 				err_extra, regno, tn_buf, off, access_size);
7499 		}
7500 		return err;
7501 	}
7502 
7503 	/* Note that there is no stack access with offset zero, so the needed stack
7504 	 * size is -min_off, not -min_off+1.
7505 	 */
7506 	return grow_stack_state(env, state, -min_off /* size */);
7507 }
7508 
7509 static bool get_func_retval_range(struct bpf_prog *prog,
7510 				  struct bpf_retval_range *range)
7511 {
7512 	if (prog->type == BPF_PROG_TYPE_LSM &&
7513 		prog->expected_attach_type == BPF_LSM_MAC &&
7514 		!bpf_lsm_get_retval_range(prog, range)) {
7515 		return true;
7516 	}
7517 	return false;
7518 }
7519 
7520 /* check whether memory at (regno + off) is accessible for t = (read | write)
7521  * if t==write, value_regno is a register which value is stored into memory
7522  * if t==read, value_regno is a register which will receive the value from memory
7523  * if t==write && value_regno==-1, some unknown value is stored into memory
7524  * if t==read && value_regno==-1, don't care what we read from memory
7525  */
7526 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
7527 			    int off, int bpf_size, enum bpf_access_type t,
7528 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7529 {
7530 	struct bpf_reg_state *regs = cur_regs(env);
7531 	struct bpf_reg_state *reg = regs + regno;
7532 	bool insn_array = reg->type == PTR_TO_MAP_VALUE &&
7533 			  reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY;
7534 	int size, err = 0;
7535 
7536 	size = bpf_size_to_bytes(bpf_size);
7537 	if (size < 0)
7538 		return size;
7539 
7540 	/* alignment checks will add in reg->off themselves */
7541 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once || insn_array);
7542 	if (err)
7543 		return err;
7544 
7545 	/* for access checks, reg->off is just part of off */
7546 	off += reg->off;
7547 
7548 	if (reg->type == PTR_TO_MAP_KEY) {
7549 		if (t == BPF_WRITE) {
7550 			verbose(env, "write to change key R%d not allowed\n", regno);
7551 			return -EACCES;
7552 		}
7553 
7554 		err = check_mem_region_access(env, regno, off, size,
7555 					      reg->map_ptr->key_size, false);
7556 		if (err)
7557 			return err;
7558 		if (value_regno >= 0)
7559 			mark_reg_unknown(env, regs, value_regno);
7560 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7561 		struct btf_field *kptr_field = NULL;
7562 
7563 		if (t == BPF_WRITE && value_regno >= 0 &&
7564 		    is_pointer_value(env, value_regno)) {
7565 			verbose(env, "R%d leaks addr into map\n", value_regno);
7566 			return -EACCES;
7567 		}
7568 		if (t == BPF_WRITE && insn_array) {
7569 			verbose(env, "writes into insn_array not allowed\n");
7570 			return -EACCES;
7571 		}
7572 
7573 		err = check_map_access_type(env, regno, off, size, t);
7574 		if (err)
7575 			return err;
7576 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
7577 		if (err)
7578 			return err;
7579 		if (tnum_is_const(reg->var_off))
7580 			kptr_field = btf_record_find(reg->map_ptr->record,
7581 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7582 		if (kptr_field) {
7583 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
7584 		} else if (t == BPF_READ && value_regno >= 0) {
7585 			struct bpf_map *map = reg->map_ptr;
7586 
7587 			/* if map is read-only, track its contents as scalars */
7588 			if (tnum_is_const(reg->var_off) &&
7589 			    bpf_map_is_rdonly(map) &&
7590 			    map->ops->map_direct_value_addr) {
7591 				int map_off = off + reg->var_off.value;
7592 				u64 val = 0;
7593 
7594 				err = bpf_map_direct_read(map, map_off, size,
7595 							  &val, is_ldsx);
7596 				if (err)
7597 					return err;
7598 
7599 				regs[value_regno].type = SCALAR_VALUE;
7600 				__mark_reg_known(&regs[value_regno], val);
7601 			} else if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
7602 				if (bpf_size != BPF_DW) {
7603 					verbose(env, "Invalid read of %d bytes from insn_array\n",
7604 						     size);
7605 					return -EACCES;
7606 				}
7607 				copy_register_state(&regs[value_regno], reg);
7608 				regs[value_regno].type = PTR_TO_INSN;
7609 			} else {
7610 				mark_reg_unknown(env, regs, value_regno);
7611 			}
7612 		}
7613 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7614 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7615 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
7616 
7617 		if (type_may_be_null(reg->type)) {
7618 			verbose(env, "R%d invalid mem access '%s'\n", regno,
7619 				reg_type_str(env, reg->type));
7620 			return -EACCES;
7621 		}
7622 
7623 		if (t == BPF_WRITE && rdonly_mem) {
7624 			verbose(env, "R%d cannot write into %s\n",
7625 				regno, reg_type_str(env, reg->type));
7626 			return -EACCES;
7627 		}
7628 
7629 		if (t == BPF_WRITE && value_regno >= 0 &&
7630 		    is_pointer_value(env, value_regno)) {
7631 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7632 			return -EACCES;
7633 		}
7634 
7635 		/*
7636 		 * Accesses to untrusted PTR_TO_MEM are done through probe
7637 		 * instructions, hence no need to check bounds in that case.
7638 		 */
7639 		if (!rdonly_untrusted)
7640 			err = check_mem_region_access(env, regno, off, size,
7641 						      reg->mem_size, false);
7642 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7643 			mark_reg_unknown(env, regs, value_regno);
7644 	} else if (reg->type == PTR_TO_CTX) {
7645 		struct bpf_retval_range range;
7646 		struct bpf_insn_access_aux info = {
7647 			.reg_type = SCALAR_VALUE,
7648 			.is_ldsx = is_ldsx,
7649 			.log = &env->log,
7650 		};
7651 
7652 		if (t == BPF_WRITE && value_regno >= 0 &&
7653 		    is_pointer_value(env, value_regno)) {
7654 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7655 			return -EACCES;
7656 		}
7657 
7658 		err = check_ptr_off_reg(env, reg, regno);
7659 		if (err < 0)
7660 			return err;
7661 
7662 		err = check_ctx_access(env, insn_idx, off, size, t, &info);
7663 		if (err)
7664 			verbose_linfo(env, insn_idx, "; ");
7665 		if (!err && t == BPF_READ && value_regno >= 0) {
7666 			/* ctx access returns either a scalar, or a
7667 			 * PTR_TO_PACKET[_META,_END]. In the latter
7668 			 * case, we know the offset is zero.
7669 			 */
7670 			if (info.reg_type == SCALAR_VALUE) {
7671 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
7672 					err = __mark_reg_s32_range(env, regs, value_regno,
7673 								   range.minval, range.maxval);
7674 					if (err)
7675 						return err;
7676 				} else {
7677 					mark_reg_unknown(env, regs, value_regno);
7678 				}
7679 			} else {
7680 				mark_reg_known_zero(env, regs,
7681 						    value_regno);
7682 				if (type_may_be_null(info.reg_type))
7683 					regs[value_regno].id = ++env->id_gen;
7684 				/* A load of ctx field could have different
7685 				 * actual load size with the one encoded in the
7686 				 * insn. When the dst is PTR, it is for sure not
7687 				 * a sub-register.
7688 				 */
7689 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7690 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
7691 					regs[value_regno].btf = info.btf;
7692 					regs[value_regno].btf_id = info.btf_id;
7693 					regs[value_regno].ref_obj_id = info.ref_obj_id;
7694 				}
7695 			}
7696 			regs[value_regno].type = info.reg_type;
7697 		}
7698 
7699 	} else if (reg->type == PTR_TO_STACK) {
7700 		/* Basic bounds checks. */
7701 		err = check_stack_access_within_bounds(env, regno, off, size, t);
7702 		if (err)
7703 			return err;
7704 
7705 		if (t == BPF_READ)
7706 			err = check_stack_read(env, regno, off, size,
7707 					       value_regno);
7708 		else
7709 			err = check_stack_write(env, regno, off, size,
7710 						value_regno, insn_idx);
7711 	} else if (reg_is_pkt_pointer(reg)) {
7712 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7713 			verbose(env, "cannot write into packet\n");
7714 			return -EACCES;
7715 		}
7716 		if (t == BPF_WRITE && value_regno >= 0 &&
7717 		    is_pointer_value(env, value_regno)) {
7718 			verbose(env, "R%d leaks addr into packet\n",
7719 				value_regno);
7720 			return -EACCES;
7721 		}
7722 		err = check_packet_access(env, regno, off, size, false);
7723 		if (!err && t == BPF_READ && value_regno >= 0)
7724 			mark_reg_unknown(env, regs, value_regno);
7725 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7726 		if (t == BPF_WRITE && value_regno >= 0 &&
7727 		    is_pointer_value(env, value_regno)) {
7728 			verbose(env, "R%d leaks addr into flow keys\n",
7729 				value_regno);
7730 			return -EACCES;
7731 		}
7732 
7733 		err = check_flow_keys_access(env, off, size);
7734 		if (!err && t == BPF_READ && value_regno >= 0)
7735 			mark_reg_unknown(env, regs, value_regno);
7736 	} else if (type_is_sk_pointer(reg->type)) {
7737 		if (t == BPF_WRITE) {
7738 			verbose(env, "R%d cannot write into %s\n",
7739 				regno, reg_type_str(env, reg->type));
7740 			return -EACCES;
7741 		}
7742 		err = check_sock_access(env, insn_idx, regno, off, size, t);
7743 		if (!err && value_regno >= 0)
7744 			mark_reg_unknown(env, regs, value_regno);
7745 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7746 		err = check_tp_buffer_access(env, reg, regno, off, size);
7747 		if (!err && t == BPF_READ && value_regno >= 0)
7748 			mark_reg_unknown(env, regs, value_regno);
7749 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7750 		   !type_may_be_null(reg->type)) {
7751 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7752 					      value_regno);
7753 	} else if (reg->type == CONST_PTR_TO_MAP) {
7754 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7755 					      value_regno);
7756 	} else if (base_type(reg->type) == PTR_TO_BUF) {
7757 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7758 		u32 *max_access;
7759 
7760 		if (rdonly_mem) {
7761 			if (t == BPF_WRITE) {
7762 				verbose(env, "R%d cannot write into %s\n",
7763 					regno, reg_type_str(env, reg->type));
7764 				return -EACCES;
7765 			}
7766 			max_access = &env->prog->aux->max_rdonly_access;
7767 		} else {
7768 			max_access = &env->prog->aux->max_rdwr_access;
7769 		}
7770 
7771 		err = check_buffer_access(env, reg, regno, off, size, false,
7772 					  max_access);
7773 
7774 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7775 			mark_reg_unknown(env, regs, value_regno);
7776 	} else if (reg->type == PTR_TO_ARENA) {
7777 		if (t == BPF_READ && value_regno >= 0)
7778 			mark_reg_unknown(env, regs, value_regno);
7779 	} else {
7780 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7781 			reg_type_str(env, reg->type));
7782 		return -EACCES;
7783 	}
7784 
7785 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7786 	    regs[value_regno].type == SCALAR_VALUE) {
7787 		if (!is_ldsx)
7788 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7789 			coerce_reg_to_size(&regs[value_regno], size);
7790 		else
7791 			coerce_reg_to_size_sx(&regs[value_regno], size);
7792 	}
7793 	return err;
7794 }
7795 
7796 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7797 			     bool allow_trust_mismatch);
7798 
7799 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
7800 			  bool strict_alignment_once, bool is_ldsx,
7801 			  bool allow_trust_mismatch, const char *ctx)
7802 {
7803 	struct bpf_reg_state *regs = cur_regs(env);
7804 	enum bpf_reg_type src_reg_type;
7805 	int err;
7806 
7807 	/* check src operand */
7808 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7809 	if (err)
7810 		return err;
7811 
7812 	/* check dst operand */
7813 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7814 	if (err)
7815 		return err;
7816 
7817 	src_reg_type = regs[insn->src_reg].type;
7818 
7819 	/* Check if (src_reg + off) is readable. The state of dst_reg will be
7820 	 * updated by this call.
7821 	 */
7822 	err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off,
7823 			       BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
7824 			       strict_alignment_once, is_ldsx);
7825 	err = err ?: save_aux_ptr_type(env, src_reg_type,
7826 				       allow_trust_mismatch);
7827 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
7828 
7829 	return err;
7830 }
7831 
7832 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
7833 			   bool strict_alignment_once)
7834 {
7835 	struct bpf_reg_state *regs = cur_regs(env);
7836 	enum bpf_reg_type dst_reg_type;
7837 	int err;
7838 
7839 	/* check src1 operand */
7840 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7841 	if (err)
7842 		return err;
7843 
7844 	/* check src2 operand */
7845 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7846 	if (err)
7847 		return err;
7848 
7849 	dst_reg_type = regs[insn->dst_reg].type;
7850 
7851 	/* Check if (dst_reg + off) is writeable. */
7852 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7853 			       BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
7854 			       strict_alignment_once, false);
7855 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
7856 
7857 	return err;
7858 }
7859 
7860 static int check_atomic_rmw(struct bpf_verifier_env *env,
7861 			    struct bpf_insn *insn)
7862 {
7863 	int load_reg;
7864 	int err;
7865 
7866 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7867 		verbose(env, "invalid atomic operand size\n");
7868 		return -EINVAL;
7869 	}
7870 
7871 	/* check src1 operand */
7872 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7873 	if (err)
7874 		return err;
7875 
7876 	/* check src2 operand */
7877 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7878 	if (err)
7879 		return err;
7880 
7881 	if (insn->imm == BPF_CMPXCHG) {
7882 		/* Check comparison of R0 with memory location */
7883 		const u32 aux_reg = BPF_REG_0;
7884 
7885 		err = check_reg_arg(env, aux_reg, SRC_OP);
7886 		if (err)
7887 			return err;
7888 
7889 		if (is_pointer_value(env, aux_reg)) {
7890 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7891 			return -EACCES;
7892 		}
7893 	}
7894 
7895 	if (is_pointer_value(env, insn->src_reg)) {
7896 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7897 		return -EACCES;
7898 	}
7899 
7900 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7901 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7902 			insn->dst_reg,
7903 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7904 		return -EACCES;
7905 	}
7906 
7907 	if (insn->imm & BPF_FETCH) {
7908 		if (insn->imm == BPF_CMPXCHG)
7909 			load_reg = BPF_REG_0;
7910 		else
7911 			load_reg = insn->src_reg;
7912 
7913 		/* check and record load of old value */
7914 		err = check_reg_arg(env, load_reg, DST_OP);
7915 		if (err)
7916 			return err;
7917 	} else {
7918 		/* This instruction accesses a memory location but doesn't
7919 		 * actually load it into a register.
7920 		 */
7921 		load_reg = -1;
7922 	}
7923 
7924 	/* Check whether we can read the memory, with second call for fetch
7925 	 * case to simulate the register fill.
7926 	 */
7927 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7928 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7929 	if (!err && load_reg >= 0)
7930 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
7931 				       insn->off, BPF_SIZE(insn->code),
7932 				       BPF_READ, load_reg, true, false);
7933 	if (err)
7934 		return err;
7935 
7936 	if (is_arena_reg(env, insn->dst_reg)) {
7937 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7938 		if (err)
7939 			return err;
7940 	}
7941 	/* Check whether we can write into the same memory. */
7942 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7943 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7944 	if (err)
7945 		return err;
7946 	return 0;
7947 }
7948 
7949 static int check_atomic_load(struct bpf_verifier_env *env,
7950 			     struct bpf_insn *insn)
7951 {
7952 	int err;
7953 
7954 	err = check_load_mem(env, insn, true, false, false, "atomic_load");
7955 	if (err)
7956 		return err;
7957 
7958 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
7959 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
7960 			insn->src_reg,
7961 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
7962 		return -EACCES;
7963 	}
7964 
7965 	return 0;
7966 }
7967 
7968 static int check_atomic_store(struct bpf_verifier_env *env,
7969 			      struct bpf_insn *insn)
7970 {
7971 	int err;
7972 
7973 	err = check_store_reg(env, insn, true);
7974 	if (err)
7975 		return err;
7976 
7977 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7978 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7979 			insn->dst_reg,
7980 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7981 		return -EACCES;
7982 	}
7983 
7984 	return 0;
7985 }
7986 
7987 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
7988 {
7989 	switch (insn->imm) {
7990 	case BPF_ADD:
7991 	case BPF_ADD | BPF_FETCH:
7992 	case BPF_AND:
7993 	case BPF_AND | BPF_FETCH:
7994 	case BPF_OR:
7995 	case BPF_OR | BPF_FETCH:
7996 	case BPF_XOR:
7997 	case BPF_XOR | BPF_FETCH:
7998 	case BPF_XCHG:
7999 	case BPF_CMPXCHG:
8000 		return check_atomic_rmw(env, insn);
8001 	case BPF_LOAD_ACQ:
8002 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
8003 			verbose(env,
8004 				"64-bit load-acquires are only supported on 64-bit arches\n");
8005 			return -EOPNOTSUPP;
8006 		}
8007 		return check_atomic_load(env, insn);
8008 	case BPF_STORE_REL:
8009 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
8010 			verbose(env,
8011 				"64-bit store-releases are only supported on 64-bit arches\n");
8012 			return -EOPNOTSUPP;
8013 		}
8014 		return check_atomic_store(env, insn);
8015 	default:
8016 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
8017 			insn->imm);
8018 		return -EINVAL;
8019 	}
8020 }
8021 
8022 /* When register 'regno' is used to read the stack (either directly or through
8023  * a helper function) make sure that it's within stack boundary and, depending
8024  * on the access type and privileges, that all elements of the stack are
8025  * initialized.
8026  *
8027  * 'off' includes 'regno->off', but not its dynamic part (if any).
8028  *
8029  * All registers that have been spilled on the stack in the slots within the
8030  * read offsets are marked as read.
8031  */
8032 static int check_stack_range_initialized(
8033 		struct bpf_verifier_env *env, int regno, int off,
8034 		int access_size, bool zero_size_allowed,
8035 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
8036 {
8037 	struct bpf_reg_state *reg = reg_state(env, regno);
8038 	struct bpf_func_state *state = func(env, reg);
8039 	int err, min_off, max_off, i, j, slot, spi;
8040 	/* Some accesses can write anything into the stack, others are
8041 	 * read-only.
8042 	 */
8043 	bool clobber = false;
8044 
8045 	if (access_size == 0 && !zero_size_allowed) {
8046 		verbose(env, "invalid zero-sized read\n");
8047 		return -EACCES;
8048 	}
8049 
8050 	if (type == BPF_WRITE)
8051 		clobber = true;
8052 
8053 	err = check_stack_access_within_bounds(env, regno, off, access_size, type);
8054 	if (err)
8055 		return err;
8056 
8057 
8058 	if (tnum_is_const(reg->var_off)) {
8059 		min_off = max_off = reg->var_off.value + off;
8060 	} else {
8061 		/* Variable offset is prohibited for unprivileged mode for
8062 		 * simplicity since it requires corresponding support in
8063 		 * Spectre masking for stack ALU.
8064 		 * See also retrieve_ptr_limit().
8065 		 */
8066 		if (!env->bypass_spec_v1) {
8067 			char tn_buf[48];
8068 
8069 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8070 			verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
8071 				regno, tn_buf);
8072 			return -EACCES;
8073 		}
8074 		/* Only initialized buffer on stack is allowed to be accessed
8075 		 * with variable offset. With uninitialized buffer it's hard to
8076 		 * guarantee that whole memory is marked as initialized on
8077 		 * helper return since specific bounds are unknown what may
8078 		 * cause uninitialized stack leaking.
8079 		 */
8080 		if (meta && meta->raw_mode)
8081 			meta = NULL;
8082 
8083 		min_off = reg->smin_value + off;
8084 		max_off = reg->smax_value + off;
8085 	}
8086 
8087 	if (meta && meta->raw_mode) {
8088 		/* Ensure we won't be overwriting dynptrs when simulating byte
8089 		 * by byte access in check_helper_call using meta.access_size.
8090 		 * This would be a problem if we have a helper in the future
8091 		 * which takes:
8092 		 *
8093 		 *	helper(uninit_mem, len, dynptr)
8094 		 *
8095 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
8096 		 * may end up writing to dynptr itself when touching memory from
8097 		 * arg 1. This can be relaxed on a case by case basis for known
8098 		 * safe cases, but reject due to the possibilitiy of aliasing by
8099 		 * default.
8100 		 */
8101 		for (i = min_off; i < max_off + access_size; i++) {
8102 			int stack_off = -i - 1;
8103 
8104 			spi = __get_spi(i);
8105 			/* raw_mode may write past allocated_stack */
8106 			if (state->allocated_stack <= stack_off)
8107 				continue;
8108 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
8109 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
8110 				return -EACCES;
8111 			}
8112 		}
8113 		meta->access_size = access_size;
8114 		meta->regno = regno;
8115 		return 0;
8116 	}
8117 
8118 	for (i = min_off; i < max_off + access_size; i++) {
8119 		u8 *stype;
8120 
8121 		slot = -i - 1;
8122 		spi = slot / BPF_REG_SIZE;
8123 		if (state->allocated_stack <= slot) {
8124 			verbose(env, "allocated_stack too small\n");
8125 			return -EFAULT;
8126 		}
8127 
8128 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
8129 		if (*stype == STACK_MISC)
8130 			goto mark;
8131 		if ((*stype == STACK_ZERO) ||
8132 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
8133 			if (clobber) {
8134 				/* helper can write anything into the stack */
8135 				*stype = STACK_MISC;
8136 			}
8137 			goto mark;
8138 		}
8139 
8140 		if (is_spilled_reg(&state->stack[spi]) &&
8141 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
8142 		     env->allow_ptr_leaks)) {
8143 			if (clobber) {
8144 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
8145 				for (j = 0; j < BPF_REG_SIZE; j++)
8146 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
8147 			}
8148 			goto mark;
8149 		}
8150 
8151 		if (tnum_is_const(reg->var_off)) {
8152 			verbose(env, "invalid read from stack R%d off %d+%d size %d\n",
8153 				regno, min_off, i - min_off, access_size);
8154 		} else {
8155 			char tn_buf[48];
8156 
8157 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8158 			verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n",
8159 				regno, tn_buf, i - min_off, access_size);
8160 		}
8161 		return -EACCES;
8162 mark:
8163 		/* reading any byte out of 8-byte 'spill_slot' will cause
8164 		 * the whole slot to be marked as 'read'
8165 		 */
8166 		err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi));
8167 		if (err)
8168 			return err;
8169 		/* We do not call bpf_mark_stack_write(), as we can not
8170 		 * be sure that whether stack slot is written to or not. Hence,
8171 		 * we must still conservatively propagate reads upwards even if
8172 		 * helper may write to the entire memory range.
8173 		 */
8174 	}
8175 	return 0;
8176 }
8177 
8178 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
8179 				   int access_size, enum bpf_access_type access_type,
8180 				   bool zero_size_allowed,
8181 				   struct bpf_call_arg_meta *meta)
8182 {
8183 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8184 	u32 *max_access;
8185 
8186 	switch (base_type(reg->type)) {
8187 	case PTR_TO_PACKET:
8188 	case PTR_TO_PACKET_META:
8189 		return check_packet_access(env, regno, reg->off, access_size,
8190 					   zero_size_allowed);
8191 	case PTR_TO_MAP_KEY:
8192 		if (access_type == BPF_WRITE) {
8193 			verbose(env, "R%d cannot write into %s\n", regno,
8194 				reg_type_str(env, reg->type));
8195 			return -EACCES;
8196 		}
8197 		return check_mem_region_access(env, regno, reg->off, access_size,
8198 					       reg->map_ptr->key_size, false);
8199 	case PTR_TO_MAP_VALUE:
8200 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
8201 			return -EACCES;
8202 		return check_map_access(env, regno, reg->off, access_size,
8203 					zero_size_allowed, ACCESS_HELPER);
8204 	case PTR_TO_MEM:
8205 		if (type_is_rdonly_mem(reg->type)) {
8206 			if (access_type == BPF_WRITE) {
8207 				verbose(env, "R%d cannot write into %s\n", regno,
8208 					reg_type_str(env, reg->type));
8209 				return -EACCES;
8210 			}
8211 		}
8212 		return check_mem_region_access(env, regno, reg->off,
8213 					       access_size, reg->mem_size,
8214 					       zero_size_allowed);
8215 	case PTR_TO_BUF:
8216 		if (type_is_rdonly_mem(reg->type)) {
8217 			if (access_type == BPF_WRITE) {
8218 				verbose(env, "R%d cannot write into %s\n", regno,
8219 					reg_type_str(env, reg->type));
8220 				return -EACCES;
8221 			}
8222 
8223 			max_access = &env->prog->aux->max_rdonly_access;
8224 		} else {
8225 			max_access = &env->prog->aux->max_rdwr_access;
8226 		}
8227 		return check_buffer_access(env, reg, regno, reg->off,
8228 					   access_size, zero_size_allowed,
8229 					   max_access);
8230 	case PTR_TO_STACK:
8231 		return check_stack_range_initialized(
8232 				env,
8233 				regno, reg->off, access_size,
8234 				zero_size_allowed, access_type, meta);
8235 	case PTR_TO_BTF_ID:
8236 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
8237 					       access_size, BPF_READ, -1);
8238 	case PTR_TO_CTX:
8239 		/* in case the function doesn't know how to access the context,
8240 		 * (because we are in a program of type SYSCALL for example), we
8241 		 * can not statically check its size.
8242 		 * Dynamically check it now.
8243 		 */
8244 		if (!env->ops->convert_ctx_access) {
8245 			int offset = access_size - 1;
8246 
8247 			/* Allow zero-byte read from PTR_TO_CTX */
8248 			if (access_size == 0)
8249 				return zero_size_allowed ? 0 : -EACCES;
8250 
8251 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
8252 						access_type, -1, false, false);
8253 		}
8254 
8255 		fallthrough;
8256 	default: /* scalar_value or invalid ptr */
8257 		/* Allow zero-byte read from NULL, regardless of pointer type */
8258 		if (zero_size_allowed && access_size == 0 &&
8259 		    register_is_null(reg))
8260 			return 0;
8261 
8262 		verbose(env, "R%d type=%s ", regno,
8263 			reg_type_str(env, reg->type));
8264 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
8265 		return -EACCES;
8266 	}
8267 }
8268 
8269 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
8270  * size.
8271  *
8272  * @regno is the register containing the access size. regno-1 is the register
8273  * containing the pointer.
8274  */
8275 static int check_mem_size_reg(struct bpf_verifier_env *env,
8276 			      struct bpf_reg_state *reg, u32 regno,
8277 			      enum bpf_access_type access_type,
8278 			      bool zero_size_allowed,
8279 			      struct bpf_call_arg_meta *meta)
8280 {
8281 	int err;
8282 
8283 	/* This is used to refine r0 return value bounds for helpers
8284 	 * that enforce this value as an upper bound on return values.
8285 	 * See do_refine_retval_range() for helpers that can refine
8286 	 * the return value. C type of helper is u32 so we pull register
8287 	 * bound from umax_value however, if negative verifier errors
8288 	 * out. Only upper bounds can be learned because retval is an
8289 	 * int type and negative retvals are allowed.
8290 	 */
8291 	meta->msize_max_value = reg->umax_value;
8292 
8293 	/* The register is SCALAR_VALUE; the access check happens using
8294 	 * its boundaries. For unprivileged variable accesses, disable
8295 	 * raw mode so that the program is required to initialize all
8296 	 * the memory that the helper could just partially fill up.
8297 	 */
8298 	if (!tnum_is_const(reg->var_off))
8299 		meta = NULL;
8300 
8301 	if (reg->smin_value < 0) {
8302 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
8303 			regno);
8304 		return -EACCES;
8305 	}
8306 
8307 	if (reg->umin_value == 0 && !zero_size_allowed) {
8308 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
8309 			regno, reg->umin_value, reg->umax_value);
8310 		return -EACCES;
8311 	}
8312 
8313 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
8314 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
8315 			regno);
8316 		return -EACCES;
8317 	}
8318 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
8319 				      access_type, zero_size_allowed, meta);
8320 	if (!err)
8321 		err = mark_chain_precision(env, regno);
8322 	return err;
8323 }
8324 
8325 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8326 			 u32 regno, u32 mem_size)
8327 {
8328 	bool may_be_null = type_may_be_null(reg->type);
8329 	struct bpf_reg_state saved_reg;
8330 	int err;
8331 
8332 	if (register_is_null(reg))
8333 		return 0;
8334 
8335 	/* Assuming that the register contains a value check if the memory
8336 	 * access is safe. Temporarily save and restore the register's state as
8337 	 * the conversion shouldn't be visible to a caller.
8338 	 */
8339 	if (may_be_null) {
8340 		saved_reg = *reg;
8341 		mark_ptr_not_null_reg(reg);
8342 	}
8343 
8344 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
8345 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
8346 
8347 	if (may_be_null)
8348 		*reg = saved_reg;
8349 
8350 	return err;
8351 }
8352 
8353 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8354 				    u32 regno)
8355 {
8356 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
8357 	bool may_be_null = type_may_be_null(mem_reg->type);
8358 	struct bpf_reg_state saved_reg;
8359 	struct bpf_call_arg_meta meta;
8360 	int err;
8361 
8362 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
8363 
8364 	memset(&meta, 0, sizeof(meta));
8365 
8366 	if (may_be_null) {
8367 		saved_reg = *mem_reg;
8368 		mark_ptr_not_null_reg(mem_reg);
8369 	}
8370 
8371 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
8372 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
8373 
8374 	if (may_be_null)
8375 		*mem_reg = saved_reg;
8376 
8377 	return err;
8378 }
8379 
8380 enum {
8381 	PROCESS_SPIN_LOCK = (1 << 0),
8382 	PROCESS_RES_LOCK  = (1 << 1),
8383 	PROCESS_LOCK_IRQ  = (1 << 2),
8384 };
8385 
8386 /* Implementation details:
8387  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
8388  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
8389  * Two bpf_map_lookups (even with the same key) will have different reg->id.
8390  * Two separate bpf_obj_new will also have different reg->id.
8391  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
8392  * clears reg->id after value_or_null->value transition, since the verifier only
8393  * cares about the range of access to valid map value pointer and doesn't care
8394  * about actual address of the map element.
8395  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
8396  * reg->id > 0 after value_or_null->value transition. By doing so
8397  * two bpf_map_lookups will be considered two different pointers that
8398  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
8399  * returned from bpf_obj_new.
8400  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8401  * dead-locks.
8402  * Since only one bpf_spin_lock is allowed the checks are simpler than
8403  * reg_is_refcounted() logic. The verifier needs to remember only
8404  * one spin_lock instead of array of acquired_refs.
8405  * env->cur_state->active_locks remembers which map value element or allocated
8406  * object got locked and clears it after bpf_spin_unlock.
8407  */
8408 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags)
8409 {
8410 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
8411 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
8412 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8413 	struct bpf_verifier_state *cur = env->cur_state;
8414 	bool is_const = tnum_is_const(reg->var_off);
8415 	bool is_irq = flags & PROCESS_LOCK_IRQ;
8416 	u64 val = reg->var_off.value;
8417 	struct bpf_map *map = NULL;
8418 	struct btf *btf = NULL;
8419 	struct btf_record *rec;
8420 	u32 spin_lock_off;
8421 	int err;
8422 
8423 	if (!is_const) {
8424 		verbose(env,
8425 			"R%d doesn't have constant offset. %s_lock has to be at the constant offset\n",
8426 			regno, lock_str);
8427 		return -EINVAL;
8428 	}
8429 	if (reg->type == PTR_TO_MAP_VALUE) {
8430 		map = reg->map_ptr;
8431 		if (!map->btf) {
8432 			verbose(env,
8433 				"map '%s' has to have BTF in order to use %s_lock\n",
8434 				map->name, lock_str);
8435 			return -EINVAL;
8436 		}
8437 	} else {
8438 		btf = reg->btf;
8439 	}
8440 
8441 	rec = reg_btf_record(reg);
8442 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
8443 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
8444 			map ? map->name : "kptr", lock_str);
8445 		return -EINVAL;
8446 	}
8447 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
8448 	if (spin_lock_off != val + reg->off) {
8449 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
8450 			val + reg->off, lock_str, spin_lock_off);
8451 		return -EINVAL;
8452 	}
8453 	if (is_lock) {
8454 		void *ptr;
8455 		int type;
8456 
8457 		if (map)
8458 			ptr = map;
8459 		else
8460 			ptr = btf;
8461 
8462 		if (!is_res_lock && cur->active_locks) {
8463 			if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) {
8464 				verbose(env,
8465 					"Locking two bpf_spin_locks are not allowed\n");
8466 				return -EINVAL;
8467 			}
8468 		} else if (is_res_lock && cur->active_locks) {
8469 			if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) {
8470 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
8471 				return -EINVAL;
8472 			}
8473 		}
8474 
8475 		if (is_res_lock && is_irq)
8476 			type = REF_TYPE_RES_LOCK_IRQ;
8477 		else if (is_res_lock)
8478 			type = REF_TYPE_RES_LOCK;
8479 		else
8480 			type = REF_TYPE_LOCK;
8481 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
8482 		if (err < 0) {
8483 			verbose(env, "Failed to acquire lock state\n");
8484 			return err;
8485 		}
8486 	} else {
8487 		void *ptr;
8488 		int type;
8489 
8490 		if (map)
8491 			ptr = map;
8492 		else
8493 			ptr = btf;
8494 
8495 		if (!cur->active_locks) {
8496 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
8497 			return -EINVAL;
8498 		}
8499 
8500 		if (is_res_lock && is_irq)
8501 			type = REF_TYPE_RES_LOCK_IRQ;
8502 		else if (is_res_lock)
8503 			type = REF_TYPE_RES_LOCK;
8504 		else
8505 			type = REF_TYPE_LOCK;
8506 		if (!find_lock_state(cur, type, reg->id, ptr)) {
8507 			verbose(env, "%s_unlock of different lock\n", lock_str);
8508 			return -EINVAL;
8509 		}
8510 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
8511 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
8512 			return -EINVAL;
8513 		}
8514 		if (release_lock_state(cur, type, reg->id, ptr)) {
8515 			verbose(env, "%s_unlock of different lock\n", lock_str);
8516 			return -EINVAL;
8517 		}
8518 
8519 		invalidate_non_owning_refs(env);
8520 	}
8521 	return 0;
8522 }
8523 
8524 /* Check if @regno is a pointer to a specific field in a map value */
8525 static int check_map_field_pointer(struct bpf_verifier_env *env, u32 regno,
8526 				   enum btf_field_type field_type)
8527 {
8528 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8529 	bool is_const = tnum_is_const(reg->var_off);
8530 	struct bpf_map *map = reg->map_ptr;
8531 	u64 val = reg->var_off.value;
8532 	const char *struct_name = btf_field_type_name(field_type);
8533 	int field_off = -1;
8534 
8535 	if (!is_const) {
8536 		verbose(env,
8537 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
8538 			regno, struct_name);
8539 		return -EINVAL;
8540 	}
8541 	if (!map->btf) {
8542 		verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name,
8543 			struct_name);
8544 		return -EINVAL;
8545 	}
8546 	if (!btf_record_has_field(map->record, field_type)) {
8547 		verbose(env, "map '%s' has no valid %s\n", map->name, struct_name);
8548 		return -EINVAL;
8549 	}
8550 	switch (field_type) {
8551 	case BPF_TIMER:
8552 		field_off = map->record->timer_off;
8553 		break;
8554 	case BPF_TASK_WORK:
8555 		field_off = map->record->task_work_off;
8556 		break;
8557 	case BPF_WORKQUEUE:
8558 		field_off = map->record->wq_off;
8559 		break;
8560 	default:
8561 		verifier_bug(env, "unsupported BTF field type: %s\n", struct_name);
8562 		return -EINVAL;
8563 	}
8564 	if (field_off != val + reg->off) {
8565 		verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n",
8566 			val + reg->off, struct_name, field_off);
8567 		return -EINVAL;
8568 	}
8569 	return 0;
8570 }
8571 
8572 static int process_timer_func(struct bpf_verifier_env *env, int regno,
8573 			      struct bpf_call_arg_meta *meta)
8574 {
8575 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8576 	struct bpf_map *map = reg->map_ptr;
8577 	int err;
8578 
8579 	err = check_map_field_pointer(env, regno, BPF_TIMER);
8580 	if (err)
8581 		return err;
8582 
8583 	if (meta->map_ptr) {
8584 		verifier_bug(env, "Two map pointers in a timer helper");
8585 		return -EFAULT;
8586 	}
8587 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8588 		verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
8589 		return -EOPNOTSUPP;
8590 	}
8591 	meta->map_uid = reg->map_uid;
8592 	meta->map_ptr = map;
8593 	return 0;
8594 }
8595 
8596 static int process_wq_func(struct bpf_verifier_env *env, int regno,
8597 			   struct bpf_kfunc_call_arg_meta *meta)
8598 {
8599 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8600 	struct bpf_map *map = reg->map_ptr;
8601 	int err;
8602 
8603 	err = check_map_field_pointer(env, regno, BPF_WORKQUEUE);
8604 	if (err)
8605 		return err;
8606 
8607 	if (meta->map.ptr) {
8608 		verifier_bug(env, "Two map pointers in a bpf_wq helper");
8609 		return -EFAULT;
8610 	}
8611 
8612 	meta->map.uid = reg->map_uid;
8613 	meta->map.ptr = map;
8614 	return 0;
8615 }
8616 
8617 static int process_task_work_func(struct bpf_verifier_env *env, int regno,
8618 				  struct bpf_kfunc_call_arg_meta *meta)
8619 {
8620 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8621 	struct bpf_map *map = reg->map_ptr;
8622 	int err;
8623 
8624 	err = check_map_field_pointer(env, regno, BPF_TASK_WORK);
8625 	if (err)
8626 		return err;
8627 
8628 	if (meta->map.ptr) {
8629 		verifier_bug(env, "Two map pointers in a bpf_task_work helper");
8630 		return -EFAULT;
8631 	}
8632 	meta->map.uid = reg->map_uid;
8633 	meta->map.ptr = map;
8634 	return 0;
8635 }
8636 
8637 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8638 			     struct bpf_call_arg_meta *meta)
8639 {
8640 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8641 	struct btf_field *kptr_field;
8642 	struct bpf_map *map_ptr;
8643 	struct btf_record *rec;
8644 	u32 kptr_off;
8645 
8646 	if (type_is_ptr_alloc_obj(reg->type)) {
8647 		rec = reg_btf_record(reg);
8648 	} else { /* PTR_TO_MAP_VALUE */
8649 		map_ptr = reg->map_ptr;
8650 		if (!map_ptr->btf) {
8651 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8652 				map_ptr->name);
8653 			return -EINVAL;
8654 		}
8655 		rec = map_ptr->record;
8656 		meta->map_ptr = map_ptr;
8657 	}
8658 
8659 	if (!tnum_is_const(reg->var_off)) {
8660 		verbose(env,
8661 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8662 			regno);
8663 		return -EINVAL;
8664 	}
8665 
8666 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8667 		verbose(env, "R%d has no valid kptr\n", regno);
8668 		return -EINVAL;
8669 	}
8670 
8671 	kptr_off = reg->off + reg->var_off.value;
8672 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8673 	if (!kptr_field) {
8674 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8675 		return -EACCES;
8676 	}
8677 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8678 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8679 		return -EACCES;
8680 	}
8681 	meta->kptr_field = kptr_field;
8682 	return 0;
8683 }
8684 
8685 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8686  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8687  *
8688  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8689  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8690  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8691  *
8692  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
8693  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
8694  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
8695  * mutate the view of the dynptr and also possibly destroy it. In the latter
8696  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
8697  * memory that dynptr points to.
8698  *
8699  * The verifier will keep track both levels of mutation (bpf_dynptr's in
8700  * reg->type and the memory's in reg->dynptr.type), but there is no support for
8701  * readonly dynptr view yet, hence only the first case is tracked and checked.
8702  *
8703  * This is consistent with how C applies the const modifier to a struct object,
8704  * where the pointer itself inside bpf_dynptr becomes const but not what it
8705  * points to.
8706  *
8707  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
8708  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
8709  */
8710 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
8711 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
8712 {
8713 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8714 	int err;
8715 
8716 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
8717 		verbose(env,
8718 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
8719 			regno - 1);
8720 		return -EINVAL;
8721 	}
8722 
8723 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
8724 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
8725 	 */
8726 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
8727 		verifier_bug(env, "misconfigured dynptr helper type flags");
8728 		return -EFAULT;
8729 	}
8730 
8731 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8732 	 *		 constructing a mutable bpf_dynptr object.
8733 	 *
8734 	 *		 Currently, this is only possible with PTR_TO_STACK
8735 	 *		 pointing to a region of at least 16 bytes which doesn't
8736 	 *		 contain an existing bpf_dynptr.
8737 	 *
8738 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
8739 	 *		 mutated or destroyed. However, the memory it points to
8740 	 *		 may be mutated.
8741 	 *
8742 	 *  None       - Points to a initialized dynptr that can be mutated and
8743 	 *		 destroyed, including mutation of the memory it points
8744 	 *		 to.
8745 	 */
8746 	if (arg_type & MEM_UNINIT) {
8747 		int i;
8748 
8749 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8750 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8751 			return -EINVAL;
8752 		}
8753 
8754 		/* we write BPF_DW bits (8 bytes) at a time */
8755 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8756 			err = check_mem_access(env, insn_idx, regno,
8757 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8758 			if (err)
8759 				return err;
8760 		}
8761 
8762 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
8763 	} else /* MEM_RDONLY and None case from above */ {
8764 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8765 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
8766 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
8767 			return -EINVAL;
8768 		}
8769 
8770 		if (!is_dynptr_reg_valid_init(env, reg)) {
8771 			verbose(env,
8772 				"Expected an initialized dynptr as arg #%d\n",
8773 				regno - 1);
8774 			return -EINVAL;
8775 		}
8776 
8777 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
8778 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
8779 			verbose(env,
8780 				"Expected a dynptr of type %s as arg #%d\n",
8781 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
8782 			return -EINVAL;
8783 		}
8784 
8785 		err = mark_dynptr_read(env, reg);
8786 	}
8787 	return err;
8788 }
8789 
8790 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
8791 {
8792 	struct bpf_func_state *state = func(env, reg);
8793 
8794 	return state->stack[spi].spilled_ptr.ref_obj_id;
8795 }
8796 
8797 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8798 {
8799 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8800 }
8801 
8802 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8803 {
8804 	return meta->kfunc_flags & KF_ITER_NEW;
8805 }
8806 
8807 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8808 {
8809 	return meta->kfunc_flags & KF_ITER_NEXT;
8810 }
8811 
8812 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8813 {
8814 	return meta->kfunc_flags & KF_ITER_DESTROY;
8815 }
8816 
8817 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
8818 			      const struct btf_param *arg)
8819 {
8820 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8821 	 * kfunc is iter state pointer
8822 	 */
8823 	if (is_iter_kfunc(meta))
8824 		return arg_idx == 0;
8825 
8826 	/* iter passed as an argument to a generic kfunc */
8827 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8828 }
8829 
8830 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
8831 			    struct bpf_kfunc_call_arg_meta *meta)
8832 {
8833 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8834 	const struct btf_type *t;
8835 	int spi, err, i, nr_slots, btf_id;
8836 
8837 	if (reg->type != PTR_TO_STACK) {
8838 		verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
8839 		return -EINVAL;
8840 	}
8841 
8842 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8843 	 * ensures struct convention, so we wouldn't need to do any BTF
8844 	 * validation here. But given iter state can be passed as a parameter
8845 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8846 	 * conservative here.
8847 	 */
8848 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8849 	if (btf_id < 0) {
8850 		verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
8851 		return -EINVAL;
8852 	}
8853 	t = btf_type_by_id(meta->btf, btf_id);
8854 	nr_slots = t->size / BPF_REG_SIZE;
8855 
8856 	if (is_iter_new_kfunc(meta)) {
8857 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8858 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8859 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8860 				iter_type_str(meta->btf, btf_id), regno - 1);
8861 			return -EINVAL;
8862 		}
8863 
8864 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8865 			err = check_mem_access(env, insn_idx, regno,
8866 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8867 			if (err)
8868 				return err;
8869 		}
8870 
8871 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8872 		if (err)
8873 			return err;
8874 	} else {
8875 		/* iter_next() or iter_destroy(), as well as any kfunc
8876 		 * accepting iter argument, expect initialized iter state
8877 		 */
8878 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8879 		switch (err) {
8880 		case 0:
8881 			break;
8882 		case -EINVAL:
8883 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
8884 				iter_type_str(meta->btf, btf_id), regno - 1);
8885 			return err;
8886 		case -EPROTO:
8887 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8888 			return err;
8889 		default:
8890 			return err;
8891 		}
8892 
8893 		spi = iter_get_spi(env, reg, nr_slots);
8894 		if (spi < 0)
8895 			return spi;
8896 
8897 		err = mark_iter_read(env, reg, spi, nr_slots);
8898 		if (err)
8899 			return err;
8900 
8901 		/* remember meta->iter info for process_iter_next_call() */
8902 		meta->iter.spi = spi;
8903 		meta->iter.frameno = reg->frameno;
8904 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8905 
8906 		if (is_iter_destroy_kfunc(meta)) {
8907 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8908 			if (err)
8909 				return err;
8910 		}
8911 	}
8912 
8913 	return 0;
8914 }
8915 
8916 /* Look for a previous loop entry at insn_idx: nearest parent state
8917  * stopped at insn_idx with callsites matching those in cur->frame.
8918  */
8919 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8920 						  struct bpf_verifier_state *cur,
8921 						  int insn_idx)
8922 {
8923 	struct bpf_verifier_state_list *sl;
8924 	struct bpf_verifier_state *st;
8925 	struct list_head *pos, *head;
8926 
8927 	/* Explored states are pushed in stack order, most recent states come first */
8928 	head = explored_state(env, insn_idx);
8929 	list_for_each(pos, head) {
8930 		sl = container_of(pos, struct bpf_verifier_state_list, node);
8931 		/* If st->branches != 0 state is a part of current DFS verification path,
8932 		 * hence cur & st for a loop.
8933 		 */
8934 		st = &sl->state;
8935 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8936 		    st->dfs_depth < cur->dfs_depth)
8937 			return st;
8938 	}
8939 
8940 	return NULL;
8941 }
8942 
8943 static void reset_idmap_scratch(struct bpf_verifier_env *env);
8944 static bool regs_exact(const struct bpf_reg_state *rold,
8945 		       const struct bpf_reg_state *rcur,
8946 		       struct bpf_idmap *idmap);
8947 
8948 static void maybe_widen_reg(struct bpf_verifier_env *env,
8949 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8950 			    struct bpf_idmap *idmap)
8951 {
8952 	if (rold->type != SCALAR_VALUE)
8953 		return;
8954 	if (rold->type != rcur->type)
8955 		return;
8956 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
8957 		return;
8958 	__mark_reg_unknown(env, rcur);
8959 }
8960 
8961 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8962 				   struct bpf_verifier_state *old,
8963 				   struct bpf_verifier_state *cur)
8964 {
8965 	struct bpf_func_state *fold, *fcur;
8966 	int i, fr, num_slots;
8967 
8968 	reset_idmap_scratch(env);
8969 	for (fr = old->curframe; fr >= 0; fr--) {
8970 		fold = old->frame[fr];
8971 		fcur = cur->frame[fr];
8972 
8973 		for (i = 0; i < MAX_BPF_REG; i++)
8974 			maybe_widen_reg(env,
8975 					&fold->regs[i],
8976 					&fcur->regs[i],
8977 					&env->idmap_scratch);
8978 
8979 		num_slots = min(fold->allocated_stack / BPF_REG_SIZE,
8980 				fcur->allocated_stack / BPF_REG_SIZE);
8981 		for (i = 0; i < num_slots; i++) {
8982 			if (!is_spilled_reg(&fold->stack[i]) ||
8983 			    !is_spilled_reg(&fcur->stack[i]))
8984 				continue;
8985 
8986 			maybe_widen_reg(env,
8987 					&fold->stack[i].spilled_ptr,
8988 					&fcur->stack[i].spilled_ptr,
8989 					&env->idmap_scratch);
8990 		}
8991 	}
8992 	return 0;
8993 }
8994 
8995 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8996 						 struct bpf_kfunc_call_arg_meta *meta)
8997 {
8998 	int iter_frameno = meta->iter.frameno;
8999 	int iter_spi = meta->iter.spi;
9000 
9001 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
9002 }
9003 
9004 /* process_iter_next_call() is called when verifier gets to iterator's next
9005  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
9006  * to it as just "iter_next()" in comments below.
9007  *
9008  * BPF verifier relies on a crucial contract for any iter_next()
9009  * implementation: it should *eventually* return NULL, and once that happens
9010  * it should keep returning NULL. That is, once iterator exhausts elements to
9011  * iterate, it should never reset or spuriously return new elements.
9012  *
9013  * With the assumption of such contract, process_iter_next_call() simulates
9014  * a fork in the verifier state to validate loop logic correctness and safety
9015  * without having to simulate infinite amount of iterations.
9016  *
9017  * In current state, we first assume that iter_next() returned NULL and
9018  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
9019  * conditions we should not form an infinite loop and should eventually reach
9020  * exit.
9021  *
9022  * Besides that, we also fork current state and enqueue it for later
9023  * verification. In a forked state we keep iterator state as ACTIVE
9024  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
9025  * also bump iteration depth to prevent erroneous infinite loop detection
9026  * later on (see iter_active_depths_differ() comment for details). In this
9027  * state we assume that we'll eventually loop back to another iter_next()
9028  * calls (it could be in exactly same location or in some other instruction,
9029  * it doesn't matter, we don't make any unnecessary assumptions about this,
9030  * everything revolves around iterator state in a stack slot, not which
9031  * instruction is calling iter_next()). When that happens, we either will come
9032  * to iter_next() with equivalent state and can conclude that next iteration
9033  * will proceed in exactly the same way as we just verified, so it's safe to
9034  * assume that loop converges. If not, we'll go on another iteration
9035  * simulation with a different input state, until all possible starting states
9036  * are validated or we reach maximum number of instructions limit.
9037  *
9038  * This way, we will either exhaustively discover all possible input states
9039  * that iterator loop can start with and eventually will converge, or we'll
9040  * effectively regress into bounded loop simulation logic and either reach
9041  * maximum number of instructions if loop is not provably convergent, or there
9042  * is some statically known limit on number of iterations (e.g., if there is
9043  * an explicit `if n > 100 then break;` statement somewhere in the loop).
9044  *
9045  * Iteration convergence logic in is_state_visited() relies on exact
9046  * states comparison, which ignores read and precision marks.
9047  * This is necessary because read and precision marks are not finalized
9048  * while in the loop. Exact comparison might preclude convergence for
9049  * simple programs like below:
9050  *
9051  *     i = 0;
9052  *     while(iter_next(&it))
9053  *       i++;
9054  *
9055  * At each iteration step i++ would produce a new distinct state and
9056  * eventually instruction processing limit would be reached.
9057  *
9058  * To avoid such behavior speculatively forget (widen) range for
9059  * imprecise scalar registers, if those registers were not precise at the
9060  * end of the previous iteration and do not match exactly.
9061  *
9062  * This is a conservative heuristic that allows to verify wide range of programs,
9063  * however it precludes verification of programs that conjure an
9064  * imprecise value on the first loop iteration and use it as precise on a second.
9065  * For example, the following safe program would fail to verify:
9066  *
9067  *     struct bpf_num_iter it;
9068  *     int arr[10];
9069  *     int i = 0, a = 0;
9070  *     bpf_iter_num_new(&it, 0, 10);
9071  *     while (bpf_iter_num_next(&it)) {
9072  *       if (a == 0) {
9073  *         a = 1;
9074  *         i = 7; // Because i changed verifier would forget
9075  *                // it's range on second loop entry.
9076  *       } else {
9077  *         arr[i] = 42; // This would fail to verify.
9078  *       }
9079  *     }
9080  *     bpf_iter_num_destroy(&it);
9081  */
9082 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
9083 				  struct bpf_kfunc_call_arg_meta *meta)
9084 {
9085 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
9086 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
9087 	struct bpf_reg_state *cur_iter, *queued_iter;
9088 
9089 	BTF_TYPE_EMIT(struct bpf_iter);
9090 
9091 	cur_iter = get_iter_from_state(cur_st, meta);
9092 
9093 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
9094 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
9095 		verifier_bug(env, "unexpected iterator state %d (%s)",
9096 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
9097 		return -EFAULT;
9098 	}
9099 
9100 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
9101 		/* Because iter_next() call is a checkpoint is_state_visitied()
9102 		 * should guarantee parent state with same call sites and insn_idx.
9103 		 */
9104 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
9105 		    !same_callsites(cur_st->parent, cur_st)) {
9106 			verifier_bug(env, "bad parent state for iter next call");
9107 			return -EFAULT;
9108 		}
9109 		/* Note cur_st->parent in the call below, it is necessary to skip
9110 		 * checkpoint created for cur_st by is_state_visited()
9111 		 * right at this instruction.
9112 		 */
9113 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
9114 		/* branch out active iter state */
9115 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
9116 		if (IS_ERR(queued_st))
9117 			return PTR_ERR(queued_st);
9118 
9119 		queued_iter = get_iter_from_state(queued_st, meta);
9120 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
9121 		queued_iter->iter.depth++;
9122 		if (prev_st)
9123 			widen_imprecise_scalars(env, prev_st, queued_st);
9124 
9125 		queued_fr = queued_st->frame[queued_st->curframe];
9126 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
9127 	}
9128 
9129 	/* switch to DRAINED state, but keep the depth unchanged */
9130 	/* mark current iter state as drained and assume returned NULL */
9131 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
9132 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
9133 
9134 	return 0;
9135 }
9136 
9137 static bool arg_type_is_mem_size(enum bpf_arg_type type)
9138 {
9139 	return type == ARG_CONST_SIZE ||
9140 	       type == ARG_CONST_SIZE_OR_ZERO;
9141 }
9142 
9143 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
9144 {
9145 	return base_type(type) == ARG_PTR_TO_MEM &&
9146 	       type & MEM_UNINIT;
9147 }
9148 
9149 static bool arg_type_is_release(enum bpf_arg_type type)
9150 {
9151 	return type & OBJ_RELEASE;
9152 }
9153 
9154 static bool arg_type_is_dynptr(enum bpf_arg_type type)
9155 {
9156 	return base_type(type) == ARG_PTR_TO_DYNPTR;
9157 }
9158 
9159 static int resolve_map_arg_type(struct bpf_verifier_env *env,
9160 				 const struct bpf_call_arg_meta *meta,
9161 				 enum bpf_arg_type *arg_type)
9162 {
9163 	if (!meta->map_ptr) {
9164 		/* kernel subsystem misconfigured verifier */
9165 		verifier_bug(env, "invalid map_ptr to access map->type");
9166 		return -EFAULT;
9167 	}
9168 
9169 	switch (meta->map_ptr->map_type) {
9170 	case BPF_MAP_TYPE_SOCKMAP:
9171 	case BPF_MAP_TYPE_SOCKHASH:
9172 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
9173 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
9174 		} else {
9175 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
9176 			return -EINVAL;
9177 		}
9178 		break;
9179 	case BPF_MAP_TYPE_BLOOM_FILTER:
9180 		if (meta->func_id == BPF_FUNC_map_peek_elem)
9181 			*arg_type = ARG_PTR_TO_MAP_VALUE;
9182 		break;
9183 	default:
9184 		break;
9185 	}
9186 	return 0;
9187 }
9188 
9189 struct bpf_reg_types {
9190 	const enum bpf_reg_type types[10];
9191 	u32 *btf_id;
9192 };
9193 
9194 static const struct bpf_reg_types sock_types = {
9195 	.types = {
9196 		PTR_TO_SOCK_COMMON,
9197 		PTR_TO_SOCKET,
9198 		PTR_TO_TCP_SOCK,
9199 		PTR_TO_XDP_SOCK,
9200 	},
9201 };
9202 
9203 #ifdef CONFIG_NET
9204 static const struct bpf_reg_types btf_id_sock_common_types = {
9205 	.types = {
9206 		PTR_TO_SOCK_COMMON,
9207 		PTR_TO_SOCKET,
9208 		PTR_TO_TCP_SOCK,
9209 		PTR_TO_XDP_SOCK,
9210 		PTR_TO_BTF_ID,
9211 		PTR_TO_BTF_ID | PTR_TRUSTED,
9212 	},
9213 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9214 };
9215 #endif
9216 
9217 static const struct bpf_reg_types mem_types = {
9218 	.types = {
9219 		PTR_TO_STACK,
9220 		PTR_TO_PACKET,
9221 		PTR_TO_PACKET_META,
9222 		PTR_TO_MAP_KEY,
9223 		PTR_TO_MAP_VALUE,
9224 		PTR_TO_MEM,
9225 		PTR_TO_MEM | MEM_RINGBUF,
9226 		PTR_TO_BUF,
9227 		PTR_TO_BTF_ID | PTR_TRUSTED,
9228 	},
9229 };
9230 
9231 static const struct bpf_reg_types spin_lock_types = {
9232 	.types = {
9233 		PTR_TO_MAP_VALUE,
9234 		PTR_TO_BTF_ID | MEM_ALLOC,
9235 	}
9236 };
9237 
9238 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
9239 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
9240 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
9241 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
9242 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
9243 static const struct bpf_reg_types btf_ptr_types = {
9244 	.types = {
9245 		PTR_TO_BTF_ID,
9246 		PTR_TO_BTF_ID | PTR_TRUSTED,
9247 		PTR_TO_BTF_ID | MEM_RCU,
9248 	},
9249 };
9250 static const struct bpf_reg_types percpu_btf_ptr_types = {
9251 	.types = {
9252 		PTR_TO_BTF_ID | MEM_PERCPU,
9253 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
9254 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
9255 	}
9256 };
9257 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
9258 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
9259 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
9260 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
9261 static const struct bpf_reg_types kptr_xchg_dest_types = {
9262 	.types = {
9263 		PTR_TO_MAP_VALUE,
9264 		PTR_TO_BTF_ID | MEM_ALLOC
9265 	}
9266 };
9267 static const struct bpf_reg_types dynptr_types = {
9268 	.types = {
9269 		PTR_TO_STACK,
9270 		CONST_PTR_TO_DYNPTR,
9271 	}
9272 };
9273 
9274 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
9275 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
9276 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
9277 	[ARG_CONST_SIZE]		= &scalar_types,
9278 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
9279 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
9280 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
9281 	[ARG_PTR_TO_CTX]		= &context_types,
9282 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
9283 #ifdef CONFIG_NET
9284 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
9285 #endif
9286 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
9287 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
9288 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
9289 	[ARG_PTR_TO_MEM]		= &mem_types,
9290 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
9291 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
9292 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
9293 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
9294 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
9295 	[ARG_PTR_TO_TIMER]		= &timer_types,
9296 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
9297 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
9298 };
9299 
9300 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
9301 			  enum bpf_arg_type arg_type,
9302 			  const u32 *arg_btf_id,
9303 			  struct bpf_call_arg_meta *meta)
9304 {
9305 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9306 	enum bpf_reg_type expected, type = reg->type;
9307 	const struct bpf_reg_types *compatible;
9308 	int i, j;
9309 
9310 	compatible = compatible_reg_types[base_type(arg_type)];
9311 	if (!compatible) {
9312 		verifier_bug(env, "unsupported arg type %d", arg_type);
9313 		return -EFAULT;
9314 	}
9315 
9316 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
9317 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
9318 	 *
9319 	 * Same for MAYBE_NULL:
9320 	 *
9321 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
9322 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
9323 	 *
9324 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
9325 	 *
9326 	 * Therefore we fold these flags depending on the arg_type before comparison.
9327 	 */
9328 	if (arg_type & MEM_RDONLY)
9329 		type &= ~MEM_RDONLY;
9330 	if (arg_type & PTR_MAYBE_NULL)
9331 		type &= ~PTR_MAYBE_NULL;
9332 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
9333 		type &= ~DYNPTR_TYPE_FLAG_MASK;
9334 
9335 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
9336 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
9337 		type &= ~MEM_ALLOC;
9338 		type &= ~MEM_PERCPU;
9339 	}
9340 
9341 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
9342 		expected = compatible->types[i];
9343 		if (expected == NOT_INIT)
9344 			break;
9345 
9346 		if (type == expected)
9347 			goto found;
9348 	}
9349 
9350 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
9351 	for (j = 0; j + 1 < i; j++)
9352 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
9353 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
9354 	return -EACCES;
9355 
9356 found:
9357 	if (base_type(reg->type) != PTR_TO_BTF_ID)
9358 		return 0;
9359 
9360 	if (compatible == &mem_types) {
9361 		if (!(arg_type & MEM_RDONLY)) {
9362 			verbose(env,
9363 				"%s() may write into memory pointed by R%d type=%s\n",
9364 				func_id_name(meta->func_id),
9365 				regno, reg_type_str(env, reg->type));
9366 			return -EACCES;
9367 		}
9368 		return 0;
9369 	}
9370 
9371 	switch ((int)reg->type) {
9372 	case PTR_TO_BTF_ID:
9373 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9374 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
9375 	case PTR_TO_BTF_ID | MEM_RCU:
9376 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
9377 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
9378 	{
9379 		/* For bpf_sk_release, it needs to match against first member
9380 		 * 'struct sock_common', hence make an exception for it. This
9381 		 * allows bpf_sk_release to work for multiple socket types.
9382 		 */
9383 		bool strict_type_match = arg_type_is_release(arg_type) &&
9384 					 meta->func_id != BPF_FUNC_sk_release;
9385 
9386 		if (type_may_be_null(reg->type) &&
9387 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
9388 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
9389 			return -EACCES;
9390 		}
9391 
9392 		if (!arg_btf_id) {
9393 			if (!compatible->btf_id) {
9394 				verifier_bug(env, "missing arg compatible BTF ID");
9395 				return -EFAULT;
9396 			}
9397 			arg_btf_id = compatible->btf_id;
9398 		}
9399 
9400 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
9401 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9402 				return -EACCES;
9403 		} else {
9404 			if (arg_btf_id == BPF_PTR_POISON) {
9405 				verbose(env, "verifier internal error:");
9406 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
9407 					regno);
9408 				return -EACCES;
9409 			}
9410 
9411 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
9412 						  btf_vmlinux, *arg_btf_id,
9413 						  strict_type_match)) {
9414 				verbose(env, "R%d is of type %s but %s is expected\n",
9415 					regno, btf_type_name(reg->btf, reg->btf_id),
9416 					btf_type_name(btf_vmlinux, *arg_btf_id));
9417 				return -EACCES;
9418 			}
9419 		}
9420 		break;
9421 	}
9422 	case PTR_TO_BTF_ID | MEM_ALLOC:
9423 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
9424 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
9425 		    meta->func_id != BPF_FUNC_kptr_xchg) {
9426 			verifier_bug(env, "unimplemented handling of MEM_ALLOC");
9427 			return -EFAULT;
9428 		}
9429 		/* Check if local kptr in src arg matches kptr in dst arg */
9430 		if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
9431 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9432 				return -EACCES;
9433 		}
9434 		break;
9435 	case PTR_TO_BTF_ID | MEM_PERCPU:
9436 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
9437 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
9438 		/* Handled by helper specific checks */
9439 		break;
9440 	default:
9441 		verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match");
9442 		return -EFAULT;
9443 	}
9444 	return 0;
9445 }
9446 
9447 static struct btf_field *
9448 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
9449 {
9450 	struct btf_field *field;
9451 	struct btf_record *rec;
9452 
9453 	rec = reg_btf_record(reg);
9454 	if (!rec)
9455 		return NULL;
9456 
9457 	field = btf_record_find(rec, off, fields);
9458 	if (!field)
9459 		return NULL;
9460 
9461 	return field;
9462 }
9463 
9464 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
9465 				  const struct bpf_reg_state *reg, int regno,
9466 				  enum bpf_arg_type arg_type)
9467 {
9468 	u32 type = reg->type;
9469 
9470 	/* When referenced register is passed to release function, its fixed
9471 	 * offset must be 0.
9472 	 *
9473 	 * We will check arg_type_is_release reg has ref_obj_id when storing
9474 	 * meta->release_regno.
9475 	 */
9476 	if (arg_type_is_release(arg_type)) {
9477 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
9478 		 * may not directly point to the object being released, but to
9479 		 * dynptr pointing to such object, which might be at some offset
9480 		 * on the stack. In that case, we simply to fallback to the
9481 		 * default handling.
9482 		 */
9483 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
9484 			return 0;
9485 
9486 		/* Doing check_ptr_off_reg check for the offset will catch this
9487 		 * because fixed_off_ok is false, but checking here allows us
9488 		 * to give the user a better error message.
9489 		 */
9490 		if (reg->off) {
9491 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
9492 				regno);
9493 			return -EINVAL;
9494 		}
9495 		return __check_ptr_off_reg(env, reg, regno, false);
9496 	}
9497 
9498 	switch (type) {
9499 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9500 	case PTR_TO_STACK:
9501 	case PTR_TO_PACKET:
9502 	case PTR_TO_PACKET_META:
9503 	case PTR_TO_MAP_KEY:
9504 	case PTR_TO_MAP_VALUE:
9505 	case PTR_TO_MEM:
9506 	case PTR_TO_MEM | MEM_RDONLY:
9507 	case PTR_TO_MEM | MEM_RINGBUF:
9508 	case PTR_TO_BUF:
9509 	case PTR_TO_BUF | MEM_RDONLY:
9510 	case PTR_TO_ARENA:
9511 	case SCALAR_VALUE:
9512 		return 0;
9513 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9514 	 * fixed offset.
9515 	 */
9516 	case PTR_TO_BTF_ID:
9517 	case PTR_TO_BTF_ID | MEM_ALLOC:
9518 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9519 	case PTR_TO_BTF_ID | MEM_RCU:
9520 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9521 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9522 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9523 		 * its fixed offset must be 0. In the other cases, fixed offset
9524 		 * can be non-zero. This was already checked above. So pass
9525 		 * fixed_off_ok as true to allow fixed offset for all other
9526 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
9527 		 * still need to do checks instead of returning.
9528 		 */
9529 		return __check_ptr_off_reg(env, reg, regno, true);
9530 	default:
9531 		return __check_ptr_off_reg(env, reg, regno, false);
9532 	}
9533 }
9534 
9535 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
9536 						const struct bpf_func_proto *fn,
9537 						struct bpf_reg_state *regs)
9538 {
9539 	struct bpf_reg_state *state = NULL;
9540 	int i;
9541 
9542 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
9543 		if (arg_type_is_dynptr(fn->arg_type[i])) {
9544 			if (state) {
9545 				verbose(env, "verifier internal error: multiple dynptr args\n");
9546 				return NULL;
9547 			}
9548 			state = &regs[BPF_REG_1 + i];
9549 		}
9550 
9551 	if (!state)
9552 		verbose(env, "verifier internal error: no dynptr arg found\n");
9553 
9554 	return state;
9555 }
9556 
9557 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9558 {
9559 	struct bpf_func_state *state = func(env, reg);
9560 	int spi;
9561 
9562 	if (reg->type == CONST_PTR_TO_DYNPTR)
9563 		return reg->id;
9564 	spi = dynptr_get_spi(env, reg);
9565 	if (spi < 0)
9566 		return spi;
9567 	return state->stack[spi].spilled_ptr.id;
9568 }
9569 
9570 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9571 {
9572 	struct bpf_func_state *state = func(env, reg);
9573 	int spi;
9574 
9575 	if (reg->type == CONST_PTR_TO_DYNPTR)
9576 		return reg->ref_obj_id;
9577 	spi = dynptr_get_spi(env, reg);
9578 	if (spi < 0)
9579 		return spi;
9580 	return state->stack[spi].spilled_ptr.ref_obj_id;
9581 }
9582 
9583 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
9584 					    struct bpf_reg_state *reg)
9585 {
9586 	struct bpf_func_state *state = func(env, reg);
9587 	int spi;
9588 
9589 	if (reg->type == CONST_PTR_TO_DYNPTR)
9590 		return reg->dynptr.type;
9591 
9592 	spi = __get_spi(reg->off);
9593 	if (spi < 0) {
9594 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
9595 		return BPF_DYNPTR_TYPE_INVALID;
9596 	}
9597 
9598 	return state->stack[spi].spilled_ptr.dynptr.type;
9599 }
9600 
9601 static int check_reg_const_str(struct bpf_verifier_env *env,
9602 			       struct bpf_reg_state *reg, u32 regno)
9603 {
9604 	struct bpf_map *map = reg->map_ptr;
9605 	int err;
9606 	int map_off;
9607 	u64 map_addr;
9608 	char *str_ptr;
9609 
9610 	if (reg->type != PTR_TO_MAP_VALUE)
9611 		return -EINVAL;
9612 
9613 	if (!bpf_map_is_rdonly(map)) {
9614 		verbose(env, "R%d does not point to a readonly map'\n", regno);
9615 		return -EACCES;
9616 	}
9617 
9618 	if (!tnum_is_const(reg->var_off)) {
9619 		verbose(env, "R%d is not a constant address'\n", regno);
9620 		return -EACCES;
9621 	}
9622 
9623 	if (!map->ops->map_direct_value_addr) {
9624 		verbose(env, "no direct value access support for this map type\n");
9625 		return -EACCES;
9626 	}
9627 
9628 	err = check_map_access(env, regno, reg->off,
9629 			       map->value_size - reg->off, false,
9630 			       ACCESS_HELPER);
9631 	if (err)
9632 		return err;
9633 
9634 	map_off = reg->off + reg->var_off.value;
9635 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9636 	if (err) {
9637 		verbose(env, "direct value access on string failed\n");
9638 		return err;
9639 	}
9640 
9641 	str_ptr = (char *)(long)(map_addr);
9642 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9643 		verbose(env, "string is not zero-terminated\n");
9644 		return -EINVAL;
9645 	}
9646 	return 0;
9647 }
9648 
9649 /* Returns constant key value in `value` if possible, else negative error */
9650 static int get_constant_map_key(struct bpf_verifier_env *env,
9651 				struct bpf_reg_state *key,
9652 				u32 key_size,
9653 				s64 *value)
9654 {
9655 	struct bpf_func_state *state = func(env, key);
9656 	struct bpf_reg_state *reg;
9657 	int slot, spi, off;
9658 	int spill_size = 0;
9659 	int zero_size = 0;
9660 	int stack_off;
9661 	int i, err;
9662 	u8 *stype;
9663 
9664 	if (!env->bpf_capable)
9665 		return -EOPNOTSUPP;
9666 	if (key->type != PTR_TO_STACK)
9667 		return -EOPNOTSUPP;
9668 	if (!tnum_is_const(key->var_off))
9669 		return -EOPNOTSUPP;
9670 
9671 	stack_off = key->off + key->var_off.value;
9672 	slot = -stack_off - 1;
9673 	spi = slot / BPF_REG_SIZE;
9674 	off = slot % BPF_REG_SIZE;
9675 	stype = state->stack[spi].slot_type;
9676 
9677 	/* First handle precisely tracked STACK_ZERO */
9678 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9679 		zero_size++;
9680 	if (zero_size >= key_size) {
9681 		*value = 0;
9682 		return 0;
9683 	}
9684 
9685 	/* Check that stack contains a scalar spill of expected size */
9686 	if (!is_spilled_scalar_reg(&state->stack[spi]))
9687 		return -EOPNOTSUPP;
9688 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9689 		spill_size++;
9690 	if (spill_size != key_size)
9691 		return -EOPNOTSUPP;
9692 
9693 	reg = &state->stack[spi].spilled_ptr;
9694 	if (!tnum_is_const(reg->var_off))
9695 		/* Stack value not statically known */
9696 		return -EOPNOTSUPP;
9697 
9698 	/* We are relying on a constant value. So mark as precise
9699 	 * to prevent pruning on it.
9700 	 */
9701 	bt_set_frame_slot(&env->bt, key->frameno, spi);
9702 	err = mark_chain_precision_batch(env, env->cur_state);
9703 	if (err < 0)
9704 		return err;
9705 
9706 	*value = reg->var_off.value;
9707 	return 0;
9708 }
9709 
9710 static bool can_elide_value_nullness(enum bpf_map_type type);
9711 
9712 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9713 			  struct bpf_call_arg_meta *meta,
9714 			  const struct bpf_func_proto *fn,
9715 			  int insn_idx)
9716 {
9717 	u32 regno = BPF_REG_1 + arg;
9718 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9719 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9720 	enum bpf_reg_type type = reg->type;
9721 	u32 *arg_btf_id = NULL;
9722 	u32 key_size;
9723 	int err = 0;
9724 
9725 	if (arg_type == ARG_DONTCARE)
9726 		return 0;
9727 
9728 	err = check_reg_arg(env, regno, SRC_OP);
9729 	if (err)
9730 		return err;
9731 
9732 	if (arg_type == ARG_ANYTHING) {
9733 		if (is_pointer_value(env, regno)) {
9734 			verbose(env, "R%d leaks addr into helper function\n",
9735 				regno);
9736 			return -EACCES;
9737 		}
9738 		return 0;
9739 	}
9740 
9741 	if (type_is_pkt_pointer(type) &&
9742 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9743 		verbose(env, "helper access to the packet is not allowed\n");
9744 		return -EACCES;
9745 	}
9746 
9747 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9748 		err = resolve_map_arg_type(env, meta, &arg_type);
9749 		if (err)
9750 			return err;
9751 	}
9752 
9753 	if (register_is_null(reg) && type_may_be_null(arg_type))
9754 		/* A NULL register has a SCALAR_VALUE type, so skip
9755 		 * type checking.
9756 		 */
9757 		goto skip_type_check;
9758 
9759 	/* arg_btf_id and arg_size are in a union. */
9760 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9761 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9762 		arg_btf_id = fn->arg_btf_id[arg];
9763 
9764 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9765 	if (err)
9766 		return err;
9767 
9768 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
9769 	if (err)
9770 		return err;
9771 
9772 skip_type_check:
9773 	if (arg_type_is_release(arg_type)) {
9774 		if (arg_type_is_dynptr(arg_type)) {
9775 			struct bpf_func_state *state = func(env, reg);
9776 			int spi;
9777 
9778 			/* Only dynptr created on stack can be released, thus
9779 			 * the get_spi and stack state checks for spilled_ptr
9780 			 * should only be done before process_dynptr_func for
9781 			 * PTR_TO_STACK.
9782 			 */
9783 			if (reg->type == PTR_TO_STACK) {
9784 				spi = dynptr_get_spi(env, reg);
9785 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9786 					verbose(env, "arg %d is an unacquired reference\n", regno);
9787 					return -EINVAL;
9788 				}
9789 			} else {
9790 				verbose(env, "cannot release unowned const bpf_dynptr\n");
9791 				return -EINVAL;
9792 			}
9793 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
9794 			verbose(env, "R%d must be referenced when passed to release function\n",
9795 				regno);
9796 			return -EINVAL;
9797 		}
9798 		if (meta->release_regno) {
9799 			verifier_bug(env, "more than one release argument");
9800 			return -EFAULT;
9801 		}
9802 		meta->release_regno = regno;
9803 	}
9804 
9805 	if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9806 		if (meta->ref_obj_id) {
9807 			verbose(env, "more than one arg with ref_obj_id R%d %u %u",
9808 				regno, reg->ref_obj_id,
9809 				meta->ref_obj_id);
9810 			return -EACCES;
9811 		}
9812 		meta->ref_obj_id = reg->ref_obj_id;
9813 	}
9814 
9815 	switch (base_type(arg_type)) {
9816 	case ARG_CONST_MAP_PTR:
9817 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9818 		if (meta->map_ptr) {
9819 			/* Use map_uid (which is unique id of inner map) to reject:
9820 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9821 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9822 			 * if (inner_map1 && inner_map2) {
9823 			 *     timer = bpf_map_lookup_elem(inner_map1);
9824 			 *     if (timer)
9825 			 *         // mismatch would have been allowed
9826 			 *         bpf_timer_init(timer, inner_map2);
9827 			 * }
9828 			 *
9829 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
9830 			 */
9831 			if (meta->map_ptr != reg->map_ptr ||
9832 			    meta->map_uid != reg->map_uid) {
9833 				verbose(env,
9834 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9835 					meta->map_uid, reg->map_uid);
9836 				return -EINVAL;
9837 			}
9838 		}
9839 		meta->map_ptr = reg->map_ptr;
9840 		meta->map_uid = reg->map_uid;
9841 		break;
9842 	case ARG_PTR_TO_MAP_KEY:
9843 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9844 		 * check that [key, key + map->key_size) are within
9845 		 * stack limits and initialized
9846 		 */
9847 		if (!meta->map_ptr) {
9848 			/* in function declaration map_ptr must come before
9849 			 * map_key, so that it's verified and known before
9850 			 * we have to check map_key here. Otherwise it means
9851 			 * that kernel subsystem misconfigured verifier
9852 			 */
9853 			verifier_bug(env, "invalid map_ptr to access map->key");
9854 			return -EFAULT;
9855 		}
9856 		key_size = meta->map_ptr->key_size;
9857 		err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL);
9858 		if (err)
9859 			return err;
9860 		if (can_elide_value_nullness(meta->map_ptr->map_type)) {
9861 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9862 			if (err < 0) {
9863 				meta->const_map_key = -1;
9864 				if (err == -EOPNOTSUPP)
9865 					err = 0;
9866 				else
9867 					return err;
9868 			}
9869 		}
9870 		break;
9871 	case ARG_PTR_TO_MAP_VALUE:
9872 		if (type_may_be_null(arg_type) && register_is_null(reg))
9873 			return 0;
9874 
9875 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9876 		 * check [value, value + map->value_size) validity
9877 		 */
9878 		if (!meta->map_ptr) {
9879 			/* kernel subsystem misconfigured verifier */
9880 			verifier_bug(env, "invalid map_ptr to access map->value");
9881 			return -EFAULT;
9882 		}
9883 		meta->raw_mode = arg_type & MEM_UNINIT;
9884 		err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
9885 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9886 					      false, meta);
9887 		break;
9888 	case ARG_PTR_TO_PERCPU_BTF_ID:
9889 		if (!reg->btf_id) {
9890 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9891 			return -EACCES;
9892 		}
9893 		meta->ret_btf = reg->btf;
9894 		meta->ret_btf_id = reg->btf_id;
9895 		break;
9896 	case ARG_PTR_TO_SPIN_LOCK:
9897 		if (in_rbtree_lock_required_cb(env)) {
9898 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9899 			return -EACCES;
9900 		}
9901 		if (meta->func_id == BPF_FUNC_spin_lock) {
9902 			err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK);
9903 			if (err)
9904 				return err;
9905 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
9906 			err = process_spin_lock(env, regno, 0);
9907 			if (err)
9908 				return err;
9909 		} else {
9910 			verifier_bug(env, "spin lock arg on unexpected helper");
9911 			return -EFAULT;
9912 		}
9913 		break;
9914 	case ARG_PTR_TO_TIMER:
9915 		err = process_timer_func(env, regno, meta);
9916 		if (err)
9917 			return err;
9918 		break;
9919 	case ARG_PTR_TO_FUNC:
9920 		meta->subprogno = reg->subprogno;
9921 		break;
9922 	case ARG_PTR_TO_MEM:
9923 		/* The access to this pointer is only checked when we hit the
9924 		 * next is_mem_size argument below.
9925 		 */
9926 		meta->raw_mode = arg_type & MEM_UNINIT;
9927 		if (arg_type & MEM_FIXED_SIZE) {
9928 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
9929 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9930 						      false, meta);
9931 			if (err)
9932 				return err;
9933 			if (arg_type & MEM_ALIGNED)
9934 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9935 		}
9936 		break;
9937 	case ARG_CONST_SIZE:
9938 		err = check_mem_size_reg(env, reg, regno,
9939 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9940 					 BPF_WRITE : BPF_READ,
9941 					 false, meta);
9942 		break;
9943 	case ARG_CONST_SIZE_OR_ZERO:
9944 		err = check_mem_size_reg(env, reg, regno,
9945 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9946 					 BPF_WRITE : BPF_READ,
9947 					 true, meta);
9948 		break;
9949 	case ARG_PTR_TO_DYNPTR:
9950 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9951 		if (err)
9952 			return err;
9953 		break;
9954 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9955 		if (!tnum_is_const(reg->var_off)) {
9956 			verbose(env, "R%d is not a known constant'\n",
9957 				regno);
9958 			return -EACCES;
9959 		}
9960 		meta->mem_size = reg->var_off.value;
9961 		err = mark_chain_precision(env, regno);
9962 		if (err)
9963 			return err;
9964 		break;
9965 	case ARG_PTR_TO_CONST_STR:
9966 	{
9967 		err = check_reg_const_str(env, reg, regno);
9968 		if (err)
9969 			return err;
9970 		break;
9971 	}
9972 	case ARG_KPTR_XCHG_DEST:
9973 		err = process_kptr_func(env, regno, meta);
9974 		if (err)
9975 			return err;
9976 		break;
9977 	}
9978 
9979 	return err;
9980 }
9981 
9982 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9983 {
9984 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
9985 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9986 
9987 	if (func_id != BPF_FUNC_map_update_elem &&
9988 	    func_id != BPF_FUNC_map_delete_elem)
9989 		return false;
9990 
9991 	/* It's not possible to get access to a locked struct sock in these
9992 	 * contexts, so updating is safe.
9993 	 */
9994 	switch (type) {
9995 	case BPF_PROG_TYPE_TRACING:
9996 		if (eatype == BPF_TRACE_ITER)
9997 			return true;
9998 		break;
9999 	case BPF_PROG_TYPE_SOCK_OPS:
10000 		/* map_update allowed only via dedicated helpers with event type checks */
10001 		if (func_id == BPF_FUNC_map_delete_elem)
10002 			return true;
10003 		break;
10004 	case BPF_PROG_TYPE_SOCKET_FILTER:
10005 	case BPF_PROG_TYPE_SCHED_CLS:
10006 	case BPF_PROG_TYPE_SCHED_ACT:
10007 	case BPF_PROG_TYPE_XDP:
10008 	case BPF_PROG_TYPE_SK_REUSEPORT:
10009 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
10010 	case BPF_PROG_TYPE_SK_LOOKUP:
10011 		return true;
10012 	default:
10013 		break;
10014 	}
10015 
10016 	verbose(env, "cannot update sockmap in this context\n");
10017 	return false;
10018 }
10019 
10020 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
10021 {
10022 	return env->prog->jit_requested &&
10023 	       bpf_jit_supports_subprog_tailcalls();
10024 }
10025 
10026 static int check_map_func_compatibility(struct bpf_verifier_env *env,
10027 					struct bpf_map *map, int func_id)
10028 {
10029 	if (!map)
10030 		return 0;
10031 
10032 	/* We need a two way check, first is from map perspective ... */
10033 	switch (map->map_type) {
10034 	case BPF_MAP_TYPE_PROG_ARRAY:
10035 		if (func_id != BPF_FUNC_tail_call)
10036 			goto error;
10037 		break;
10038 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
10039 		if (func_id != BPF_FUNC_perf_event_read &&
10040 		    func_id != BPF_FUNC_perf_event_output &&
10041 		    func_id != BPF_FUNC_skb_output &&
10042 		    func_id != BPF_FUNC_perf_event_read_value &&
10043 		    func_id != BPF_FUNC_xdp_output)
10044 			goto error;
10045 		break;
10046 	case BPF_MAP_TYPE_RINGBUF:
10047 		if (func_id != BPF_FUNC_ringbuf_output &&
10048 		    func_id != BPF_FUNC_ringbuf_reserve &&
10049 		    func_id != BPF_FUNC_ringbuf_query &&
10050 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
10051 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
10052 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
10053 			goto error;
10054 		break;
10055 	case BPF_MAP_TYPE_USER_RINGBUF:
10056 		if (func_id != BPF_FUNC_user_ringbuf_drain)
10057 			goto error;
10058 		break;
10059 	case BPF_MAP_TYPE_STACK_TRACE:
10060 		if (func_id != BPF_FUNC_get_stackid)
10061 			goto error;
10062 		break;
10063 	case BPF_MAP_TYPE_CGROUP_ARRAY:
10064 		if (func_id != BPF_FUNC_skb_under_cgroup &&
10065 		    func_id != BPF_FUNC_current_task_under_cgroup)
10066 			goto error;
10067 		break;
10068 	case BPF_MAP_TYPE_CGROUP_STORAGE:
10069 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
10070 		if (func_id != BPF_FUNC_get_local_storage)
10071 			goto error;
10072 		break;
10073 	case BPF_MAP_TYPE_DEVMAP:
10074 	case BPF_MAP_TYPE_DEVMAP_HASH:
10075 		if (func_id != BPF_FUNC_redirect_map &&
10076 		    func_id != BPF_FUNC_map_lookup_elem)
10077 			goto error;
10078 		break;
10079 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
10080 	 * appear.
10081 	 */
10082 	case BPF_MAP_TYPE_CPUMAP:
10083 		if (func_id != BPF_FUNC_redirect_map)
10084 			goto error;
10085 		break;
10086 	case BPF_MAP_TYPE_XSKMAP:
10087 		if (func_id != BPF_FUNC_redirect_map &&
10088 		    func_id != BPF_FUNC_map_lookup_elem)
10089 			goto error;
10090 		break;
10091 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10092 	case BPF_MAP_TYPE_HASH_OF_MAPS:
10093 		if (func_id != BPF_FUNC_map_lookup_elem)
10094 			goto error;
10095 		break;
10096 	case BPF_MAP_TYPE_SOCKMAP:
10097 		if (func_id != BPF_FUNC_sk_redirect_map &&
10098 		    func_id != BPF_FUNC_sock_map_update &&
10099 		    func_id != BPF_FUNC_msg_redirect_map &&
10100 		    func_id != BPF_FUNC_sk_select_reuseport &&
10101 		    func_id != BPF_FUNC_map_lookup_elem &&
10102 		    !may_update_sockmap(env, func_id))
10103 			goto error;
10104 		break;
10105 	case BPF_MAP_TYPE_SOCKHASH:
10106 		if (func_id != BPF_FUNC_sk_redirect_hash &&
10107 		    func_id != BPF_FUNC_sock_hash_update &&
10108 		    func_id != BPF_FUNC_msg_redirect_hash &&
10109 		    func_id != BPF_FUNC_sk_select_reuseport &&
10110 		    func_id != BPF_FUNC_map_lookup_elem &&
10111 		    !may_update_sockmap(env, func_id))
10112 			goto error;
10113 		break;
10114 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
10115 		if (func_id != BPF_FUNC_sk_select_reuseport)
10116 			goto error;
10117 		break;
10118 	case BPF_MAP_TYPE_QUEUE:
10119 	case BPF_MAP_TYPE_STACK:
10120 		if (func_id != BPF_FUNC_map_peek_elem &&
10121 		    func_id != BPF_FUNC_map_pop_elem &&
10122 		    func_id != BPF_FUNC_map_push_elem)
10123 			goto error;
10124 		break;
10125 	case BPF_MAP_TYPE_SK_STORAGE:
10126 		if (func_id != BPF_FUNC_sk_storage_get &&
10127 		    func_id != BPF_FUNC_sk_storage_delete &&
10128 		    func_id != BPF_FUNC_kptr_xchg)
10129 			goto error;
10130 		break;
10131 	case BPF_MAP_TYPE_INODE_STORAGE:
10132 		if (func_id != BPF_FUNC_inode_storage_get &&
10133 		    func_id != BPF_FUNC_inode_storage_delete &&
10134 		    func_id != BPF_FUNC_kptr_xchg)
10135 			goto error;
10136 		break;
10137 	case BPF_MAP_TYPE_TASK_STORAGE:
10138 		if (func_id != BPF_FUNC_task_storage_get &&
10139 		    func_id != BPF_FUNC_task_storage_delete &&
10140 		    func_id != BPF_FUNC_kptr_xchg)
10141 			goto error;
10142 		break;
10143 	case BPF_MAP_TYPE_CGRP_STORAGE:
10144 		if (func_id != BPF_FUNC_cgrp_storage_get &&
10145 		    func_id != BPF_FUNC_cgrp_storage_delete &&
10146 		    func_id != BPF_FUNC_kptr_xchg)
10147 			goto error;
10148 		break;
10149 	case BPF_MAP_TYPE_BLOOM_FILTER:
10150 		if (func_id != BPF_FUNC_map_peek_elem &&
10151 		    func_id != BPF_FUNC_map_push_elem)
10152 			goto error;
10153 		break;
10154 	case BPF_MAP_TYPE_INSN_ARRAY:
10155 		goto error;
10156 	default:
10157 		break;
10158 	}
10159 
10160 	/* ... and second from the function itself. */
10161 	switch (func_id) {
10162 	case BPF_FUNC_tail_call:
10163 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
10164 			goto error;
10165 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
10166 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
10167 			return -EINVAL;
10168 		}
10169 		break;
10170 	case BPF_FUNC_perf_event_read:
10171 	case BPF_FUNC_perf_event_output:
10172 	case BPF_FUNC_perf_event_read_value:
10173 	case BPF_FUNC_skb_output:
10174 	case BPF_FUNC_xdp_output:
10175 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10176 			goto error;
10177 		break;
10178 	case BPF_FUNC_ringbuf_output:
10179 	case BPF_FUNC_ringbuf_reserve:
10180 	case BPF_FUNC_ringbuf_query:
10181 	case BPF_FUNC_ringbuf_reserve_dynptr:
10182 	case BPF_FUNC_ringbuf_submit_dynptr:
10183 	case BPF_FUNC_ringbuf_discard_dynptr:
10184 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
10185 			goto error;
10186 		break;
10187 	case BPF_FUNC_user_ringbuf_drain:
10188 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
10189 			goto error;
10190 		break;
10191 	case BPF_FUNC_get_stackid:
10192 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
10193 			goto error;
10194 		break;
10195 	case BPF_FUNC_current_task_under_cgroup:
10196 	case BPF_FUNC_skb_under_cgroup:
10197 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
10198 			goto error;
10199 		break;
10200 	case BPF_FUNC_redirect_map:
10201 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
10202 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
10203 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
10204 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
10205 			goto error;
10206 		break;
10207 	case BPF_FUNC_sk_redirect_map:
10208 	case BPF_FUNC_msg_redirect_map:
10209 	case BPF_FUNC_sock_map_update:
10210 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10211 			goto error;
10212 		break;
10213 	case BPF_FUNC_sk_redirect_hash:
10214 	case BPF_FUNC_msg_redirect_hash:
10215 	case BPF_FUNC_sock_hash_update:
10216 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10217 			goto error;
10218 		break;
10219 	case BPF_FUNC_get_local_storage:
10220 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10221 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10222 			goto error;
10223 		break;
10224 	case BPF_FUNC_sk_select_reuseport:
10225 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10226 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10227 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
10228 			goto error;
10229 		break;
10230 	case BPF_FUNC_map_pop_elem:
10231 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10232 		    map->map_type != BPF_MAP_TYPE_STACK)
10233 			goto error;
10234 		break;
10235 	case BPF_FUNC_map_peek_elem:
10236 	case BPF_FUNC_map_push_elem:
10237 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10238 		    map->map_type != BPF_MAP_TYPE_STACK &&
10239 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10240 			goto error;
10241 		break;
10242 	case BPF_FUNC_map_lookup_percpu_elem:
10243 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10244 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10245 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10246 			goto error;
10247 		break;
10248 	case BPF_FUNC_sk_storage_get:
10249 	case BPF_FUNC_sk_storage_delete:
10250 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10251 			goto error;
10252 		break;
10253 	case BPF_FUNC_inode_storage_get:
10254 	case BPF_FUNC_inode_storage_delete:
10255 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10256 			goto error;
10257 		break;
10258 	case BPF_FUNC_task_storage_get:
10259 	case BPF_FUNC_task_storage_delete:
10260 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10261 			goto error;
10262 		break;
10263 	case BPF_FUNC_cgrp_storage_get:
10264 	case BPF_FUNC_cgrp_storage_delete:
10265 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10266 			goto error;
10267 		break;
10268 	default:
10269 		break;
10270 	}
10271 
10272 	return 0;
10273 error:
10274 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
10275 		map->map_type, func_id_name(func_id), func_id);
10276 	return -EINVAL;
10277 }
10278 
10279 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
10280 {
10281 	int count = 0;
10282 
10283 	if (arg_type_is_raw_mem(fn->arg1_type))
10284 		count++;
10285 	if (arg_type_is_raw_mem(fn->arg2_type))
10286 		count++;
10287 	if (arg_type_is_raw_mem(fn->arg3_type))
10288 		count++;
10289 	if (arg_type_is_raw_mem(fn->arg4_type))
10290 		count++;
10291 	if (arg_type_is_raw_mem(fn->arg5_type))
10292 		count++;
10293 
10294 	/* We only support one arg being in raw mode at the moment,
10295 	 * which is sufficient for the helper functions we have
10296 	 * right now.
10297 	 */
10298 	return count <= 1;
10299 }
10300 
10301 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10302 {
10303 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10304 	bool has_size = fn->arg_size[arg] != 0;
10305 	bool is_next_size = false;
10306 
10307 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10308 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10309 
10310 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10311 		return is_next_size;
10312 
10313 	return has_size == is_next_size || is_next_size == is_fixed;
10314 }
10315 
10316 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10317 {
10318 	/* bpf_xxx(..., buf, len) call will access 'len'
10319 	 * bytes from memory 'buf'. Both arg types need
10320 	 * to be paired, so make sure there's no buggy
10321 	 * helper function specification.
10322 	 */
10323 	if (arg_type_is_mem_size(fn->arg1_type) ||
10324 	    check_args_pair_invalid(fn, 0) ||
10325 	    check_args_pair_invalid(fn, 1) ||
10326 	    check_args_pair_invalid(fn, 2) ||
10327 	    check_args_pair_invalid(fn, 3) ||
10328 	    check_args_pair_invalid(fn, 4))
10329 		return false;
10330 
10331 	return true;
10332 }
10333 
10334 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10335 {
10336 	int i;
10337 
10338 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10339 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10340 			return !!fn->arg_btf_id[i];
10341 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10342 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
10343 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10344 		    /* arg_btf_id and arg_size are in a union. */
10345 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10346 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10347 			return false;
10348 	}
10349 
10350 	return true;
10351 }
10352 
10353 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
10354 {
10355 	return check_raw_mode_ok(fn) &&
10356 	       check_arg_pair_ok(fn) &&
10357 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
10358 }
10359 
10360 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
10361  * are now invalid, so turn them into unknown SCALAR_VALUE.
10362  *
10363  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
10364  * since these slices point to packet data.
10365  */
10366 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
10367 {
10368 	struct bpf_func_state *state;
10369 	struct bpf_reg_state *reg;
10370 
10371 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10372 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
10373 			mark_reg_invalid(env, reg);
10374 	}));
10375 }
10376 
10377 enum {
10378 	AT_PKT_END = -1,
10379 	BEYOND_PKT_END = -2,
10380 };
10381 
10382 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
10383 {
10384 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10385 	struct bpf_reg_state *reg = &state->regs[regn];
10386 
10387 	if (reg->type != PTR_TO_PACKET)
10388 		/* PTR_TO_PACKET_META is not supported yet */
10389 		return;
10390 
10391 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
10392 	 * How far beyond pkt_end it goes is unknown.
10393 	 * if (!range_open) it's the case of pkt >= pkt_end
10394 	 * if (range_open) it's the case of pkt > pkt_end
10395 	 * hence this pointer is at least 1 byte bigger than pkt_end
10396 	 */
10397 	if (range_open)
10398 		reg->range = BEYOND_PKT_END;
10399 	else
10400 		reg->range = AT_PKT_END;
10401 }
10402 
10403 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id)
10404 {
10405 	int i;
10406 
10407 	for (i = 0; i < state->acquired_refs; i++) {
10408 		if (state->refs[i].type != REF_TYPE_PTR)
10409 			continue;
10410 		if (state->refs[i].id == ref_obj_id) {
10411 			release_reference_state(state, i);
10412 			return 0;
10413 		}
10414 	}
10415 	return -EINVAL;
10416 }
10417 
10418 /* The pointer with the specified id has released its reference to kernel
10419  * resources. Identify all copies of the same pointer and clear the reference.
10420  *
10421  * This is the release function corresponding to acquire_reference(). Idempotent.
10422  */
10423 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id)
10424 {
10425 	struct bpf_verifier_state *vstate = env->cur_state;
10426 	struct bpf_func_state *state;
10427 	struct bpf_reg_state *reg;
10428 	int err;
10429 
10430 	err = release_reference_nomark(vstate, ref_obj_id);
10431 	if (err)
10432 		return err;
10433 
10434 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10435 		if (reg->ref_obj_id == ref_obj_id)
10436 			mark_reg_invalid(env, reg);
10437 	}));
10438 
10439 	return 0;
10440 }
10441 
10442 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
10443 {
10444 	struct bpf_func_state *unused;
10445 	struct bpf_reg_state *reg;
10446 
10447 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10448 		if (type_is_non_owning_ref(reg->type))
10449 			mark_reg_invalid(env, reg);
10450 	}));
10451 }
10452 
10453 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
10454 				    struct bpf_reg_state *regs)
10455 {
10456 	int i;
10457 
10458 	/* after the call registers r0 - r5 were scratched */
10459 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10460 		mark_reg_not_init(env, regs, caller_saved[i]);
10461 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
10462 	}
10463 }
10464 
10465 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
10466 				   struct bpf_func_state *caller,
10467 				   struct bpf_func_state *callee,
10468 				   int insn_idx);
10469 
10470 static int set_callee_state(struct bpf_verifier_env *env,
10471 			    struct bpf_func_state *caller,
10472 			    struct bpf_func_state *callee, int insn_idx);
10473 
10474 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
10475 			    set_callee_state_fn set_callee_state_cb,
10476 			    struct bpf_verifier_state *state)
10477 {
10478 	struct bpf_func_state *caller, *callee;
10479 	int err;
10480 
10481 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
10482 		verbose(env, "the call stack of %d frames is too deep\n",
10483 			state->curframe + 2);
10484 		return -E2BIG;
10485 	}
10486 
10487 	if (state->frame[state->curframe + 1]) {
10488 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
10489 		return -EFAULT;
10490 	}
10491 
10492 	caller = state->frame[state->curframe];
10493 	callee = kzalloc(sizeof(*callee), GFP_KERNEL_ACCOUNT);
10494 	if (!callee)
10495 		return -ENOMEM;
10496 	state->frame[state->curframe + 1] = callee;
10497 
10498 	/* callee cannot access r0, r6 - r9 for reading and has to write
10499 	 * into its own stack before reading from it.
10500 	 * callee can read/write into caller's stack
10501 	 */
10502 	init_func_state(env, callee,
10503 			/* remember the callsite, it will be used by bpf_exit */
10504 			callsite,
10505 			state->curframe + 1 /* frameno within this callchain */,
10506 			subprog /* subprog number within this prog */);
10507 	err = set_callee_state_cb(env, caller, callee, callsite);
10508 	if (err)
10509 		goto err_out;
10510 
10511 	/* only increment it after check_reg_arg() finished */
10512 	state->curframe++;
10513 
10514 	return 0;
10515 
10516 err_out:
10517 	free_func_state(callee);
10518 	state->frame[state->curframe + 1] = NULL;
10519 	return err;
10520 }
10521 
10522 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
10523 				    const struct btf *btf,
10524 				    struct bpf_reg_state *regs)
10525 {
10526 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
10527 	struct bpf_verifier_log *log = &env->log;
10528 	u32 i;
10529 	int ret;
10530 
10531 	ret = btf_prepare_func_args(env, subprog);
10532 	if (ret)
10533 		return ret;
10534 
10535 	/* check that BTF function arguments match actual types that the
10536 	 * verifier sees.
10537 	 */
10538 	for (i = 0; i < sub->arg_cnt; i++) {
10539 		u32 regno = i + 1;
10540 		struct bpf_reg_state *reg = &regs[regno];
10541 		struct bpf_subprog_arg_info *arg = &sub->args[i];
10542 
10543 		if (arg->arg_type == ARG_ANYTHING) {
10544 			if (reg->type != SCALAR_VALUE) {
10545 				bpf_log(log, "R%d is not a scalar\n", regno);
10546 				return -EINVAL;
10547 			}
10548 		} else if (arg->arg_type & PTR_UNTRUSTED) {
10549 			/*
10550 			 * Anything is allowed for untrusted arguments, as these are
10551 			 * read-only and probe read instructions would protect against
10552 			 * invalid memory access.
10553 			 */
10554 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
10555 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10556 			if (ret < 0)
10557 				return ret;
10558 			/* If function expects ctx type in BTF check that caller
10559 			 * is passing PTR_TO_CTX.
10560 			 */
10561 			if (reg->type != PTR_TO_CTX) {
10562 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
10563 				return -EINVAL;
10564 			}
10565 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
10566 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10567 			if (ret < 0)
10568 				return ret;
10569 			if (check_mem_reg(env, reg, regno, arg->mem_size))
10570 				return -EINVAL;
10571 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
10572 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
10573 				return -EINVAL;
10574 			}
10575 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
10576 			/*
10577 			 * Can pass any value and the kernel won't crash, but
10578 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
10579 			 * else is a bug in the bpf program. Point it out to
10580 			 * the user at the verification time instead of
10581 			 * run-time debug nightmare.
10582 			 */
10583 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
10584 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
10585 				return -EINVAL;
10586 			}
10587 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
10588 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
10589 			if (ret)
10590 				return ret;
10591 
10592 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
10593 			if (ret)
10594 				return ret;
10595 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
10596 			struct bpf_call_arg_meta meta;
10597 			int err;
10598 
10599 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
10600 				continue;
10601 
10602 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
10603 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
10604 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
10605 			if (err)
10606 				return err;
10607 		} else {
10608 			verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type);
10609 			return -EFAULT;
10610 		}
10611 	}
10612 
10613 	return 0;
10614 }
10615 
10616 /* Compare BTF of a function call with given bpf_reg_state.
10617  * Returns:
10618  * EFAULT - there is a verifier bug. Abort verification.
10619  * EINVAL - there is a type mismatch or BTF is not available.
10620  * 0 - BTF matches with what bpf_reg_state expects.
10621  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
10622  */
10623 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
10624 				  struct bpf_reg_state *regs)
10625 {
10626 	struct bpf_prog *prog = env->prog;
10627 	struct btf *btf = prog->aux->btf;
10628 	u32 btf_id;
10629 	int err;
10630 
10631 	if (!prog->aux->func_info)
10632 		return -EINVAL;
10633 
10634 	btf_id = prog->aux->func_info[subprog].type_id;
10635 	if (!btf_id)
10636 		return -EFAULT;
10637 
10638 	if (prog->aux->func_info_aux[subprog].unreliable)
10639 		return -EINVAL;
10640 
10641 	err = btf_check_func_arg_match(env, subprog, btf, regs);
10642 	/* Compiler optimizations can remove arguments from static functions
10643 	 * or mismatched type can be passed into a global function.
10644 	 * In such cases mark the function as unreliable from BTF point of view.
10645 	 */
10646 	if (err)
10647 		prog->aux->func_info_aux[subprog].unreliable = true;
10648 	return err;
10649 }
10650 
10651 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10652 			      int insn_idx, int subprog,
10653 			      set_callee_state_fn set_callee_state_cb)
10654 {
10655 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
10656 	struct bpf_func_state *caller, *callee;
10657 	int err;
10658 
10659 	caller = state->frame[state->curframe];
10660 	err = btf_check_subprog_call(env, subprog, caller->regs);
10661 	if (err == -EFAULT)
10662 		return err;
10663 
10664 	/* set_callee_state is used for direct subprog calls, but we are
10665 	 * interested in validating only BPF helpers that can call subprogs as
10666 	 * callbacks
10667 	 */
10668 	env->subprog_info[subprog].is_cb = true;
10669 	if (bpf_pseudo_kfunc_call(insn) &&
10670 	    !is_callback_calling_kfunc(insn->imm)) {
10671 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
10672 			     func_id_name(insn->imm), insn->imm);
10673 		return -EFAULT;
10674 	} else if (!bpf_pseudo_kfunc_call(insn) &&
10675 		   !is_callback_calling_function(insn->imm)) { /* helper */
10676 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
10677 			     func_id_name(insn->imm), insn->imm);
10678 		return -EFAULT;
10679 	}
10680 
10681 	if (is_async_callback_calling_insn(insn)) {
10682 		struct bpf_verifier_state *async_cb;
10683 
10684 		/* there is no real recursion here. timer and workqueue callbacks are async */
10685 		env->subprog_info[subprog].is_async_cb = true;
10686 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
10687 					 insn_idx, subprog,
10688 					 is_async_cb_sleepable(env, insn));
10689 		if (IS_ERR(async_cb))
10690 			return PTR_ERR(async_cb);
10691 		callee = async_cb->frame[0];
10692 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
10693 
10694 		/* Convert bpf_timer_set_callback() args into timer callback args */
10695 		err = set_callee_state_cb(env, caller, callee, insn_idx);
10696 		if (err)
10697 			return err;
10698 
10699 		return 0;
10700 	}
10701 
10702 	/* for callback functions enqueue entry to callback and
10703 	 * proceed with next instruction within current frame.
10704 	 */
10705 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
10706 	if (IS_ERR(callback_state))
10707 		return PTR_ERR(callback_state);
10708 
10709 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
10710 			       callback_state);
10711 	if (err)
10712 		return err;
10713 
10714 	callback_state->callback_unroll_depth++;
10715 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
10716 	caller->callback_depth = 0;
10717 	return 0;
10718 }
10719 
10720 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10721 			   int *insn_idx)
10722 {
10723 	struct bpf_verifier_state *state = env->cur_state;
10724 	struct bpf_func_state *caller;
10725 	int err, subprog, target_insn;
10726 
10727 	target_insn = *insn_idx + insn->imm + 1;
10728 	subprog = find_subprog(env, target_insn);
10729 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
10730 			    target_insn))
10731 		return -EFAULT;
10732 
10733 	caller = state->frame[state->curframe];
10734 	err = btf_check_subprog_call(env, subprog, caller->regs);
10735 	if (err == -EFAULT)
10736 		return err;
10737 	if (subprog_is_global(env, subprog)) {
10738 		const char *sub_name = subprog_name(env, subprog);
10739 
10740 		if (env->cur_state->active_locks) {
10741 			verbose(env, "global function calls are not allowed while holding a lock,\n"
10742 				     "use static function instead\n");
10743 			return -EINVAL;
10744 		}
10745 
10746 		if (env->subprog_info[subprog].might_sleep &&
10747 		    (env->cur_state->active_rcu_locks || env->cur_state->active_preempt_locks ||
10748 		     env->cur_state->active_irq_id || !in_sleepable(env))) {
10749 			verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n"
10750 				     "i.e., in a RCU/IRQ/preempt-disabled section, or in\n"
10751 				     "a non-sleepable BPF program context\n");
10752 			return -EINVAL;
10753 		}
10754 
10755 		if (err) {
10756 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10757 				subprog, sub_name);
10758 			return err;
10759 		}
10760 
10761 		if (env->log.level & BPF_LOG_LEVEL)
10762 			verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10763 				subprog, sub_name);
10764 		if (env->subprog_info[subprog].changes_pkt_data)
10765 			clear_all_pkt_pointers(env);
10766 		/* mark global subprog for verifying after main prog */
10767 		subprog_aux(env, subprog)->called = true;
10768 		clear_caller_saved_regs(env, caller->regs);
10769 
10770 		/* All global functions return a 64-bit SCALAR_VALUE */
10771 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
10772 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10773 
10774 		/* continue with next insn after call */
10775 		return 0;
10776 	}
10777 
10778 	/* for regular function entry setup new frame and continue
10779 	 * from that frame.
10780 	 */
10781 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10782 	if (err)
10783 		return err;
10784 
10785 	clear_caller_saved_regs(env, caller->regs);
10786 
10787 	/* and go analyze first insn of the callee */
10788 	*insn_idx = env->subprog_info[subprog].start - 1;
10789 
10790 	bpf_reset_live_stack_callchain(env);
10791 
10792 	if (env->log.level & BPF_LOG_LEVEL) {
10793 		verbose(env, "caller:\n");
10794 		print_verifier_state(env, state, caller->frameno, true);
10795 		verbose(env, "callee:\n");
10796 		print_verifier_state(env, state, state->curframe, true);
10797 	}
10798 
10799 	return 0;
10800 }
10801 
10802 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10803 				   struct bpf_func_state *caller,
10804 				   struct bpf_func_state *callee)
10805 {
10806 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10807 	 *      void *callback_ctx, u64 flags);
10808 	 * callback_fn(struct bpf_map *map, void *key, void *value,
10809 	 *      void *callback_ctx);
10810 	 */
10811 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10812 
10813 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10814 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10815 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10816 
10817 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10818 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10819 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10820 
10821 	/* pointer to stack or null */
10822 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10823 
10824 	/* unused */
10825 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10826 	return 0;
10827 }
10828 
10829 static int set_callee_state(struct bpf_verifier_env *env,
10830 			    struct bpf_func_state *caller,
10831 			    struct bpf_func_state *callee, int insn_idx)
10832 {
10833 	int i;
10834 
10835 	/* copy r1 - r5 args that callee can access.  The copy includes parent
10836 	 * pointers, which connects us up to the liveness chain
10837 	 */
10838 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10839 		callee->regs[i] = caller->regs[i];
10840 	return 0;
10841 }
10842 
10843 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10844 				       struct bpf_func_state *caller,
10845 				       struct bpf_func_state *callee,
10846 				       int insn_idx)
10847 {
10848 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10849 	struct bpf_map *map;
10850 	int err;
10851 
10852 	/* valid map_ptr and poison value does not matter */
10853 	map = insn_aux->map_ptr_state.map_ptr;
10854 	if (!map->ops->map_set_for_each_callback_args ||
10855 	    !map->ops->map_for_each_callback) {
10856 		verbose(env, "callback function not allowed for map\n");
10857 		return -ENOTSUPP;
10858 	}
10859 
10860 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10861 	if (err)
10862 		return err;
10863 
10864 	callee->in_callback_fn = true;
10865 	callee->callback_ret_range = retval_range(0, 1);
10866 	return 0;
10867 }
10868 
10869 static int set_loop_callback_state(struct bpf_verifier_env *env,
10870 				   struct bpf_func_state *caller,
10871 				   struct bpf_func_state *callee,
10872 				   int insn_idx)
10873 {
10874 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10875 	 *	    u64 flags);
10876 	 * callback_fn(u64 index, void *callback_ctx);
10877 	 */
10878 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10879 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10880 
10881 	/* unused */
10882 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10883 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10884 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10885 
10886 	callee->in_callback_fn = true;
10887 	callee->callback_ret_range = retval_range(0, 1);
10888 	return 0;
10889 }
10890 
10891 static int set_timer_callback_state(struct bpf_verifier_env *env,
10892 				    struct bpf_func_state *caller,
10893 				    struct bpf_func_state *callee,
10894 				    int insn_idx)
10895 {
10896 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10897 
10898 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10899 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10900 	 */
10901 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10902 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10903 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10904 
10905 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10906 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10907 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10908 
10909 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10910 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10911 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10912 
10913 	/* unused */
10914 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10915 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10916 	callee->in_async_callback_fn = true;
10917 	callee->callback_ret_range = retval_range(0, 0);
10918 	return 0;
10919 }
10920 
10921 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
10922 				       struct bpf_func_state *caller,
10923 				       struct bpf_func_state *callee,
10924 				       int insn_idx)
10925 {
10926 	/* bpf_find_vma(struct task_struct *task, u64 addr,
10927 	 *               void *callback_fn, void *callback_ctx, u64 flags)
10928 	 * (callback_fn)(struct task_struct *task,
10929 	 *               struct vm_area_struct *vma, void *callback_ctx);
10930 	 */
10931 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10932 
10933 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
10934 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10935 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
10936 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
10937 
10938 	/* pointer to stack or null */
10939 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
10940 
10941 	/* unused */
10942 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10943 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10944 	callee->in_callback_fn = true;
10945 	callee->callback_ret_range = retval_range(0, 1);
10946 	return 0;
10947 }
10948 
10949 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10950 					   struct bpf_func_state *caller,
10951 					   struct bpf_func_state *callee,
10952 					   int insn_idx)
10953 {
10954 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10955 	 *			  callback_ctx, u64 flags);
10956 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10957 	 */
10958 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10959 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10960 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10961 
10962 	/* unused */
10963 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10964 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10965 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10966 
10967 	callee->in_callback_fn = true;
10968 	callee->callback_ret_range = retval_range(0, 1);
10969 	return 0;
10970 }
10971 
10972 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10973 					 struct bpf_func_state *caller,
10974 					 struct bpf_func_state *callee,
10975 					 int insn_idx)
10976 {
10977 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10978 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10979 	 *
10980 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10981 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10982 	 * by this point, so look at 'root'
10983 	 */
10984 	struct btf_field *field;
10985 
10986 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10987 				      BPF_RB_ROOT);
10988 	if (!field || !field->graph_root.value_btf_id)
10989 		return -EFAULT;
10990 
10991 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10992 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10993 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10994 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10995 
10996 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10997 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10998 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10999 	callee->in_callback_fn = true;
11000 	callee->callback_ret_range = retval_range(0, 1);
11001 	return 0;
11002 }
11003 
11004 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
11005 						 struct bpf_func_state *caller,
11006 						 struct bpf_func_state *callee,
11007 						 int insn_idx)
11008 {
11009 	struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
11010 
11011 	/*
11012 	 * callback_fn(struct bpf_map *map, void *key, void *value);
11013 	 */
11014 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
11015 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
11016 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
11017 
11018 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11019 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11020 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
11021 
11022 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11023 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11024 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
11025 
11026 	/* unused */
11027 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11028 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11029 	callee->in_async_callback_fn = true;
11030 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
11031 	return 0;
11032 }
11033 
11034 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
11035 
11036 /* Are we currently verifying the callback for a rbtree helper that must
11037  * be called with lock held? If so, no need to complain about unreleased
11038  * lock
11039  */
11040 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
11041 {
11042 	struct bpf_verifier_state *state = env->cur_state;
11043 	struct bpf_insn *insn = env->prog->insnsi;
11044 	struct bpf_func_state *callee;
11045 	int kfunc_btf_id;
11046 
11047 	if (!state->curframe)
11048 		return false;
11049 
11050 	callee = state->frame[state->curframe];
11051 
11052 	if (!callee->in_callback_fn)
11053 		return false;
11054 
11055 	kfunc_btf_id = insn[callee->callsite].imm;
11056 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
11057 }
11058 
11059 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
11060 				bool return_32bit)
11061 {
11062 	if (return_32bit)
11063 		return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
11064 	else
11065 		return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
11066 }
11067 
11068 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
11069 {
11070 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
11071 	struct bpf_func_state *caller, *callee;
11072 	struct bpf_reg_state *r0;
11073 	bool in_callback_fn;
11074 	int err;
11075 
11076 	err = bpf_update_live_stack(env);
11077 	if (err)
11078 		return err;
11079 
11080 	callee = state->frame[state->curframe];
11081 	r0 = &callee->regs[BPF_REG_0];
11082 	if (r0->type == PTR_TO_STACK) {
11083 		/* technically it's ok to return caller's stack pointer
11084 		 * (or caller's caller's pointer) back to the caller,
11085 		 * since these pointers are valid. Only current stack
11086 		 * pointer will be invalid as soon as function exits,
11087 		 * but let's be conservative
11088 		 */
11089 		verbose(env, "cannot return stack pointer to the caller\n");
11090 		return -EINVAL;
11091 	}
11092 
11093 	caller = state->frame[state->curframe - 1];
11094 	if (callee->in_callback_fn) {
11095 		if (r0->type != SCALAR_VALUE) {
11096 			verbose(env, "R0 not a scalar value\n");
11097 			return -EACCES;
11098 		}
11099 
11100 		/* we are going to rely on register's precise value */
11101 		err = mark_chain_precision(env, BPF_REG_0);
11102 		if (err)
11103 			return err;
11104 
11105 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
11106 		if (!retval_range_within(callee->callback_ret_range, r0, false)) {
11107 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
11108 					       "At callback return", "R0");
11109 			return -EINVAL;
11110 		}
11111 		if (!bpf_calls_callback(env, callee->callsite)) {
11112 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
11113 				     *insn_idx, callee->callsite);
11114 			return -EFAULT;
11115 		}
11116 	} else {
11117 		/* return to the caller whatever r0 had in the callee */
11118 		caller->regs[BPF_REG_0] = *r0;
11119 	}
11120 
11121 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
11122 	 * there function call logic would reschedule callback visit. If iteration
11123 	 * converges is_state_visited() would prune that visit eventually.
11124 	 */
11125 	in_callback_fn = callee->in_callback_fn;
11126 	if (in_callback_fn)
11127 		*insn_idx = callee->callsite;
11128 	else
11129 		*insn_idx = callee->callsite + 1;
11130 
11131 	if (env->log.level & BPF_LOG_LEVEL) {
11132 		verbose(env, "returning from callee:\n");
11133 		print_verifier_state(env, state, callee->frameno, true);
11134 		verbose(env, "to caller at %d:\n", *insn_idx);
11135 		print_verifier_state(env, state, caller->frameno, true);
11136 	}
11137 	/* clear everything in the callee. In case of exceptional exits using
11138 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
11139 	free_func_state(callee);
11140 	state->frame[state->curframe--] = NULL;
11141 
11142 	/* for callbacks widen imprecise scalars to make programs like below verify:
11143 	 *
11144 	 *   struct ctx { int i; }
11145 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
11146 	 *   ...
11147 	 *   struct ctx = { .i = 0; }
11148 	 *   bpf_loop(100, cb, &ctx, 0);
11149 	 *
11150 	 * This is similar to what is done in process_iter_next_call() for open
11151 	 * coded iterators.
11152 	 */
11153 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
11154 	if (prev_st) {
11155 		err = widen_imprecise_scalars(env, prev_st, state);
11156 		if (err)
11157 			return err;
11158 	}
11159 	return 0;
11160 }
11161 
11162 static int do_refine_retval_range(struct bpf_verifier_env *env,
11163 				  struct bpf_reg_state *regs, int ret_type,
11164 				  int func_id,
11165 				  struct bpf_call_arg_meta *meta)
11166 {
11167 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
11168 
11169 	if (ret_type != RET_INTEGER)
11170 		return 0;
11171 
11172 	switch (func_id) {
11173 	case BPF_FUNC_get_stack:
11174 	case BPF_FUNC_get_task_stack:
11175 	case BPF_FUNC_probe_read_str:
11176 	case BPF_FUNC_probe_read_kernel_str:
11177 	case BPF_FUNC_probe_read_user_str:
11178 		ret_reg->smax_value = meta->msize_max_value;
11179 		ret_reg->s32_max_value = meta->msize_max_value;
11180 		ret_reg->smin_value = -MAX_ERRNO;
11181 		ret_reg->s32_min_value = -MAX_ERRNO;
11182 		reg_bounds_sync(ret_reg);
11183 		break;
11184 	case BPF_FUNC_get_smp_processor_id:
11185 		ret_reg->umax_value = nr_cpu_ids - 1;
11186 		ret_reg->u32_max_value = nr_cpu_ids - 1;
11187 		ret_reg->smax_value = nr_cpu_ids - 1;
11188 		ret_reg->s32_max_value = nr_cpu_ids - 1;
11189 		ret_reg->umin_value = 0;
11190 		ret_reg->u32_min_value = 0;
11191 		ret_reg->smin_value = 0;
11192 		ret_reg->s32_min_value = 0;
11193 		reg_bounds_sync(ret_reg);
11194 		break;
11195 	}
11196 
11197 	return reg_bounds_sanity_check(env, ret_reg, "retval");
11198 }
11199 
11200 static int
11201 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11202 		int func_id, int insn_idx)
11203 {
11204 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11205 	struct bpf_map *map = meta->map_ptr;
11206 
11207 	if (func_id != BPF_FUNC_tail_call &&
11208 	    func_id != BPF_FUNC_map_lookup_elem &&
11209 	    func_id != BPF_FUNC_map_update_elem &&
11210 	    func_id != BPF_FUNC_map_delete_elem &&
11211 	    func_id != BPF_FUNC_map_push_elem &&
11212 	    func_id != BPF_FUNC_map_pop_elem &&
11213 	    func_id != BPF_FUNC_map_peek_elem &&
11214 	    func_id != BPF_FUNC_for_each_map_elem &&
11215 	    func_id != BPF_FUNC_redirect_map &&
11216 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
11217 		return 0;
11218 
11219 	if (map == NULL) {
11220 		verifier_bug(env, "expected map for helper call");
11221 		return -EFAULT;
11222 	}
11223 
11224 	/* In case of read-only, some additional restrictions
11225 	 * need to be applied in order to prevent altering the
11226 	 * state of the map from program side.
11227 	 */
11228 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
11229 	    (func_id == BPF_FUNC_map_delete_elem ||
11230 	     func_id == BPF_FUNC_map_update_elem ||
11231 	     func_id == BPF_FUNC_map_push_elem ||
11232 	     func_id == BPF_FUNC_map_pop_elem)) {
11233 		verbose(env, "write into map forbidden\n");
11234 		return -EACCES;
11235 	}
11236 
11237 	if (!aux->map_ptr_state.map_ptr)
11238 		bpf_map_ptr_store(aux, meta->map_ptr,
11239 				  !meta->map_ptr->bypass_spec_v1, false);
11240 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
11241 		bpf_map_ptr_store(aux, meta->map_ptr,
11242 				  !meta->map_ptr->bypass_spec_v1, true);
11243 	return 0;
11244 }
11245 
11246 static int
11247 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11248 		int func_id, int insn_idx)
11249 {
11250 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11251 	struct bpf_reg_state *regs = cur_regs(env), *reg;
11252 	struct bpf_map *map = meta->map_ptr;
11253 	u64 val, max;
11254 	int err;
11255 
11256 	if (func_id != BPF_FUNC_tail_call)
11257 		return 0;
11258 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
11259 		verbose(env, "expected prog array map for tail call");
11260 		return -EINVAL;
11261 	}
11262 
11263 	reg = &regs[BPF_REG_3];
11264 	val = reg->var_off.value;
11265 	max = map->max_entries;
11266 
11267 	if (!(is_reg_const(reg, false) && val < max)) {
11268 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11269 		return 0;
11270 	}
11271 
11272 	err = mark_chain_precision(env, BPF_REG_3);
11273 	if (err)
11274 		return err;
11275 	if (bpf_map_key_unseen(aux))
11276 		bpf_map_key_store(aux, val);
11277 	else if (!bpf_map_key_poisoned(aux) &&
11278 		  bpf_map_key_immediate(aux) != val)
11279 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11280 	return 0;
11281 }
11282 
11283 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
11284 {
11285 	struct bpf_verifier_state *state = env->cur_state;
11286 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11287 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
11288 	bool refs_lingering = false;
11289 	int i;
11290 
11291 	if (!exception_exit && cur_func(env)->frameno)
11292 		return 0;
11293 
11294 	for (i = 0; i < state->acquired_refs; i++) {
11295 		if (state->refs[i].type != REF_TYPE_PTR)
11296 			continue;
11297 		/* Allow struct_ops programs to return a referenced kptr back to
11298 		 * kernel. Type checks are performed later in check_return_code.
11299 		 */
11300 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
11301 		    reg->ref_obj_id == state->refs[i].id)
11302 			continue;
11303 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
11304 			state->refs[i].id, state->refs[i].insn_idx);
11305 		refs_lingering = true;
11306 	}
11307 	return refs_lingering ? -EINVAL : 0;
11308 }
11309 
11310 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
11311 {
11312 	int err;
11313 
11314 	if (check_lock && env->cur_state->active_locks) {
11315 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
11316 		return -EINVAL;
11317 	}
11318 
11319 	err = check_reference_leak(env, exception_exit);
11320 	if (err) {
11321 		verbose(env, "%s would lead to reference leak\n", prefix);
11322 		return err;
11323 	}
11324 
11325 	if (check_lock && env->cur_state->active_irq_id) {
11326 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
11327 		return -EINVAL;
11328 	}
11329 
11330 	if (check_lock && env->cur_state->active_rcu_locks) {
11331 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
11332 		return -EINVAL;
11333 	}
11334 
11335 	if (check_lock && env->cur_state->active_preempt_locks) {
11336 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
11337 		return -EINVAL;
11338 	}
11339 
11340 	return 0;
11341 }
11342 
11343 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
11344 				   struct bpf_reg_state *regs)
11345 {
11346 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
11347 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
11348 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
11349 	struct bpf_bprintf_data data = {};
11350 	int err, fmt_map_off, num_args;
11351 	u64 fmt_addr;
11352 	char *fmt;
11353 
11354 	/* data must be an array of u64 */
11355 	if (data_len_reg->var_off.value % 8)
11356 		return -EINVAL;
11357 	num_args = data_len_reg->var_off.value / 8;
11358 
11359 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
11360 	 * and map_direct_value_addr is set.
11361 	 */
11362 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
11363 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
11364 						  fmt_map_off);
11365 	if (err) {
11366 		verbose(env, "failed to retrieve map value address\n");
11367 		return -EFAULT;
11368 	}
11369 	fmt = (char *)(long)fmt_addr + fmt_map_off;
11370 
11371 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
11372 	 * can focus on validating the format specifiers.
11373 	 */
11374 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
11375 	if (err < 0)
11376 		verbose(env, "Invalid format string\n");
11377 
11378 	return err;
11379 }
11380 
11381 static int check_get_func_ip(struct bpf_verifier_env *env)
11382 {
11383 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11384 	int func_id = BPF_FUNC_get_func_ip;
11385 
11386 	if (type == BPF_PROG_TYPE_TRACING) {
11387 		if (!bpf_prog_has_trampoline(env->prog)) {
11388 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
11389 				func_id_name(func_id), func_id);
11390 			return -ENOTSUPP;
11391 		}
11392 		return 0;
11393 	} else if (type == BPF_PROG_TYPE_KPROBE) {
11394 		return 0;
11395 	}
11396 
11397 	verbose(env, "func %s#%d not supported for program type %d\n",
11398 		func_id_name(func_id), func_id, type);
11399 	return -ENOTSUPP;
11400 }
11401 
11402 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
11403 {
11404 	return &env->insn_aux_data[env->insn_idx];
11405 }
11406 
11407 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
11408 {
11409 	struct bpf_reg_state *regs = cur_regs(env);
11410 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
11411 	bool reg_is_null = register_is_null(reg);
11412 
11413 	if (reg_is_null)
11414 		mark_chain_precision(env, BPF_REG_4);
11415 
11416 	return reg_is_null;
11417 }
11418 
11419 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
11420 {
11421 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
11422 
11423 	if (!state->initialized) {
11424 		state->initialized = 1;
11425 		state->fit_for_inline = loop_flag_is_zero(env);
11426 		state->callback_subprogno = subprogno;
11427 		return;
11428 	}
11429 
11430 	if (!state->fit_for_inline)
11431 		return;
11432 
11433 	state->fit_for_inline = (loop_flag_is_zero(env) &&
11434 				 state->callback_subprogno == subprogno);
11435 }
11436 
11437 /* Returns whether or not the given map type can potentially elide
11438  * lookup return value nullness check. This is possible if the key
11439  * is statically known.
11440  */
11441 static bool can_elide_value_nullness(enum bpf_map_type type)
11442 {
11443 	switch (type) {
11444 	case BPF_MAP_TYPE_ARRAY:
11445 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11446 		return true;
11447 	default:
11448 		return false;
11449 	}
11450 }
11451 
11452 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
11453 			    const struct bpf_func_proto **ptr)
11454 {
11455 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
11456 		return -ERANGE;
11457 
11458 	if (!env->ops->get_func_proto)
11459 		return -EINVAL;
11460 
11461 	*ptr = env->ops->get_func_proto(func_id, env->prog);
11462 	return *ptr && (*ptr)->func ? 0 : -EINVAL;
11463 }
11464 
11465 /* Check if we're in a sleepable context. */
11466 static inline bool in_sleepable_context(struct bpf_verifier_env *env)
11467 {
11468 	return !env->cur_state->active_rcu_locks &&
11469 	       !env->cur_state->active_preempt_locks &&
11470 	       !env->cur_state->active_irq_id &&
11471 	       in_sleepable(env);
11472 }
11473 
11474 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11475 			     int *insn_idx_p)
11476 {
11477 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11478 	bool returns_cpu_specific_alloc_ptr = false;
11479 	const struct bpf_func_proto *fn = NULL;
11480 	enum bpf_return_type ret_type;
11481 	enum bpf_type_flag ret_flag;
11482 	struct bpf_reg_state *regs;
11483 	struct bpf_call_arg_meta meta;
11484 	int insn_idx = *insn_idx_p;
11485 	bool changes_data;
11486 	int i, err, func_id;
11487 
11488 	/* find function prototype */
11489 	func_id = insn->imm;
11490 	err = get_helper_proto(env, insn->imm, &fn);
11491 	if (err == -ERANGE) {
11492 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
11493 		return -EINVAL;
11494 	}
11495 
11496 	if (err) {
11497 		verbose(env, "program of this type cannot use helper %s#%d\n",
11498 			func_id_name(func_id), func_id);
11499 		return err;
11500 	}
11501 
11502 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
11503 	if (!env->prog->gpl_compatible && fn->gpl_only) {
11504 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
11505 		return -EINVAL;
11506 	}
11507 
11508 	if (fn->allowed && !fn->allowed(env->prog)) {
11509 		verbose(env, "helper call is not allowed in probe\n");
11510 		return -EINVAL;
11511 	}
11512 
11513 	if (!in_sleepable(env) && fn->might_sleep) {
11514 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
11515 		return -EINVAL;
11516 	}
11517 
11518 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
11519 	changes_data = bpf_helper_changes_pkt_data(func_id);
11520 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
11521 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
11522 		return -EFAULT;
11523 	}
11524 
11525 	memset(&meta, 0, sizeof(meta));
11526 	meta.pkt_access = fn->pkt_access;
11527 
11528 	err = check_func_proto(fn, func_id);
11529 	if (err) {
11530 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
11531 		return err;
11532 	}
11533 
11534 	if (env->cur_state->active_rcu_locks) {
11535 		if (fn->might_sleep) {
11536 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
11537 				func_id_name(func_id), func_id);
11538 			return -EINVAL;
11539 		}
11540 	}
11541 
11542 	if (env->cur_state->active_preempt_locks) {
11543 		if (fn->might_sleep) {
11544 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
11545 				func_id_name(func_id), func_id);
11546 			return -EINVAL;
11547 		}
11548 	}
11549 
11550 	if (env->cur_state->active_irq_id) {
11551 		if (fn->might_sleep) {
11552 			verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n",
11553 				func_id_name(func_id), func_id);
11554 			return -EINVAL;
11555 		}
11556 	}
11557 
11558 	/* Track non-sleepable context for helpers. */
11559 	if (!in_sleepable_context(env))
11560 		env->insn_aux_data[insn_idx].non_sleepable = true;
11561 
11562 	meta.func_id = func_id;
11563 	/* check args */
11564 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
11565 		err = check_func_arg(env, i, &meta, fn, insn_idx);
11566 		if (err)
11567 			return err;
11568 	}
11569 
11570 	err = record_func_map(env, &meta, func_id, insn_idx);
11571 	if (err)
11572 		return err;
11573 
11574 	err = record_func_key(env, &meta, func_id, insn_idx);
11575 	if (err)
11576 		return err;
11577 
11578 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
11579 	 * is inferred from register state.
11580 	 */
11581 	for (i = 0; i < meta.access_size; i++) {
11582 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
11583 				       BPF_WRITE, -1, false, false);
11584 		if (err)
11585 			return err;
11586 	}
11587 
11588 	regs = cur_regs(env);
11589 
11590 	if (meta.release_regno) {
11591 		err = -EINVAL;
11592 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
11593 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
11594 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
11595 			u32 ref_obj_id = meta.ref_obj_id;
11596 			bool in_rcu = in_rcu_cs(env);
11597 			struct bpf_func_state *state;
11598 			struct bpf_reg_state *reg;
11599 
11600 			err = release_reference_nomark(env->cur_state, ref_obj_id);
11601 			if (!err) {
11602 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11603 					if (reg->ref_obj_id == ref_obj_id) {
11604 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11605 							reg->ref_obj_id = 0;
11606 							reg->type &= ~MEM_ALLOC;
11607 							reg->type |= MEM_RCU;
11608 						} else {
11609 							mark_reg_invalid(env, reg);
11610 						}
11611 					}
11612 				}));
11613 			}
11614 		} else if (meta.ref_obj_id) {
11615 			err = release_reference(env, meta.ref_obj_id);
11616 		} else if (register_is_null(&regs[meta.release_regno])) {
11617 			/* meta.ref_obj_id can only be 0 if register that is meant to be
11618 			 * released is NULL, which must be > R0.
11619 			 */
11620 			err = 0;
11621 		}
11622 		if (err) {
11623 			verbose(env, "func %s#%d reference has not been acquired before\n",
11624 				func_id_name(func_id), func_id);
11625 			return err;
11626 		}
11627 	}
11628 
11629 	switch (func_id) {
11630 	case BPF_FUNC_tail_call:
11631 		err = check_resource_leak(env, false, true, "tail_call");
11632 		if (err)
11633 			return err;
11634 		break;
11635 	case BPF_FUNC_get_local_storage:
11636 		/* check that flags argument in get_local_storage(map, flags) is 0,
11637 		 * this is required because get_local_storage() can't return an error.
11638 		 */
11639 		if (!register_is_null(&regs[BPF_REG_2])) {
11640 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
11641 			return -EINVAL;
11642 		}
11643 		break;
11644 	case BPF_FUNC_for_each_map_elem:
11645 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11646 					 set_map_elem_callback_state);
11647 		break;
11648 	case BPF_FUNC_timer_set_callback:
11649 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11650 					 set_timer_callback_state);
11651 		break;
11652 	case BPF_FUNC_find_vma:
11653 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11654 					 set_find_vma_callback_state);
11655 		break;
11656 	case BPF_FUNC_snprintf:
11657 		err = check_bpf_snprintf_call(env, regs);
11658 		break;
11659 	case BPF_FUNC_loop:
11660 		update_loop_inline_state(env, meta.subprogno);
11661 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
11662 		 * is finished, thus mark it precise.
11663 		 */
11664 		err = mark_chain_precision(env, BPF_REG_1);
11665 		if (err)
11666 			return err;
11667 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
11668 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11669 						 set_loop_callback_state);
11670 		} else {
11671 			cur_func(env)->callback_depth = 0;
11672 			if (env->log.level & BPF_LOG_LEVEL2)
11673 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
11674 					env->cur_state->curframe);
11675 		}
11676 		break;
11677 	case BPF_FUNC_dynptr_from_mem:
11678 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
11679 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
11680 				reg_type_str(env, regs[BPF_REG_1].type));
11681 			return -EACCES;
11682 		}
11683 		break;
11684 	case BPF_FUNC_set_retval:
11685 		if (prog_type == BPF_PROG_TYPE_LSM &&
11686 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11687 			if (!env->prog->aux->attach_func_proto->type) {
11688 				/* Make sure programs that attach to void
11689 				 * hooks don't try to modify return value.
11690 				 */
11691 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11692 				return -EINVAL;
11693 			}
11694 		}
11695 		break;
11696 	case BPF_FUNC_dynptr_data:
11697 	{
11698 		struct bpf_reg_state *reg;
11699 		int id, ref_obj_id;
11700 
11701 		reg = get_dynptr_arg_reg(env, fn, regs);
11702 		if (!reg)
11703 			return -EFAULT;
11704 
11705 
11706 		if (meta.dynptr_id) {
11707 			verifier_bug(env, "meta.dynptr_id already set");
11708 			return -EFAULT;
11709 		}
11710 		if (meta.ref_obj_id) {
11711 			verifier_bug(env, "meta.ref_obj_id already set");
11712 			return -EFAULT;
11713 		}
11714 
11715 		id = dynptr_id(env, reg);
11716 		if (id < 0) {
11717 			verifier_bug(env, "failed to obtain dynptr id");
11718 			return id;
11719 		}
11720 
11721 		ref_obj_id = dynptr_ref_obj_id(env, reg);
11722 		if (ref_obj_id < 0) {
11723 			verifier_bug(env, "failed to obtain dynptr ref_obj_id");
11724 			return ref_obj_id;
11725 		}
11726 
11727 		meta.dynptr_id = id;
11728 		meta.ref_obj_id = ref_obj_id;
11729 
11730 		break;
11731 	}
11732 	case BPF_FUNC_dynptr_write:
11733 	{
11734 		enum bpf_dynptr_type dynptr_type;
11735 		struct bpf_reg_state *reg;
11736 
11737 		reg = get_dynptr_arg_reg(env, fn, regs);
11738 		if (!reg)
11739 			return -EFAULT;
11740 
11741 		dynptr_type = dynptr_get_type(env, reg);
11742 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11743 			return -EFAULT;
11744 
11745 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
11746 		    dynptr_type == BPF_DYNPTR_TYPE_SKB_META)
11747 			/* this will trigger clear_all_pkt_pointers(), which will
11748 			 * invalidate all dynptr slices associated with the skb
11749 			 */
11750 			changes_data = true;
11751 
11752 		break;
11753 	}
11754 	case BPF_FUNC_per_cpu_ptr:
11755 	case BPF_FUNC_this_cpu_ptr:
11756 	{
11757 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
11758 		const struct btf_type *type;
11759 
11760 		if (reg->type & MEM_RCU) {
11761 			type = btf_type_by_id(reg->btf, reg->btf_id);
11762 			if (!type || !btf_type_is_struct(type)) {
11763 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
11764 				return -EFAULT;
11765 			}
11766 			returns_cpu_specific_alloc_ptr = true;
11767 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11768 		}
11769 		break;
11770 	}
11771 	case BPF_FUNC_user_ringbuf_drain:
11772 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11773 					 set_user_ringbuf_callback_state);
11774 		break;
11775 	}
11776 
11777 	if (err)
11778 		return err;
11779 
11780 	/* reset caller saved regs */
11781 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11782 		mark_reg_not_init(env, regs, caller_saved[i]);
11783 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11784 	}
11785 
11786 	/* helper call returns 64-bit value. */
11787 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
11788 
11789 	/* update return register (already marked as written above) */
11790 	ret_type = fn->ret_type;
11791 	ret_flag = type_flag(ret_type);
11792 
11793 	switch (base_type(ret_type)) {
11794 	case RET_INTEGER:
11795 		/* sets type to SCALAR_VALUE */
11796 		mark_reg_unknown(env, regs, BPF_REG_0);
11797 		break;
11798 	case RET_VOID:
11799 		regs[BPF_REG_0].type = NOT_INIT;
11800 		break;
11801 	case RET_PTR_TO_MAP_VALUE:
11802 		/* There is no offset yet applied, variable or fixed */
11803 		mark_reg_known_zero(env, regs, BPF_REG_0);
11804 		/* remember map_ptr, so that check_map_access()
11805 		 * can check 'value_size' boundary of memory access
11806 		 * to map element returned from bpf_map_lookup_elem()
11807 		 */
11808 		if (meta.map_ptr == NULL) {
11809 			verifier_bug(env, "unexpected null map_ptr");
11810 			return -EFAULT;
11811 		}
11812 
11813 		if (func_id == BPF_FUNC_map_lookup_elem &&
11814 		    can_elide_value_nullness(meta.map_ptr->map_type) &&
11815 		    meta.const_map_key >= 0 &&
11816 		    meta.const_map_key < meta.map_ptr->max_entries)
11817 			ret_flag &= ~PTR_MAYBE_NULL;
11818 
11819 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
11820 		regs[BPF_REG_0].map_uid = meta.map_uid;
11821 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11822 		if (!type_may_be_null(ret_flag) &&
11823 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
11824 			regs[BPF_REG_0].id = ++env->id_gen;
11825 		}
11826 		break;
11827 	case RET_PTR_TO_SOCKET:
11828 		mark_reg_known_zero(env, regs, BPF_REG_0);
11829 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11830 		break;
11831 	case RET_PTR_TO_SOCK_COMMON:
11832 		mark_reg_known_zero(env, regs, BPF_REG_0);
11833 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11834 		break;
11835 	case RET_PTR_TO_TCP_SOCK:
11836 		mark_reg_known_zero(env, regs, BPF_REG_0);
11837 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11838 		break;
11839 	case RET_PTR_TO_MEM:
11840 		mark_reg_known_zero(env, regs, BPF_REG_0);
11841 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11842 		regs[BPF_REG_0].mem_size = meta.mem_size;
11843 		break;
11844 	case RET_PTR_TO_MEM_OR_BTF_ID:
11845 	{
11846 		const struct btf_type *t;
11847 
11848 		mark_reg_known_zero(env, regs, BPF_REG_0);
11849 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11850 		if (!btf_type_is_struct(t)) {
11851 			u32 tsize;
11852 			const struct btf_type *ret;
11853 			const char *tname;
11854 
11855 			/* resolve the type size of ksym. */
11856 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11857 			if (IS_ERR(ret)) {
11858 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11859 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
11860 					tname, PTR_ERR(ret));
11861 				return -EINVAL;
11862 			}
11863 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11864 			regs[BPF_REG_0].mem_size = tsize;
11865 		} else {
11866 			if (returns_cpu_specific_alloc_ptr) {
11867 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11868 			} else {
11869 				/* MEM_RDONLY may be carried from ret_flag, but it
11870 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11871 				 * it will confuse the check of PTR_TO_BTF_ID in
11872 				 * check_mem_access().
11873 				 */
11874 				ret_flag &= ~MEM_RDONLY;
11875 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11876 			}
11877 
11878 			regs[BPF_REG_0].btf = meta.ret_btf;
11879 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11880 		}
11881 		break;
11882 	}
11883 	case RET_PTR_TO_BTF_ID:
11884 	{
11885 		struct btf *ret_btf;
11886 		int ret_btf_id;
11887 
11888 		mark_reg_known_zero(env, regs, BPF_REG_0);
11889 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11890 		if (func_id == BPF_FUNC_kptr_xchg) {
11891 			ret_btf = meta.kptr_field->kptr.btf;
11892 			ret_btf_id = meta.kptr_field->kptr.btf_id;
11893 			if (!btf_is_kernel(ret_btf)) {
11894 				regs[BPF_REG_0].type |= MEM_ALLOC;
11895 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11896 					regs[BPF_REG_0].type |= MEM_PERCPU;
11897 			}
11898 		} else {
11899 			if (fn->ret_btf_id == BPF_PTR_POISON) {
11900 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
11901 					     func_id_name(func_id));
11902 				return -EFAULT;
11903 			}
11904 			ret_btf = btf_vmlinux;
11905 			ret_btf_id = *fn->ret_btf_id;
11906 		}
11907 		if (ret_btf_id == 0) {
11908 			verbose(env, "invalid return type %u of func %s#%d\n",
11909 				base_type(ret_type), func_id_name(func_id),
11910 				func_id);
11911 			return -EINVAL;
11912 		}
11913 		regs[BPF_REG_0].btf = ret_btf;
11914 		regs[BPF_REG_0].btf_id = ret_btf_id;
11915 		break;
11916 	}
11917 	default:
11918 		verbose(env, "unknown return type %u of func %s#%d\n",
11919 			base_type(ret_type), func_id_name(func_id), func_id);
11920 		return -EINVAL;
11921 	}
11922 
11923 	if (type_may_be_null(regs[BPF_REG_0].type))
11924 		regs[BPF_REG_0].id = ++env->id_gen;
11925 
11926 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
11927 		verifier_bug(env, "func %s#%d sets ref_obj_id more than once",
11928 			     func_id_name(func_id), func_id);
11929 		return -EFAULT;
11930 	}
11931 
11932 	if (is_dynptr_ref_function(func_id))
11933 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
11934 
11935 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
11936 		/* For release_reference() */
11937 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11938 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
11939 		int id = acquire_reference(env, insn_idx);
11940 
11941 		if (id < 0)
11942 			return id;
11943 		/* For mark_ptr_or_null_reg() */
11944 		regs[BPF_REG_0].id = id;
11945 		/* For release_reference() */
11946 		regs[BPF_REG_0].ref_obj_id = id;
11947 	}
11948 
11949 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
11950 	if (err)
11951 		return err;
11952 
11953 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
11954 	if (err)
11955 		return err;
11956 
11957 	if ((func_id == BPF_FUNC_get_stack ||
11958 	     func_id == BPF_FUNC_get_task_stack) &&
11959 	    !env->prog->has_callchain_buf) {
11960 		const char *err_str;
11961 
11962 #ifdef CONFIG_PERF_EVENTS
11963 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
11964 		err_str = "cannot get callchain buffer for func %s#%d\n";
11965 #else
11966 		err = -ENOTSUPP;
11967 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
11968 #endif
11969 		if (err) {
11970 			verbose(env, err_str, func_id_name(func_id), func_id);
11971 			return err;
11972 		}
11973 
11974 		env->prog->has_callchain_buf = true;
11975 	}
11976 
11977 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
11978 		env->prog->call_get_stack = true;
11979 
11980 	if (func_id == BPF_FUNC_get_func_ip) {
11981 		if (check_get_func_ip(env))
11982 			return -ENOTSUPP;
11983 		env->prog->call_get_func_ip = true;
11984 	}
11985 
11986 	if (func_id == BPF_FUNC_tail_call) {
11987 		if (env->cur_state->curframe) {
11988 			struct bpf_verifier_state *branch;
11989 
11990 			mark_reg_scratched(env, BPF_REG_0);
11991 			branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
11992 			if (IS_ERR(branch))
11993 				return PTR_ERR(branch);
11994 			clear_all_pkt_pointers(env);
11995 			mark_reg_unknown(env, regs, BPF_REG_0);
11996 			err = prepare_func_exit(env, &env->insn_idx);
11997 			if (err)
11998 				return err;
11999 			env->insn_idx--;
12000 		} else {
12001 			changes_data = false;
12002 		}
12003 	}
12004 
12005 	if (changes_data)
12006 		clear_all_pkt_pointers(env);
12007 	return 0;
12008 }
12009 
12010 /* mark_btf_func_reg_size() is used when the reg size is determined by
12011  * the BTF func_proto's return value size and argument.
12012  */
12013 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
12014 				     u32 regno, size_t reg_size)
12015 {
12016 	struct bpf_reg_state *reg = &regs[regno];
12017 
12018 	if (regno == BPF_REG_0) {
12019 		/* Function return value */
12020 		reg->subreg_def = reg_size == sizeof(u64) ?
12021 			DEF_NOT_SUBREG : env->insn_idx + 1;
12022 	} else if (reg_size == sizeof(u64)) {
12023 		/* Function argument */
12024 		mark_insn_zext(env, reg);
12025 	}
12026 }
12027 
12028 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
12029 				   size_t reg_size)
12030 {
12031 	return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size);
12032 }
12033 
12034 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
12035 {
12036 	return meta->kfunc_flags & KF_ACQUIRE;
12037 }
12038 
12039 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
12040 {
12041 	return meta->kfunc_flags & KF_RELEASE;
12042 }
12043 
12044 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
12045 {
12046 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
12047 }
12048 
12049 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
12050 {
12051 	return meta->kfunc_flags & KF_SLEEPABLE;
12052 }
12053 
12054 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
12055 {
12056 	return meta->kfunc_flags & KF_DESTRUCTIVE;
12057 }
12058 
12059 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
12060 {
12061 	return meta->kfunc_flags & KF_RCU;
12062 }
12063 
12064 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
12065 {
12066 	return meta->kfunc_flags & KF_RCU_PROTECTED;
12067 }
12068 
12069 static bool is_kfunc_arg_mem_size(const struct btf *btf,
12070 				  const struct btf_param *arg,
12071 				  const struct bpf_reg_state *reg)
12072 {
12073 	const struct btf_type *t;
12074 
12075 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12076 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
12077 		return false;
12078 
12079 	return btf_param_match_suffix(btf, arg, "__sz");
12080 }
12081 
12082 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
12083 					const struct btf_param *arg,
12084 					const struct bpf_reg_state *reg)
12085 {
12086 	const struct btf_type *t;
12087 
12088 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12089 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
12090 		return false;
12091 
12092 	return btf_param_match_suffix(btf, arg, "__szk");
12093 }
12094 
12095 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
12096 {
12097 	return btf_param_match_suffix(btf, arg, "__opt");
12098 }
12099 
12100 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
12101 {
12102 	return btf_param_match_suffix(btf, arg, "__k");
12103 }
12104 
12105 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
12106 {
12107 	return btf_param_match_suffix(btf, arg, "__ign");
12108 }
12109 
12110 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
12111 {
12112 	return btf_param_match_suffix(btf, arg, "__map");
12113 }
12114 
12115 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
12116 {
12117 	return btf_param_match_suffix(btf, arg, "__alloc");
12118 }
12119 
12120 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
12121 {
12122 	return btf_param_match_suffix(btf, arg, "__uninit");
12123 }
12124 
12125 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
12126 {
12127 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
12128 }
12129 
12130 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
12131 {
12132 	return btf_param_match_suffix(btf, arg, "__nullable");
12133 }
12134 
12135 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
12136 {
12137 	return btf_param_match_suffix(btf, arg, "__str");
12138 }
12139 
12140 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
12141 {
12142 	return btf_param_match_suffix(btf, arg, "__irq_flag");
12143 }
12144 
12145 static bool is_kfunc_arg_prog(const struct btf *btf, const struct btf_param *arg)
12146 {
12147 	return btf_param_match_suffix(btf, arg, "__prog");
12148 }
12149 
12150 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
12151 					  const struct btf_param *arg,
12152 					  const char *name)
12153 {
12154 	int len, target_len = strlen(name);
12155 	const char *param_name;
12156 
12157 	param_name = btf_name_by_offset(btf, arg->name_off);
12158 	if (str_is_empty(param_name))
12159 		return false;
12160 	len = strlen(param_name);
12161 	if (len != target_len)
12162 		return false;
12163 	if (strcmp(param_name, name))
12164 		return false;
12165 
12166 	return true;
12167 }
12168 
12169 enum {
12170 	KF_ARG_DYNPTR_ID,
12171 	KF_ARG_LIST_HEAD_ID,
12172 	KF_ARG_LIST_NODE_ID,
12173 	KF_ARG_RB_ROOT_ID,
12174 	KF_ARG_RB_NODE_ID,
12175 	KF_ARG_WORKQUEUE_ID,
12176 	KF_ARG_RES_SPIN_LOCK_ID,
12177 	KF_ARG_TASK_WORK_ID,
12178 };
12179 
12180 BTF_ID_LIST(kf_arg_btf_ids)
12181 BTF_ID(struct, bpf_dynptr)
12182 BTF_ID(struct, bpf_list_head)
12183 BTF_ID(struct, bpf_list_node)
12184 BTF_ID(struct, bpf_rb_root)
12185 BTF_ID(struct, bpf_rb_node)
12186 BTF_ID(struct, bpf_wq)
12187 BTF_ID(struct, bpf_res_spin_lock)
12188 BTF_ID(struct, bpf_task_work)
12189 
12190 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
12191 				    const struct btf_param *arg, int type)
12192 {
12193 	const struct btf_type *t;
12194 	u32 res_id;
12195 
12196 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12197 	if (!t)
12198 		return false;
12199 	if (!btf_type_is_ptr(t))
12200 		return false;
12201 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
12202 	if (!t)
12203 		return false;
12204 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
12205 }
12206 
12207 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
12208 {
12209 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
12210 }
12211 
12212 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
12213 {
12214 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
12215 }
12216 
12217 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
12218 {
12219 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
12220 }
12221 
12222 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
12223 {
12224 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
12225 }
12226 
12227 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
12228 {
12229 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
12230 }
12231 
12232 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
12233 {
12234 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
12235 }
12236 
12237 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
12238 {
12239 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
12240 }
12241 
12242 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
12243 {
12244 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
12245 }
12246 
12247 static bool is_rbtree_node_type(const struct btf_type *t)
12248 {
12249 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
12250 }
12251 
12252 static bool is_list_node_type(const struct btf_type *t)
12253 {
12254 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
12255 }
12256 
12257 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
12258 				  const struct btf_param *arg)
12259 {
12260 	const struct btf_type *t;
12261 
12262 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
12263 	if (!t)
12264 		return false;
12265 
12266 	return true;
12267 }
12268 
12269 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
12270 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
12271 					const struct btf *btf,
12272 					const struct btf_type *t, int rec)
12273 {
12274 	const struct btf_type *member_type;
12275 	const struct btf_member *member;
12276 	u32 i;
12277 
12278 	if (!btf_type_is_struct(t))
12279 		return false;
12280 
12281 	for_each_member(i, t, member) {
12282 		const struct btf_array *array;
12283 
12284 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
12285 		if (btf_type_is_struct(member_type)) {
12286 			if (rec >= 3) {
12287 				verbose(env, "max struct nesting depth exceeded\n");
12288 				return false;
12289 			}
12290 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
12291 				return false;
12292 			continue;
12293 		}
12294 		if (btf_type_is_array(member_type)) {
12295 			array = btf_array(member_type);
12296 			if (!array->nelems)
12297 				return false;
12298 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
12299 			if (!btf_type_is_scalar(member_type))
12300 				return false;
12301 			continue;
12302 		}
12303 		if (!btf_type_is_scalar(member_type))
12304 			return false;
12305 	}
12306 	return true;
12307 }
12308 
12309 enum kfunc_ptr_arg_type {
12310 	KF_ARG_PTR_TO_CTX,
12311 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
12312 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
12313 	KF_ARG_PTR_TO_DYNPTR,
12314 	KF_ARG_PTR_TO_ITER,
12315 	KF_ARG_PTR_TO_LIST_HEAD,
12316 	KF_ARG_PTR_TO_LIST_NODE,
12317 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
12318 	KF_ARG_PTR_TO_MEM,
12319 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
12320 	KF_ARG_PTR_TO_CALLBACK,
12321 	KF_ARG_PTR_TO_RB_ROOT,
12322 	KF_ARG_PTR_TO_RB_NODE,
12323 	KF_ARG_PTR_TO_NULL,
12324 	KF_ARG_PTR_TO_CONST_STR,
12325 	KF_ARG_PTR_TO_MAP,
12326 	KF_ARG_PTR_TO_WORKQUEUE,
12327 	KF_ARG_PTR_TO_IRQ_FLAG,
12328 	KF_ARG_PTR_TO_RES_SPIN_LOCK,
12329 	KF_ARG_PTR_TO_TASK_WORK,
12330 };
12331 
12332 enum special_kfunc_type {
12333 	KF_bpf_obj_new_impl,
12334 	KF_bpf_obj_drop_impl,
12335 	KF_bpf_refcount_acquire_impl,
12336 	KF_bpf_list_push_front_impl,
12337 	KF_bpf_list_push_back_impl,
12338 	KF_bpf_list_pop_front,
12339 	KF_bpf_list_pop_back,
12340 	KF_bpf_list_front,
12341 	KF_bpf_list_back,
12342 	KF_bpf_cast_to_kern_ctx,
12343 	KF_bpf_rdonly_cast,
12344 	KF_bpf_rcu_read_lock,
12345 	KF_bpf_rcu_read_unlock,
12346 	KF_bpf_rbtree_remove,
12347 	KF_bpf_rbtree_add_impl,
12348 	KF_bpf_rbtree_first,
12349 	KF_bpf_rbtree_root,
12350 	KF_bpf_rbtree_left,
12351 	KF_bpf_rbtree_right,
12352 	KF_bpf_dynptr_from_skb,
12353 	KF_bpf_dynptr_from_xdp,
12354 	KF_bpf_dynptr_from_skb_meta,
12355 	KF_bpf_xdp_pull_data,
12356 	KF_bpf_dynptr_slice,
12357 	KF_bpf_dynptr_slice_rdwr,
12358 	KF_bpf_dynptr_clone,
12359 	KF_bpf_percpu_obj_new_impl,
12360 	KF_bpf_percpu_obj_drop_impl,
12361 	KF_bpf_throw,
12362 	KF_bpf_wq_set_callback_impl,
12363 	KF_bpf_preempt_disable,
12364 	KF_bpf_preempt_enable,
12365 	KF_bpf_iter_css_task_new,
12366 	KF_bpf_session_cookie,
12367 	KF_bpf_get_kmem_cache,
12368 	KF_bpf_local_irq_save,
12369 	KF_bpf_local_irq_restore,
12370 	KF_bpf_iter_num_new,
12371 	KF_bpf_iter_num_next,
12372 	KF_bpf_iter_num_destroy,
12373 	KF_bpf_set_dentry_xattr,
12374 	KF_bpf_remove_dentry_xattr,
12375 	KF_bpf_res_spin_lock,
12376 	KF_bpf_res_spin_unlock,
12377 	KF_bpf_res_spin_lock_irqsave,
12378 	KF_bpf_res_spin_unlock_irqrestore,
12379 	KF_bpf_dynptr_from_file,
12380 	KF_bpf_dynptr_file_discard,
12381 	KF___bpf_trap,
12382 	KF_bpf_task_work_schedule_signal_impl,
12383 	KF_bpf_task_work_schedule_resume_impl,
12384 };
12385 
12386 BTF_ID_LIST(special_kfunc_list)
12387 BTF_ID(func, bpf_obj_new_impl)
12388 BTF_ID(func, bpf_obj_drop_impl)
12389 BTF_ID(func, bpf_refcount_acquire_impl)
12390 BTF_ID(func, bpf_list_push_front_impl)
12391 BTF_ID(func, bpf_list_push_back_impl)
12392 BTF_ID(func, bpf_list_pop_front)
12393 BTF_ID(func, bpf_list_pop_back)
12394 BTF_ID(func, bpf_list_front)
12395 BTF_ID(func, bpf_list_back)
12396 BTF_ID(func, bpf_cast_to_kern_ctx)
12397 BTF_ID(func, bpf_rdonly_cast)
12398 BTF_ID(func, bpf_rcu_read_lock)
12399 BTF_ID(func, bpf_rcu_read_unlock)
12400 BTF_ID(func, bpf_rbtree_remove)
12401 BTF_ID(func, bpf_rbtree_add_impl)
12402 BTF_ID(func, bpf_rbtree_first)
12403 BTF_ID(func, bpf_rbtree_root)
12404 BTF_ID(func, bpf_rbtree_left)
12405 BTF_ID(func, bpf_rbtree_right)
12406 #ifdef CONFIG_NET
12407 BTF_ID(func, bpf_dynptr_from_skb)
12408 BTF_ID(func, bpf_dynptr_from_xdp)
12409 BTF_ID(func, bpf_dynptr_from_skb_meta)
12410 BTF_ID(func, bpf_xdp_pull_data)
12411 #else
12412 BTF_ID_UNUSED
12413 BTF_ID_UNUSED
12414 BTF_ID_UNUSED
12415 BTF_ID_UNUSED
12416 #endif
12417 BTF_ID(func, bpf_dynptr_slice)
12418 BTF_ID(func, bpf_dynptr_slice_rdwr)
12419 BTF_ID(func, bpf_dynptr_clone)
12420 BTF_ID(func, bpf_percpu_obj_new_impl)
12421 BTF_ID(func, bpf_percpu_obj_drop_impl)
12422 BTF_ID(func, bpf_throw)
12423 BTF_ID(func, bpf_wq_set_callback_impl)
12424 BTF_ID(func, bpf_preempt_disable)
12425 BTF_ID(func, bpf_preempt_enable)
12426 #ifdef CONFIG_CGROUPS
12427 BTF_ID(func, bpf_iter_css_task_new)
12428 #else
12429 BTF_ID_UNUSED
12430 #endif
12431 #ifdef CONFIG_BPF_EVENTS
12432 BTF_ID(func, bpf_session_cookie)
12433 #else
12434 BTF_ID_UNUSED
12435 #endif
12436 BTF_ID(func, bpf_get_kmem_cache)
12437 BTF_ID(func, bpf_local_irq_save)
12438 BTF_ID(func, bpf_local_irq_restore)
12439 BTF_ID(func, bpf_iter_num_new)
12440 BTF_ID(func, bpf_iter_num_next)
12441 BTF_ID(func, bpf_iter_num_destroy)
12442 #ifdef CONFIG_BPF_LSM
12443 BTF_ID(func, bpf_set_dentry_xattr)
12444 BTF_ID(func, bpf_remove_dentry_xattr)
12445 #else
12446 BTF_ID_UNUSED
12447 BTF_ID_UNUSED
12448 #endif
12449 BTF_ID(func, bpf_res_spin_lock)
12450 BTF_ID(func, bpf_res_spin_unlock)
12451 BTF_ID(func, bpf_res_spin_lock_irqsave)
12452 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
12453 BTF_ID(func, bpf_dynptr_from_file)
12454 BTF_ID(func, bpf_dynptr_file_discard)
12455 BTF_ID(func, __bpf_trap)
12456 BTF_ID(func, bpf_task_work_schedule_signal_impl)
12457 BTF_ID(func, bpf_task_work_schedule_resume_impl)
12458 
12459 static bool is_task_work_add_kfunc(u32 func_id)
12460 {
12461 	return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal_impl] ||
12462 	       func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume_impl];
12463 }
12464 
12465 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
12466 {
12467 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
12468 	    meta->arg_owning_ref) {
12469 		return false;
12470 	}
12471 
12472 	return meta->kfunc_flags & KF_RET_NULL;
12473 }
12474 
12475 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
12476 {
12477 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
12478 }
12479 
12480 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
12481 {
12482 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
12483 }
12484 
12485 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
12486 {
12487 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
12488 }
12489 
12490 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
12491 {
12492 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
12493 }
12494 
12495 static bool is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta)
12496 {
12497 	return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data];
12498 }
12499 
12500 static enum kfunc_ptr_arg_type
12501 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
12502 		       struct bpf_kfunc_call_arg_meta *meta,
12503 		       const struct btf_type *t, const struct btf_type *ref_t,
12504 		       const char *ref_tname, const struct btf_param *args,
12505 		       int argno, int nargs)
12506 {
12507 	u32 regno = argno + 1;
12508 	struct bpf_reg_state *regs = cur_regs(env);
12509 	struct bpf_reg_state *reg = &regs[regno];
12510 	bool arg_mem_size = false;
12511 
12512 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
12513 		return KF_ARG_PTR_TO_CTX;
12514 
12515 	/* In this function, we verify the kfunc's BTF as per the argument type,
12516 	 * leaving the rest of the verification with respect to the register
12517 	 * type to our caller. When a set of conditions hold in the BTF type of
12518 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
12519 	 */
12520 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
12521 		return KF_ARG_PTR_TO_CTX;
12522 
12523 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
12524 		return KF_ARG_PTR_TO_NULL;
12525 
12526 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
12527 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
12528 
12529 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
12530 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
12531 
12532 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
12533 		return KF_ARG_PTR_TO_DYNPTR;
12534 
12535 	if (is_kfunc_arg_iter(meta, argno, &args[argno]))
12536 		return KF_ARG_PTR_TO_ITER;
12537 
12538 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
12539 		return KF_ARG_PTR_TO_LIST_HEAD;
12540 
12541 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
12542 		return KF_ARG_PTR_TO_LIST_NODE;
12543 
12544 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
12545 		return KF_ARG_PTR_TO_RB_ROOT;
12546 
12547 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
12548 		return KF_ARG_PTR_TO_RB_NODE;
12549 
12550 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
12551 		return KF_ARG_PTR_TO_CONST_STR;
12552 
12553 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
12554 		return KF_ARG_PTR_TO_MAP;
12555 
12556 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
12557 		return KF_ARG_PTR_TO_WORKQUEUE;
12558 
12559 	if (is_kfunc_arg_task_work(meta->btf, &args[argno]))
12560 		return KF_ARG_PTR_TO_TASK_WORK;
12561 
12562 	if (is_kfunc_arg_irq_flag(meta->btf, &args[argno]))
12563 		return KF_ARG_PTR_TO_IRQ_FLAG;
12564 
12565 	if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno]))
12566 		return KF_ARG_PTR_TO_RES_SPIN_LOCK;
12567 
12568 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
12569 		if (!btf_type_is_struct(ref_t)) {
12570 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
12571 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
12572 			return -EINVAL;
12573 		}
12574 		return KF_ARG_PTR_TO_BTF_ID;
12575 	}
12576 
12577 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
12578 		return KF_ARG_PTR_TO_CALLBACK;
12579 
12580 	if (argno + 1 < nargs &&
12581 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
12582 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
12583 		arg_mem_size = true;
12584 
12585 	/* This is the catch all argument type of register types supported by
12586 	 * check_helper_mem_access. However, we only allow when argument type is
12587 	 * pointer to scalar, or struct composed (recursively) of scalars. When
12588 	 * arg_mem_size is true, the pointer can be void *.
12589 	 */
12590 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
12591 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
12592 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
12593 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
12594 		return -EINVAL;
12595 	}
12596 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
12597 }
12598 
12599 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
12600 					struct bpf_reg_state *reg,
12601 					const struct btf_type *ref_t,
12602 					const char *ref_tname, u32 ref_id,
12603 					struct bpf_kfunc_call_arg_meta *meta,
12604 					int argno)
12605 {
12606 	const struct btf_type *reg_ref_t;
12607 	bool strict_type_match = false;
12608 	const struct btf *reg_btf;
12609 	const char *reg_ref_tname;
12610 	bool taking_projection;
12611 	bool struct_same;
12612 	u32 reg_ref_id;
12613 
12614 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
12615 		reg_btf = reg->btf;
12616 		reg_ref_id = reg->btf_id;
12617 	} else {
12618 		reg_btf = btf_vmlinux;
12619 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
12620 	}
12621 
12622 	/* Enforce strict type matching for calls to kfuncs that are acquiring
12623 	 * or releasing a reference, or are no-cast aliases. We do _not_
12624 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
12625 	 * as we want to enable BPF programs to pass types that are bitwise
12626 	 * equivalent without forcing them to explicitly cast with something
12627 	 * like bpf_cast_to_kern_ctx().
12628 	 *
12629 	 * For example, say we had a type like the following:
12630 	 *
12631 	 * struct bpf_cpumask {
12632 	 *	cpumask_t cpumask;
12633 	 *	refcount_t usage;
12634 	 * };
12635 	 *
12636 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
12637 	 * to a struct cpumask, so it would be safe to pass a struct
12638 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
12639 	 *
12640 	 * The philosophy here is similar to how we allow scalars of different
12641 	 * types to be passed to kfuncs as long as the size is the same. The
12642 	 * only difference here is that we're simply allowing
12643 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
12644 	 * resolve types.
12645 	 */
12646 	if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
12647 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
12648 		strict_type_match = true;
12649 
12650 	WARN_ON_ONCE(is_kfunc_release(meta) &&
12651 		     (reg->off || !tnum_is_const(reg->var_off) ||
12652 		      reg->var_off.value));
12653 
12654 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
12655 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
12656 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
12657 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
12658 	 * actually use it -- it must cast to the underlying type. So we allow
12659 	 * caller to pass in the underlying type.
12660 	 */
12661 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
12662 	if (!taking_projection && !struct_same) {
12663 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
12664 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
12665 			btf_type_str(reg_ref_t), reg_ref_tname);
12666 		return -EINVAL;
12667 	}
12668 	return 0;
12669 }
12670 
12671 static int process_irq_flag(struct bpf_verifier_env *env, int regno,
12672 			     struct bpf_kfunc_call_arg_meta *meta)
12673 {
12674 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
12675 	int err, kfunc_class = IRQ_NATIVE_KFUNC;
12676 	bool irq_save;
12677 
12678 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
12679 	    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
12680 		irq_save = true;
12681 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12682 			kfunc_class = IRQ_LOCK_KFUNC;
12683 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
12684 		   meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
12685 		irq_save = false;
12686 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12687 			kfunc_class = IRQ_LOCK_KFUNC;
12688 	} else {
12689 		verifier_bug(env, "unknown irq flags kfunc");
12690 		return -EFAULT;
12691 	}
12692 
12693 	if (irq_save) {
12694 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
12695 			verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1);
12696 			return -EINVAL;
12697 		}
12698 
12699 		err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false);
12700 		if (err)
12701 			return err;
12702 
12703 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
12704 		if (err)
12705 			return err;
12706 	} else {
12707 		err = is_irq_flag_reg_valid_init(env, reg);
12708 		if (err) {
12709 			verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1);
12710 			return err;
12711 		}
12712 
12713 		err = mark_irq_flag_read(env, reg);
12714 		if (err)
12715 			return err;
12716 
12717 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
12718 		if (err)
12719 			return err;
12720 	}
12721 	return 0;
12722 }
12723 
12724 
12725 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12726 {
12727 	struct btf_record *rec = reg_btf_record(reg);
12728 
12729 	if (!env->cur_state->active_locks) {
12730 		verifier_bug(env, "%s w/o active lock", __func__);
12731 		return -EFAULT;
12732 	}
12733 
12734 	if (type_flag(reg->type) & NON_OWN_REF) {
12735 		verifier_bug(env, "NON_OWN_REF already set");
12736 		return -EFAULT;
12737 	}
12738 
12739 	reg->type |= NON_OWN_REF;
12740 	if (rec->refcount_off >= 0)
12741 		reg->type |= MEM_RCU;
12742 
12743 	return 0;
12744 }
12745 
12746 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
12747 {
12748 	struct bpf_verifier_state *state = env->cur_state;
12749 	struct bpf_func_state *unused;
12750 	struct bpf_reg_state *reg;
12751 	int i;
12752 
12753 	if (!ref_obj_id) {
12754 		verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion");
12755 		return -EFAULT;
12756 	}
12757 
12758 	for (i = 0; i < state->acquired_refs; i++) {
12759 		if (state->refs[i].id != ref_obj_id)
12760 			continue;
12761 
12762 		/* Clear ref_obj_id here so release_reference doesn't clobber
12763 		 * the whole reg
12764 		 */
12765 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12766 			if (reg->ref_obj_id == ref_obj_id) {
12767 				reg->ref_obj_id = 0;
12768 				ref_set_non_owning(env, reg);
12769 			}
12770 		}));
12771 		return 0;
12772 	}
12773 
12774 	verifier_bug(env, "ref state missing for ref_obj_id");
12775 	return -EFAULT;
12776 }
12777 
12778 /* Implementation details:
12779  *
12780  * Each register points to some region of memory, which we define as an
12781  * allocation. Each allocation may embed a bpf_spin_lock which protects any
12782  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12783  * allocation. The lock and the data it protects are colocated in the same
12784  * memory region.
12785  *
12786  * Hence, everytime a register holds a pointer value pointing to such
12787  * allocation, the verifier preserves a unique reg->id for it.
12788  *
12789  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12790  * bpf_spin_lock is called.
12791  *
12792  * To enable this, lock state in the verifier captures two values:
12793  *	active_lock.ptr = Register's type specific pointer
12794  *	active_lock.id  = A unique ID for each register pointer value
12795  *
12796  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12797  * supported register types.
12798  *
12799  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12800  * allocated objects is the reg->btf pointer.
12801  *
12802  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12803  * can establish the provenance of the map value statically for each distinct
12804  * lookup into such maps. They always contain a single map value hence unique
12805  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12806  *
12807  * So, in case of global variables, they use array maps with max_entries = 1,
12808  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12809  * into the same map value as max_entries is 1, as described above).
12810  *
12811  * In case of inner map lookups, the inner map pointer has same map_ptr as the
12812  * outer map pointer (in verifier context), but each lookup into an inner map
12813  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12814  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12815  * will get different reg->id assigned to each lookup, hence different
12816  * active_lock.id.
12817  *
12818  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12819  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12820  * returned from bpf_obj_new. Each allocation receives a new reg->id.
12821  */
12822 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12823 {
12824 	struct bpf_reference_state *s;
12825 	void *ptr;
12826 	u32 id;
12827 
12828 	switch ((int)reg->type) {
12829 	case PTR_TO_MAP_VALUE:
12830 		ptr = reg->map_ptr;
12831 		break;
12832 	case PTR_TO_BTF_ID | MEM_ALLOC:
12833 		ptr = reg->btf;
12834 		break;
12835 	default:
12836 		verifier_bug(env, "unknown reg type for lock check");
12837 		return -EFAULT;
12838 	}
12839 	id = reg->id;
12840 
12841 	if (!env->cur_state->active_locks)
12842 		return -EINVAL;
12843 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
12844 	if (!s) {
12845 		verbose(env, "held lock and object are not in the same allocation\n");
12846 		return -EINVAL;
12847 	}
12848 	return 0;
12849 }
12850 
12851 static bool is_bpf_list_api_kfunc(u32 btf_id)
12852 {
12853 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12854 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12855 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12856 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
12857 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
12858 	       btf_id == special_kfunc_list[KF_bpf_list_back];
12859 }
12860 
12861 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
12862 {
12863 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12864 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12865 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
12866 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
12867 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12868 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
12869 }
12870 
12871 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
12872 {
12873 	return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
12874 	       btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
12875 	       btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
12876 }
12877 
12878 static bool is_bpf_graph_api_kfunc(u32 btf_id)
12879 {
12880 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
12881 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
12882 }
12883 
12884 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
12885 {
12886 	return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
12887 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
12888 	       btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
12889 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
12890 }
12891 
12892 static bool kfunc_spin_allowed(u32 btf_id)
12893 {
12894 	return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) ||
12895 	       is_bpf_res_spin_lock_kfunc(btf_id);
12896 }
12897 
12898 static bool is_sync_callback_calling_kfunc(u32 btf_id)
12899 {
12900 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
12901 }
12902 
12903 static bool is_async_callback_calling_kfunc(u32 btf_id)
12904 {
12905 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl] ||
12906 	       is_task_work_add_kfunc(btf_id);
12907 }
12908 
12909 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
12910 {
12911 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
12912 	       insn->imm == special_kfunc_list[KF_bpf_throw];
12913 }
12914 
12915 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
12916 {
12917 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12918 }
12919 
12920 static bool is_callback_calling_kfunc(u32 btf_id)
12921 {
12922 	return is_sync_callback_calling_kfunc(btf_id) ||
12923 	       is_async_callback_calling_kfunc(btf_id);
12924 }
12925 
12926 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
12927 {
12928 	return is_bpf_rbtree_api_kfunc(btf_id);
12929 }
12930 
12931 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
12932 					  enum btf_field_type head_field_type,
12933 					  u32 kfunc_btf_id)
12934 {
12935 	bool ret;
12936 
12937 	switch (head_field_type) {
12938 	case BPF_LIST_HEAD:
12939 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
12940 		break;
12941 	case BPF_RB_ROOT:
12942 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
12943 		break;
12944 	default:
12945 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
12946 			btf_field_type_name(head_field_type));
12947 		return false;
12948 	}
12949 
12950 	if (!ret)
12951 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
12952 			btf_field_type_name(head_field_type));
12953 	return ret;
12954 }
12955 
12956 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
12957 					  enum btf_field_type node_field_type,
12958 					  u32 kfunc_btf_id)
12959 {
12960 	bool ret;
12961 
12962 	switch (node_field_type) {
12963 	case BPF_LIST_NODE:
12964 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12965 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
12966 		break;
12967 	case BPF_RB_NODE:
12968 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12969 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12970 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12971 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
12972 		break;
12973 	default:
12974 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
12975 			btf_field_type_name(node_field_type));
12976 		return false;
12977 	}
12978 
12979 	if (!ret)
12980 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
12981 			btf_field_type_name(node_field_type));
12982 	return ret;
12983 }
12984 
12985 static int
12986 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
12987 				   struct bpf_reg_state *reg, u32 regno,
12988 				   struct bpf_kfunc_call_arg_meta *meta,
12989 				   enum btf_field_type head_field_type,
12990 				   struct btf_field **head_field)
12991 {
12992 	const char *head_type_name;
12993 	struct btf_field *field;
12994 	struct btf_record *rec;
12995 	u32 head_off;
12996 
12997 	if (meta->btf != btf_vmlinux) {
12998 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
12999 		return -EFAULT;
13000 	}
13001 
13002 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
13003 		return -EFAULT;
13004 
13005 	head_type_name = btf_field_type_name(head_field_type);
13006 	if (!tnum_is_const(reg->var_off)) {
13007 		verbose(env,
13008 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
13009 			regno, head_type_name);
13010 		return -EINVAL;
13011 	}
13012 
13013 	rec = reg_btf_record(reg);
13014 	head_off = reg->off + reg->var_off.value;
13015 	field = btf_record_find(rec, head_off, head_field_type);
13016 	if (!field) {
13017 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
13018 		return -EINVAL;
13019 	}
13020 
13021 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
13022 	if (check_reg_allocation_locked(env, reg)) {
13023 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
13024 			rec->spin_lock_off, head_type_name);
13025 		return -EINVAL;
13026 	}
13027 
13028 	if (*head_field) {
13029 		verifier_bug(env, "repeating %s arg", head_type_name);
13030 		return -EFAULT;
13031 	}
13032 	*head_field = field;
13033 	return 0;
13034 }
13035 
13036 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
13037 					   struct bpf_reg_state *reg, u32 regno,
13038 					   struct bpf_kfunc_call_arg_meta *meta)
13039 {
13040 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
13041 							  &meta->arg_list_head.field);
13042 }
13043 
13044 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
13045 					     struct bpf_reg_state *reg, u32 regno,
13046 					     struct bpf_kfunc_call_arg_meta *meta)
13047 {
13048 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
13049 							  &meta->arg_rbtree_root.field);
13050 }
13051 
13052 static int
13053 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
13054 				   struct bpf_reg_state *reg, u32 regno,
13055 				   struct bpf_kfunc_call_arg_meta *meta,
13056 				   enum btf_field_type head_field_type,
13057 				   enum btf_field_type node_field_type,
13058 				   struct btf_field **node_field)
13059 {
13060 	const char *node_type_name;
13061 	const struct btf_type *et, *t;
13062 	struct btf_field *field;
13063 	u32 node_off;
13064 
13065 	if (meta->btf != btf_vmlinux) {
13066 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
13067 		return -EFAULT;
13068 	}
13069 
13070 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
13071 		return -EFAULT;
13072 
13073 	node_type_name = btf_field_type_name(node_field_type);
13074 	if (!tnum_is_const(reg->var_off)) {
13075 		verbose(env,
13076 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
13077 			regno, node_type_name);
13078 		return -EINVAL;
13079 	}
13080 
13081 	node_off = reg->off + reg->var_off.value;
13082 	field = reg_find_field_offset(reg, node_off, node_field_type);
13083 	if (!field) {
13084 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
13085 		return -EINVAL;
13086 	}
13087 
13088 	field = *node_field;
13089 
13090 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
13091 	t = btf_type_by_id(reg->btf, reg->btf_id);
13092 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
13093 				  field->graph_root.value_btf_id, true)) {
13094 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
13095 			"in struct %s, but arg is at offset=%d in struct %s\n",
13096 			btf_field_type_name(head_field_type),
13097 			btf_field_type_name(node_field_type),
13098 			field->graph_root.node_offset,
13099 			btf_name_by_offset(field->graph_root.btf, et->name_off),
13100 			node_off, btf_name_by_offset(reg->btf, t->name_off));
13101 		return -EINVAL;
13102 	}
13103 	meta->arg_btf = reg->btf;
13104 	meta->arg_btf_id = reg->btf_id;
13105 
13106 	if (node_off != field->graph_root.node_offset) {
13107 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
13108 			node_off, btf_field_type_name(node_field_type),
13109 			field->graph_root.node_offset,
13110 			btf_name_by_offset(field->graph_root.btf, et->name_off));
13111 		return -EINVAL;
13112 	}
13113 
13114 	return 0;
13115 }
13116 
13117 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
13118 					   struct bpf_reg_state *reg, u32 regno,
13119 					   struct bpf_kfunc_call_arg_meta *meta)
13120 {
13121 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13122 						  BPF_LIST_HEAD, BPF_LIST_NODE,
13123 						  &meta->arg_list_head.field);
13124 }
13125 
13126 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
13127 					     struct bpf_reg_state *reg, u32 regno,
13128 					     struct bpf_kfunc_call_arg_meta *meta)
13129 {
13130 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13131 						  BPF_RB_ROOT, BPF_RB_NODE,
13132 						  &meta->arg_rbtree_root.field);
13133 }
13134 
13135 /*
13136  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
13137  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
13138  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
13139  * them can only be attached to some specific hook points.
13140  */
13141 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
13142 {
13143 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13144 
13145 	switch (prog_type) {
13146 	case BPF_PROG_TYPE_LSM:
13147 		return true;
13148 	case BPF_PROG_TYPE_TRACING:
13149 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
13150 			return true;
13151 		fallthrough;
13152 	default:
13153 		return in_sleepable(env);
13154 	}
13155 }
13156 
13157 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13158 			    int insn_idx)
13159 {
13160 	const char *func_name = meta->func_name, *ref_tname;
13161 	const struct btf *btf = meta->btf;
13162 	const struct btf_param *args;
13163 	struct btf_record *rec;
13164 	u32 i, nargs;
13165 	int ret;
13166 
13167 	args = (const struct btf_param *)(meta->func_proto + 1);
13168 	nargs = btf_type_vlen(meta->func_proto);
13169 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
13170 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
13171 			MAX_BPF_FUNC_REG_ARGS);
13172 		return -EINVAL;
13173 	}
13174 
13175 	/* Check that BTF function arguments match actual types that the
13176 	 * verifier sees.
13177 	 */
13178 	for (i = 0; i < nargs; i++) {
13179 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
13180 		const struct btf_type *t, *ref_t, *resolve_ret;
13181 		enum bpf_arg_type arg_type = ARG_DONTCARE;
13182 		u32 regno = i + 1, ref_id, type_size;
13183 		bool is_ret_buf_sz = false;
13184 		int kf_arg_type;
13185 
13186 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
13187 
13188 		if (is_kfunc_arg_ignore(btf, &args[i]))
13189 			continue;
13190 
13191 		if (is_kfunc_arg_prog(btf, &args[i])) {
13192 			/* Used to reject repeated use of __prog. */
13193 			if (meta->arg_prog) {
13194 				verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc");
13195 				return -EFAULT;
13196 			}
13197 			meta->arg_prog = true;
13198 			cur_aux(env)->arg_prog = regno;
13199 			continue;
13200 		}
13201 
13202 		if (btf_type_is_scalar(t)) {
13203 			if (reg->type != SCALAR_VALUE) {
13204 				verbose(env, "R%d is not a scalar\n", regno);
13205 				return -EINVAL;
13206 			}
13207 
13208 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
13209 				if (meta->arg_constant.found) {
13210 					verifier_bug(env, "only one constant argument permitted");
13211 					return -EFAULT;
13212 				}
13213 				if (!tnum_is_const(reg->var_off)) {
13214 					verbose(env, "R%d must be a known constant\n", regno);
13215 					return -EINVAL;
13216 				}
13217 				ret = mark_chain_precision(env, regno);
13218 				if (ret < 0)
13219 					return ret;
13220 				meta->arg_constant.found = true;
13221 				meta->arg_constant.value = reg->var_off.value;
13222 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
13223 				meta->r0_rdonly = true;
13224 				is_ret_buf_sz = true;
13225 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
13226 				is_ret_buf_sz = true;
13227 			}
13228 
13229 			if (is_ret_buf_sz) {
13230 				if (meta->r0_size) {
13231 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
13232 					return -EINVAL;
13233 				}
13234 
13235 				if (!tnum_is_const(reg->var_off)) {
13236 					verbose(env, "R%d is not a const\n", regno);
13237 					return -EINVAL;
13238 				}
13239 
13240 				meta->r0_size = reg->var_off.value;
13241 				ret = mark_chain_precision(env, regno);
13242 				if (ret)
13243 					return ret;
13244 			}
13245 			continue;
13246 		}
13247 
13248 		if (!btf_type_is_ptr(t)) {
13249 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
13250 			return -EINVAL;
13251 		}
13252 
13253 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
13254 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
13255 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
13256 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
13257 			return -EACCES;
13258 		}
13259 
13260 		if (reg->ref_obj_id) {
13261 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
13262 				verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u",
13263 					     regno, reg->ref_obj_id,
13264 					     meta->ref_obj_id);
13265 				return -EFAULT;
13266 			}
13267 			meta->ref_obj_id = reg->ref_obj_id;
13268 			if (is_kfunc_release(meta))
13269 				meta->release_regno = regno;
13270 		}
13271 
13272 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
13273 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13274 
13275 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
13276 		if (kf_arg_type < 0)
13277 			return kf_arg_type;
13278 
13279 		switch (kf_arg_type) {
13280 		case KF_ARG_PTR_TO_NULL:
13281 			continue;
13282 		case KF_ARG_PTR_TO_MAP:
13283 			if (!reg->map_ptr) {
13284 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
13285 				return -EINVAL;
13286 			}
13287 			if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 ||
13288 					      reg->map_ptr->record->task_work_off >= 0)) {
13289 				/* Use map_uid (which is unique id of inner map) to reject:
13290 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
13291 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
13292 				 * if (inner_map1 && inner_map2) {
13293 				 *     wq = bpf_map_lookup_elem(inner_map1);
13294 				 *     if (wq)
13295 				 *         // mismatch would have been allowed
13296 				 *         bpf_wq_init(wq, inner_map2);
13297 				 * }
13298 				 *
13299 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
13300 				 */
13301 				if (meta->map.ptr != reg->map_ptr ||
13302 				    meta->map.uid != reg->map_uid) {
13303 					if (reg->map_ptr->record->task_work_off >= 0) {
13304 						verbose(env,
13305 							"bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n",
13306 							meta->map.uid, reg->map_uid);
13307 						return -EINVAL;
13308 					}
13309 					verbose(env,
13310 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
13311 						meta->map.uid, reg->map_uid);
13312 					return -EINVAL;
13313 				}
13314 			}
13315 			meta->map.ptr = reg->map_ptr;
13316 			meta->map.uid = reg->map_uid;
13317 			fallthrough;
13318 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13319 		case KF_ARG_PTR_TO_BTF_ID:
13320 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
13321 				break;
13322 
13323 			if (!is_trusted_reg(reg)) {
13324 				if (!is_kfunc_rcu(meta)) {
13325 					verbose(env, "R%d must be referenced or trusted\n", regno);
13326 					return -EINVAL;
13327 				}
13328 				if (!is_rcu_reg(reg)) {
13329 					verbose(env, "R%d must be a rcu pointer\n", regno);
13330 					return -EINVAL;
13331 				}
13332 			}
13333 			fallthrough;
13334 		case KF_ARG_PTR_TO_CTX:
13335 		case KF_ARG_PTR_TO_DYNPTR:
13336 		case KF_ARG_PTR_TO_ITER:
13337 		case KF_ARG_PTR_TO_LIST_HEAD:
13338 		case KF_ARG_PTR_TO_LIST_NODE:
13339 		case KF_ARG_PTR_TO_RB_ROOT:
13340 		case KF_ARG_PTR_TO_RB_NODE:
13341 		case KF_ARG_PTR_TO_MEM:
13342 		case KF_ARG_PTR_TO_MEM_SIZE:
13343 		case KF_ARG_PTR_TO_CALLBACK:
13344 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13345 		case KF_ARG_PTR_TO_CONST_STR:
13346 		case KF_ARG_PTR_TO_WORKQUEUE:
13347 		case KF_ARG_PTR_TO_TASK_WORK:
13348 		case KF_ARG_PTR_TO_IRQ_FLAG:
13349 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13350 			break;
13351 		default:
13352 			verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type);
13353 			return -EFAULT;
13354 		}
13355 
13356 		if (is_kfunc_release(meta) && reg->ref_obj_id)
13357 			arg_type |= OBJ_RELEASE;
13358 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
13359 		if (ret < 0)
13360 			return ret;
13361 
13362 		switch (kf_arg_type) {
13363 		case KF_ARG_PTR_TO_CTX:
13364 			if (reg->type != PTR_TO_CTX) {
13365 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
13366 					i, reg_type_str(env, reg->type));
13367 				return -EINVAL;
13368 			}
13369 
13370 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13371 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
13372 				if (ret < 0)
13373 					return -EINVAL;
13374 				meta->ret_btf_id  = ret;
13375 			}
13376 			break;
13377 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13378 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
13379 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
13380 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
13381 					return -EINVAL;
13382 				}
13383 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
13384 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13385 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
13386 					return -EINVAL;
13387 				}
13388 			} else {
13389 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13390 				return -EINVAL;
13391 			}
13392 			if (!reg->ref_obj_id) {
13393 				verbose(env, "allocated object must be referenced\n");
13394 				return -EINVAL;
13395 			}
13396 			if (meta->btf == btf_vmlinux) {
13397 				meta->arg_btf = reg->btf;
13398 				meta->arg_btf_id = reg->btf_id;
13399 			}
13400 			break;
13401 		case KF_ARG_PTR_TO_DYNPTR:
13402 		{
13403 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
13404 			int clone_ref_obj_id = 0;
13405 
13406 			if (reg->type == CONST_PTR_TO_DYNPTR)
13407 				dynptr_arg_type |= MEM_RDONLY;
13408 
13409 			if (is_kfunc_arg_uninit(btf, &args[i]))
13410 				dynptr_arg_type |= MEM_UNINIT;
13411 
13412 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
13413 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
13414 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
13415 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
13416 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
13417 				dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
13418 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
13419 				dynptr_arg_type |= DYNPTR_TYPE_FILE;
13420 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) {
13421 				dynptr_arg_type |= DYNPTR_TYPE_FILE;
13422 				meta->release_regno = regno;
13423 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
13424 				   (dynptr_arg_type & MEM_UNINIT)) {
13425 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
13426 
13427 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
13428 					verifier_bug(env, "no dynptr type for parent of clone");
13429 					return -EFAULT;
13430 				}
13431 
13432 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
13433 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
13434 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
13435 					verifier_bug(env, "missing ref obj id for parent of clone");
13436 					return -EFAULT;
13437 				}
13438 			}
13439 
13440 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
13441 			if (ret < 0)
13442 				return ret;
13443 
13444 			if (!(dynptr_arg_type & MEM_UNINIT)) {
13445 				int id = dynptr_id(env, reg);
13446 
13447 				if (id < 0) {
13448 					verifier_bug(env, "failed to obtain dynptr id");
13449 					return id;
13450 				}
13451 				meta->initialized_dynptr.id = id;
13452 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
13453 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
13454 			}
13455 
13456 			break;
13457 		}
13458 		case KF_ARG_PTR_TO_ITER:
13459 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
13460 				if (!check_css_task_iter_allowlist(env)) {
13461 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
13462 					return -EINVAL;
13463 				}
13464 			}
13465 			ret = process_iter_arg(env, regno, insn_idx, meta);
13466 			if (ret < 0)
13467 				return ret;
13468 			break;
13469 		case KF_ARG_PTR_TO_LIST_HEAD:
13470 			if (reg->type != PTR_TO_MAP_VALUE &&
13471 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13472 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13473 				return -EINVAL;
13474 			}
13475 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13476 				verbose(env, "allocated object must be referenced\n");
13477 				return -EINVAL;
13478 			}
13479 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
13480 			if (ret < 0)
13481 				return ret;
13482 			break;
13483 		case KF_ARG_PTR_TO_RB_ROOT:
13484 			if (reg->type != PTR_TO_MAP_VALUE &&
13485 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13486 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13487 				return -EINVAL;
13488 			}
13489 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13490 				verbose(env, "allocated object must be referenced\n");
13491 				return -EINVAL;
13492 			}
13493 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
13494 			if (ret < 0)
13495 				return ret;
13496 			break;
13497 		case KF_ARG_PTR_TO_LIST_NODE:
13498 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13499 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13500 				return -EINVAL;
13501 			}
13502 			if (!reg->ref_obj_id) {
13503 				verbose(env, "allocated object must be referenced\n");
13504 				return -EINVAL;
13505 			}
13506 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
13507 			if (ret < 0)
13508 				return ret;
13509 			break;
13510 		case KF_ARG_PTR_TO_RB_NODE:
13511 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13512 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13513 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
13514 					return -EINVAL;
13515 				}
13516 				if (!reg->ref_obj_id) {
13517 					verbose(env, "allocated object must be referenced\n");
13518 					return -EINVAL;
13519 				}
13520 			} else {
13521 				if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) {
13522 					verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
13523 					return -EINVAL;
13524 				}
13525 				if (in_rbtree_lock_required_cb(env)) {
13526 					verbose(env, "%s not allowed in rbtree cb\n", func_name);
13527 					return -EINVAL;
13528 				}
13529 			}
13530 
13531 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
13532 			if (ret < 0)
13533 				return ret;
13534 			break;
13535 		case KF_ARG_PTR_TO_MAP:
13536 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
13537 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
13538 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
13539 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13540 			fallthrough;
13541 		case KF_ARG_PTR_TO_BTF_ID:
13542 			/* Only base_type is checked, further checks are done here */
13543 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
13544 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
13545 			    !reg2btf_ids[base_type(reg->type)]) {
13546 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
13547 				verbose(env, "expected %s or socket\n",
13548 					reg_type_str(env, base_type(reg->type) |
13549 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
13550 				return -EINVAL;
13551 			}
13552 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
13553 			if (ret < 0)
13554 				return ret;
13555 			break;
13556 		case KF_ARG_PTR_TO_MEM:
13557 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
13558 			if (IS_ERR(resolve_ret)) {
13559 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
13560 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
13561 				return -EINVAL;
13562 			}
13563 			ret = check_mem_reg(env, reg, regno, type_size);
13564 			if (ret < 0)
13565 				return ret;
13566 			break;
13567 		case KF_ARG_PTR_TO_MEM_SIZE:
13568 		{
13569 			struct bpf_reg_state *buff_reg = &regs[regno];
13570 			const struct btf_param *buff_arg = &args[i];
13571 			struct bpf_reg_state *size_reg = &regs[regno + 1];
13572 			const struct btf_param *size_arg = &args[i + 1];
13573 
13574 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
13575 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
13576 				if (ret < 0) {
13577 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
13578 					return ret;
13579 				}
13580 			}
13581 
13582 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
13583 				if (meta->arg_constant.found) {
13584 					verifier_bug(env, "only one constant argument permitted");
13585 					return -EFAULT;
13586 				}
13587 				if (!tnum_is_const(size_reg->var_off)) {
13588 					verbose(env, "R%d must be a known constant\n", regno + 1);
13589 					return -EINVAL;
13590 				}
13591 				meta->arg_constant.found = true;
13592 				meta->arg_constant.value = size_reg->var_off.value;
13593 			}
13594 
13595 			/* Skip next '__sz' or '__szk' argument */
13596 			i++;
13597 			break;
13598 		}
13599 		case KF_ARG_PTR_TO_CALLBACK:
13600 			if (reg->type != PTR_TO_FUNC) {
13601 				verbose(env, "arg%d expected pointer to func\n", i);
13602 				return -EINVAL;
13603 			}
13604 			meta->subprogno = reg->subprogno;
13605 			break;
13606 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13607 			if (!type_is_ptr_alloc_obj(reg->type)) {
13608 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
13609 				return -EINVAL;
13610 			}
13611 			if (!type_is_non_owning_ref(reg->type))
13612 				meta->arg_owning_ref = true;
13613 
13614 			rec = reg_btf_record(reg);
13615 			if (!rec) {
13616 				verifier_bug(env, "Couldn't find btf_record");
13617 				return -EFAULT;
13618 			}
13619 
13620 			if (rec->refcount_off < 0) {
13621 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
13622 				return -EINVAL;
13623 			}
13624 
13625 			meta->arg_btf = reg->btf;
13626 			meta->arg_btf_id = reg->btf_id;
13627 			break;
13628 		case KF_ARG_PTR_TO_CONST_STR:
13629 			if (reg->type != PTR_TO_MAP_VALUE) {
13630 				verbose(env, "arg#%d doesn't point to a const string\n", i);
13631 				return -EINVAL;
13632 			}
13633 			ret = check_reg_const_str(env, reg, regno);
13634 			if (ret)
13635 				return ret;
13636 			break;
13637 		case KF_ARG_PTR_TO_WORKQUEUE:
13638 			if (reg->type != PTR_TO_MAP_VALUE) {
13639 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13640 				return -EINVAL;
13641 			}
13642 			ret = process_wq_func(env, regno, meta);
13643 			if (ret < 0)
13644 				return ret;
13645 			break;
13646 		case KF_ARG_PTR_TO_TASK_WORK:
13647 			if (reg->type != PTR_TO_MAP_VALUE) {
13648 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13649 				return -EINVAL;
13650 			}
13651 			ret = process_task_work_func(env, regno, meta);
13652 			if (ret < 0)
13653 				return ret;
13654 			break;
13655 		case KF_ARG_PTR_TO_IRQ_FLAG:
13656 			if (reg->type != PTR_TO_STACK) {
13657 				verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i);
13658 				return -EINVAL;
13659 			}
13660 			ret = process_irq_flag(env, regno, meta);
13661 			if (ret < 0)
13662 				return ret;
13663 			break;
13664 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13665 		{
13666 			int flags = PROCESS_RES_LOCK;
13667 
13668 			if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13669 				verbose(env, "arg#%d doesn't point to map value or allocated object\n", i);
13670 				return -EINVAL;
13671 			}
13672 
13673 			if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
13674 				return -EFAULT;
13675 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13676 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
13677 				flags |= PROCESS_SPIN_LOCK;
13678 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
13679 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
13680 				flags |= PROCESS_LOCK_IRQ;
13681 			ret = process_spin_lock(env, regno, flags);
13682 			if (ret < 0)
13683 				return ret;
13684 			break;
13685 		}
13686 		}
13687 	}
13688 
13689 	if (is_kfunc_release(meta) && !meta->release_regno) {
13690 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
13691 			func_name);
13692 		return -EINVAL;
13693 	}
13694 
13695 	return 0;
13696 }
13697 
13698 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
13699 			    struct bpf_insn *insn,
13700 			    struct bpf_kfunc_call_arg_meta *meta,
13701 			    const char **kfunc_name)
13702 {
13703 	const struct btf_type *func, *func_proto;
13704 	u32 func_id, *kfunc_flags;
13705 	const char *func_name;
13706 	struct btf *desc_btf;
13707 
13708 	if (kfunc_name)
13709 		*kfunc_name = NULL;
13710 
13711 	if (!insn->imm)
13712 		return -EINVAL;
13713 
13714 	desc_btf = find_kfunc_desc_btf(env, insn->off);
13715 	if (IS_ERR(desc_btf))
13716 		return PTR_ERR(desc_btf);
13717 
13718 	func_id = insn->imm;
13719 	func = btf_type_by_id(desc_btf, func_id);
13720 	func_name = btf_name_by_offset(desc_btf, func->name_off);
13721 	if (kfunc_name)
13722 		*kfunc_name = func_name;
13723 	func_proto = btf_type_by_id(desc_btf, func->type);
13724 
13725 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
13726 	if (!kfunc_flags) {
13727 		return -EACCES;
13728 	}
13729 
13730 	memset(meta, 0, sizeof(*meta));
13731 	meta->btf = desc_btf;
13732 	meta->func_id = func_id;
13733 	meta->kfunc_flags = *kfunc_flags;
13734 	meta->func_proto = func_proto;
13735 	meta->func_name = func_name;
13736 
13737 	return 0;
13738 }
13739 
13740 /* check special kfuncs and return:
13741  *  1  - not fall-through to 'else' branch, continue verification
13742  *  0  - fall-through to 'else' branch
13743  * < 0 - not fall-through to 'else' branch, return error
13744  */
13745 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13746 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
13747 			       const struct btf_type *ptr_type, struct btf *desc_btf)
13748 {
13749 	const struct btf_type *ret_t;
13750 	int err = 0;
13751 
13752 	if (meta->btf != btf_vmlinux)
13753 		return 0;
13754 
13755 	if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
13756 	    meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13757 		struct btf_struct_meta *struct_meta;
13758 		struct btf *ret_btf;
13759 		u32 ret_btf_id;
13760 
13761 		if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
13762 			return -ENOMEM;
13763 
13764 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
13765 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13766 			return -EINVAL;
13767 		}
13768 
13769 		ret_btf = env->prog->aux->btf;
13770 		ret_btf_id = meta->arg_constant.value;
13771 
13772 		/* This may be NULL due to user not supplying a BTF */
13773 		if (!ret_btf) {
13774 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13775 			return -EINVAL;
13776 		}
13777 
13778 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13779 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
13780 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13781 			return -EINVAL;
13782 		}
13783 
13784 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13785 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13786 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13787 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13788 				return -EINVAL;
13789 			}
13790 
13791 			if (!bpf_global_percpu_ma_set) {
13792 				mutex_lock(&bpf_percpu_ma_lock);
13793 				if (!bpf_global_percpu_ma_set) {
13794 					/* Charge memory allocated with bpf_global_percpu_ma to
13795 					 * root memcg. The obj_cgroup for root memcg is NULL.
13796 					 */
13797 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13798 					if (!err)
13799 						bpf_global_percpu_ma_set = true;
13800 				}
13801 				mutex_unlock(&bpf_percpu_ma_lock);
13802 				if (err)
13803 					return err;
13804 			}
13805 
13806 			mutex_lock(&bpf_percpu_ma_lock);
13807 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13808 			mutex_unlock(&bpf_percpu_ma_lock);
13809 			if (err)
13810 				return err;
13811 		}
13812 
13813 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13814 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13815 			if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13816 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13817 				return -EINVAL;
13818 			}
13819 
13820 			if (struct_meta) {
13821 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13822 				return -EINVAL;
13823 			}
13824 		}
13825 
13826 		mark_reg_known_zero(env, regs, BPF_REG_0);
13827 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13828 		regs[BPF_REG_0].btf = ret_btf;
13829 		regs[BPF_REG_0].btf_id = ret_btf_id;
13830 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
13831 			regs[BPF_REG_0].type |= MEM_PERCPU;
13832 
13833 		insn_aux->obj_new_size = ret_t->size;
13834 		insn_aux->kptr_struct_meta = struct_meta;
13835 	} else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
13836 		mark_reg_known_zero(env, regs, BPF_REG_0);
13837 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13838 		regs[BPF_REG_0].btf = meta->arg_btf;
13839 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
13840 
13841 		insn_aux->kptr_struct_meta =
13842 			btf_find_struct_meta(meta->arg_btf,
13843 					     meta->arg_btf_id);
13844 	} else if (is_list_node_type(ptr_type)) {
13845 		struct btf_field *field = meta->arg_list_head.field;
13846 
13847 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13848 	} else if (is_rbtree_node_type(ptr_type)) {
13849 		struct btf_field *field = meta->arg_rbtree_root.field;
13850 
13851 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13852 	} else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13853 		mark_reg_known_zero(env, regs, BPF_REG_0);
13854 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13855 		regs[BPF_REG_0].btf = desc_btf;
13856 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
13857 	} else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
13858 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
13859 		if (!ret_t) {
13860 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
13861 				meta->arg_constant.value);
13862 			return -EINVAL;
13863 		} else if (btf_type_is_struct(ret_t)) {
13864 			mark_reg_known_zero(env, regs, BPF_REG_0);
13865 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13866 			regs[BPF_REG_0].btf = desc_btf;
13867 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
13868 		} else if (btf_type_is_void(ret_t)) {
13869 			mark_reg_known_zero(env, regs, BPF_REG_0);
13870 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
13871 			regs[BPF_REG_0].mem_size = 0;
13872 		} else {
13873 			verbose(env,
13874 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
13875 			return -EINVAL;
13876 		}
13877 	} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13878 		   meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13879 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type);
13880 
13881 		mark_reg_known_zero(env, regs, BPF_REG_0);
13882 
13883 		if (!meta->arg_constant.found) {
13884 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
13885 			return -EFAULT;
13886 		}
13887 
13888 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
13889 
13890 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
13891 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
13892 
13893 		if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
13894 			regs[BPF_REG_0].type |= MEM_RDONLY;
13895 		} else {
13896 			/* this will set env->seen_direct_write to true */
13897 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
13898 				verbose(env, "the prog does not allow writes to packet data\n");
13899 				return -EINVAL;
13900 			}
13901 		}
13902 
13903 		if (!meta->initialized_dynptr.id) {
13904 			verifier_bug(env, "no dynptr id");
13905 			return -EFAULT;
13906 		}
13907 		regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id;
13908 
13909 		/* we don't need to set BPF_REG_0's ref obj id
13910 		 * because packet slices are not refcounted (see
13911 		 * dynptr_type_refcounted)
13912 		 */
13913 	} else {
13914 		return 0;
13915 	}
13916 
13917 	return 1;
13918 }
13919 
13920 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
13921 
13922 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
13923 			    int *insn_idx_p)
13924 {
13925 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
13926 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
13927 	struct bpf_reg_state *regs = cur_regs(env);
13928 	const char *func_name, *ptr_type_name;
13929 	const struct btf_type *t, *ptr_type;
13930 	struct bpf_kfunc_call_arg_meta meta;
13931 	struct bpf_insn_aux_data *insn_aux;
13932 	int err, insn_idx = *insn_idx_p;
13933 	const struct btf_param *args;
13934 	struct btf *desc_btf;
13935 
13936 	/* skip for now, but return error when we find this in fixup_kfunc_call */
13937 	if (!insn->imm)
13938 		return 0;
13939 
13940 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
13941 	if (err == -EACCES && func_name)
13942 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
13943 	if (err)
13944 		return err;
13945 	desc_btf = meta.btf;
13946 	insn_aux = &env->insn_aux_data[insn_idx];
13947 
13948 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
13949 
13950 	if (!insn->off &&
13951 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
13952 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
13953 		struct bpf_verifier_state *branch;
13954 		struct bpf_reg_state *regs;
13955 
13956 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13957 		if (IS_ERR(branch)) {
13958 			verbose(env, "failed to push state for failed lock acquisition\n");
13959 			return PTR_ERR(branch);
13960 		}
13961 
13962 		regs = branch->frame[branch->curframe]->regs;
13963 
13964 		/* Clear r0-r5 registers in forked state */
13965 		for (i = 0; i < CALLER_SAVED_REGS; i++)
13966 			mark_reg_not_init(env, regs, caller_saved[i]);
13967 
13968 		mark_reg_unknown(env, regs, BPF_REG_0);
13969 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
13970 		if (err) {
13971 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
13972 			return err;
13973 		}
13974 		__mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32));
13975 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
13976 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
13977 		return -EFAULT;
13978 	}
13979 
13980 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
13981 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
13982 		return -EACCES;
13983 	}
13984 
13985 	sleepable = is_kfunc_sleepable(&meta);
13986 	if (sleepable && !in_sleepable(env)) {
13987 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
13988 		return -EACCES;
13989 	}
13990 
13991 	/* Track non-sleepable context for kfuncs, same as for helpers. */
13992 	if (!in_sleepable_context(env))
13993 		insn_aux->non_sleepable = true;
13994 
13995 	/* Check the arguments */
13996 	err = check_kfunc_args(env, &meta, insn_idx);
13997 	if (err < 0)
13998 		return err;
13999 
14000 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
14001 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14002 					 set_rbtree_add_callback_state);
14003 		if (err) {
14004 			verbose(env, "kfunc %s#%d failed callback verification\n",
14005 				func_name, meta.func_id);
14006 			return err;
14007 		}
14008 	}
14009 
14010 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
14011 		meta.r0_size = sizeof(u64);
14012 		meta.r0_rdonly = false;
14013 	}
14014 
14015 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
14016 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14017 					 set_timer_callback_state);
14018 		if (err) {
14019 			verbose(env, "kfunc %s#%d failed callback verification\n",
14020 				func_name, meta.func_id);
14021 			return err;
14022 		}
14023 	}
14024 
14025 	if (is_task_work_add_kfunc(meta.func_id)) {
14026 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14027 					 set_task_work_schedule_callback_state);
14028 		if (err) {
14029 			verbose(env, "kfunc %s#%d failed callback verification\n",
14030 				func_name, meta.func_id);
14031 			return err;
14032 		}
14033 	}
14034 
14035 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
14036 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
14037 
14038 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
14039 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
14040 
14041 	if (rcu_lock) {
14042 		env->cur_state->active_rcu_locks++;
14043 	} else if (rcu_unlock) {
14044 		struct bpf_func_state *state;
14045 		struct bpf_reg_state *reg;
14046 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
14047 
14048 		if (env->cur_state->active_rcu_locks == 0) {
14049 			verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
14050 			return -EINVAL;
14051 		}
14052 		if (--env->cur_state->active_rcu_locks == 0) {
14053 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
14054 				if (reg->type & MEM_RCU) {
14055 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
14056 					reg->type |= PTR_UNTRUSTED;
14057 				}
14058 			}));
14059 		}
14060 	} else if (sleepable && env->cur_state->active_rcu_locks) {
14061 		verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
14062 		return -EACCES;
14063 	}
14064 
14065 	if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
14066 		verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
14067 		return -EACCES;
14068 	}
14069 
14070 	if (env->cur_state->active_preempt_locks) {
14071 		if (preempt_disable) {
14072 			env->cur_state->active_preempt_locks++;
14073 		} else if (preempt_enable) {
14074 			env->cur_state->active_preempt_locks--;
14075 		} else if (sleepable) {
14076 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
14077 			return -EACCES;
14078 		}
14079 	} else if (preempt_disable) {
14080 		env->cur_state->active_preempt_locks++;
14081 	} else if (preempt_enable) {
14082 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
14083 		return -EINVAL;
14084 	}
14085 
14086 	if (env->cur_state->active_irq_id && sleepable) {
14087 		verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name);
14088 		return -EACCES;
14089 	}
14090 
14091 	if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
14092 		verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
14093 		return -EACCES;
14094 	}
14095 
14096 	/* In case of release function, we get register number of refcounted
14097 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
14098 	 */
14099 	if (meta.release_regno) {
14100 		struct bpf_reg_state *reg = &regs[meta.release_regno];
14101 
14102 		if (meta.initialized_dynptr.ref_obj_id) {
14103 			err = unmark_stack_slots_dynptr(env, reg);
14104 		} else {
14105 			err = release_reference(env, reg->ref_obj_id);
14106 			if (err)
14107 				verbose(env, "kfunc %s#%d reference has not been acquired before\n",
14108 					func_name, meta.func_id);
14109 		}
14110 		if (err)
14111 			return err;
14112 	}
14113 
14114 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
14115 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
14116 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
14117 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
14118 		insn_aux->insert_off = regs[BPF_REG_2].off;
14119 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
14120 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
14121 		if (err) {
14122 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
14123 				func_name, meta.func_id);
14124 			return err;
14125 		}
14126 
14127 		err = release_reference(env, release_ref_obj_id);
14128 		if (err) {
14129 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
14130 				func_name, meta.func_id);
14131 			return err;
14132 		}
14133 	}
14134 
14135 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
14136 		if (!bpf_jit_supports_exceptions()) {
14137 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
14138 				func_name, meta.func_id);
14139 			return -ENOTSUPP;
14140 		}
14141 		env->seen_exception = true;
14142 
14143 		/* In the case of the default callback, the cookie value passed
14144 		 * to bpf_throw becomes the return value of the program.
14145 		 */
14146 		if (!env->exception_callback_subprog) {
14147 			err = check_return_code(env, BPF_REG_1, "R1");
14148 			if (err < 0)
14149 				return err;
14150 		}
14151 	}
14152 
14153 	for (i = 0; i < CALLER_SAVED_REGS; i++)
14154 		mark_reg_not_init(env, regs, caller_saved[i]);
14155 
14156 	/* Check return type */
14157 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
14158 
14159 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
14160 		/* Only exception is bpf_obj_new_impl */
14161 		if (meta.btf != btf_vmlinux ||
14162 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
14163 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
14164 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
14165 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
14166 			return -EINVAL;
14167 		}
14168 	}
14169 
14170 	if (btf_type_is_scalar(t)) {
14171 		mark_reg_unknown(env, regs, BPF_REG_0);
14172 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
14173 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14174 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
14175 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
14176 	} else if (btf_type_is_ptr(t)) {
14177 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
14178 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
14179 		if (err) {
14180 			if (err < 0)
14181 				return err;
14182 		} else if (btf_type_is_void(ptr_type)) {
14183 			/* kfunc returning 'void *' is equivalent to returning scalar */
14184 			mark_reg_unknown(env, regs, BPF_REG_0);
14185 		} else if (!__btf_type_is_struct(ptr_type)) {
14186 			if (!meta.r0_size) {
14187 				__u32 sz;
14188 
14189 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
14190 					meta.r0_size = sz;
14191 					meta.r0_rdonly = true;
14192 				}
14193 			}
14194 			if (!meta.r0_size) {
14195 				ptr_type_name = btf_name_by_offset(desc_btf,
14196 								   ptr_type->name_off);
14197 				verbose(env,
14198 					"kernel function %s returns pointer type %s %s is not supported\n",
14199 					func_name,
14200 					btf_type_str(ptr_type),
14201 					ptr_type_name);
14202 				return -EINVAL;
14203 			}
14204 
14205 			mark_reg_known_zero(env, regs, BPF_REG_0);
14206 			regs[BPF_REG_0].type = PTR_TO_MEM;
14207 			regs[BPF_REG_0].mem_size = meta.r0_size;
14208 
14209 			if (meta.r0_rdonly)
14210 				regs[BPF_REG_0].type |= MEM_RDONLY;
14211 
14212 			/* Ensures we don't access the memory after a release_reference() */
14213 			if (meta.ref_obj_id)
14214 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
14215 
14216 			if (is_kfunc_rcu_protected(&meta))
14217 				regs[BPF_REG_0].type |= MEM_RCU;
14218 		} else {
14219 			mark_reg_known_zero(env, regs, BPF_REG_0);
14220 			regs[BPF_REG_0].btf = desc_btf;
14221 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
14222 			regs[BPF_REG_0].btf_id = ptr_type_id;
14223 
14224 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
14225 				regs[BPF_REG_0].type |= PTR_UNTRUSTED;
14226 			else if (is_kfunc_rcu_protected(&meta))
14227 				regs[BPF_REG_0].type |= MEM_RCU;
14228 
14229 			if (is_iter_next_kfunc(&meta)) {
14230 				struct bpf_reg_state *cur_iter;
14231 
14232 				cur_iter = get_iter_from_state(env->cur_state, &meta);
14233 
14234 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
14235 					regs[BPF_REG_0].type |= MEM_RCU;
14236 				else
14237 					regs[BPF_REG_0].type |= PTR_TRUSTED;
14238 			}
14239 		}
14240 
14241 		if (is_kfunc_ret_null(&meta)) {
14242 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
14243 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
14244 			regs[BPF_REG_0].id = ++env->id_gen;
14245 		}
14246 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
14247 		if (is_kfunc_acquire(&meta)) {
14248 			int id = acquire_reference(env, insn_idx);
14249 
14250 			if (id < 0)
14251 				return id;
14252 			if (is_kfunc_ret_null(&meta))
14253 				regs[BPF_REG_0].id = id;
14254 			regs[BPF_REG_0].ref_obj_id = id;
14255 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
14256 			ref_set_non_owning(env, &regs[BPF_REG_0]);
14257 		}
14258 
14259 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
14260 			regs[BPF_REG_0].id = ++env->id_gen;
14261 	} else if (btf_type_is_void(t)) {
14262 		if (meta.btf == btf_vmlinux) {
14263 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
14264 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
14265 				insn_aux->kptr_struct_meta =
14266 					btf_find_struct_meta(meta.arg_btf,
14267 							     meta.arg_btf_id);
14268 			}
14269 		}
14270 	}
14271 
14272 	if (is_kfunc_pkt_changing(&meta))
14273 		clear_all_pkt_pointers(env);
14274 
14275 	nargs = btf_type_vlen(meta.func_proto);
14276 	args = (const struct btf_param *)(meta.func_proto + 1);
14277 	for (i = 0; i < nargs; i++) {
14278 		u32 regno = i + 1;
14279 
14280 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
14281 		if (btf_type_is_ptr(t))
14282 			mark_btf_func_reg_size(env, regno, sizeof(void *));
14283 		else
14284 			/* scalar. ensured by btf_check_kfunc_arg_match() */
14285 			mark_btf_func_reg_size(env, regno, t->size);
14286 	}
14287 
14288 	if (is_iter_next_kfunc(&meta)) {
14289 		err = process_iter_next_call(env, insn_idx, &meta);
14290 		if (err)
14291 			return err;
14292 	}
14293 
14294 	return 0;
14295 }
14296 
14297 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
14298 				  const struct bpf_reg_state *reg,
14299 				  enum bpf_reg_type type)
14300 {
14301 	bool known = tnum_is_const(reg->var_off);
14302 	s64 val = reg->var_off.value;
14303 	s64 smin = reg->smin_value;
14304 
14305 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
14306 		verbose(env, "math between %s pointer and %lld is not allowed\n",
14307 			reg_type_str(env, type), val);
14308 		return false;
14309 	}
14310 
14311 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
14312 		verbose(env, "%s pointer offset %d is not allowed\n",
14313 			reg_type_str(env, type), reg->off);
14314 		return false;
14315 	}
14316 
14317 	if (smin == S64_MIN) {
14318 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
14319 			reg_type_str(env, type));
14320 		return false;
14321 	}
14322 
14323 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
14324 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
14325 			smin, reg_type_str(env, type));
14326 		return false;
14327 	}
14328 
14329 	return true;
14330 }
14331 
14332 enum {
14333 	REASON_BOUNDS	= -1,
14334 	REASON_TYPE	= -2,
14335 	REASON_PATHS	= -3,
14336 	REASON_LIMIT	= -4,
14337 	REASON_STACK	= -5,
14338 };
14339 
14340 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
14341 			      u32 *alu_limit, bool mask_to_left)
14342 {
14343 	u32 max = 0, ptr_limit = 0;
14344 
14345 	switch (ptr_reg->type) {
14346 	case PTR_TO_STACK:
14347 		/* Offset 0 is out-of-bounds, but acceptable start for the
14348 		 * left direction, see BPF_REG_FP. Also, unknown scalar
14349 		 * offset where we would need to deal with min/max bounds is
14350 		 * currently prohibited for unprivileged.
14351 		 */
14352 		max = MAX_BPF_STACK + mask_to_left;
14353 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
14354 		break;
14355 	case PTR_TO_MAP_VALUE:
14356 		max = ptr_reg->map_ptr->value_size;
14357 		ptr_limit = (mask_to_left ?
14358 			     ptr_reg->smin_value :
14359 			     ptr_reg->umax_value) + ptr_reg->off;
14360 		break;
14361 	default:
14362 		return REASON_TYPE;
14363 	}
14364 
14365 	if (ptr_limit >= max)
14366 		return REASON_LIMIT;
14367 	*alu_limit = ptr_limit;
14368 	return 0;
14369 }
14370 
14371 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
14372 				    const struct bpf_insn *insn)
14373 {
14374 	return env->bypass_spec_v1 ||
14375 		BPF_SRC(insn->code) == BPF_K ||
14376 		cur_aux(env)->nospec;
14377 }
14378 
14379 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
14380 				       u32 alu_state, u32 alu_limit)
14381 {
14382 	/* If we arrived here from different branches with different
14383 	 * state or limits to sanitize, then this won't work.
14384 	 */
14385 	if (aux->alu_state &&
14386 	    (aux->alu_state != alu_state ||
14387 	     aux->alu_limit != alu_limit))
14388 		return REASON_PATHS;
14389 
14390 	/* Corresponding fixup done in do_misc_fixups(). */
14391 	aux->alu_state = alu_state;
14392 	aux->alu_limit = alu_limit;
14393 	return 0;
14394 }
14395 
14396 static int sanitize_val_alu(struct bpf_verifier_env *env,
14397 			    struct bpf_insn *insn)
14398 {
14399 	struct bpf_insn_aux_data *aux = cur_aux(env);
14400 
14401 	if (can_skip_alu_sanitation(env, insn))
14402 		return 0;
14403 
14404 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
14405 }
14406 
14407 static bool sanitize_needed(u8 opcode)
14408 {
14409 	return opcode == BPF_ADD || opcode == BPF_SUB;
14410 }
14411 
14412 struct bpf_sanitize_info {
14413 	struct bpf_insn_aux_data aux;
14414 	bool mask_to_left;
14415 };
14416 
14417 static int sanitize_speculative_path(struct bpf_verifier_env *env,
14418 				     const struct bpf_insn *insn,
14419 				     u32 next_idx, u32 curr_idx)
14420 {
14421 	struct bpf_verifier_state *branch;
14422 	struct bpf_reg_state *regs;
14423 
14424 	branch = push_stack(env, next_idx, curr_idx, true);
14425 	if (!IS_ERR(branch) && insn) {
14426 		regs = branch->frame[branch->curframe]->regs;
14427 		if (BPF_SRC(insn->code) == BPF_K) {
14428 			mark_reg_unknown(env, regs, insn->dst_reg);
14429 		} else if (BPF_SRC(insn->code) == BPF_X) {
14430 			mark_reg_unknown(env, regs, insn->dst_reg);
14431 			mark_reg_unknown(env, regs, insn->src_reg);
14432 		}
14433 	}
14434 	return PTR_ERR_OR_ZERO(branch);
14435 }
14436 
14437 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
14438 			    struct bpf_insn *insn,
14439 			    const struct bpf_reg_state *ptr_reg,
14440 			    const struct bpf_reg_state *off_reg,
14441 			    struct bpf_reg_state *dst_reg,
14442 			    struct bpf_sanitize_info *info,
14443 			    const bool commit_window)
14444 {
14445 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
14446 	struct bpf_verifier_state *vstate = env->cur_state;
14447 	bool off_is_imm = tnum_is_const(off_reg->var_off);
14448 	bool off_is_neg = off_reg->smin_value < 0;
14449 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
14450 	u8 opcode = BPF_OP(insn->code);
14451 	u32 alu_state, alu_limit;
14452 	struct bpf_reg_state tmp;
14453 	int err;
14454 
14455 	if (can_skip_alu_sanitation(env, insn))
14456 		return 0;
14457 
14458 	/* We already marked aux for masking from non-speculative
14459 	 * paths, thus we got here in the first place. We only care
14460 	 * to explore bad access from here.
14461 	 */
14462 	if (vstate->speculative)
14463 		goto do_sim;
14464 
14465 	if (!commit_window) {
14466 		if (!tnum_is_const(off_reg->var_off) &&
14467 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
14468 			return REASON_BOUNDS;
14469 
14470 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
14471 				     (opcode == BPF_SUB && !off_is_neg);
14472 	}
14473 
14474 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
14475 	if (err < 0)
14476 		return err;
14477 
14478 	if (commit_window) {
14479 		/* In commit phase we narrow the masking window based on
14480 		 * the observed pointer move after the simulated operation.
14481 		 */
14482 		alu_state = info->aux.alu_state;
14483 		alu_limit = abs(info->aux.alu_limit - alu_limit);
14484 	} else {
14485 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
14486 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
14487 		alu_state |= ptr_is_dst_reg ?
14488 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
14489 
14490 		/* Limit pruning on unknown scalars to enable deep search for
14491 		 * potential masking differences from other program paths.
14492 		 */
14493 		if (!off_is_imm)
14494 			env->explore_alu_limits = true;
14495 	}
14496 
14497 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
14498 	if (err < 0)
14499 		return err;
14500 do_sim:
14501 	/* If we're in commit phase, we're done here given we already
14502 	 * pushed the truncated dst_reg into the speculative verification
14503 	 * stack.
14504 	 *
14505 	 * Also, when register is a known constant, we rewrite register-based
14506 	 * operation to immediate-based, and thus do not need masking (and as
14507 	 * a consequence, do not need to simulate the zero-truncation either).
14508 	 */
14509 	if (commit_window || off_is_imm)
14510 		return 0;
14511 
14512 	/* Simulate and find potential out-of-bounds access under
14513 	 * speculative execution from truncation as a result of
14514 	 * masking when off was not within expected range. If off
14515 	 * sits in dst, then we temporarily need to move ptr there
14516 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
14517 	 * for cases where we use K-based arithmetic in one direction
14518 	 * and truncated reg-based in the other in order to explore
14519 	 * bad access.
14520 	 */
14521 	if (!ptr_is_dst_reg) {
14522 		tmp = *dst_reg;
14523 		copy_register_state(dst_reg, ptr_reg);
14524 	}
14525 	err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx);
14526 	if (err < 0)
14527 		return REASON_STACK;
14528 	if (!ptr_is_dst_reg)
14529 		*dst_reg = tmp;
14530 	return 0;
14531 }
14532 
14533 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
14534 {
14535 	struct bpf_verifier_state *vstate = env->cur_state;
14536 
14537 	/* If we simulate paths under speculation, we don't update the
14538 	 * insn as 'seen' such that when we verify unreachable paths in
14539 	 * the non-speculative domain, sanitize_dead_code() can still
14540 	 * rewrite/sanitize them.
14541 	 */
14542 	if (!vstate->speculative)
14543 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
14544 }
14545 
14546 static int sanitize_err(struct bpf_verifier_env *env,
14547 			const struct bpf_insn *insn, int reason,
14548 			const struct bpf_reg_state *off_reg,
14549 			const struct bpf_reg_state *dst_reg)
14550 {
14551 	static const char *err = "pointer arithmetic with it prohibited for !root";
14552 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
14553 	u32 dst = insn->dst_reg, src = insn->src_reg;
14554 
14555 	switch (reason) {
14556 	case REASON_BOUNDS:
14557 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
14558 			off_reg == dst_reg ? dst : src, err);
14559 		break;
14560 	case REASON_TYPE:
14561 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
14562 			off_reg == dst_reg ? src : dst, err);
14563 		break;
14564 	case REASON_PATHS:
14565 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
14566 			dst, op, err);
14567 		break;
14568 	case REASON_LIMIT:
14569 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
14570 			dst, op, err);
14571 		break;
14572 	case REASON_STACK:
14573 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
14574 			dst, err);
14575 		return -ENOMEM;
14576 	default:
14577 		verifier_bug(env, "unknown reason (%d)", reason);
14578 		break;
14579 	}
14580 
14581 	return -EACCES;
14582 }
14583 
14584 /* check that stack access falls within stack limits and that 'reg' doesn't
14585  * have a variable offset.
14586  *
14587  * Variable offset is prohibited for unprivileged mode for simplicity since it
14588  * requires corresponding support in Spectre masking for stack ALU.  See also
14589  * retrieve_ptr_limit().
14590  *
14591  *
14592  * 'off' includes 'reg->off'.
14593  */
14594 static int check_stack_access_for_ptr_arithmetic(
14595 				struct bpf_verifier_env *env,
14596 				int regno,
14597 				const struct bpf_reg_state *reg,
14598 				int off)
14599 {
14600 	if (!tnum_is_const(reg->var_off)) {
14601 		char tn_buf[48];
14602 
14603 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
14604 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
14605 			regno, tn_buf, off);
14606 		return -EACCES;
14607 	}
14608 
14609 	if (off >= 0 || off < -MAX_BPF_STACK) {
14610 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
14611 			"prohibited for !root; off=%d\n", regno, off);
14612 		return -EACCES;
14613 	}
14614 
14615 	return 0;
14616 }
14617 
14618 static int sanitize_check_bounds(struct bpf_verifier_env *env,
14619 				 const struct bpf_insn *insn,
14620 				 const struct bpf_reg_state *dst_reg)
14621 {
14622 	u32 dst = insn->dst_reg;
14623 
14624 	/* For unprivileged we require that resulting offset must be in bounds
14625 	 * in order to be able to sanitize access later on.
14626 	 */
14627 	if (env->bypass_spec_v1)
14628 		return 0;
14629 
14630 	switch (dst_reg->type) {
14631 	case PTR_TO_STACK:
14632 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
14633 					dst_reg->off + dst_reg->var_off.value))
14634 			return -EACCES;
14635 		break;
14636 	case PTR_TO_MAP_VALUE:
14637 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
14638 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
14639 				"prohibited for !root\n", dst);
14640 			return -EACCES;
14641 		}
14642 		break;
14643 	default:
14644 		return -EOPNOTSUPP;
14645 	}
14646 
14647 	return 0;
14648 }
14649 
14650 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
14651  * Caller should also handle BPF_MOV case separately.
14652  * If we return -EACCES, caller may want to try again treating pointer as a
14653  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
14654  */
14655 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
14656 				   struct bpf_insn *insn,
14657 				   const struct bpf_reg_state *ptr_reg,
14658 				   const struct bpf_reg_state *off_reg)
14659 {
14660 	struct bpf_verifier_state *vstate = env->cur_state;
14661 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14662 	struct bpf_reg_state *regs = state->regs, *dst_reg;
14663 	bool known = tnum_is_const(off_reg->var_off);
14664 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
14665 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
14666 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
14667 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
14668 	struct bpf_sanitize_info info = {};
14669 	u8 opcode = BPF_OP(insn->code);
14670 	u32 dst = insn->dst_reg;
14671 	int ret, bounds_ret;
14672 
14673 	dst_reg = &regs[dst];
14674 
14675 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
14676 	    smin_val > smax_val || umin_val > umax_val) {
14677 		/* Taint dst register if offset had invalid bounds derived from
14678 		 * e.g. dead branches.
14679 		 */
14680 		__mark_reg_unknown(env, dst_reg);
14681 		return 0;
14682 	}
14683 
14684 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
14685 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
14686 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14687 			__mark_reg_unknown(env, dst_reg);
14688 			return 0;
14689 		}
14690 
14691 		verbose(env,
14692 			"R%d 32-bit pointer arithmetic prohibited\n",
14693 			dst);
14694 		return -EACCES;
14695 	}
14696 
14697 	if (ptr_reg->type & PTR_MAYBE_NULL) {
14698 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
14699 			dst, reg_type_str(env, ptr_reg->type));
14700 		return -EACCES;
14701 	}
14702 
14703 	/*
14704 	 * Accesses to untrusted PTR_TO_MEM are done through probe
14705 	 * instructions, hence no need to track offsets.
14706 	 */
14707 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
14708 		return 0;
14709 
14710 	switch (base_type(ptr_reg->type)) {
14711 	case PTR_TO_CTX:
14712 	case PTR_TO_MAP_VALUE:
14713 	case PTR_TO_MAP_KEY:
14714 	case PTR_TO_STACK:
14715 	case PTR_TO_PACKET_META:
14716 	case PTR_TO_PACKET:
14717 	case PTR_TO_TP_BUFFER:
14718 	case PTR_TO_BTF_ID:
14719 	case PTR_TO_MEM:
14720 	case PTR_TO_BUF:
14721 	case PTR_TO_FUNC:
14722 	case CONST_PTR_TO_DYNPTR:
14723 		break;
14724 	case PTR_TO_FLOW_KEYS:
14725 		if (known)
14726 			break;
14727 		fallthrough;
14728 	case CONST_PTR_TO_MAP:
14729 		/* smin_val represents the known value */
14730 		if (known && smin_val == 0 && opcode == BPF_ADD)
14731 			break;
14732 		fallthrough;
14733 	default:
14734 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
14735 			dst, reg_type_str(env, ptr_reg->type));
14736 		return -EACCES;
14737 	}
14738 
14739 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
14740 	 * The id may be overwritten later if we create a new variable offset.
14741 	 */
14742 	dst_reg->type = ptr_reg->type;
14743 	dst_reg->id = ptr_reg->id;
14744 
14745 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
14746 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
14747 		return -EINVAL;
14748 
14749 	/* pointer types do not carry 32-bit bounds at the moment. */
14750 	__mark_reg32_unbounded(dst_reg);
14751 
14752 	if (sanitize_needed(opcode)) {
14753 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
14754 				       &info, false);
14755 		if (ret < 0)
14756 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14757 	}
14758 
14759 	switch (opcode) {
14760 	case BPF_ADD:
14761 		/* We can take a fixed offset as long as it doesn't overflow
14762 		 * the s32 'off' field
14763 		 */
14764 		if (known && (ptr_reg->off + smin_val ==
14765 			      (s64)(s32)(ptr_reg->off + smin_val))) {
14766 			/* pointer += K.  Accumulate it into fixed offset */
14767 			dst_reg->smin_value = smin_ptr;
14768 			dst_reg->smax_value = smax_ptr;
14769 			dst_reg->umin_value = umin_ptr;
14770 			dst_reg->umax_value = umax_ptr;
14771 			dst_reg->var_off = ptr_reg->var_off;
14772 			dst_reg->off = ptr_reg->off + smin_val;
14773 			dst_reg->raw = ptr_reg->raw;
14774 			break;
14775 		}
14776 		/* A new variable offset is created.  Note that off_reg->off
14777 		 * == 0, since it's a scalar.
14778 		 * dst_reg gets the pointer type and since some positive
14779 		 * integer value was added to the pointer, give it a new 'id'
14780 		 * if it's a PTR_TO_PACKET.
14781 		 * this creates a new 'base' pointer, off_reg (variable) gets
14782 		 * added into the variable offset, and we copy the fixed offset
14783 		 * from ptr_reg.
14784 		 */
14785 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
14786 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
14787 			dst_reg->smin_value = S64_MIN;
14788 			dst_reg->smax_value = S64_MAX;
14789 		}
14790 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
14791 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
14792 			dst_reg->umin_value = 0;
14793 			dst_reg->umax_value = U64_MAX;
14794 		}
14795 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
14796 		dst_reg->off = ptr_reg->off;
14797 		dst_reg->raw = ptr_reg->raw;
14798 		if (reg_is_pkt_pointer(ptr_reg)) {
14799 			dst_reg->id = ++env->id_gen;
14800 			/* something was added to pkt_ptr, set range to zero */
14801 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14802 		}
14803 		break;
14804 	case BPF_SUB:
14805 		if (dst_reg == off_reg) {
14806 			/* scalar -= pointer.  Creates an unknown scalar */
14807 			verbose(env, "R%d tried to subtract pointer from scalar\n",
14808 				dst);
14809 			return -EACCES;
14810 		}
14811 		/* We don't allow subtraction from FP, because (according to
14812 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
14813 		 * be able to deal with it.
14814 		 */
14815 		if (ptr_reg->type == PTR_TO_STACK) {
14816 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
14817 				dst);
14818 			return -EACCES;
14819 		}
14820 		if (known && (ptr_reg->off - smin_val ==
14821 			      (s64)(s32)(ptr_reg->off - smin_val))) {
14822 			/* pointer -= K.  Subtract it from fixed offset */
14823 			dst_reg->smin_value = smin_ptr;
14824 			dst_reg->smax_value = smax_ptr;
14825 			dst_reg->umin_value = umin_ptr;
14826 			dst_reg->umax_value = umax_ptr;
14827 			dst_reg->var_off = ptr_reg->var_off;
14828 			dst_reg->id = ptr_reg->id;
14829 			dst_reg->off = ptr_reg->off - smin_val;
14830 			dst_reg->raw = ptr_reg->raw;
14831 			break;
14832 		}
14833 		/* A new variable offset is created.  If the subtrahend is known
14834 		 * nonnegative, then any reg->range we had before is still good.
14835 		 */
14836 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
14837 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
14838 			/* Overflow possible, we know nothing */
14839 			dst_reg->smin_value = S64_MIN;
14840 			dst_reg->smax_value = S64_MAX;
14841 		}
14842 		if (umin_ptr < umax_val) {
14843 			/* Overflow possible, we know nothing */
14844 			dst_reg->umin_value = 0;
14845 			dst_reg->umax_value = U64_MAX;
14846 		} else {
14847 			/* Cannot overflow (as long as bounds are consistent) */
14848 			dst_reg->umin_value = umin_ptr - umax_val;
14849 			dst_reg->umax_value = umax_ptr - umin_val;
14850 		}
14851 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
14852 		dst_reg->off = ptr_reg->off;
14853 		dst_reg->raw = ptr_reg->raw;
14854 		if (reg_is_pkt_pointer(ptr_reg)) {
14855 			dst_reg->id = ++env->id_gen;
14856 			/* something was added to pkt_ptr, set range to zero */
14857 			if (smin_val < 0)
14858 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14859 		}
14860 		break;
14861 	case BPF_AND:
14862 	case BPF_OR:
14863 	case BPF_XOR:
14864 		/* bitwise ops on pointers are troublesome, prohibit. */
14865 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
14866 			dst, bpf_alu_string[opcode >> 4]);
14867 		return -EACCES;
14868 	default:
14869 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
14870 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
14871 			dst, bpf_alu_string[opcode >> 4]);
14872 		return -EACCES;
14873 	}
14874 
14875 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
14876 		return -EINVAL;
14877 	reg_bounds_sync(dst_reg);
14878 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
14879 	if (bounds_ret == -EACCES)
14880 		return bounds_ret;
14881 	if (sanitize_needed(opcode)) {
14882 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
14883 				       &info, true);
14884 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
14885 				    && !env->cur_state->speculative
14886 				    && bounds_ret
14887 				    && !ret,
14888 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
14889 			return -EFAULT;
14890 		}
14891 		if (ret < 0)
14892 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14893 	}
14894 
14895 	return 0;
14896 }
14897 
14898 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
14899 				 struct bpf_reg_state *src_reg)
14900 {
14901 	s32 *dst_smin = &dst_reg->s32_min_value;
14902 	s32 *dst_smax = &dst_reg->s32_max_value;
14903 	u32 *dst_umin = &dst_reg->u32_min_value;
14904 	u32 *dst_umax = &dst_reg->u32_max_value;
14905 	u32 umin_val = src_reg->u32_min_value;
14906 	u32 umax_val = src_reg->u32_max_value;
14907 	bool min_overflow, max_overflow;
14908 
14909 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
14910 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
14911 		*dst_smin = S32_MIN;
14912 		*dst_smax = S32_MAX;
14913 	}
14914 
14915 	/* If either all additions overflow or no additions overflow, then
14916 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14917 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
14918 	 * the output bounds to unbounded.
14919 	 */
14920 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14921 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14922 
14923 	if (!min_overflow && max_overflow) {
14924 		*dst_umin = 0;
14925 		*dst_umax = U32_MAX;
14926 	}
14927 }
14928 
14929 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
14930 			       struct bpf_reg_state *src_reg)
14931 {
14932 	s64 *dst_smin = &dst_reg->smin_value;
14933 	s64 *dst_smax = &dst_reg->smax_value;
14934 	u64 *dst_umin = &dst_reg->umin_value;
14935 	u64 *dst_umax = &dst_reg->umax_value;
14936 	u64 umin_val = src_reg->umin_value;
14937 	u64 umax_val = src_reg->umax_value;
14938 	bool min_overflow, max_overflow;
14939 
14940 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
14941 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
14942 		*dst_smin = S64_MIN;
14943 		*dst_smax = S64_MAX;
14944 	}
14945 
14946 	/* If either all additions overflow or no additions overflow, then
14947 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14948 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
14949 	 * the output bounds to unbounded.
14950 	 */
14951 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14952 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14953 
14954 	if (!min_overflow && max_overflow) {
14955 		*dst_umin = 0;
14956 		*dst_umax = U64_MAX;
14957 	}
14958 }
14959 
14960 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
14961 				 struct bpf_reg_state *src_reg)
14962 {
14963 	s32 *dst_smin = &dst_reg->s32_min_value;
14964 	s32 *dst_smax = &dst_reg->s32_max_value;
14965 	u32 *dst_umin = &dst_reg->u32_min_value;
14966 	u32 *dst_umax = &dst_reg->u32_max_value;
14967 	u32 umin_val = src_reg->u32_min_value;
14968 	u32 umax_val = src_reg->u32_max_value;
14969 	bool min_underflow, max_underflow;
14970 
14971 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
14972 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
14973 		/* Overflow possible, we know nothing */
14974 		*dst_smin = S32_MIN;
14975 		*dst_smax = S32_MAX;
14976 	}
14977 
14978 	/* If either all subtractions underflow or no subtractions
14979 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
14980 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
14981 	 * underflow), set the output bounds to unbounded.
14982 	 */
14983 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
14984 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
14985 
14986 	if (min_underflow && !max_underflow) {
14987 		*dst_umin = 0;
14988 		*dst_umax = U32_MAX;
14989 	}
14990 }
14991 
14992 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
14993 			       struct bpf_reg_state *src_reg)
14994 {
14995 	s64 *dst_smin = &dst_reg->smin_value;
14996 	s64 *dst_smax = &dst_reg->smax_value;
14997 	u64 *dst_umin = &dst_reg->umin_value;
14998 	u64 *dst_umax = &dst_reg->umax_value;
14999 	u64 umin_val = src_reg->umin_value;
15000 	u64 umax_val = src_reg->umax_value;
15001 	bool min_underflow, max_underflow;
15002 
15003 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
15004 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
15005 		/* Overflow possible, we know nothing */
15006 		*dst_smin = S64_MIN;
15007 		*dst_smax = S64_MAX;
15008 	}
15009 
15010 	/* If either all subtractions underflow or no subtractions
15011 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
15012 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
15013 	 * underflow), set the output bounds to unbounded.
15014 	 */
15015 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
15016 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
15017 
15018 	if (min_underflow && !max_underflow) {
15019 		*dst_umin = 0;
15020 		*dst_umax = U64_MAX;
15021 	}
15022 }
15023 
15024 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
15025 				 struct bpf_reg_state *src_reg)
15026 {
15027 	s32 *dst_smin = &dst_reg->s32_min_value;
15028 	s32 *dst_smax = &dst_reg->s32_max_value;
15029 	u32 *dst_umin = &dst_reg->u32_min_value;
15030 	u32 *dst_umax = &dst_reg->u32_max_value;
15031 	s32 tmp_prod[4];
15032 
15033 	if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) ||
15034 	    check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) {
15035 		/* Overflow possible, we know nothing */
15036 		*dst_umin = 0;
15037 		*dst_umax = U32_MAX;
15038 	}
15039 	if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) ||
15040 	    check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) ||
15041 	    check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) ||
15042 	    check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) {
15043 		/* Overflow possible, we know nothing */
15044 		*dst_smin = S32_MIN;
15045 		*dst_smax = S32_MAX;
15046 	} else {
15047 		*dst_smin = min_array(tmp_prod, 4);
15048 		*dst_smax = max_array(tmp_prod, 4);
15049 	}
15050 }
15051 
15052 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
15053 			       struct bpf_reg_state *src_reg)
15054 {
15055 	s64 *dst_smin = &dst_reg->smin_value;
15056 	s64 *dst_smax = &dst_reg->smax_value;
15057 	u64 *dst_umin = &dst_reg->umin_value;
15058 	u64 *dst_umax = &dst_reg->umax_value;
15059 	s64 tmp_prod[4];
15060 
15061 	if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) ||
15062 	    check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) {
15063 		/* Overflow possible, we know nothing */
15064 		*dst_umin = 0;
15065 		*dst_umax = U64_MAX;
15066 	}
15067 	if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) ||
15068 	    check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) ||
15069 	    check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) ||
15070 	    check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) {
15071 		/* Overflow possible, we know nothing */
15072 		*dst_smin = S64_MIN;
15073 		*dst_smax = S64_MAX;
15074 	} else {
15075 		*dst_smin = min_array(tmp_prod, 4);
15076 		*dst_smax = max_array(tmp_prod, 4);
15077 	}
15078 }
15079 
15080 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
15081 				 struct bpf_reg_state *src_reg)
15082 {
15083 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15084 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15085 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15086 	u32 umax_val = src_reg->u32_max_value;
15087 
15088 	if (src_known && dst_known) {
15089 		__mark_reg32_known(dst_reg, var32_off.value);
15090 		return;
15091 	}
15092 
15093 	/* We get our minimum from the var_off, since that's inherently
15094 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
15095 	 */
15096 	dst_reg->u32_min_value = var32_off.value;
15097 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
15098 
15099 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15100 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15101 	 */
15102 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15103 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15104 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15105 	} else {
15106 		dst_reg->s32_min_value = S32_MIN;
15107 		dst_reg->s32_max_value = S32_MAX;
15108 	}
15109 }
15110 
15111 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
15112 			       struct bpf_reg_state *src_reg)
15113 {
15114 	bool src_known = tnum_is_const(src_reg->var_off);
15115 	bool dst_known = tnum_is_const(dst_reg->var_off);
15116 	u64 umax_val = src_reg->umax_value;
15117 
15118 	if (src_known && dst_known) {
15119 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15120 		return;
15121 	}
15122 
15123 	/* We get our minimum from the var_off, since that's inherently
15124 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
15125 	 */
15126 	dst_reg->umin_value = dst_reg->var_off.value;
15127 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
15128 
15129 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15130 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15131 	 */
15132 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15133 		dst_reg->smin_value = dst_reg->umin_value;
15134 		dst_reg->smax_value = dst_reg->umax_value;
15135 	} else {
15136 		dst_reg->smin_value = S64_MIN;
15137 		dst_reg->smax_value = S64_MAX;
15138 	}
15139 	/* We may learn something more from the var_off */
15140 	__update_reg_bounds(dst_reg);
15141 }
15142 
15143 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
15144 				struct bpf_reg_state *src_reg)
15145 {
15146 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15147 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15148 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15149 	u32 umin_val = src_reg->u32_min_value;
15150 
15151 	if (src_known && dst_known) {
15152 		__mark_reg32_known(dst_reg, var32_off.value);
15153 		return;
15154 	}
15155 
15156 	/* We get our maximum from the var_off, and our minimum is the
15157 	 * maximum of the operands' minima
15158 	 */
15159 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
15160 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15161 
15162 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15163 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15164 	 */
15165 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15166 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15167 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15168 	} else {
15169 		dst_reg->s32_min_value = S32_MIN;
15170 		dst_reg->s32_max_value = S32_MAX;
15171 	}
15172 }
15173 
15174 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
15175 			      struct bpf_reg_state *src_reg)
15176 {
15177 	bool src_known = tnum_is_const(src_reg->var_off);
15178 	bool dst_known = tnum_is_const(dst_reg->var_off);
15179 	u64 umin_val = src_reg->umin_value;
15180 
15181 	if (src_known && dst_known) {
15182 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15183 		return;
15184 	}
15185 
15186 	/* We get our maximum from the var_off, and our minimum is the
15187 	 * maximum of the operands' minima
15188 	 */
15189 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
15190 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15191 
15192 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15193 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15194 	 */
15195 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15196 		dst_reg->smin_value = dst_reg->umin_value;
15197 		dst_reg->smax_value = dst_reg->umax_value;
15198 	} else {
15199 		dst_reg->smin_value = S64_MIN;
15200 		dst_reg->smax_value = S64_MAX;
15201 	}
15202 	/* We may learn something more from the var_off */
15203 	__update_reg_bounds(dst_reg);
15204 }
15205 
15206 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
15207 				 struct bpf_reg_state *src_reg)
15208 {
15209 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15210 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15211 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15212 
15213 	if (src_known && dst_known) {
15214 		__mark_reg32_known(dst_reg, var32_off.value);
15215 		return;
15216 	}
15217 
15218 	/* We get both minimum and maximum from the var32_off. */
15219 	dst_reg->u32_min_value = var32_off.value;
15220 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15221 
15222 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15223 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15224 	 */
15225 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15226 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15227 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15228 	} else {
15229 		dst_reg->s32_min_value = S32_MIN;
15230 		dst_reg->s32_max_value = S32_MAX;
15231 	}
15232 }
15233 
15234 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
15235 			       struct bpf_reg_state *src_reg)
15236 {
15237 	bool src_known = tnum_is_const(src_reg->var_off);
15238 	bool dst_known = tnum_is_const(dst_reg->var_off);
15239 
15240 	if (src_known && dst_known) {
15241 		/* dst_reg->var_off.value has been updated earlier */
15242 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15243 		return;
15244 	}
15245 
15246 	/* We get both minimum and maximum from the var_off. */
15247 	dst_reg->umin_value = dst_reg->var_off.value;
15248 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15249 
15250 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15251 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15252 	 */
15253 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15254 		dst_reg->smin_value = dst_reg->umin_value;
15255 		dst_reg->smax_value = dst_reg->umax_value;
15256 	} else {
15257 		dst_reg->smin_value = S64_MIN;
15258 		dst_reg->smax_value = S64_MAX;
15259 	}
15260 
15261 	__update_reg_bounds(dst_reg);
15262 }
15263 
15264 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15265 				   u64 umin_val, u64 umax_val)
15266 {
15267 	/* We lose all sign bit information (except what we can pick
15268 	 * up from var_off)
15269 	 */
15270 	dst_reg->s32_min_value = S32_MIN;
15271 	dst_reg->s32_max_value = S32_MAX;
15272 	/* If we might shift our top bit out, then we know nothing */
15273 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
15274 		dst_reg->u32_min_value = 0;
15275 		dst_reg->u32_max_value = U32_MAX;
15276 	} else {
15277 		dst_reg->u32_min_value <<= umin_val;
15278 		dst_reg->u32_max_value <<= umax_val;
15279 	}
15280 }
15281 
15282 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15283 				 struct bpf_reg_state *src_reg)
15284 {
15285 	u32 umax_val = src_reg->u32_max_value;
15286 	u32 umin_val = src_reg->u32_min_value;
15287 	/* u32 alu operation will zext upper bits */
15288 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15289 
15290 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15291 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
15292 	/* Not required but being careful mark reg64 bounds as unknown so
15293 	 * that we are forced to pick them up from tnum and zext later and
15294 	 * if some path skips this step we are still safe.
15295 	 */
15296 	__mark_reg64_unbounded(dst_reg);
15297 	__update_reg32_bounds(dst_reg);
15298 }
15299 
15300 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
15301 				   u64 umin_val, u64 umax_val)
15302 {
15303 	/* Special case <<32 because it is a common compiler pattern to sign
15304 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
15305 	 * positive we know this shift will also be positive so we can track
15306 	 * bounds correctly. Otherwise we lose all sign bit information except
15307 	 * what we can pick up from var_off. Perhaps we can generalize this
15308 	 * later to shifts of any length.
15309 	 */
15310 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
15311 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
15312 	else
15313 		dst_reg->smax_value = S64_MAX;
15314 
15315 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
15316 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
15317 	else
15318 		dst_reg->smin_value = S64_MIN;
15319 
15320 	/* If we might shift our top bit out, then we know nothing */
15321 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
15322 		dst_reg->umin_value = 0;
15323 		dst_reg->umax_value = U64_MAX;
15324 	} else {
15325 		dst_reg->umin_value <<= umin_val;
15326 		dst_reg->umax_value <<= umax_val;
15327 	}
15328 }
15329 
15330 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
15331 			       struct bpf_reg_state *src_reg)
15332 {
15333 	u64 umax_val = src_reg->umax_value;
15334 	u64 umin_val = src_reg->umin_value;
15335 
15336 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
15337 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
15338 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15339 
15340 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
15341 	/* We may learn something more from the var_off */
15342 	__update_reg_bounds(dst_reg);
15343 }
15344 
15345 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
15346 				 struct bpf_reg_state *src_reg)
15347 {
15348 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15349 	u32 umax_val = src_reg->u32_max_value;
15350 	u32 umin_val = src_reg->u32_min_value;
15351 
15352 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15353 	 * be negative, then either:
15354 	 * 1) src_reg might be zero, so the sign bit of the result is
15355 	 *    unknown, so we lose our signed bounds
15356 	 * 2) it's known negative, thus the unsigned bounds capture the
15357 	 *    signed bounds
15358 	 * 3) the signed bounds cross zero, so they tell us nothing
15359 	 *    about the result
15360 	 * If the value in dst_reg is known nonnegative, then again the
15361 	 * unsigned bounds capture the signed bounds.
15362 	 * Thus, in all cases it suffices to blow away our signed bounds
15363 	 * and rely on inferring new ones from the unsigned bounds and
15364 	 * var_off of the result.
15365 	 */
15366 	dst_reg->s32_min_value = S32_MIN;
15367 	dst_reg->s32_max_value = S32_MAX;
15368 
15369 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
15370 	dst_reg->u32_min_value >>= umax_val;
15371 	dst_reg->u32_max_value >>= umin_val;
15372 
15373 	__mark_reg64_unbounded(dst_reg);
15374 	__update_reg32_bounds(dst_reg);
15375 }
15376 
15377 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
15378 			       struct bpf_reg_state *src_reg)
15379 {
15380 	u64 umax_val = src_reg->umax_value;
15381 	u64 umin_val = src_reg->umin_value;
15382 
15383 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15384 	 * be negative, then either:
15385 	 * 1) src_reg might be zero, so the sign bit of the result is
15386 	 *    unknown, so we lose our signed bounds
15387 	 * 2) it's known negative, thus the unsigned bounds capture the
15388 	 *    signed bounds
15389 	 * 3) the signed bounds cross zero, so they tell us nothing
15390 	 *    about the result
15391 	 * If the value in dst_reg is known nonnegative, then again the
15392 	 * unsigned bounds capture the signed bounds.
15393 	 * Thus, in all cases it suffices to blow away our signed bounds
15394 	 * and rely on inferring new ones from the unsigned bounds and
15395 	 * var_off of the result.
15396 	 */
15397 	dst_reg->smin_value = S64_MIN;
15398 	dst_reg->smax_value = S64_MAX;
15399 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
15400 	dst_reg->umin_value >>= umax_val;
15401 	dst_reg->umax_value >>= umin_val;
15402 
15403 	/* Its not easy to operate on alu32 bounds here because it depends
15404 	 * on bits being shifted in. Take easy way out and mark unbounded
15405 	 * so we can recalculate later from tnum.
15406 	 */
15407 	__mark_reg32_unbounded(dst_reg);
15408 	__update_reg_bounds(dst_reg);
15409 }
15410 
15411 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
15412 				  struct bpf_reg_state *src_reg)
15413 {
15414 	u64 umin_val = src_reg->u32_min_value;
15415 
15416 	/* Upon reaching here, src_known is true and
15417 	 * umax_val is equal to umin_val.
15418 	 */
15419 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
15420 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
15421 
15422 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
15423 
15424 	/* blow away the dst_reg umin_value/umax_value and rely on
15425 	 * dst_reg var_off to refine the result.
15426 	 */
15427 	dst_reg->u32_min_value = 0;
15428 	dst_reg->u32_max_value = U32_MAX;
15429 
15430 	__mark_reg64_unbounded(dst_reg);
15431 	__update_reg32_bounds(dst_reg);
15432 }
15433 
15434 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
15435 				struct bpf_reg_state *src_reg)
15436 {
15437 	u64 umin_val = src_reg->umin_value;
15438 
15439 	/* Upon reaching here, src_known is true and umax_val is equal
15440 	 * to umin_val.
15441 	 */
15442 	dst_reg->smin_value >>= umin_val;
15443 	dst_reg->smax_value >>= umin_val;
15444 
15445 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
15446 
15447 	/* blow away the dst_reg umin_value/umax_value and rely on
15448 	 * dst_reg var_off to refine the result.
15449 	 */
15450 	dst_reg->umin_value = 0;
15451 	dst_reg->umax_value = U64_MAX;
15452 
15453 	/* Its not easy to operate on alu32 bounds here because it depends
15454 	 * on bits being shifted in from upper 32-bits. Take easy way out
15455 	 * and mark unbounded so we can recalculate later from tnum.
15456 	 */
15457 	__mark_reg32_unbounded(dst_reg);
15458 	__update_reg_bounds(dst_reg);
15459 }
15460 
15461 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
15462 					     const struct bpf_reg_state *src_reg)
15463 {
15464 	bool src_is_const = false;
15465 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
15466 
15467 	if (insn_bitness == 32) {
15468 		if (tnum_subreg_is_const(src_reg->var_off)
15469 		    && src_reg->s32_min_value == src_reg->s32_max_value
15470 		    && src_reg->u32_min_value == src_reg->u32_max_value)
15471 			src_is_const = true;
15472 	} else {
15473 		if (tnum_is_const(src_reg->var_off)
15474 		    && src_reg->smin_value == src_reg->smax_value
15475 		    && src_reg->umin_value == src_reg->umax_value)
15476 			src_is_const = true;
15477 	}
15478 
15479 	switch (BPF_OP(insn->code)) {
15480 	case BPF_ADD:
15481 	case BPF_SUB:
15482 	case BPF_NEG:
15483 	case BPF_AND:
15484 	case BPF_XOR:
15485 	case BPF_OR:
15486 	case BPF_MUL:
15487 		return true;
15488 
15489 	/* Shift operators range is only computable if shift dimension operand
15490 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
15491 	 * includes shifts by a negative number.
15492 	 */
15493 	case BPF_LSH:
15494 	case BPF_RSH:
15495 	case BPF_ARSH:
15496 		return (src_is_const && src_reg->umax_value < insn_bitness);
15497 	default:
15498 		return false;
15499 	}
15500 }
15501 
15502 /* WARNING: This function does calculations on 64-bit values, but the actual
15503  * execution may occur on 32-bit values. Therefore, things like bitshifts
15504  * need extra checks in the 32-bit case.
15505  */
15506 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
15507 				      struct bpf_insn *insn,
15508 				      struct bpf_reg_state *dst_reg,
15509 				      struct bpf_reg_state src_reg)
15510 {
15511 	u8 opcode = BPF_OP(insn->code);
15512 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15513 	int ret;
15514 
15515 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
15516 		__mark_reg_unknown(env, dst_reg);
15517 		return 0;
15518 	}
15519 
15520 	if (sanitize_needed(opcode)) {
15521 		ret = sanitize_val_alu(env, insn);
15522 		if (ret < 0)
15523 			return sanitize_err(env, insn, ret, NULL, NULL);
15524 	}
15525 
15526 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
15527 	 * There are two classes of instructions: The first class we track both
15528 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
15529 	 * greatest amount of precision when alu operations are mixed with jmp32
15530 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
15531 	 * and BPF_OR. This is possible because these ops have fairly easy to
15532 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
15533 	 * See alu32 verifier tests for examples. The second class of
15534 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
15535 	 * with regards to tracking sign/unsigned bounds because the bits may
15536 	 * cross subreg boundaries in the alu64 case. When this happens we mark
15537 	 * the reg unbounded in the subreg bound space and use the resulting
15538 	 * tnum to calculate an approximation of the sign/unsigned bounds.
15539 	 */
15540 	switch (opcode) {
15541 	case BPF_ADD:
15542 		scalar32_min_max_add(dst_reg, &src_reg);
15543 		scalar_min_max_add(dst_reg, &src_reg);
15544 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
15545 		break;
15546 	case BPF_SUB:
15547 		scalar32_min_max_sub(dst_reg, &src_reg);
15548 		scalar_min_max_sub(dst_reg, &src_reg);
15549 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
15550 		break;
15551 	case BPF_NEG:
15552 		env->fake_reg[0] = *dst_reg;
15553 		__mark_reg_known(dst_reg, 0);
15554 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
15555 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
15556 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
15557 		break;
15558 	case BPF_MUL:
15559 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
15560 		scalar32_min_max_mul(dst_reg, &src_reg);
15561 		scalar_min_max_mul(dst_reg, &src_reg);
15562 		break;
15563 	case BPF_AND:
15564 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
15565 		scalar32_min_max_and(dst_reg, &src_reg);
15566 		scalar_min_max_and(dst_reg, &src_reg);
15567 		break;
15568 	case BPF_OR:
15569 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
15570 		scalar32_min_max_or(dst_reg, &src_reg);
15571 		scalar_min_max_or(dst_reg, &src_reg);
15572 		break;
15573 	case BPF_XOR:
15574 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
15575 		scalar32_min_max_xor(dst_reg, &src_reg);
15576 		scalar_min_max_xor(dst_reg, &src_reg);
15577 		break;
15578 	case BPF_LSH:
15579 		if (alu32)
15580 			scalar32_min_max_lsh(dst_reg, &src_reg);
15581 		else
15582 			scalar_min_max_lsh(dst_reg, &src_reg);
15583 		break;
15584 	case BPF_RSH:
15585 		if (alu32)
15586 			scalar32_min_max_rsh(dst_reg, &src_reg);
15587 		else
15588 			scalar_min_max_rsh(dst_reg, &src_reg);
15589 		break;
15590 	case BPF_ARSH:
15591 		if (alu32)
15592 			scalar32_min_max_arsh(dst_reg, &src_reg);
15593 		else
15594 			scalar_min_max_arsh(dst_reg, &src_reg);
15595 		break;
15596 	default:
15597 		break;
15598 	}
15599 
15600 	/* ALU32 ops are zero extended into 64bit register */
15601 	if (alu32)
15602 		zext_32_to_64(dst_reg);
15603 	reg_bounds_sync(dst_reg);
15604 	return 0;
15605 }
15606 
15607 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
15608  * and var_off.
15609  */
15610 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
15611 				   struct bpf_insn *insn)
15612 {
15613 	struct bpf_verifier_state *vstate = env->cur_state;
15614 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15615 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
15616 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
15617 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15618 	u8 opcode = BPF_OP(insn->code);
15619 	int err;
15620 
15621 	dst_reg = &regs[insn->dst_reg];
15622 	src_reg = NULL;
15623 
15624 	if (dst_reg->type == PTR_TO_ARENA) {
15625 		struct bpf_insn_aux_data *aux = cur_aux(env);
15626 
15627 		if (BPF_CLASS(insn->code) == BPF_ALU64)
15628 			/*
15629 			 * 32-bit operations zero upper bits automatically.
15630 			 * 64-bit operations need to be converted to 32.
15631 			 */
15632 			aux->needs_zext = true;
15633 
15634 		/* Any arithmetic operations are allowed on arena pointers */
15635 		return 0;
15636 	}
15637 
15638 	if (dst_reg->type != SCALAR_VALUE)
15639 		ptr_reg = dst_reg;
15640 
15641 	if (BPF_SRC(insn->code) == BPF_X) {
15642 		src_reg = &regs[insn->src_reg];
15643 		if (src_reg->type != SCALAR_VALUE) {
15644 			if (dst_reg->type != SCALAR_VALUE) {
15645 				/* Combining two pointers by any ALU op yields
15646 				 * an arbitrary scalar. Disallow all math except
15647 				 * pointer subtraction
15648 				 */
15649 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
15650 					mark_reg_unknown(env, regs, insn->dst_reg);
15651 					return 0;
15652 				}
15653 				verbose(env, "R%d pointer %s pointer prohibited\n",
15654 					insn->dst_reg,
15655 					bpf_alu_string[opcode >> 4]);
15656 				return -EACCES;
15657 			} else {
15658 				/* scalar += pointer
15659 				 * This is legal, but we have to reverse our
15660 				 * src/dest handling in computing the range
15661 				 */
15662 				err = mark_chain_precision(env, insn->dst_reg);
15663 				if (err)
15664 					return err;
15665 				return adjust_ptr_min_max_vals(env, insn,
15666 							       src_reg, dst_reg);
15667 			}
15668 		} else if (ptr_reg) {
15669 			/* pointer += scalar */
15670 			err = mark_chain_precision(env, insn->src_reg);
15671 			if (err)
15672 				return err;
15673 			return adjust_ptr_min_max_vals(env, insn,
15674 						       dst_reg, src_reg);
15675 		} else if (dst_reg->precise) {
15676 			/* if dst_reg is precise, src_reg should be precise as well */
15677 			err = mark_chain_precision(env, insn->src_reg);
15678 			if (err)
15679 				return err;
15680 		}
15681 	} else {
15682 		/* Pretend the src is a reg with a known value, since we only
15683 		 * need to be able to read from this state.
15684 		 */
15685 		off_reg.type = SCALAR_VALUE;
15686 		__mark_reg_known(&off_reg, insn->imm);
15687 		src_reg = &off_reg;
15688 		if (ptr_reg) /* pointer += K */
15689 			return adjust_ptr_min_max_vals(env, insn,
15690 						       ptr_reg, src_reg);
15691 	}
15692 
15693 	/* Got here implies adding two SCALAR_VALUEs */
15694 	if (WARN_ON_ONCE(ptr_reg)) {
15695 		print_verifier_state(env, vstate, vstate->curframe, true);
15696 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
15697 		return -EFAULT;
15698 	}
15699 	if (WARN_ON(!src_reg)) {
15700 		print_verifier_state(env, vstate, vstate->curframe, true);
15701 		verbose(env, "verifier internal error: no src_reg\n");
15702 		return -EFAULT;
15703 	}
15704 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
15705 	if (err)
15706 		return err;
15707 	/*
15708 	 * Compilers can generate the code
15709 	 * r1 = r2
15710 	 * r1 += 0x1
15711 	 * if r2 < 1000 goto ...
15712 	 * use r1 in memory access
15713 	 * So for 64-bit alu remember constant delta between r2 and r1 and
15714 	 * update r1 after 'if' condition.
15715 	 */
15716 	if (env->bpf_capable &&
15717 	    BPF_OP(insn->code) == BPF_ADD && !alu32 &&
15718 	    dst_reg->id && is_reg_const(src_reg, false)) {
15719 		u64 val = reg_const_value(src_reg, false);
15720 
15721 		if ((dst_reg->id & BPF_ADD_CONST) ||
15722 		    /* prevent overflow in sync_linked_regs() later */
15723 		    val > (u32)S32_MAX) {
15724 			/*
15725 			 * If the register already went through rX += val
15726 			 * we cannot accumulate another val into rx->off.
15727 			 */
15728 			dst_reg->off = 0;
15729 			dst_reg->id = 0;
15730 		} else {
15731 			dst_reg->id |= BPF_ADD_CONST;
15732 			dst_reg->off = val;
15733 		}
15734 	} else {
15735 		/*
15736 		 * Make sure ID is cleared otherwise dst_reg min/max could be
15737 		 * incorrectly propagated into other registers by sync_linked_regs()
15738 		 */
15739 		dst_reg->id = 0;
15740 	}
15741 	return 0;
15742 }
15743 
15744 /* check validity of 32-bit and 64-bit arithmetic operations */
15745 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
15746 {
15747 	struct bpf_reg_state *regs = cur_regs(env);
15748 	u8 opcode = BPF_OP(insn->code);
15749 	int err;
15750 
15751 	if (opcode == BPF_END || opcode == BPF_NEG) {
15752 		if (opcode == BPF_NEG) {
15753 			if (BPF_SRC(insn->code) != BPF_K ||
15754 			    insn->src_reg != BPF_REG_0 ||
15755 			    insn->off != 0 || insn->imm != 0) {
15756 				verbose(env, "BPF_NEG uses reserved fields\n");
15757 				return -EINVAL;
15758 			}
15759 		} else {
15760 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
15761 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
15762 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
15763 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
15764 				verbose(env, "BPF_END uses reserved fields\n");
15765 				return -EINVAL;
15766 			}
15767 		}
15768 
15769 		/* check src operand */
15770 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15771 		if (err)
15772 			return err;
15773 
15774 		if (is_pointer_value(env, insn->dst_reg)) {
15775 			verbose(env, "R%d pointer arithmetic prohibited\n",
15776 				insn->dst_reg);
15777 			return -EACCES;
15778 		}
15779 
15780 		/* check dest operand */
15781 		if (opcode == BPF_NEG &&
15782 		    regs[insn->dst_reg].type == SCALAR_VALUE) {
15783 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15784 			err = err ?: adjust_scalar_min_max_vals(env, insn,
15785 							 &regs[insn->dst_reg],
15786 							 regs[insn->dst_reg]);
15787 		} else {
15788 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
15789 		}
15790 		if (err)
15791 			return err;
15792 
15793 	} else if (opcode == BPF_MOV) {
15794 
15795 		if (BPF_SRC(insn->code) == BPF_X) {
15796 			if (BPF_CLASS(insn->code) == BPF_ALU) {
15797 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
15798 				    insn->imm) {
15799 					verbose(env, "BPF_MOV uses reserved fields\n");
15800 					return -EINVAL;
15801 				}
15802 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
15803 				if (insn->imm != 1 && insn->imm != 1u << 16) {
15804 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
15805 					return -EINVAL;
15806 				}
15807 				if (!env->prog->aux->arena) {
15808 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
15809 					return -EINVAL;
15810 				}
15811 			} else {
15812 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
15813 				     insn->off != 32) || insn->imm) {
15814 					verbose(env, "BPF_MOV uses reserved fields\n");
15815 					return -EINVAL;
15816 				}
15817 			}
15818 
15819 			/* check src operand */
15820 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15821 			if (err)
15822 				return err;
15823 		} else {
15824 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
15825 				verbose(env, "BPF_MOV uses reserved fields\n");
15826 				return -EINVAL;
15827 			}
15828 		}
15829 
15830 		/* check dest operand, mark as required later */
15831 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15832 		if (err)
15833 			return err;
15834 
15835 		if (BPF_SRC(insn->code) == BPF_X) {
15836 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
15837 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
15838 
15839 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15840 				if (insn->imm) {
15841 					/* off == BPF_ADDR_SPACE_CAST */
15842 					mark_reg_unknown(env, regs, insn->dst_reg);
15843 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
15844 						dst_reg->type = PTR_TO_ARENA;
15845 						/* PTR_TO_ARENA is 32-bit */
15846 						dst_reg->subreg_def = env->insn_idx + 1;
15847 					}
15848 				} else if (insn->off == 0) {
15849 					/* case: R1 = R2
15850 					 * copy register state to dest reg
15851 					 */
15852 					assign_scalar_id_before_mov(env, src_reg);
15853 					copy_register_state(dst_reg, src_reg);
15854 					dst_reg->subreg_def = DEF_NOT_SUBREG;
15855 				} else {
15856 					/* case: R1 = (s8, s16 s32)R2 */
15857 					if (is_pointer_value(env, insn->src_reg)) {
15858 						verbose(env,
15859 							"R%d sign-extension part of pointer\n",
15860 							insn->src_reg);
15861 						return -EACCES;
15862 					} else if (src_reg->type == SCALAR_VALUE) {
15863 						bool no_sext;
15864 
15865 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15866 						if (no_sext)
15867 							assign_scalar_id_before_mov(env, src_reg);
15868 						copy_register_state(dst_reg, src_reg);
15869 						if (!no_sext)
15870 							dst_reg->id = 0;
15871 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
15872 						dst_reg->subreg_def = DEF_NOT_SUBREG;
15873 					} else {
15874 						mark_reg_unknown(env, regs, insn->dst_reg);
15875 					}
15876 				}
15877 			} else {
15878 				/* R1 = (u32) R2 */
15879 				if (is_pointer_value(env, insn->src_reg)) {
15880 					verbose(env,
15881 						"R%d partial copy of pointer\n",
15882 						insn->src_reg);
15883 					return -EACCES;
15884 				} else if (src_reg->type == SCALAR_VALUE) {
15885 					if (insn->off == 0) {
15886 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
15887 
15888 						if (is_src_reg_u32)
15889 							assign_scalar_id_before_mov(env, src_reg);
15890 						copy_register_state(dst_reg, src_reg);
15891 						/* Make sure ID is cleared if src_reg is not in u32
15892 						 * range otherwise dst_reg min/max could be incorrectly
15893 						 * propagated into src_reg by sync_linked_regs()
15894 						 */
15895 						if (!is_src_reg_u32)
15896 							dst_reg->id = 0;
15897 						dst_reg->subreg_def = env->insn_idx + 1;
15898 					} else {
15899 						/* case: W1 = (s8, s16)W2 */
15900 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15901 
15902 						if (no_sext)
15903 							assign_scalar_id_before_mov(env, src_reg);
15904 						copy_register_state(dst_reg, src_reg);
15905 						if (!no_sext)
15906 							dst_reg->id = 0;
15907 						dst_reg->subreg_def = env->insn_idx + 1;
15908 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
15909 					}
15910 				} else {
15911 					mark_reg_unknown(env, regs,
15912 							 insn->dst_reg);
15913 				}
15914 				zext_32_to_64(dst_reg);
15915 				reg_bounds_sync(dst_reg);
15916 			}
15917 		} else {
15918 			/* case: R = imm
15919 			 * remember the value we stored into this reg
15920 			 */
15921 			/* clear any state __mark_reg_known doesn't set */
15922 			mark_reg_unknown(env, regs, insn->dst_reg);
15923 			regs[insn->dst_reg].type = SCALAR_VALUE;
15924 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15925 				__mark_reg_known(regs + insn->dst_reg,
15926 						 insn->imm);
15927 			} else {
15928 				__mark_reg_known(regs + insn->dst_reg,
15929 						 (u32)insn->imm);
15930 			}
15931 		}
15932 
15933 	} else if (opcode > BPF_END) {
15934 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
15935 		return -EINVAL;
15936 
15937 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
15938 
15939 		if (BPF_SRC(insn->code) == BPF_X) {
15940 			if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
15941 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15942 				verbose(env, "BPF_ALU uses reserved fields\n");
15943 				return -EINVAL;
15944 			}
15945 			/* check src1 operand */
15946 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15947 			if (err)
15948 				return err;
15949 		} else {
15950 			if (insn->src_reg != BPF_REG_0 || (insn->off != 0 && insn->off != 1) ||
15951 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15952 				verbose(env, "BPF_ALU uses reserved fields\n");
15953 				return -EINVAL;
15954 			}
15955 		}
15956 
15957 		/* check src2 operand */
15958 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15959 		if (err)
15960 			return err;
15961 
15962 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
15963 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
15964 			verbose(env, "div by zero\n");
15965 			return -EINVAL;
15966 		}
15967 
15968 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
15969 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
15970 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
15971 
15972 			if (insn->imm < 0 || insn->imm >= size) {
15973 				verbose(env, "invalid shift %d\n", insn->imm);
15974 				return -EINVAL;
15975 			}
15976 		}
15977 
15978 		/* check dest operand */
15979 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15980 		err = err ?: adjust_reg_min_max_vals(env, insn);
15981 		if (err)
15982 			return err;
15983 	}
15984 
15985 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
15986 }
15987 
15988 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
15989 				   struct bpf_reg_state *dst_reg,
15990 				   enum bpf_reg_type type,
15991 				   bool range_right_open)
15992 {
15993 	struct bpf_func_state *state;
15994 	struct bpf_reg_state *reg;
15995 	int new_range;
15996 
15997 	if (dst_reg->off < 0 ||
15998 	    (dst_reg->off == 0 && range_right_open))
15999 		/* This doesn't give us any range */
16000 		return;
16001 
16002 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
16003 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
16004 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
16005 		 * than pkt_end, but that's because it's also less than pkt.
16006 		 */
16007 		return;
16008 
16009 	new_range = dst_reg->off;
16010 	if (range_right_open)
16011 		new_range++;
16012 
16013 	/* Examples for register markings:
16014 	 *
16015 	 * pkt_data in dst register:
16016 	 *
16017 	 *   r2 = r3;
16018 	 *   r2 += 8;
16019 	 *   if (r2 > pkt_end) goto <handle exception>
16020 	 *   <access okay>
16021 	 *
16022 	 *   r2 = r3;
16023 	 *   r2 += 8;
16024 	 *   if (r2 < pkt_end) goto <access okay>
16025 	 *   <handle exception>
16026 	 *
16027 	 *   Where:
16028 	 *     r2 == dst_reg, pkt_end == src_reg
16029 	 *     r2=pkt(id=n,off=8,r=0)
16030 	 *     r3=pkt(id=n,off=0,r=0)
16031 	 *
16032 	 * pkt_data in src register:
16033 	 *
16034 	 *   r2 = r3;
16035 	 *   r2 += 8;
16036 	 *   if (pkt_end >= r2) goto <access okay>
16037 	 *   <handle exception>
16038 	 *
16039 	 *   r2 = r3;
16040 	 *   r2 += 8;
16041 	 *   if (pkt_end <= r2) goto <handle exception>
16042 	 *   <access okay>
16043 	 *
16044 	 *   Where:
16045 	 *     pkt_end == dst_reg, r2 == src_reg
16046 	 *     r2=pkt(id=n,off=8,r=0)
16047 	 *     r3=pkt(id=n,off=0,r=0)
16048 	 *
16049 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
16050 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
16051 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
16052 	 * the check.
16053 	 */
16054 
16055 	/* If our ids match, then we must have the same max_value.  And we
16056 	 * don't care about the other reg's fixed offset, since if it's too big
16057 	 * the range won't allow anything.
16058 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
16059 	 */
16060 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16061 		if (reg->type == type && reg->id == dst_reg->id)
16062 			/* keep the maximum range already checked */
16063 			reg->range = max(reg->range, new_range);
16064 	}));
16065 }
16066 
16067 /*
16068  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
16069  */
16070 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16071 				  u8 opcode, bool is_jmp32)
16072 {
16073 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
16074 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
16075 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
16076 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
16077 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
16078 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
16079 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
16080 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
16081 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
16082 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
16083 
16084 	if (reg1 == reg2) {
16085 		switch (opcode) {
16086 		case BPF_JGE:
16087 		case BPF_JLE:
16088 		case BPF_JSGE:
16089 		case BPF_JSLE:
16090 		case BPF_JEQ:
16091 			return 1;
16092 		case BPF_JGT:
16093 		case BPF_JLT:
16094 		case BPF_JSGT:
16095 		case BPF_JSLT:
16096 		case BPF_JNE:
16097 			return 0;
16098 		case BPF_JSET:
16099 			if (tnum_is_const(t1))
16100 				return t1.value != 0;
16101 			else
16102 				return (smin1 <= 0 && smax1 >= 0) ? -1 : 1;
16103 		default:
16104 			return -1;
16105 		}
16106 	}
16107 
16108 	switch (opcode) {
16109 	case BPF_JEQ:
16110 		/* constants, umin/umax and smin/smax checks would be
16111 		 * redundant in this case because they all should match
16112 		 */
16113 		if (tnum_is_const(t1) && tnum_is_const(t2))
16114 			return t1.value == t2.value;
16115 		if (!tnum_overlap(t1, t2))
16116 			return 0;
16117 		/* non-overlapping ranges */
16118 		if (umin1 > umax2 || umax1 < umin2)
16119 			return 0;
16120 		if (smin1 > smax2 || smax1 < smin2)
16121 			return 0;
16122 		if (!is_jmp32) {
16123 			/* if 64-bit ranges are inconclusive, see if we can
16124 			 * utilize 32-bit subrange knowledge to eliminate
16125 			 * branches that can't be taken a priori
16126 			 */
16127 			if (reg1->u32_min_value > reg2->u32_max_value ||
16128 			    reg1->u32_max_value < reg2->u32_min_value)
16129 				return 0;
16130 			if (reg1->s32_min_value > reg2->s32_max_value ||
16131 			    reg1->s32_max_value < reg2->s32_min_value)
16132 				return 0;
16133 		}
16134 		break;
16135 	case BPF_JNE:
16136 		/* constants, umin/umax and smin/smax checks would be
16137 		 * redundant in this case because they all should match
16138 		 */
16139 		if (tnum_is_const(t1) && tnum_is_const(t2))
16140 			return t1.value != t2.value;
16141 		if (!tnum_overlap(t1, t2))
16142 			return 1;
16143 		/* non-overlapping ranges */
16144 		if (umin1 > umax2 || umax1 < umin2)
16145 			return 1;
16146 		if (smin1 > smax2 || smax1 < smin2)
16147 			return 1;
16148 		if (!is_jmp32) {
16149 			/* if 64-bit ranges are inconclusive, see if we can
16150 			 * utilize 32-bit subrange knowledge to eliminate
16151 			 * branches that can't be taken a priori
16152 			 */
16153 			if (reg1->u32_min_value > reg2->u32_max_value ||
16154 			    reg1->u32_max_value < reg2->u32_min_value)
16155 				return 1;
16156 			if (reg1->s32_min_value > reg2->s32_max_value ||
16157 			    reg1->s32_max_value < reg2->s32_min_value)
16158 				return 1;
16159 		}
16160 		break;
16161 	case BPF_JSET:
16162 		if (!is_reg_const(reg2, is_jmp32)) {
16163 			swap(reg1, reg2);
16164 			swap(t1, t2);
16165 		}
16166 		if (!is_reg_const(reg2, is_jmp32))
16167 			return -1;
16168 		if ((~t1.mask & t1.value) & t2.value)
16169 			return 1;
16170 		if (!((t1.mask | t1.value) & t2.value))
16171 			return 0;
16172 		break;
16173 	case BPF_JGT:
16174 		if (umin1 > umax2)
16175 			return 1;
16176 		else if (umax1 <= umin2)
16177 			return 0;
16178 		break;
16179 	case BPF_JSGT:
16180 		if (smin1 > smax2)
16181 			return 1;
16182 		else if (smax1 <= smin2)
16183 			return 0;
16184 		break;
16185 	case BPF_JLT:
16186 		if (umax1 < umin2)
16187 			return 1;
16188 		else if (umin1 >= umax2)
16189 			return 0;
16190 		break;
16191 	case BPF_JSLT:
16192 		if (smax1 < smin2)
16193 			return 1;
16194 		else if (smin1 >= smax2)
16195 			return 0;
16196 		break;
16197 	case BPF_JGE:
16198 		if (umin1 >= umax2)
16199 			return 1;
16200 		else if (umax1 < umin2)
16201 			return 0;
16202 		break;
16203 	case BPF_JSGE:
16204 		if (smin1 >= smax2)
16205 			return 1;
16206 		else if (smax1 < smin2)
16207 			return 0;
16208 		break;
16209 	case BPF_JLE:
16210 		if (umax1 <= umin2)
16211 			return 1;
16212 		else if (umin1 > umax2)
16213 			return 0;
16214 		break;
16215 	case BPF_JSLE:
16216 		if (smax1 <= smin2)
16217 			return 1;
16218 		else if (smin1 > smax2)
16219 			return 0;
16220 		break;
16221 	}
16222 
16223 	return -1;
16224 }
16225 
16226 static int flip_opcode(u32 opcode)
16227 {
16228 	/* How can we transform "a <op> b" into "b <op> a"? */
16229 	static const u8 opcode_flip[16] = {
16230 		/* these stay the same */
16231 		[BPF_JEQ  >> 4] = BPF_JEQ,
16232 		[BPF_JNE  >> 4] = BPF_JNE,
16233 		[BPF_JSET >> 4] = BPF_JSET,
16234 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
16235 		[BPF_JGE  >> 4] = BPF_JLE,
16236 		[BPF_JGT  >> 4] = BPF_JLT,
16237 		[BPF_JLE  >> 4] = BPF_JGE,
16238 		[BPF_JLT  >> 4] = BPF_JGT,
16239 		[BPF_JSGE >> 4] = BPF_JSLE,
16240 		[BPF_JSGT >> 4] = BPF_JSLT,
16241 		[BPF_JSLE >> 4] = BPF_JSGE,
16242 		[BPF_JSLT >> 4] = BPF_JSGT
16243 	};
16244 	return opcode_flip[opcode >> 4];
16245 }
16246 
16247 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
16248 				   struct bpf_reg_state *src_reg,
16249 				   u8 opcode)
16250 {
16251 	struct bpf_reg_state *pkt;
16252 
16253 	if (src_reg->type == PTR_TO_PACKET_END) {
16254 		pkt = dst_reg;
16255 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
16256 		pkt = src_reg;
16257 		opcode = flip_opcode(opcode);
16258 	} else {
16259 		return -1;
16260 	}
16261 
16262 	if (pkt->range >= 0)
16263 		return -1;
16264 
16265 	switch (opcode) {
16266 	case BPF_JLE:
16267 		/* pkt <= pkt_end */
16268 		fallthrough;
16269 	case BPF_JGT:
16270 		/* pkt > pkt_end */
16271 		if (pkt->range == BEYOND_PKT_END)
16272 			/* pkt has at last one extra byte beyond pkt_end */
16273 			return opcode == BPF_JGT;
16274 		break;
16275 	case BPF_JLT:
16276 		/* pkt < pkt_end */
16277 		fallthrough;
16278 	case BPF_JGE:
16279 		/* pkt >= pkt_end */
16280 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
16281 			return opcode == BPF_JGE;
16282 		break;
16283 	}
16284 	return -1;
16285 }
16286 
16287 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
16288  * and return:
16289  *  1 - branch will be taken and "goto target" will be executed
16290  *  0 - branch will not be taken and fall-through to next insn
16291  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
16292  *      range [0,10]
16293  */
16294 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16295 			   u8 opcode, bool is_jmp32)
16296 {
16297 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
16298 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
16299 
16300 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
16301 		u64 val;
16302 
16303 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
16304 		if (!is_reg_const(reg2, is_jmp32)) {
16305 			opcode = flip_opcode(opcode);
16306 			swap(reg1, reg2);
16307 		}
16308 		/* and ensure that reg2 is a constant */
16309 		if (!is_reg_const(reg2, is_jmp32))
16310 			return -1;
16311 
16312 		if (!reg_not_null(reg1))
16313 			return -1;
16314 
16315 		/* If pointer is valid tests against zero will fail so we can
16316 		 * use this to direct branch taken.
16317 		 */
16318 		val = reg_const_value(reg2, is_jmp32);
16319 		if (val != 0)
16320 			return -1;
16321 
16322 		switch (opcode) {
16323 		case BPF_JEQ:
16324 			return 0;
16325 		case BPF_JNE:
16326 			return 1;
16327 		default:
16328 			return -1;
16329 		}
16330 	}
16331 
16332 	/* now deal with two scalars, but not necessarily constants */
16333 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
16334 }
16335 
16336 /* Opcode that corresponds to a *false* branch condition.
16337  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
16338  */
16339 static u8 rev_opcode(u8 opcode)
16340 {
16341 	switch (opcode) {
16342 	case BPF_JEQ:		return BPF_JNE;
16343 	case BPF_JNE:		return BPF_JEQ;
16344 	/* JSET doesn't have it's reverse opcode in BPF, so add
16345 	 * BPF_X flag to denote the reverse of that operation
16346 	 */
16347 	case BPF_JSET:		return BPF_JSET | BPF_X;
16348 	case BPF_JSET | BPF_X:	return BPF_JSET;
16349 	case BPF_JGE:		return BPF_JLT;
16350 	case BPF_JGT:		return BPF_JLE;
16351 	case BPF_JLE:		return BPF_JGT;
16352 	case BPF_JLT:		return BPF_JGE;
16353 	case BPF_JSGE:		return BPF_JSLT;
16354 	case BPF_JSGT:		return BPF_JSLE;
16355 	case BPF_JSLE:		return BPF_JSGT;
16356 	case BPF_JSLT:		return BPF_JSGE;
16357 	default:		return 0;
16358 	}
16359 }
16360 
16361 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
16362 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16363 				u8 opcode, bool is_jmp32)
16364 {
16365 	struct tnum t;
16366 	u64 val;
16367 
16368 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
16369 	switch (opcode) {
16370 	case BPF_JGE:
16371 	case BPF_JGT:
16372 	case BPF_JSGE:
16373 	case BPF_JSGT:
16374 		opcode = flip_opcode(opcode);
16375 		swap(reg1, reg2);
16376 		break;
16377 	default:
16378 		break;
16379 	}
16380 
16381 	switch (opcode) {
16382 	case BPF_JEQ:
16383 		if (is_jmp32) {
16384 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16385 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16386 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16387 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16388 			reg2->u32_min_value = reg1->u32_min_value;
16389 			reg2->u32_max_value = reg1->u32_max_value;
16390 			reg2->s32_min_value = reg1->s32_min_value;
16391 			reg2->s32_max_value = reg1->s32_max_value;
16392 
16393 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
16394 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16395 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
16396 		} else {
16397 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
16398 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16399 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
16400 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16401 			reg2->umin_value = reg1->umin_value;
16402 			reg2->umax_value = reg1->umax_value;
16403 			reg2->smin_value = reg1->smin_value;
16404 			reg2->smax_value = reg1->smax_value;
16405 
16406 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
16407 			reg2->var_off = reg1->var_off;
16408 		}
16409 		break;
16410 	case BPF_JNE:
16411 		if (!is_reg_const(reg2, is_jmp32))
16412 			swap(reg1, reg2);
16413 		if (!is_reg_const(reg2, is_jmp32))
16414 			break;
16415 
16416 		/* try to recompute the bound of reg1 if reg2 is a const and
16417 		 * is exactly the edge of reg1.
16418 		 */
16419 		val = reg_const_value(reg2, is_jmp32);
16420 		if (is_jmp32) {
16421 			/* u32_min_value is not equal to 0xffffffff at this point,
16422 			 * because otherwise u32_max_value is 0xffffffff as well,
16423 			 * in such a case both reg1 and reg2 would be constants,
16424 			 * jump would be predicted and reg_set_min_max() won't
16425 			 * be called.
16426 			 *
16427 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
16428 			 * below.
16429 			 */
16430 			if (reg1->u32_min_value == (u32)val)
16431 				reg1->u32_min_value++;
16432 			if (reg1->u32_max_value == (u32)val)
16433 				reg1->u32_max_value--;
16434 			if (reg1->s32_min_value == (s32)val)
16435 				reg1->s32_min_value++;
16436 			if (reg1->s32_max_value == (s32)val)
16437 				reg1->s32_max_value--;
16438 		} else {
16439 			if (reg1->umin_value == (u64)val)
16440 				reg1->umin_value++;
16441 			if (reg1->umax_value == (u64)val)
16442 				reg1->umax_value--;
16443 			if (reg1->smin_value == (s64)val)
16444 				reg1->smin_value++;
16445 			if (reg1->smax_value == (s64)val)
16446 				reg1->smax_value--;
16447 		}
16448 		break;
16449 	case BPF_JSET:
16450 		if (!is_reg_const(reg2, is_jmp32))
16451 			swap(reg1, reg2);
16452 		if (!is_reg_const(reg2, is_jmp32))
16453 			break;
16454 		val = reg_const_value(reg2, is_jmp32);
16455 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
16456 		 * requires single bit to learn something useful. E.g., if we
16457 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
16458 		 * are actually set? We can learn something definite only if
16459 		 * it's a single-bit value to begin with.
16460 		 *
16461 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
16462 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
16463 		 * bit 1 is set, which we can readily use in adjustments.
16464 		 */
16465 		if (!is_power_of_2(val))
16466 			break;
16467 		if (is_jmp32) {
16468 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
16469 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16470 		} else {
16471 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
16472 		}
16473 		break;
16474 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
16475 		if (!is_reg_const(reg2, is_jmp32))
16476 			swap(reg1, reg2);
16477 		if (!is_reg_const(reg2, is_jmp32))
16478 			break;
16479 		val = reg_const_value(reg2, is_jmp32);
16480 		/* Forget the ranges before narrowing tnums, to avoid invariant
16481 		 * violations if we're on a dead branch.
16482 		 */
16483 		__mark_reg_unbounded(reg1);
16484 		if (is_jmp32) {
16485 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
16486 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16487 		} else {
16488 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
16489 		}
16490 		break;
16491 	case BPF_JLE:
16492 		if (is_jmp32) {
16493 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16494 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16495 		} else {
16496 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16497 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
16498 		}
16499 		break;
16500 	case BPF_JLT:
16501 		if (is_jmp32) {
16502 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
16503 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
16504 		} else {
16505 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
16506 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
16507 		}
16508 		break;
16509 	case BPF_JSLE:
16510 		if (is_jmp32) {
16511 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16512 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16513 		} else {
16514 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16515 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
16516 		}
16517 		break;
16518 	case BPF_JSLT:
16519 		if (is_jmp32) {
16520 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
16521 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
16522 		} else {
16523 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
16524 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
16525 		}
16526 		break;
16527 	default:
16528 		return;
16529 	}
16530 }
16531 
16532 /* Adjusts the register min/max values in the case that the dst_reg and
16533  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
16534  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
16535  * Technically we can do similar adjustments for pointers to the same object,
16536  * but we don't support that right now.
16537  */
16538 static int reg_set_min_max(struct bpf_verifier_env *env,
16539 			   struct bpf_reg_state *true_reg1,
16540 			   struct bpf_reg_state *true_reg2,
16541 			   struct bpf_reg_state *false_reg1,
16542 			   struct bpf_reg_state *false_reg2,
16543 			   u8 opcode, bool is_jmp32)
16544 {
16545 	int err;
16546 
16547 	/* If either register is a pointer, we can't learn anything about its
16548 	 * variable offset from the compare (unless they were a pointer into
16549 	 * the same object, but we don't bother with that).
16550 	 */
16551 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
16552 		return 0;
16553 
16554 	/* We compute branch direction for same SCALAR_VALUE registers in
16555 	 * is_scalar_branch_taken(). For unknown branch directions (e.g., BPF_JSET)
16556 	 * on the same registers, we don't need to adjust the min/max values.
16557 	 */
16558 	if (false_reg1 == false_reg2)
16559 		return 0;
16560 
16561 	/* fallthrough (FALSE) branch */
16562 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
16563 	reg_bounds_sync(false_reg1);
16564 	reg_bounds_sync(false_reg2);
16565 
16566 	/* jump (TRUE) branch */
16567 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
16568 	reg_bounds_sync(true_reg1);
16569 	reg_bounds_sync(true_reg2);
16570 
16571 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
16572 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
16573 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
16574 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
16575 	return err;
16576 }
16577 
16578 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
16579 				 struct bpf_reg_state *reg, u32 id,
16580 				 bool is_null)
16581 {
16582 	if (type_may_be_null(reg->type) && reg->id == id &&
16583 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
16584 		/* Old offset (both fixed and variable parts) should have been
16585 		 * known-zero, because we don't allow pointer arithmetic on
16586 		 * pointers that might be NULL. If we see this happening, don't
16587 		 * convert the register.
16588 		 *
16589 		 * But in some cases, some helpers that return local kptrs
16590 		 * advance offset for the returned pointer. In those cases, it
16591 		 * is fine to expect to see reg->off.
16592 		 */
16593 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
16594 			return;
16595 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
16596 		    WARN_ON_ONCE(reg->off))
16597 			return;
16598 
16599 		if (is_null) {
16600 			reg->type = SCALAR_VALUE;
16601 			/* We don't need id and ref_obj_id from this point
16602 			 * onwards anymore, thus we should better reset it,
16603 			 * so that state pruning has chances to take effect.
16604 			 */
16605 			reg->id = 0;
16606 			reg->ref_obj_id = 0;
16607 
16608 			return;
16609 		}
16610 
16611 		mark_ptr_not_null_reg(reg);
16612 
16613 		if (!reg_may_point_to_spin_lock(reg)) {
16614 			/* For not-NULL ptr, reg->ref_obj_id will be reset
16615 			 * in release_reference().
16616 			 *
16617 			 * reg->id is still used by spin_lock ptr. Other
16618 			 * than spin_lock ptr type, reg->id can be reset.
16619 			 */
16620 			reg->id = 0;
16621 		}
16622 	}
16623 }
16624 
16625 /* The logic is similar to find_good_pkt_pointers(), both could eventually
16626  * be folded together at some point.
16627  */
16628 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
16629 				  bool is_null)
16630 {
16631 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
16632 	struct bpf_reg_state *regs = state->regs, *reg;
16633 	u32 ref_obj_id = regs[regno].ref_obj_id;
16634 	u32 id = regs[regno].id;
16635 
16636 	if (ref_obj_id && ref_obj_id == id && is_null)
16637 		/* regs[regno] is in the " == NULL" branch.
16638 		 * No one could have freed the reference state before
16639 		 * doing the NULL check.
16640 		 */
16641 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
16642 
16643 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16644 		mark_ptr_or_null_reg(state, reg, id, is_null);
16645 	}));
16646 }
16647 
16648 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
16649 				   struct bpf_reg_state *dst_reg,
16650 				   struct bpf_reg_state *src_reg,
16651 				   struct bpf_verifier_state *this_branch,
16652 				   struct bpf_verifier_state *other_branch)
16653 {
16654 	if (BPF_SRC(insn->code) != BPF_X)
16655 		return false;
16656 
16657 	/* Pointers are always 64-bit. */
16658 	if (BPF_CLASS(insn->code) == BPF_JMP32)
16659 		return false;
16660 
16661 	switch (BPF_OP(insn->code)) {
16662 	case BPF_JGT:
16663 		if ((dst_reg->type == PTR_TO_PACKET &&
16664 		     src_reg->type == PTR_TO_PACKET_END) ||
16665 		    (dst_reg->type == PTR_TO_PACKET_META &&
16666 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16667 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
16668 			find_good_pkt_pointers(this_branch, dst_reg,
16669 					       dst_reg->type, false);
16670 			mark_pkt_end(other_branch, insn->dst_reg, true);
16671 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16672 			    src_reg->type == PTR_TO_PACKET) ||
16673 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16674 			    src_reg->type == PTR_TO_PACKET_META)) {
16675 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
16676 			find_good_pkt_pointers(other_branch, src_reg,
16677 					       src_reg->type, true);
16678 			mark_pkt_end(this_branch, insn->src_reg, false);
16679 		} else {
16680 			return false;
16681 		}
16682 		break;
16683 	case BPF_JLT:
16684 		if ((dst_reg->type == PTR_TO_PACKET &&
16685 		     src_reg->type == PTR_TO_PACKET_END) ||
16686 		    (dst_reg->type == PTR_TO_PACKET_META &&
16687 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16688 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
16689 			find_good_pkt_pointers(other_branch, dst_reg,
16690 					       dst_reg->type, true);
16691 			mark_pkt_end(this_branch, insn->dst_reg, false);
16692 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16693 			    src_reg->type == PTR_TO_PACKET) ||
16694 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16695 			    src_reg->type == PTR_TO_PACKET_META)) {
16696 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
16697 			find_good_pkt_pointers(this_branch, src_reg,
16698 					       src_reg->type, false);
16699 			mark_pkt_end(other_branch, insn->src_reg, true);
16700 		} else {
16701 			return false;
16702 		}
16703 		break;
16704 	case BPF_JGE:
16705 		if ((dst_reg->type == PTR_TO_PACKET &&
16706 		     src_reg->type == PTR_TO_PACKET_END) ||
16707 		    (dst_reg->type == PTR_TO_PACKET_META &&
16708 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16709 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
16710 			find_good_pkt_pointers(this_branch, dst_reg,
16711 					       dst_reg->type, true);
16712 			mark_pkt_end(other_branch, insn->dst_reg, false);
16713 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16714 			    src_reg->type == PTR_TO_PACKET) ||
16715 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16716 			    src_reg->type == PTR_TO_PACKET_META)) {
16717 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
16718 			find_good_pkt_pointers(other_branch, src_reg,
16719 					       src_reg->type, false);
16720 			mark_pkt_end(this_branch, insn->src_reg, true);
16721 		} else {
16722 			return false;
16723 		}
16724 		break;
16725 	case BPF_JLE:
16726 		if ((dst_reg->type == PTR_TO_PACKET &&
16727 		     src_reg->type == PTR_TO_PACKET_END) ||
16728 		    (dst_reg->type == PTR_TO_PACKET_META &&
16729 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16730 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
16731 			find_good_pkt_pointers(other_branch, dst_reg,
16732 					       dst_reg->type, false);
16733 			mark_pkt_end(this_branch, insn->dst_reg, true);
16734 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16735 			    src_reg->type == PTR_TO_PACKET) ||
16736 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16737 			    src_reg->type == PTR_TO_PACKET_META)) {
16738 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
16739 			find_good_pkt_pointers(this_branch, src_reg,
16740 					       src_reg->type, true);
16741 			mark_pkt_end(other_branch, insn->src_reg, false);
16742 		} else {
16743 			return false;
16744 		}
16745 		break;
16746 	default:
16747 		return false;
16748 	}
16749 
16750 	return true;
16751 }
16752 
16753 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
16754 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
16755 {
16756 	struct linked_reg *e;
16757 
16758 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
16759 		return;
16760 
16761 	e = linked_regs_push(reg_set);
16762 	if (e) {
16763 		e->frameno = frameno;
16764 		e->is_reg = is_reg;
16765 		e->regno = spi_or_reg;
16766 	} else {
16767 		reg->id = 0;
16768 	}
16769 }
16770 
16771 /* For all R being scalar registers or spilled scalar registers
16772  * in verifier state, save R in linked_regs if R->id == id.
16773  * If there are too many Rs sharing same id, reset id for leftover Rs.
16774  */
16775 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
16776 				struct linked_regs *linked_regs)
16777 {
16778 	struct bpf_func_state *func;
16779 	struct bpf_reg_state *reg;
16780 	int i, j;
16781 
16782 	id = id & ~BPF_ADD_CONST;
16783 	for (i = vstate->curframe; i >= 0; i--) {
16784 		func = vstate->frame[i];
16785 		for (j = 0; j < BPF_REG_FP; j++) {
16786 			reg = &func->regs[j];
16787 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
16788 		}
16789 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
16790 			if (!is_spilled_reg(&func->stack[j]))
16791 				continue;
16792 			reg = &func->stack[j].spilled_ptr;
16793 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
16794 		}
16795 	}
16796 }
16797 
16798 /* For all R in linked_regs, copy known_reg range into R
16799  * if R->id == known_reg->id.
16800  */
16801 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
16802 			     struct linked_regs *linked_regs)
16803 {
16804 	struct bpf_reg_state fake_reg;
16805 	struct bpf_reg_state *reg;
16806 	struct linked_reg *e;
16807 	int i;
16808 
16809 	for (i = 0; i < linked_regs->cnt; ++i) {
16810 		e = &linked_regs->entries[i];
16811 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
16812 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
16813 		if (reg->type != SCALAR_VALUE || reg == known_reg)
16814 			continue;
16815 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
16816 			continue;
16817 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
16818 		    reg->off == known_reg->off) {
16819 			s32 saved_subreg_def = reg->subreg_def;
16820 
16821 			copy_register_state(reg, known_reg);
16822 			reg->subreg_def = saved_subreg_def;
16823 		} else {
16824 			s32 saved_subreg_def = reg->subreg_def;
16825 			s32 saved_off = reg->off;
16826 
16827 			fake_reg.type = SCALAR_VALUE;
16828 			__mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
16829 
16830 			/* reg = known_reg; reg += delta */
16831 			copy_register_state(reg, known_reg);
16832 			/*
16833 			 * Must preserve off, id and add_const flag,
16834 			 * otherwise another sync_linked_regs() will be incorrect.
16835 			 */
16836 			reg->off = saved_off;
16837 			reg->subreg_def = saved_subreg_def;
16838 
16839 			scalar32_min_max_add(reg, &fake_reg);
16840 			scalar_min_max_add(reg, &fake_reg);
16841 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
16842 		}
16843 	}
16844 }
16845 
16846 static int check_cond_jmp_op(struct bpf_verifier_env *env,
16847 			     struct bpf_insn *insn, int *insn_idx)
16848 {
16849 	struct bpf_verifier_state *this_branch = env->cur_state;
16850 	struct bpf_verifier_state *other_branch;
16851 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
16852 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
16853 	struct bpf_reg_state *eq_branch_regs;
16854 	struct linked_regs linked_regs = {};
16855 	u8 opcode = BPF_OP(insn->code);
16856 	int insn_flags = 0;
16857 	bool is_jmp32;
16858 	int pred = -1;
16859 	int err;
16860 
16861 	/* Only conditional jumps are expected to reach here. */
16862 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
16863 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
16864 		return -EINVAL;
16865 	}
16866 
16867 	if (opcode == BPF_JCOND) {
16868 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
16869 		int idx = *insn_idx;
16870 
16871 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
16872 		    insn->src_reg != BPF_MAY_GOTO ||
16873 		    insn->dst_reg || insn->imm) {
16874 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
16875 			return -EINVAL;
16876 		}
16877 		prev_st = find_prev_entry(env, cur_st->parent, idx);
16878 
16879 		/* branch out 'fallthrough' insn as a new state to explore */
16880 		queued_st = push_stack(env, idx + 1, idx, false);
16881 		if (IS_ERR(queued_st))
16882 			return PTR_ERR(queued_st);
16883 
16884 		queued_st->may_goto_depth++;
16885 		if (prev_st)
16886 			widen_imprecise_scalars(env, prev_st, queued_st);
16887 		*insn_idx += insn->off;
16888 		return 0;
16889 	}
16890 
16891 	/* check src2 operand */
16892 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16893 	if (err)
16894 		return err;
16895 
16896 	dst_reg = &regs[insn->dst_reg];
16897 	if (BPF_SRC(insn->code) == BPF_X) {
16898 		if (insn->imm != 0) {
16899 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16900 			return -EINVAL;
16901 		}
16902 
16903 		/* check src1 operand */
16904 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16905 		if (err)
16906 			return err;
16907 
16908 		src_reg = &regs[insn->src_reg];
16909 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
16910 		    is_pointer_value(env, insn->src_reg)) {
16911 			verbose(env, "R%d pointer comparison prohibited\n",
16912 				insn->src_reg);
16913 			return -EACCES;
16914 		}
16915 
16916 		if (src_reg->type == PTR_TO_STACK)
16917 			insn_flags |= INSN_F_SRC_REG_STACK;
16918 		if (dst_reg->type == PTR_TO_STACK)
16919 			insn_flags |= INSN_F_DST_REG_STACK;
16920 	} else {
16921 		if (insn->src_reg != BPF_REG_0) {
16922 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16923 			return -EINVAL;
16924 		}
16925 		src_reg = &env->fake_reg[0];
16926 		memset(src_reg, 0, sizeof(*src_reg));
16927 		src_reg->type = SCALAR_VALUE;
16928 		__mark_reg_known(src_reg, insn->imm);
16929 
16930 		if (dst_reg->type == PTR_TO_STACK)
16931 			insn_flags |= INSN_F_DST_REG_STACK;
16932 	}
16933 
16934 	if (insn_flags) {
16935 		err = push_jmp_history(env, this_branch, insn_flags, 0);
16936 		if (err)
16937 			return err;
16938 	}
16939 
16940 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
16941 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
16942 	if (pred >= 0) {
16943 		/* If we get here with a dst_reg pointer type it is because
16944 		 * above is_branch_taken() special cased the 0 comparison.
16945 		 */
16946 		if (!__is_pointer_value(false, dst_reg))
16947 			err = mark_chain_precision(env, insn->dst_reg);
16948 		if (BPF_SRC(insn->code) == BPF_X && !err &&
16949 		    !__is_pointer_value(false, src_reg))
16950 			err = mark_chain_precision(env, insn->src_reg);
16951 		if (err)
16952 			return err;
16953 	}
16954 
16955 	if (pred == 1) {
16956 		/* Only follow the goto, ignore fall-through. If needed, push
16957 		 * the fall-through branch for simulation under speculative
16958 		 * execution.
16959 		 */
16960 		if (!env->bypass_spec_v1) {
16961 			err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx);
16962 			if (err < 0)
16963 				return err;
16964 		}
16965 		if (env->log.level & BPF_LOG_LEVEL)
16966 			print_insn_state(env, this_branch, this_branch->curframe);
16967 		*insn_idx += insn->off;
16968 		return 0;
16969 	} else if (pred == 0) {
16970 		/* Only follow the fall-through branch, since that's where the
16971 		 * program will go. If needed, push the goto branch for
16972 		 * simulation under speculative execution.
16973 		 */
16974 		if (!env->bypass_spec_v1) {
16975 			err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1,
16976 							*insn_idx);
16977 			if (err < 0)
16978 				return err;
16979 		}
16980 		if (env->log.level & BPF_LOG_LEVEL)
16981 			print_insn_state(env, this_branch, this_branch->curframe);
16982 		return 0;
16983 	}
16984 
16985 	/* Push scalar registers sharing same ID to jump history,
16986 	 * do this before creating 'other_branch', so that both
16987 	 * 'this_branch' and 'other_branch' share this history
16988 	 * if parent state is created.
16989 	 */
16990 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
16991 		collect_linked_regs(this_branch, src_reg->id, &linked_regs);
16992 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
16993 		collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
16994 	if (linked_regs.cnt > 1) {
16995 		err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
16996 		if (err)
16997 			return err;
16998 	}
16999 
17000 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
17001 	if (IS_ERR(other_branch))
17002 		return PTR_ERR(other_branch);
17003 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17004 
17005 	if (BPF_SRC(insn->code) == BPF_X) {
17006 		err = reg_set_min_max(env,
17007 				      &other_branch_regs[insn->dst_reg],
17008 				      &other_branch_regs[insn->src_reg],
17009 				      dst_reg, src_reg, opcode, is_jmp32);
17010 	} else /* BPF_SRC(insn->code) == BPF_K */ {
17011 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
17012 		 * so that these are two different memory locations. The
17013 		 * src_reg is not used beyond here in context of K.
17014 		 */
17015 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
17016 		       sizeof(env->fake_reg[0]));
17017 		err = reg_set_min_max(env,
17018 				      &other_branch_regs[insn->dst_reg],
17019 				      &env->fake_reg[0],
17020 				      dst_reg, &env->fake_reg[1],
17021 				      opcode, is_jmp32);
17022 	}
17023 	if (err)
17024 		return err;
17025 
17026 	if (BPF_SRC(insn->code) == BPF_X &&
17027 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
17028 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
17029 		sync_linked_regs(this_branch, src_reg, &linked_regs);
17030 		sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
17031 	}
17032 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
17033 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
17034 		sync_linked_regs(this_branch, dst_reg, &linked_regs);
17035 		sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
17036 	}
17037 
17038 	/* if one pointer register is compared to another pointer
17039 	 * register check if PTR_MAYBE_NULL could be lifted.
17040 	 * E.g. register A - maybe null
17041 	 *      register B - not null
17042 	 * for JNE A, B, ... - A is not null in the false branch;
17043 	 * for JEQ A, B, ... - A is not null in the true branch.
17044 	 *
17045 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
17046 	 * not need to be null checked by the BPF program, i.e.,
17047 	 * could be null even without PTR_MAYBE_NULL marking, so
17048 	 * only propagate nullness when neither reg is that type.
17049 	 */
17050 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
17051 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
17052 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
17053 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
17054 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
17055 		eq_branch_regs = NULL;
17056 		switch (opcode) {
17057 		case BPF_JEQ:
17058 			eq_branch_regs = other_branch_regs;
17059 			break;
17060 		case BPF_JNE:
17061 			eq_branch_regs = regs;
17062 			break;
17063 		default:
17064 			/* do nothing */
17065 			break;
17066 		}
17067 		if (eq_branch_regs) {
17068 			if (type_may_be_null(src_reg->type))
17069 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
17070 			else
17071 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
17072 		}
17073 	}
17074 
17075 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
17076 	 * NOTE: these optimizations below are related with pointer comparison
17077 	 *       which will never be JMP32.
17078 	 */
17079 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
17080 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
17081 	    type_may_be_null(dst_reg->type)) {
17082 		/* Mark all identical registers in each branch as either
17083 		 * safe or unknown depending R == 0 or R != 0 conditional.
17084 		 */
17085 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
17086 				      opcode == BPF_JNE);
17087 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
17088 				      opcode == BPF_JEQ);
17089 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
17090 					   this_branch, other_branch) &&
17091 		   is_pointer_value(env, insn->dst_reg)) {
17092 		verbose(env, "R%d pointer comparison prohibited\n",
17093 			insn->dst_reg);
17094 		return -EACCES;
17095 	}
17096 	if (env->log.level & BPF_LOG_LEVEL)
17097 		print_insn_state(env, this_branch, this_branch->curframe);
17098 	return 0;
17099 }
17100 
17101 /* verify BPF_LD_IMM64 instruction */
17102 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17103 {
17104 	struct bpf_insn_aux_data *aux = cur_aux(env);
17105 	struct bpf_reg_state *regs = cur_regs(env);
17106 	struct bpf_reg_state *dst_reg;
17107 	struct bpf_map *map;
17108 	int err;
17109 
17110 	if (BPF_SIZE(insn->code) != BPF_DW) {
17111 		verbose(env, "invalid BPF_LD_IMM insn\n");
17112 		return -EINVAL;
17113 	}
17114 	if (insn->off != 0) {
17115 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17116 		return -EINVAL;
17117 	}
17118 
17119 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
17120 	if (err)
17121 		return err;
17122 
17123 	dst_reg = &regs[insn->dst_reg];
17124 	if (insn->src_reg == 0) {
17125 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
17126 
17127 		dst_reg->type = SCALAR_VALUE;
17128 		__mark_reg_known(&regs[insn->dst_reg], imm);
17129 		return 0;
17130 	}
17131 
17132 	/* All special src_reg cases are listed below. From this point onwards
17133 	 * we either succeed and assign a corresponding dst_reg->type after
17134 	 * zeroing the offset, or fail and reject the program.
17135 	 */
17136 	mark_reg_known_zero(env, regs, insn->dst_reg);
17137 
17138 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
17139 		dst_reg->type = aux->btf_var.reg_type;
17140 		switch (base_type(dst_reg->type)) {
17141 		case PTR_TO_MEM:
17142 			dst_reg->mem_size = aux->btf_var.mem_size;
17143 			break;
17144 		case PTR_TO_BTF_ID:
17145 			dst_reg->btf = aux->btf_var.btf;
17146 			dst_reg->btf_id = aux->btf_var.btf_id;
17147 			break;
17148 		default:
17149 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
17150 			return -EFAULT;
17151 		}
17152 		return 0;
17153 	}
17154 
17155 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
17156 		struct bpf_prog_aux *aux = env->prog->aux;
17157 		u32 subprogno = find_subprog(env,
17158 					     env->insn_idx + insn->imm + 1);
17159 
17160 		if (!aux->func_info) {
17161 			verbose(env, "missing btf func_info\n");
17162 			return -EINVAL;
17163 		}
17164 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
17165 			verbose(env, "callback function not static\n");
17166 			return -EINVAL;
17167 		}
17168 
17169 		dst_reg->type = PTR_TO_FUNC;
17170 		dst_reg->subprogno = subprogno;
17171 		return 0;
17172 	}
17173 
17174 	map = env->used_maps[aux->map_index];
17175 	dst_reg->map_ptr = map;
17176 
17177 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
17178 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
17179 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
17180 			__mark_reg_unknown(env, dst_reg);
17181 			return 0;
17182 		}
17183 		dst_reg->type = PTR_TO_MAP_VALUE;
17184 		dst_reg->off = aux->map_off;
17185 		WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY &&
17186 			     map->max_entries != 1);
17187 		/* We want reg->id to be same (0) as map_value is not distinct */
17188 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
17189 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
17190 		dst_reg->type = CONST_PTR_TO_MAP;
17191 	} else {
17192 		verifier_bug(env, "unexpected src reg value for ldimm64");
17193 		return -EFAULT;
17194 	}
17195 
17196 	return 0;
17197 }
17198 
17199 static bool may_access_skb(enum bpf_prog_type type)
17200 {
17201 	switch (type) {
17202 	case BPF_PROG_TYPE_SOCKET_FILTER:
17203 	case BPF_PROG_TYPE_SCHED_CLS:
17204 	case BPF_PROG_TYPE_SCHED_ACT:
17205 		return true;
17206 	default:
17207 		return false;
17208 	}
17209 }
17210 
17211 /* verify safety of LD_ABS|LD_IND instructions:
17212  * - they can only appear in the programs where ctx == skb
17213  * - since they are wrappers of function calls, they scratch R1-R5 registers,
17214  *   preserve R6-R9, and store return value into R0
17215  *
17216  * Implicit input:
17217  *   ctx == skb == R6 == CTX
17218  *
17219  * Explicit input:
17220  *   SRC == any register
17221  *   IMM == 32-bit immediate
17222  *
17223  * Output:
17224  *   R0 - 8/16/32-bit skb data converted to cpu endianness
17225  */
17226 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
17227 {
17228 	struct bpf_reg_state *regs = cur_regs(env);
17229 	static const int ctx_reg = BPF_REG_6;
17230 	u8 mode = BPF_MODE(insn->code);
17231 	int i, err;
17232 
17233 	if (!may_access_skb(resolve_prog_type(env->prog))) {
17234 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
17235 		return -EINVAL;
17236 	}
17237 
17238 	if (!env->ops->gen_ld_abs) {
17239 		verifier_bug(env, "gen_ld_abs is null");
17240 		return -EFAULT;
17241 	}
17242 
17243 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
17244 	    BPF_SIZE(insn->code) == BPF_DW ||
17245 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
17246 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
17247 		return -EINVAL;
17248 	}
17249 
17250 	/* check whether implicit source operand (register R6) is readable */
17251 	err = check_reg_arg(env, ctx_reg, SRC_OP);
17252 	if (err)
17253 		return err;
17254 
17255 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
17256 	 * gen_ld_abs() may terminate the program at runtime, leading to
17257 	 * reference leak.
17258 	 */
17259 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
17260 	if (err)
17261 		return err;
17262 
17263 	if (regs[ctx_reg].type != PTR_TO_CTX) {
17264 		verbose(env,
17265 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
17266 		return -EINVAL;
17267 	}
17268 
17269 	if (mode == BPF_IND) {
17270 		/* check explicit source operand */
17271 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
17272 		if (err)
17273 			return err;
17274 	}
17275 
17276 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
17277 	if (err < 0)
17278 		return err;
17279 
17280 	/* reset caller saved regs to unreadable */
17281 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
17282 		mark_reg_not_init(env, regs, caller_saved[i]);
17283 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
17284 	}
17285 
17286 	/* mark destination R0 register as readable, since it contains
17287 	 * the value fetched from the packet.
17288 	 * Already marked as written above.
17289 	 */
17290 	mark_reg_unknown(env, regs, BPF_REG_0);
17291 	/* ld_abs load up to 32-bit skb data. */
17292 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
17293 	return 0;
17294 }
17295 
17296 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
17297 {
17298 	const char *exit_ctx = "At program exit";
17299 	struct tnum enforce_attach_type_range = tnum_unknown;
17300 	const struct bpf_prog *prog = env->prog;
17301 	struct bpf_reg_state *reg = reg_state(env, regno);
17302 	struct bpf_retval_range range = retval_range(0, 1);
17303 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17304 	int err;
17305 	struct bpf_func_state *frame = env->cur_state->frame[0];
17306 	const bool is_subprog = frame->subprogno;
17307 	bool return_32bit = false;
17308 	const struct btf_type *reg_type, *ret_type = NULL;
17309 
17310 	/* LSM and struct_ops func-ptr's return type could be "void" */
17311 	if (!is_subprog || frame->in_exception_callback_fn) {
17312 		switch (prog_type) {
17313 		case BPF_PROG_TYPE_LSM:
17314 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
17315 				/* See below, can be 0 or 0-1 depending on hook. */
17316 				break;
17317 			if (!prog->aux->attach_func_proto->type)
17318 				return 0;
17319 			break;
17320 		case BPF_PROG_TYPE_STRUCT_OPS:
17321 			if (!prog->aux->attach_func_proto->type)
17322 				return 0;
17323 
17324 			if (frame->in_exception_callback_fn)
17325 				break;
17326 
17327 			/* Allow a struct_ops program to return a referenced kptr if it
17328 			 * matches the operator's return type and is in its unmodified
17329 			 * form. A scalar zero (i.e., a null pointer) is also allowed.
17330 			 */
17331 			reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
17332 			ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
17333 							prog->aux->attach_func_proto->type,
17334 							NULL);
17335 			if (ret_type && ret_type == reg_type && reg->ref_obj_id)
17336 				return __check_ptr_off_reg(env, reg, regno, false);
17337 			break;
17338 		default:
17339 			break;
17340 		}
17341 	}
17342 
17343 	/* eBPF calling convention is such that R0 is used
17344 	 * to return the value from eBPF program.
17345 	 * Make sure that it's readable at this time
17346 	 * of bpf_exit, which means that program wrote
17347 	 * something into it earlier
17348 	 */
17349 	err = check_reg_arg(env, regno, SRC_OP);
17350 	if (err)
17351 		return err;
17352 
17353 	if (is_pointer_value(env, regno)) {
17354 		verbose(env, "R%d leaks addr as return value\n", regno);
17355 		return -EACCES;
17356 	}
17357 
17358 	if (frame->in_async_callback_fn) {
17359 		exit_ctx = "At async callback return";
17360 		range = frame->callback_ret_range;
17361 		goto enforce_retval;
17362 	}
17363 
17364 	if (is_subprog && !frame->in_exception_callback_fn) {
17365 		if (reg->type != SCALAR_VALUE) {
17366 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
17367 				regno, reg_type_str(env, reg->type));
17368 			return -EINVAL;
17369 		}
17370 		return 0;
17371 	}
17372 
17373 	switch (prog_type) {
17374 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
17375 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
17376 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
17377 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
17378 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
17379 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
17380 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
17381 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
17382 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
17383 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
17384 			range = retval_range(1, 1);
17385 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
17386 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
17387 			range = retval_range(0, 3);
17388 		break;
17389 	case BPF_PROG_TYPE_CGROUP_SKB:
17390 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
17391 			range = retval_range(0, 3);
17392 			enforce_attach_type_range = tnum_range(2, 3);
17393 		}
17394 		break;
17395 	case BPF_PROG_TYPE_CGROUP_SOCK:
17396 	case BPF_PROG_TYPE_SOCK_OPS:
17397 	case BPF_PROG_TYPE_CGROUP_DEVICE:
17398 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
17399 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
17400 		break;
17401 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17402 		if (!env->prog->aux->attach_btf_id)
17403 			return 0;
17404 		range = retval_range(0, 0);
17405 		break;
17406 	case BPF_PROG_TYPE_TRACING:
17407 		switch (env->prog->expected_attach_type) {
17408 		case BPF_TRACE_FENTRY:
17409 		case BPF_TRACE_FEXIT:
17410 			range = retval_range(0, 0);
17411 			break;
17412 		case BPF_TRACE_RAW_TP:
17413 		case BPF_MODIFY_RETURN:
17414 			return 0;
17415 		case BPF_TRACE_ITER:
17416 			break;
17417 		default:
17418 			return -ENOTSUPP;
17419 		}
17420 		break;
17421 	case BPF_PROG_TYPE_KPROBE:
17422 		switch (env->prog->expected_attach_type) {
17423 		case BPF_TRACE_KPROBE_SESSION:
17424 		case BPF_TRACE_UPROBE_SESSION:
17425 			range = retval_range(0, 1);
17426 			break;
17427 		default:
17428 			return 0;
17429 		}
17430 		break;
17431 	case BPF_PROG_TYPE_SK_LOOKUP:
17432 		range = retval_range(SK_DROP, SK_PASS);
17433 		break;
17434 
17435 	case BPF_PROG_TYPE_LSM:
17436 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
17437 			/* no range found, any return value is allowed */
17438 			if (!get_func_retval_range(env->prog, &range))
17439 				return 0;
17440 			/* no restricted range, any return value is allowed */
17441 			if (range.minval == S32_MIN && range.maxval == S32_MAX)
17442 				return 0;
17443 			return_32bit = true;
17444 		} else if (!env->prog->aux->attach_func_proto->type) {
17445 			/* Make sure programs that attach to void
17446 			 * hooks don't try to modify return value.
17447 			 */
17448 			range = retval_range(1, 1);
17449 		}
17450 		break;
17451 
17452 	case BPF_PROG_TYPE_NETFILTER:
17453 		range = retval_range(NF_DROP, NF_ACCEPT);
17454 		break;
17455 	case BPF_PROG_TYPE_STRUCT_OPS:
17456 		if (!ret_type)
17457 			return 0;
17458 		range = retval_range(0, 0);
17459 		break;
17460 	case BPF_PROG_TYPE_EXT:
17461 		/* freplace program can return anything as its return value
17462 		 * depends on the to-be-replaced kernel func or bpf program.
17463 		 */
17464 	default:
17465 		return 0;
17466 	}
17467 
17468 enforce_retval:
17469 	if (reg->type != SCALAR_VALUE) {
17470 		verbose(env, "%s the register R%d is not a known value (%s)\n",
17471 			exit_ctx, regno, reg_type_str(env, reg->type));
17472 		return -EINVAL;
17473 	}
17474 
17475 	err = mark_chain_precision(env, regno);
17476 	if (err)
17477 		return err;
17478 
17479 	if (!retval_range_within(range, reg, return_32bit)) {
17480 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
17481 		if (!is_subprog &&
17482 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
17483 		    prog_type == BPF_PROG_TYPE_LSM &&
17484 		    !prog->aux->attach_func_proto->type)
17485 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
17486 		return -EINVAL;
17487 	}
17488 
17489 	if (!tnum_is_unknown(enforce_attach_type_range) &&
17490 	    tnum_in(enforce_attach_type_range, reg->var_off))
17491 		env->prog->enforce_expected_attach_type = 1;
17492 	return 0;
17493 }
17494 
17495 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
17496 {
17497 	struct bpf_subprog_info *subprog;
17498 
17499 	subprog = bpf_find_containing_subprog(env, off);
17500 	subprog->changes_pkt_data = true;
17501 }
17502 
17503 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off)
17504 {
17505 	struct bpf_subprog_info *subprog;
17506 
17507 	subprog = bpf_find_containing_subprog(env, off);
17508 	subprog->might_sleep = true;
17509 }
17510 
17511 /* 't' is an index of a call-site.
17512  * 'w' is a callee entry point.
17513  * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
17514  * Rely on DFS traversal order and absence of recursive calls to guarantee that
17515  * callee's change_pkt_data marks would be correct at that moment.
17516  */
17517 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
17518 {
17519 	struct bpf_subprog_info *caller, *callee;
17520 
17521 	caller = bpf_find_containing_subprog(env, t);
17522 	callee = bpf_find_containing_subprog(env, w);
17523 	caller->changes_pkt_data |= callee->changes_pkt_data;
17524 	caller->might_sleep |= callee->might_sleep;
17525 }
17526 
17527 /* non-recursive DFS pseudo code
17528  * 1  procedure DFS-iterative(G,v):
17529  * 2      label v as discovered
17530  * 3      let S be a stack
17531  * 4      S.push(v)
17532  * 5      while S is not empty
17533  * 6            t <- S.peek()
17534  * 7            if t is what we're looking for:
17535  * 8                return t
17536  * 9            for all edges e in G.adjacentEdges(t) do
17537  * 10               if edge e is already labelled
17538  * 11                   continue with the next edge
17539  * 12               w <- G.adjacentVertex(t,e)
17540  * 13               if vertex w is not discovered and not explored
17541  * 14                   label e as tree-edge
17542  * 15                   label w as discovered
17543  * 16                   S.push(w)
17544  * 17                   continue at 5
17545  * 18               else if vertex w is discovered
17546  * 19                   label e as back-edge
17547  * 20               else
17548  * 21                   // vertex w is explored
17549  * 22                   label e as forward- or cross-edge
17550  * 23           label t as explored
17551  * 24           S.pop()
17552  *
17553  * convention:
17554  * 0x10 - discovered
17555  * 0x11 - discovered and fall-through edge labelled
17556  * 0x12 - discovered and fall-through and branch edges labelled
17557  * 0x20 - explored
17558  */
17559 
17560 enum {
17561 	DISCOVERED = 0x10,
17562 	EXPLORED = 0x20,
17563 	FALLTHROUGH = 1,
17564 	BRANCH = 2,
17565 };
17566 
17567 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
17568 {
17569 	env->insn_aux_data[idx].prune_point = true;
17570 }
17571 
17572 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
17573 {
17574 	return env->insn_aux_data[insn_idx].prune_point;
17575 }
17576 
17577 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
17578 {
17579 	env->insn_aux_data[idx].force_checkpoint = true;
17580 }
17581 
17582 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
17583 {
17584 	return env->insn_aux_data[insn_idx].force_checkpoint;
17585 }
17586 
17587 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
17588 {
17589 	env->insn_aux_data[idx].calls_callback = true;
17590 }
17591 
17592 bool bpf_calls_callback(struct bpf_verifier_env *env, int insn_idx)
17593 {
17594 	return env->insn_aux_data[insn_idx].calls_callback;
17595 }
17596 
17597 enum {
17598 	DONE_EXPLORING = 0,
17599 	KEEP_EXPLORING = 1,
17600 };
17601 
17602 /* t, w, e - match pseudo-code above:
17603  * t - index of current instruction
17604  * w - next instruction
17605  * e - edge
17606  */
17607 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
17608 {
17609 	int *insn_stack = env->cfg.insn_stack;
17610 	int *insn_state = env->cfg.insn_state;
17611 
17612 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
17613 		return DONE_EXPLORING;
17614 
17615 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
17616 		return DONE_EXPLORING;
17617 
17618 	if (w < 0 || w >= env->prog->len) {
17619 		verbose_linfo(env, t, "%d: ", t);
17620 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
17621 		return -EINVAL;
17622 	}
17623 
17624 	if (e == BRANCH) {
17625 		/* mark branch target for state pruning */
17626 		mark_prune_point(env, w);
17627 		mark_jmp_point(env, w);
17628 	}
17629 
17630 	if (insn_state[w] == 0) {
17631 		/* tree-edge */
17632 		insn_state[t] = DISCOVERED | e;
17633 		insn_state[w] = DISCOVERED;
17634 		if (env->cfg.cur_stack >= env->prog->len)
17635 			return -E2BIG;
17636 		insn_stack[env->cfg.cur_stack++] = w;
17637 		return KEEP_EXPLORING;
17638 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
17639 		if (env->bpf_capable)
17640 			return DONE_EXPLORING;
17641 		verbose_linfo(env, t, "%d: ", t);
17642 		verbose_linfo(env, w, "%d: ", w);
17643 		verbose(env, "back-edge from insn %d to %d\n", t, w);
17644 		return -EINVAL;
17645 	} else if (insn_state[w] == EXPLORED) {
17646 		/* forward- or cross-edge */
17647 		insn_state[t] = DISCOVERED | e;
17648 	} else {
17649 		verifier_bug(env, "insn state internal bug");
17650 		return -EFAULT;
17651 	}
17652 	return DONE_EXPLORING;
17653 }
17654 
17655 static int visit_func_call_insn(int t, struct bpf_insn *insns,
17656 				struct bpf_verifier_env *env,
17657 				bool visit_callee)
17658 {
17659 	int ret, insn_sz;
17660 	int w;
17661 
17662 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
17663 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
17664 	if (ret)
17665 		return ret;
17666 
17667 	mark_prune_point(env, t + insn_sz);
17668 	/* when we exit from subprog, we need to record non-linear history */
17669 	mark_jmp_point(env, t + insn_sz);
17670 
17671 	if (visit_callee) {
17672 		w = t + insns[t].imm + 1;
17673 		mark_prune_point(env, t);
17674 		merge_callee_effects(env, t, w);
17675 		ret = push_insn(t, w, BRANCH, env);
17676 	}
17677 	return ret;
17678 }
17679 
17680 /* Bitmask with 1s for all caller saved registers */
17681 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
17682 
17683 /* True if do_misc_fixups() replaces calls to helper number 'imm',
17684  * replacement patch is presumed to follow bpf_fastcall contract
17685  * (see mark_fastcall_pattern_for_call() below).
17686  */
17687 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
17688 {
17689 	switch (imm) {
17690 #ifdef CONFIG_X86_64
17691 	case BPF_FUNC_get_smp_processor_id:
17692 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
17693 #endif
17694 	default:
17695 		return false;
17696 	}
17697 }
17698 
17699 struct call_summary {
17700 	u8 num_params;
17701 	bool is_void;
17702 	bool fastcall;
17703 };
17704 
17705 /* If @call is a kfunc or helper call, fills @cs and returns true,
17706  * otherwise returns false.
17707  */
17708 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
17709 			     struct call_summary *cs)
17710 {
17711 	struct bpf_kfunc_call_arg_meta meta;
17712 	const struct bpf_func_proto *fn;
17713 	int i;
17714 
17715 	if (bpf_helper_call(call)) {
17716 
17717 		if (get_helper_proto(env, call->imm, &fn) < 0)
17718 			/* error would be reported later */
17719 			return false;
17720 		cs->fastcall = fn->allow_fastcall &&
17721 			       (verifier_inlines_helper_call(env, call->imm) ||
17722 				bpf_jit_inlines_helper_call(call->imm));
17723 		cs->is_void = fn->ret_type == RET_VOID;
17724 		cs->num_params = 0;
17725 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
17726 			if (fn->arg_type[i] == ARG_DONTCARE)
17727 				break;
17728 			cs->num_params++;
17729 		}
17730 		return true;
17731 	}
17732 
17733 	if (bpf_pseudo_kfunc_call(call)) {
17734 		int err;
17735 
17736 		err = fetch_kfunc_meta(env, call, &meta, NULL);
17737 		if (err < 0)
17738 			/* error would be reported later */
17739 			return false;
17740 		cs->num_params = btf_type_vlen(meta.func_proto);
17741 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
17742 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
17743 		return true;
17744 	}
17745 
17746 	return false;
17747 }
17748 
17749 /* LLVM define a bpf_fastcall function attribute.
17750  * This attribute means that function scratches only some of
17751  * the caller saved registers defined by ABI.
17752  * For BPF the set of such registers could be defined as follows:
17753  * - R0 is scratched only if function is non-void;
17754  * - R1-R5 are scratched only if corresponding parameter type is defined
17755  *   in the function prototype.
17756  *
17757  * The contract between kernel and clang allows to simultaneously use
17758  * such functions and maintain backwards compatibility with old
17759  * kernels that don't understand bpf_fastcall calls:
17760  *
17761  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
17762  *   registers are not scratched by the call;
17763  *
17764  * - as a post-processing step, clang visits each bpf_fastcall call and adds
17765  *   spill/fill for every live r0-r5;
17766  *
17767  * - stack offsets used for the spill/fill are allocated as lowest
17768  *   stack offsets in whole function and are not used for any other
17769  *   purposes;
17770  *
17771  * - when kernel loads a program, it looks for such patterns
17772  *   (bpf_fastcall function surrounded by spills/fills) and checks if
17773  *   spill/fill stack offsets are used exclusively in fastcall patterns;
17774  *
17775  * - if so, and if verifier or current JIT inlines the call to the
17776  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
17777  *   spill/fill pairs;
17778  *
17779  * - when old kernel loads a program, presence of spill/fill pairs
17780  *   keeps BPF program valid, albeit slightly less efficient.
17781  *
17782  * For example:
17783  *
17784  *   r1 = 1;
17785  *   r2 = 2;
17786  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17787  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
17788  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17789  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
17790  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
17791  *   r0 = r1;                            exit;
17792  *   r0 += r2;
17793  *   exit;
17794  *
17795  * The purpose of mark_fastcall_pattern_for_call is to:
17796  * - look for such patterns;
17797  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
17798  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
17799  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
17800  *   at which bpf_fastcall spill/fill stack slots start;
17801  * - update env->subprog_info[*]->keep_fastcall_stack.
17802  *
17803  * The .fastcall_pattern and .fastcall_stack_off are used by
17804  * check_fastcall_stack_contract() to check if every stack access to
17805  * fastcall spill/fill stack slot originates from spill/fill
17806  * instructions, members of fastcall patterns.
17807  *
17808  * If such condition holds true for a subprogram, fastcall patterns could
17809  * be rewritten by remove_fastcall_spills_fills().
17810  * Otherwise bpf_fastcall patterns are not changed in the subprogram
17811  * (code, presumably, generated by an older clang version).
17812  *
17813  * For example, it is *not* safe to remove spill/fill below:
17814  *
17815  *   r1 = 1;
17816  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17817  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17818  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
17819  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
17820  *   r0 += r1;                           exit;
17821  *   exit;
17822  */
17823 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
17824 					   struct bpf_subprog_info *subprog,
17825 					   int insn_idx, s16 lowest_off)
17826 {
17827 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
17828 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
17829 	u32 clobbered_regs_mask;
17830 	struct call_summary cs;
17831 	u32 expected_regs_mask;
17832 	s16 off;
17833 	int i;
17834 
17835 	if (!get_call_summary(env, call, &cs))
17836 		return;
17837 
17838 	/* A bitmask specifying which caller saved registers are clobbered
17839 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
17840 	 * bpf_fastcall contract:
17841 	 * - includes R0 if function is non-void;
17842 	 * - includes R1-R5 if corresponding parameter has is described
17843 	 *   in the function prototype.
17844 	 */
17845 	clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
17846 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
17847 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
17848 
17849 	/* match pairs of form:
17850 	 *
17851 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
17852 	 * ...
17853 	 * call %[to_be_inlined]
17854 	 * ...
17855 	 * rX = *(u64 *)(r10 - Y)
17856 	 */
17857 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
17858 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
17859 			break;
17860 		stx = &insns[insn_idx - i];
17861 		ldx = &insns[insn_idx + i];
17862 		/* must be a stack spill/fill pair */
17863 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17864 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
17865 		    stx->dst_reg != BPF_REG_10 ||
17866 		    ldx->src_reg != BPF_REG_10)
17867 			break;
17868 		/* must be a spill/fill for the same reg */
17869 		if (stx->src_reg != ldx->dst_reg)
17870 			break;
17871 		/* must be one of the previously unseen registers */
17872 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
17873 			break;
17874 		/* must be a spill/fill for the same expected offset,
17875 		 * no need to check offset alignment, BPF_DW stack access
17876 		 * is always 8-byte aligned.
17877 		 */
17878 		if (stx->off != off || ldx->off != off)
17879 			break;
17880 		expected_regs_mask &= ~BIT(stx->src_reg);
17881 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
17882 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
17883 	}
17884 	if (i == 1)
17885 		return;
17886 
17887 	/* Conditionally set 'fastcall_spills_num' to allow forward
17888 	 * compatibility when more helper functions are marked as
17889 	 * bpf_fastcall at compile time than current kernel supports, e.g:
17890 	 *
17891 	 *   1: *(u64 *)(r10 - 8) = r1
17892 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
17893 	 *   3: r1 = *(u64 *)(r10 - 8)
17894 	 *   4: *(u64 *)(r10 - 8) = r1
17895 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
17896 	 *   6: r1 = *(u64 *)(r10 - 8)
17897 	 *
17898 	 * There is no need to block bpf_fastcall rewrite for such program.
17899 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
17900 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
17901 	 * does not remove spill/fill pair {4,6}.
17902 	 */
17903 	if (cs.fastcall)
17904 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
17905 	else
17906 		subprog->keep_fastcall_stack = 1;
17907 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
17908 }
17909 
17910 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
17911 {
17912 	struct bpf_subprog_info *subprog = env->subprog_info;
17913 	struct bpf_insn *insn;
17914 	s16 lowest_off;
17915 	int s, i;
17916 
17917 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
17918 		/* find lowest stack spill offset used in this subprog */
17919 		lowest_off = 0;
17920 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17921 			insn = env->prog->insnsi + i;
17922 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17923 			    insn->dst_reg != BPF_REG_10)
17924 				continue;
17925 			lowest_off = min(lowest_off, insn->off);
17926 		}
17927 		/* use this offset to find fastcall patterns */
17928 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17929 			insn = env->prog->insnsi + i;
17930 			if (insn->code != (BPF_JMP | BPF_CALL))
17931 				continue;
17932 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
17933 		}
17934 	}
17935 	return 0;
17936 }
17937 
17938 static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem)
17939 {
17940 	size_t new_size = sizeof(struct bpf_iarray) + n_elem * sizeof(old->items[0]);
17941 	struct bpf_iarray *new;
17942 
17943 	new = kvrealloc(old, new_size, GFP_KERNEL_ACCOUNT);
17944 	if (!new) {
17945 		/* this is what callers always want, so simplify the call site */
17946 		kvfree(old);
17947 		return NULL;
17948 	}
17949 
17950 	new->cnt = n_elem;
17951 	return new;
17952 }
17953 
17954 static int copy_insn_array(struct bpf_map *map, u32 start, u32 end, u32 *items)
17955 {
17956 	struct bpf_insn_array_value *value;
17957 	u32 i;
17958 
17959 	for (i = start; i <= end; i++) {
17960 		value = map->ops->map_lookup_elem(map, &i);
17961 		/*
17962 		 * map_lookup_elem of an array map will never return an error,
17963 		 * but not checking it makes some static analysers to worry
17964 		 */
17965 		if (IS_ERR(value))
17966 			return PTR_ERR(value);
17967 		else if (!value)
17968 			return -EINVAL;
17969 		items[i - start] = value->xlated_off;
17970 	}
17971 	return 0;
17972 }
17973 
17974 static int cmp_ptr_to_u32(const void *a, const void *b)
17975 {
17976 	return *(u32 *)a - *(u32 *)b;
17977 }
17978 
17979 static int sort_insn_array_uniq(u32 *items, int cnt)
17980 {
17981 	int unique = 1;
17982 	int i;
17983 
17984 	sort(items, cnt, sizeof(items[0]), cmp_ptr_to_u32, NULL);
17985 
17986 	for (i = 1; i < cnt; i++)
17987 		if (items[i] != items[unique - 1])
17988 			items[unique++] = items[i];
17989 
17990 	return unique;
17991 }
17992 
17993 /*
17994  * sort_unique({map[start], ..., map[end]}) into off
17995  */
17996 static int copy_insn_array_uniq(struct bpf_map *map, u32 start, u32 end, u32 *off)
17997 {
17998 	u32 n = end - start + 1;
17999 	int err;
18000 
18001 	err = copy_insn_array(map, start, end, off);
18002 	if (err)
18003 		return err;
18004 
18005 	return sort_insn_array_uniq(off, n);
18006 }
18007 
18008 /*
18009  * Copy all unique offsets from the map
18010  */
18011 static struct bpf_iarray *jt_from_map(struct bpf_map *map)
18012 {
18013 	struct bpf_iarray *jt;
18014 	int err;
18015 	int n;
18016 
18017 	jt = iarray_realloc(NULL, map->max_entries);
18018 	if (!jt)
18019 		return ERR_PTR(-ENOMEM);
18020 
18021 	n = copy_insn_array_uniq(map, 0, map->max_entries - 1, jt->items);
18022 	if (n < 0) {
18023 		err = n;
18024 		goto err_free;
18025 	}
18026 	if (n == 0) {
18027 		err = -EINVAL;
18028 		goto err_free;
18029 	}
18030 	jt->cnt = n;
18031 	return jt;
18032 
18033 err_free:
18034 	kvfree(jt);
18035 	return ERR_PTR(err);
18036 }
18037 
18038 /*
18039  * Find and collect all maps which fit in the subprog. Return the result as one
18040  * combined jump table in jt->items (allocated with kvcalloc)
18041  */
18042 static struct bpf_iarray *jt_from_subprog(struct bpf_verifier_env *env,
18043 					  int subprog_start, int subprog_end)
18044 {
18045 	struct bpf_iarray *jt = NULL;
18046 	struct bpf_map *map;
18047 	struct bpf_iarray *jt_cur;
18048 	int i;
18049 
18050 	for (i = 0; i < env->insn_array_map_cnt; i++) {
18051 		/*
18052 		 * TODO (when needed): collect only jump tables, not static keys
18053 		 * or maps for indirect calls
18054 		 */
18055 		map = env->insn_array_maps[i];
18056 
18057 		jt_cur = jt_from_map(map);
18058 		if (IS_ERR(jt_cur)) {
18059 			kvfree(jt);
18060 			return jt_cur;
18061 		}
18062 
18063 		/*
18064 		 * This is enough to check one element. The full table is
18065 		 * checked to fit inside the subprog later in create_jt()
18066 		 */
18067 		if (jt_cur->items[0] >= subprog_start && jt_cur->items[0] < subprog_end) {
18068 			u32 old_cnt = jt ? jt->cnt : 0;
18069 			jt = iarray_realloc(jt, old_cnt + jt_cur->cnt);
18070 			if (!jt) {
18071 				kvfree(jt_cur);
18072 				return ERR_PTR(-ENOMEM);
18073 			}
18074 			memcpy(jt->items + old_cnt, jt_cur->items, jt_cur->cnt << 2);
18075 		}
18076 
18077 		kvfree(jt_cur);
18078 	}
18079 
18080 	if (!jt) {
18081 		verbose(env, "no jump tables found for subprog starting at %u\n", subprog_start);
18082 		return ERR_PTR(-EINVAL);
18083 	}
18084 
18085 	jt->cnt = sort_insn_array_uniq(jt->items, jt->cnt);
18086 	return jt;
18087 }
18088 
18089 static struct bpf_iarray *
18090 create_jt(int t, struct bpf_verifier_env *env)
18091 {
18092 	static struct bpf_subprog_info *subprog;
18093 	int subprog_start, subprog_end;
18094 	struct bpf_iarray *jt;
18095 	int i;
18096 
18097 	subprog = bpf_find_containing_subprog(env, t);
18098 	subprog_start = subprog->start;
18099 	subprog_end = (subprog + 1)->start;
18100 	jt = jt_from_subprog(env, subprog_start, subprog_end);
18101 	if (IS_ERR(jt))
18102 		return jt;
18103 
18104 	/* Check that the every element of the jump table fits within the given subprogram */
18105 	for (i = 0; i < jt->cnt; i++) {
18106 		if (jt->items[i] < subprog_start || jt->items[i] >= subprog_end) {
18107 			verbose(env, "jump table for insn %d points outside of the subprog [%u,%u]\n",
18108 					t, subprog_start, subprog_end);
18109 			kvfree(jt);
18110 			return ERR_PTR(-EINVAL);
18111 		}
18112 	}
18113 
18114 	return jt;
18115 }
18116 
18117 /* "conditional jump with N edges" */
18118 static int visit_gotox_insn(int t, struct bpf_verifier_env *env)
18119 {
18120 	int *insn_stack = env->cfg.insn_stack;
18121 	int *insn_state = env->cfg.insn_state;
18122 	bool keep_exploring = false;
18123 	struct bpf_iarray *jt;
18124 	int i, w;
18125 
18126 	jt = env->insn_aux_data[t].jt;
18127 	if (!jt) {
18128 		jt = create_jt(t, env);
18129 		if (IS_ERR(jt))
18130 			return PTR_ERR(jt);
18131 
18132 		env->insn_aux_data[t].jt = jt;
18133 	}
18134 
18135 	mark_prune_point(env, t);
18136 	for (i = 0; i < jt->cnt; i++) {
18137 		w = jt->items[i];
18138 		if (w < 0 || w >= env->prog->len) {
18139 			verbose(env, "indirect jump out of range from insn %d to %d\n", t, w);
18140 			return -EINVAL;
18141 		}
18142 
18143 		mark_jmp_point(env, w);
18144 
18145 		/* EXPLORED || DISCOVERED */
18146 		if (insn_state[w])
18147 			continue;
18148 
18149 		if (env->cfg.cur_stack >= env->prog->len)
18150 			return -E2BIG;
18151 
18152 		insn_stack[env->cfg.cur_stack++] = w;
18153 		insn_state[w] |= DISCOVERED;
18154 		keep_exploring = true;
18155 	}
18156 
18157 	return keep_exploring ? KEEP_EXPLORING : DONE_EXPLORING;
18158 }
18159 
18160 static int visit_tailcall_insn(struct bpf_verifier_env *env, int t)
18161 {
18162 	static struct bpf_subprog_info *subprog;
18163 	struct bpf_iarray *jt;
18164 
18165 	if (env->insn_aux_data[t].jt)
18166 		return 0;
18167 
18168 	jt = iarray_realloc(NULL, 2);
18169 	if (!jt)
18170 		return -ENOMEM;
18171 
18172 	subprog = bpf_find_containing_subprog(env, t);
18173 	jt->items[0] = t + 1;
18174 	jt->items[1] = subprog->exit_idx;
18175 	env->insn_aux_data[t].jt = jt;
18176 	return 0;
18177 }
18178 
18179 /* Visits the instruction at index t and returns one of the following:
18180  *  < 0 - an error occurred
18181  *  DONE_EXPLORING - the instruction was fully explored
18182  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
18183  */
18184 static int visit_insn(int t, struct bpf_verifier_env *env)
18185 {
18186 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
18187 	int ret, off, insn_sz;
18188 
18189 	if (bpf_pseudo_func(insn))
18190 		return visit_func_call_insn(t, insns, env, true);
18191 
18192 	/* All non-branch instructions have a single fall-through edge. */
18193 	if (BPF_CLASS(insn->code) != BPF_JMP &&
18194 	    BPF_CLASS(insn->code) != BPF_JMP32) {
18195 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
18196 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
18197 	}
18198 
18199 	switch (BPF_OP(insn->code)) {
18200 	case BPF_EXIT:
18201 		return DONE_EXPLORING;
18202 
18203 	case BPF_CALL:
18204 		if (is_async_callback_calling_insn(insn))
18205 			/* Mark this call insn as a prune point to trigger
18206 			 * is_state_visited() check before call itself is
18207 			 * processed by __check_func_call(). Otherwise new
18208 			 * async state will be pushed for further exploration.
18209 			 */
18210 			mark_prune_point(env, t);
18211 		/* For functions that invoke callbacks it is not known how many times
18212 		 * callback would be called. Verifier models callback calling functions
18213 		 * by repeatedly visiting callback bodies and returning to origin call
18214 		 * instruction.
18215 		 * In order to stop such iteration verifier needs to identify when a
18216 		 * state identical some state from a previous iteration is reached.
18217 		 * Check below forces creation of checkpoint before callback calling
18218 		 * instruction to allow search for such identical states.
18219 		 */
18220 		if (is_sync_callback_calling_insn(insn)) {
18221 			mark_calls_callback(env, t);
18222 			mark_force_checkpoint(env, t);
18223 			mark_prune_point(env, t);
18224 			mark_jmp_point(env, t);
18225 		}
18226 		if (bpf_helper_call(insn)) {
18227 			const struct bpf_func_proto *fp;
18228 
18229 			ret = get_helper_proto(env, insn->imm, &fp);
18230 			/* If called in a non-sleepable context program will be
18231 			 * rejected anyway, so we should end up with precise
18232 			 * sleepable marks on subprogs, except for dead code
18233 			 * elimination.
18234 			 */
18235 			if (ret == 0 && fp->might_sleep)
18236 				mark_subprog_might_sleep(env, t);
18237 			if (bpf_helper_changes_pkt_data(insn->imm))
18238 				mark_subprog_changes_pkt_data(env, t);
18239 			if (insn->imm == BPF_FUNC_tail_call)
18240 				visit_tailcall_insn(env, t);
18241 		} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18242 			struct bpf_kfunc_call_arg_meta meta;
18243 
18244 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
18245 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
18246 				mark_prune_point(env, t);
18247 				/* Checking and saving state checkpoints at iter_next() call
18248 				 * is crucial for fast convergence of open-coded iterator loop
18249 				 * logic, so we need to force it. If we don't do that,
18250 				 * is_state_visited() might skip saving a checkpoint, causing
18251 				 * unnecessarily long sequence of not checkpointed
18252 				 * instructions and jumps, leading to exhaustion of jump
18253 				 * history buffer, and potentially other undesired outcomes.
18254 				 * It is expected that with correct open-coded iterators
18255 				 * convergence will happen quickly, so we don't run a risk of
18256 				 * exhausting memory.
18257 				 */
18258 				mark_force_checkpoint(env, t);
18259 			}
18260 			/* Same as helpers, if called in a non-sleepable context
18261 			 * program will be rejected anyway, so we should end up
18262 			 * with precise sleepable marks on subprogs, except for
18263 			 * dead code elimination.
18264 			 */
18265 			if (ret == 0 && is_kfunc_sleepable(&meta))
18266 				mark_subprog_might_sleep(env, t);
18267 			if (ret == 0 && is_kfunc_pkt_changing(&meta))
18268 				mark_subprog_changes_pkt_data(env, t);
18269 		}
18270 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
18271 
18272 	case BPF_JA:
18273 		if (BPF_SRC(insn->code) == BPF_X)
18274 			return visit_gotox_insn(t, env);
18275 
18276 		if (BPF_CLASS(insn->code) == BPF_JMP)
18277 			off = insn->off;
18278 		else
18279 			off = insn->imm;
18280 
18281 		/* unconditional jump with single edge */
18282 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
18283 		if (ret)
18284 			return ret;
18285 
18286 		mark_prune_point(env, t + off + 1);
18287 		mark_jmp_point(env, t + off + 1);
18288 
18289 		return ret;
18290 
18291 	default:
18292 		/* conditional jump with two edges */
18293 		mark_prune_point(env, t);
18294 		if (is_may_goto_insn(insn))
18295 			mark_force_checkpoint(env, t);
18296 
18297 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
18298 		if (ret)
18299 			return ret;
18300 
18301 		return push_insn(t, t + insn->off + 1, BRANCH, env);
18302 	}
18303 }
18304 
18305 /* non-recursive depth-first-search to detect loops in BPF program
18306  * loop == back-edge in directed graph
18307  */
18308 static int check_cfg(struct bpf_verifier_env *env)
18309 {
18310 	int insn_cnt = env->prog->len;
18311 	int *insn_stack, *insn_state;
18312 	int ex_insn_beg, i, ret = 0;
18313 
18314 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
18315 	if (!insn_state)
18316 		return -ENOMEM;
18317 
18318 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
18319 	if (!insn_stack) {
18320 		kvfree(insn_state);
18321 		return -ENOMEM;
18322 	}
18323 
18324 	ex_insn_beg = env->exception_callback_subprog
18325 		      ? env->subprog_info[env->exception_callback_subprog].start
18326 		      : 0;
18327 
18328 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
18329 	insn_stack[0] = 0; /* 0 is the first instruction */
18330 	env->cfg.cur_stack = 1;
18331 
18332 walk_cfg:
18333 	while (env->cfg.cur_stack > 0) {
18334 		int t = insn_stack[env->cfg.cur_stack - 1];
18335 
18336 		ret = visit_insn(t, env);
18337 		switch (ret) {
18338 		case DONE_EXPLORING:
18339 			insn_state[t] = EXPLORED;
18340 			env->cfg.cur_stack--;
18341 			break;
18342 		case KEEP_EXPLORING:
18343 			break;
18344 		default:
18345 			if (ret > 0) {
18346 				verifier_bug(env, "visit_insn internal bug");
18347 				ret = -EFAULT;
18348 			}
18349 			goto err_free;
18350 		}
18351 	}
18352 
18353 	if (env->cfg.cur_stack < 0) {
18354 		verifier_bug(env, "pop stack internal bug");
18355 		ret = -EFAULT;
18356 		goto err_free;
18357 	}
18358 
18359 	if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) {
18360 		insn_state[ex_insn_beg] = DISCOVERED;
18361 		insn_stack[0] = ex_insn_beg;
18362 		env->cfg.cur_stack = 1;
18363 		goto walk_cfg;
18364 	}
18365 
18366 	for (i = 0; i < insn_cnt; i++) {
18367 		struct bpf_insn *insn = &env->prog->insnsi[i];
18368 
18369 		if (insn_state[i] != EXPLORED) {
18370 			verbose(env, "unreachable insn %d\n", i);
18371 			ret = -EINVAL;
18372 			goto err_free;
18373 		}
18374 		if (bpf_is_ldimm64(insn)) {
18375 			if (insn_state[i + 1] != 0) {
18376 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
18377 				ret = -EINVAL;
18378 				goto err_free;
18379 			}
18380 			i++; /* skip second half of ldimm64 */
18381 		}
18382 	}
18383 	ret = 0; /* cfg looks good */
18384 	env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
18385 	env->prog->aux->might_sleep = env->subprog_info[0].might_sleep;
18386 
18387 err_free:
18388 	kvfree(insn_state);
18389 	kvfree(insn_stack);
18390 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
18391 	return ret;
18392 }
18393 
18394 /*
18395  * For each subprogram 'i' fill array env->cfg.insn_subprogram sub-range
18396  * [env->subprog_info[i].postorder_start, env->subprog_info[i+1].postorder_start)
18397  * with indices of 'i' instructions in postorder.
18398  */
18399 static int compute_postorder(struct bpf_verifier_env *env)
18400 {
18401 	u32 cur_postorder, i, top, stack_sz, s;
18402 	int *stack = NULL, *postorder = NULL, *state = NULL;
18403 	struct bpf_iarray *succ;
18404 
18405 	postorder = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18406 	state = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18407 	stack = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18408 	if (!postorder || !state || !stack) {
18409 		kvfree(postorder);
18410 		kvfree(state);
18411 		kvfree(stack);
18412 		return -ENOMEM;
18413 	}
18414 	cur_postorder = 0;
18415 	for (i = 0; i < env->subprog_cnt; i++) {
18416 		env->subprog_info[i].postorder_start = cur_postorder;
18417 		stack[0] = env->subprog_info[i].start;
18418 		stack_sz = 1;
18419 		do {
18420 			top = stack[stack_sz - 1];
18421 			state[top] |= DISCOVERED;
18422 			if (state[top] & EXPLORED) {
18423 				postorder[cur_postorder++] = top;
18424 				stack_sz--;
18425 				continue;
18426 			}
18427 			succ = bpf_insn_successors(env, top);
18428 			for (s = 0; s < succ->cnt; ++s) {
18429 				if (!state[succ->items[s]]) {
18430 					stack[stack_sz++] = succ->items[s];
18431 					state[succ->items[s]] |= DISCOVERED;
18432 				}
18433 			}
18434 			state[top] |= EXPLORED;
18435 		} while (stack_sz);
18436 	}
18437 	env->subprog_info[i].postorder_start = cur_postorder;
18438 	env->cfg.insn_postorder = postorder;
18439 	env->cfg.cur_postorder = cur_postorder;
18440 	kvfree(stack);
18441 	kvfree(state);
18442 	return 0;
18443 }
18444 
18445 static int check_abnormal_return(struct bpf_verifier_env *env)
18446 {
18447 	int i;
18448 
18449 	for (i = 1; i < env->subprog_cnt; i++) {
18450 		if (env->subprog_info[i].has_ld_abs) {
18451 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
18452 			return -EINVAL;
18453 		}
18454 		if (env->subprog_info[i].has_tail_call) {
18455 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
18456 			return -EINVAL;
18457 		}
18458 	}
18459 	return 0;
18460 }
18461 
18462 /* The minimum supported BTF func info size */
18463 #define MIN_BPF_FUNCINFO_SIZE	8
18464 #define MAX_FUNCINFO_REC_SIZE	252
18465 
18466 static int check_btf_func_early(struct bpf_verifier_env *env,
18467 				const union bpf_attr *attr,
18468 				bpfptr_t uattr)
18469 {
18470 	u32 krec_size = sizeof(struct bpf_func_info);
18471 	const struct btf_type *type, *func_proto;
18472 	u32 i, nfuncs, urec_size, min_size;
18473 	struct bpf_func_info *krecord;
18474 	struct bpf_prog *prog;
18475 	const struct btf *btf;
18476 	u32 prev_offset = 0;
18477 	bpfptr_t urecord;
18478 	int ret = -ENOMEM;
18479 
18480 	nfuncs = attr->func_info_cnt;
18481 	if (!nfuncs) {
18482 		if (check_abnormal_return(env))
18483 			return -EINVAL;
18484 		return 0;
18485 	}
18486 
18487 	urec_size = attr->func_info_rec_size;
18488 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
18489 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
18490 	    urec_size % sizeof(u32)) {
18491 		verbose(env, "invalid func info rec size %u\n", urec_size);
18492 		return -EINVAL;
18493 	}
18494 
18495 	prog = env->prog;
18496 	btf = prog->aux->btf;
18497 
18498 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18499 	min_size = min_t(u32, krec_size, urec_size);
18500 
18501 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18502 	if (!krecord)
18503 		return -ENOMEM;
18504 
18505 	for (i = 0; i < nfuncs; i++) {
18506 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
18507 		if (ret) {
18508 			if (ret == -E2BIG) {
18509 				verbose(env, "nonzero tailing record in func info");
18510 				/* set the size kernel expects so loader can zero
18511 				 * out the rest of the record.
18512 				 */
18513 				if (copy_to_bpfptr_offset(uattr,
18514 							  offsetof(union bpf_attr, func_info_rec_size),
18515 							  &min_size, sizeof(min_size)))
18516 					ret = -EFAULT;
18517 			}
18518 			goto err_free;
18519 		}
18520 
18521 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
18522 			ret = -EFAULT;
18523 			goto err_free;
18524 		}
18525 
18526 		/* check insn_off */
18527 		ret = -EINVAL;
18528 		if (i == 0) {
18529 			if (krecord[i].insn_off) {
18530 				verbose(env,
18531 					"nonzero insn_off %u for the first func info record",
18532 					krecord[i].insn_off);
18533 				goto err_free;
18534 			}
18535 		} else if (krecord[i].insn_off <= prev_offset) {
18536 			verbose(env,
18537 				"same or smaller insn offset (%u) than previous func info record (%u)",
18538 				krecord[i].insn_off, prev_offset);
18539 			goto err_free;
18540 		}
18541 
18542 		/* check type_id */
18543 		type = btf_type_by_id(btf, krecord[i].type_id);
18544 		if (!type || !btf_type_is_func(type)) {
18545 			verbose(env, "invalid type id %d in func info",
18546 				krecord[i].type_id);
18547 			goto err_free;
18548 		}
18549 
18550 		func_proto = btf_type_by_id(btf, type->type);
18551 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
18552 			/* btf_func_check() already verified it during BTF load */
18553 			goto err_free;
18554 
18555 		prev_offset = krecord[i].insn_off;
18556 		bpfptr_add(&urecord, urec_size);
18557 	}
18558 
18559 	prog->aux->func_info = krecord;
18560 	prog->aux->func_info_cnt = nfuncs;
18561 	return 0;
18562 
18563 err_free:
18564 	kvfree(krecord);
18565 	return ret;
18566 }
18567 
18568 static int check_btf_func(struct bpf_verifier_env *env,
18569 			  const union bpf_attr *attr,
18570 			  bpfptr_t uattr)
18571 {
18572 	const struct btf_type *type, *func_proto, *ret_type;
18573 	u32 i, nfuncs, urec_size;
18574 	struct bpf_func_info *krecord;
18575 	struct bpf_func_info_aux *info_aux = NULL;
18576 	struct bpf_prog *prog;
18577 	const struct btf *btf;
18578 	bpfptr_t urecord;
18579 	bool scalar_return;
18580 	int ret = -ENOMEM;
18581 
18582 	nfuncs = attr->func_info_cnt;
18583 	if (!nfuncs) {
18584 		if (check_abnormal_return(env))
18585 			return -EINVAL;
18586 		return 0;
18587 	}
18588 	if (nfuncs != env->subprog_cnt) {
18589 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
18590 		return -EINVAL;
18591 	}
18592 
18593 	urec_size = attr->func_info_rec_size;
18594 
18595 	prog = env->prog;
18596 	btf = prog->aux->btf;
18597 
18598 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18599 
18600 	krecord = prog->aux->func_info;
18601 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18602 	if (!info_aux)
18603 		return -ENOMEM;
18604 
18605 	for (i = 0; i < nfuncs; i++) {
18606 		/* check insn_off */
18607 		ret = -EINVAL;
18608 
18609 		if (env->subprog_info[i].start != krecord[i].insn_off) {
18610 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
18611 			goto err_free;
18612 		}
18613 
18614 		/* Already checked type_id */
18615 		type = btf_type_by_id(btf, krecord[i].type_id);
18616 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
18617 		/* Already checked func_proto */
18618 		func_proto = btf_type_by_id(btf, type->type);
18619 
18620 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
18621 		scalar_return =
18622 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
18623 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
18624 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
18625 			goto err_free;
18626 		}
18627 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
18628 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
18629 			goto err_free;
18630 		}
18631 
18632 		bpfptr_add(&urecord, urec_size);
18633 	}
18634 
18635 	prog->aux->func_info_aux = info_aux;
18636 	return 0;
18637 
18638 err_free:
18639 	kfree(info_aux);
18640 	return ret;
18641 }
18642 
18643 static void adjust_btf_func(struct bpf_verifier_env *env)
18644 {
18645 	struct bpf_prog_aux *aux = env->prog->aux;
18646 	int i;
18647 
18648 	if (!aux->func_info)
18649 		return;
18650 
18651 	/* func_info is not available for hidden subprogs */
18652 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
18653 		aux->func_info[i].insn_off = env->subprog_info[i].start;
18654 }
18655 
18656 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
18657 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
18658 
18659 static int check_btf_line(struct bpf_verifier_env *env,
18660 			  const union bpf_attr *attr,
18661 			  bpfptr_t uattr)
18662 {
18663 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
18664 	struct bpf_subprog_info *sub;
18665 	struct bpf_line_info *linfo;
18666 	struct bpf_prog *prog;
18667 	const struct btf *btf;
18668 	bpfptr_t ulinfo;
18669 	int err;
18670 
18671 	nr_linfo = attr->line_info_cnt;
18672 	if (!nr_linfo)
18673 		return 0;
18674 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
18675 		return -EINVAL;
18676 
18677 	rec_size = attr->line_info_rec_size;
18678 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
18679 	    rec_size > MAX_LINEINFO_REC_SIZE ||
18680 	    rec_size & (sizeof(u32) - 1))
18681 		return -EINVAL;
18682 
18683 	/* Need to zero it in case the userspace may
18684 	 * pass in a smaller bpf_line_info object.
18685 	 */
18686 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
18687 			 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18688 	if (!linfo)
18689 		return -ENOMEM;
18690 
18691 	prog = env->prog;
18692 	btf = prog->aux->btf;
18693 
18694 	s = 0;
18695 	sub = env->subprog_info;
18696 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
18697 	expected_size = sizeof(struct bpf_line_info);
18698 	ncopy = min_t(u32, expected_size, rec_size);
18699 	for (i = 0; i < nr_linfo; i++) {
18700 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
18701 		if (err) {
18702 			if (err == -E2BIG) {
18703 				verbose(env, "nonzero tailing record in line_info");
18704 				if (copy_to_bpfptr_offset(uattr,
18705 							  offsetof(union bpf_attr, line_info_rec_size),
18706 							  &expected_size, sizeof(expected_size)))
18707 					err = -EFAULT;
18708 			}
18709 			goto err_free;
18710 		}
18711 
18712 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
18713 			err = -EFAULT;
18714 			goto err_free;
18715 		}
18716 
18717 		/*
18718 		 * Check insn_off to ensure
18719 		 * 1) strictly increasing AND
18720 		 * 2) bounded by prog->len
18721 		 *
18722 		 * The linfo[0].insn_off == 0 check logically falls into
18723 		 * the later "missing bpf_line_info for func..." case
18724 		 * because the first linfo[0].insn_off must be the
18725 		 * first sub also and the first sub must have
18726 		 * subprog_info[0].start == 0.
18727 		 */
18728 		if ((i && linfo[i].insn_off <= prev_offset) ||
18729 		    linfo[i].insn_off >= prog->len) {
18730 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
18731 				i, linfo[i].insn_off, prev_offset,
18732 				prog->len);
18733 			err = -EINVAL;
18734 			goto err_free;
18735 		}
18736 
18737 		if (!prog->insnsi[linfo[i].insn_off].code) {
18738 			verbose(env,
18739 				"Invalid insn code at line_info[%u].insn_off\n",
18740 				i);
18741 			err = -EINVAL;
18742 			goto err_free;
18743 		}
18744 
18745 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
18746 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
18747 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
18748 			err = -EINVAL;
18749 			goto err_free;
18750 		}
18751 
18752 		if (s != env->subprog_cnt) {
18753 			if (linfo[i].insn_off == sub[s].start) {
18754 				sub[s].linfo_idx = i;
18755 				s++;
18756 			} else if (sub[s].start < linfo[i].insn_off) {
18757 				verbose(env, "missing bpf_line_info for func#%u\n", s);
18758 				err = -EINVAL;
18759 				goto err_free;
18760 			}
18761 		}
18762 
18763 		prev_offset = linfo[i].insn_off;
18764 		bpfptr_add(&ulinfo, rec_size);
18765 	}
18766 
18767 	if (s != env->subprog_cnt) {
18768 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
18769 			env->subprog_cnt - s, s);
18770 		err = -EINVAL;
18771 		goto err_free;
18772 	}
18773 
18774 	prog->aux->linfo = linfo;
18775 	prog->aux->nr_linfo = nr_linfo;
18776 
18777 	return 0;
18778 
18779 err_free:
18780 	kvfree(linfo);
18781 	return err;
18782 }
18783 
18784 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
18785 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
18786 
18787 static int check_core_relo(struct bpf_verifier_env *env,
18788 			   const union bpf_attr *attr,
18789 			   bpfptr_t uattr)
18790 {
18791 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
18792 	struct bpf_core_relo core_relo = {};
18793 	struct bpf_prog *prog = env->prog;
18794 	const struct btf *btf = prog->aux->btf;
18795 	struct bpf_core_ctx ctx = {
18796 		.log = &env->log,
18797 		.btf = btf,
18798 	};
18799 	bpfptr_t u_core_relo;
18800 	int err;
18801 
18802 	nr_core_relo = attr->core_relo_cnt;
18803 	if (!nr_core_relo)
18804 		return 0;
18805 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
18806 		return -EINVAL;
18807 
18808 	rec_size = attr->core_relo_rec_size;
18809 	if (rec_size < MIN_CORE_RELO_SIZE ||
18810 	    rec_size > MAX_CORE_RELO_SIZE ||
18811 	    rec_size % sizeof(u32))
18812 		return -EINVAL;
18813 
18814 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
18815 	expected_size = sizeof(struct bpf_core_relo);
18816 	ncopy = min_t(u32, expected_size, rec_size);
18817 
18818 	/* Unlike func_info and line_info, copy and apply each CO-RE
18819 	 * relocation record one at a time.
18820 	 */
18821 	for (i = 0; i < nr_core_relo; i++) {
18822 		/* future proofing when sizeof(bpf_core_relo) changes */
18823 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
18824 		if (err) {
18825 			if (err == -E2BIG) {
18826 				verbose(env, "nonzero tailing record in core_relo");
18827 				if (copy_to_bpfptr_offset(uattr,
18828 							  offsetof(union bpf_attr, core_relo_rec_size),
18829 							  &expected_size, sizeof(expected_size)))
18830 					err = -EFAULT;
18831 			}
18832 			break;
18833 		}
18834 
18835 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
18836 			err = -EFAULT;
18837 			break;
18838 		}
18839 
18840 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
18841 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
18842 				i, core_relo.insn_off, prog->len);
18843 			err = -EINVAL;
18844 			break;
18845 		}
18846 
18847 		err = bpf_core_apply(&ctx, &core_relo, i,
18848 				     &prog->insnsi[core_relo.insn_off / 8]);
18849 		if (err)
18850 			break;
18851 		bpfptr_add(&u_core_relo, rec_size);
18852 	}
18853 	return err;
18854 }
18855 
18856 static int check_btf_info_early(struct bpf_verifier_env *env,
18857 				const union bpf_attr *attr,
18858 				bpfptr_t uattr)
18859 {
18860 	struct btf *btf;
18861 	int err;
18862 
18863 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18864 		if (check_abnormal_return(env))
18865 			return -EINVAL;
18866 		return 0;
18867 	}
18868 
18869 	btf = btf_get_by_fd(attr->prog_btf_fd);
18870 	if (IS_ERR(btf))
18871 		return PTR_ERR(btf);
18872 	if (btf_is_kernel(btf)) {
18873 		btf_put(btf);
18874 		return -EACCES;
18875 	}
18876 	env->prog->aux->btf = btf;
18877 
18878 	err = check_btf_func_early(env, attr, uattr);
18879 	if (err)
18880 		return err;
18881 	return 0;
18882 }
18883 
18884 static int check_btf_info(struct bpf_verifier_env *env,
18885 			  const union bpf_attr *attr,
18886 			  bpfptr_t uattr)
18887 {
18888 	int err;
18889 
18890 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18891 		if (check_abnormal_return(env))
18892 			return -EINVAL;
18893 		return 0;
18894 	}
18895 
18896 	err = check_btf_func(env, attr, uattr);
18897 	if (err)
18898 		return err;
18899 
18900 	err = check_btf_line(env, attr, uattr);
18901 	if (err)
18902 		return err;
18903 
18904 	err = check_core_relo(env, attr, uattr);
18905 	if (err)
18906 		return err;
18907 
18908 	return 0;
18909 }
18910 
18911 /* check %cur's range satisfies %old's */
18912 static bool range_within(const struct bpf_reg_state *old,
18913 			 const struct bpf_reg_state *cur)
18914 {
18915 	return old->umin_value <= cur->umin_value &&
18916 	       old->umax_value >= cur->umax_value &&
18917 	       old->smin_value <= cur->smin_value &&
18918 	       old->smax_value >= cur->smax_value &&
18919 	       old->u32_min_value <= cur->u32_min_value &&
18920 	       old->u32_max_value >= cur->u32_max_value &&
18921 	       old->s32_min_value <= cur->s32_min_value &&
18922 	       old->s32_max_value >= cur->s32_max_value;
18923 }
18924 
18925 /* If in the old state two registers had the same id, then they need to have
18926  * the same id in the new state as well.  But that id could be different from
18927  * the old state, so we need to track the mapping from old to new ids.
18928  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
18929  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
18930  * regs with a different old id could still have new id 9, we don't care about
18931  * that.
18932  * So we look through our idmap to see if this old id has been seen before.  If
18933  * so, we require the new id to match; otherwise, we add the id pair to the map.
18934  */
18935 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18936 {
18937 	struct bpf_id_pair *map = idmap->map;
18938 	unsigned int i;
18939 
18940 	/* either both IDs should be set or both should be zero */
18941 	if (!!old_id != !!cur_id)
18942 		return false;
18943 
18944 	if (old_id == 0) /* cur_id == 0 as well */
18945 		return true;
18946 
18947 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
18948 		if (!map[i].old) {
18949 			/* Reached an empty slot; haven't seen this id before */
18950 			map[i].old = old_id;
18951 			map[i].cur = cur_id;
18952 			return true;
18953 		}
18954 		if (map[i].old == old_id)
18955 			return map[i].cur == cur_id;
18956 		if (map[i].cur == cur_id)
18957 			return false;
18958 	}
18959 	/* We ran out of idmap slots, which should be impossible */
18960 	WARN_ON_ONCE(1);
18961 	return false;
18962 }
18963 
18964 /* Similar to check_ids(), but allocate a unique temporary ID
18965  * for 'old_id' or 'cur_id' of zero.
18966  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
18967  */
18968 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18969 {
18970 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
18971 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
18972 
18973 	return check_ids(old_id, cur_id, idmap);
18974 }
18975 
18976 static void clean_func_state(struct bpf_verifier_env *env,
18977 			     struct bpf_func_state *st,
18978 			     u32 ip)
18979 {
18980 	u16 live_regs = env->insn_aux_data[ip].live_regs_before;
18981 	int i, j;
18982 
18983 	for (i = 0; i < BPF_REG_FP; i++) {
18984 		/* liveness must not touch this register anymore */
18985 		if (!(live_regs & BIT(i)))
18986 			/* since the register is unused, clear its state
18987 			 * to make further comparison simpler
18988 			 */
18989 			__mark_reg_not_init(env, &st->regs[i]);
18990 	}
18991 
18992 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
18993 		if (!bpf_stack_slot_alive(env, st->frameno, i)) {
18994 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
18995 			for (j = 0; j < BPF_REG_SIZE; j++)
18996 				st->stack[i].slot_type[j] = STACK_INVALID;
18997 		}
18998 	}
18999 }
19000 
19001 static void clean_verifier_state(struct bpf_verifier_env *env,
19002 				 struct bpf_verifier_state *st)
19003 {
19004 	int i, ip;
19005 
19006 	bpf_live_stack_query_init(env, st);
19007 	st->cleaned = true;
19008 	for (i = 0; i <= st->curframe; i++) {
19009 		ip = frame_insn_idx(st, i);
19010 		clean_func_state(env, st->frame[i], ip);
19011 	}
19012 }
19013 
19014 /* the parentage chains form a tree.
19015  * the verifier states are added to state lists at given insn and
19016  * pushed into state stack for future exploration.
19017  * when the verifier reaches bpf_exit insn some of the verifier states
19018  * stored in the state lists have their final liveness state already,
19019  * but a lot of states will get revised from liveness point of view when
19020  * the verifier explores other branches.
19021  * Example:
19022  * 1: *(u64)(r10 - 8) = 1
19023  * 2: if r1 == 100 goto pc+1
19024  * 3: *(u64)(r10 - 8) = 2
19025  * 4: r0 = *(u64)(r10 - 8)
19026  * 5: exit
19027  * when the verifier reaches exit insn the stack slot -8 in the state list of
19028  * insn 2 is not yet marked alive. Then the verifier pops the other_branch
19029  * of insn 2 and goes exploring further. After the insn 4 read, liveness
19030  * analysis would propagate read mark for -8 at insn 2.
19031  *
19032  * Since the verifier pushes the branch states as it sees them while exploring
19033  * the program the condition of walking the branch instruction for the second
19034  * time means that all states below this branch were already explored and
19035  * their final liveness marks are already propagated.
19036  * Hence when the verifier completes the search of state list in is_state_visited()
19037  * we can call this clean_live_states() function to clear dead the registers and stack
19038  * slots to simplify state merging.
19039  *
19040  * Important note here that walking the same branch instruction in the callee
19041  * doesn't meant that the states are DONE. The verifier has to compare
19042  * the callsites
19043  */
19044 static void clean_live_states(struct bpf_verifier_env *env, int insn,
19045 			      struct bpf_verifier_state *cur)
19046 {
19047 	struct bpf_verifier_state_list *sl;
19048 	struct list_head *pos, *head;
19049 
19050 	head = explored_state(env, insn);
19051 	list_for_each(pos, head) {
19052 		sl = container_of(pos, struct bpf_verifier_state_list, node);
19053 		if (sl->state.branches)
19054 			continue;
19055 		if (sl->state.insn_idx != insn ||
19056 		    !same_callsites(&sl->state, cur))
19057 			continue;
19058 		if (sl->state.cleaned)
19059 			/* all regs in this state in all frames were already marked */
19060 			continue;
19061 		if (incomplete_read_marks(env, &sl->state))
19062 			continue;
19063 		clean_verifier_state(env, &sl->state);
19064 	}
19065 }
19066 
19067 static bool regs_exact(const struct bpf_reg_state *rold,
19068 		       const struct bpf_reg_state *rcur,
19069 		       struct bpf_idmap *idmap)
19070 {
19071 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
19072 	       check_ids(rold->id, rcur->id, idmap) &&
19073 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
19074 }
19075 
19076 enum exact_level {
19077 	NOT_EXACT,
19078 	EXACT,
19079 	RANGE_WITHIN
19080 };
19081 
19082 /* Returns true if (rold safe implies rcur safe) */
19083 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
19084 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
19085 		    enum exact_level exact)
19086 {
19087 	if (exact == EXACT)
19088 		return regs_exact(rold, rcur, idmap);
19089 
19090 	if (rold->type == NOT_INIT) {
19091 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
19092 			/* explored state can't have used this */
19093 			return true;
19094 	}
19095 
19096 	/* Enforce that register types have to match exactly, including their
19097 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
19098 	 * rule.
19099 	 *
19100 	 * One can make a point that using a pointer register as unbounded
19101 	 * SCALAR would be technically acceptable, but this could lead to
19102 	 * pointer leaks because scalars are allowed to leak while pointers
19103 	 * are not. We could make this safe in special cases if root is
19104 	 * calling us, but it's probably not worth the hassle.
19105 	 *
19106 	 * Also, register types that are *not* MAYBE_NULL could technically be
19107 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
19108 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
19109 	 * to the same map).
19110 	 * However, if the old MAYBE_NULL register then got NULL checked,
19111 	 * doing so could have affected others with the same id, and we can't
19112 	 * check for that because we lost the id when we converted to
19113 	 * a non-MAYBE_NULL variant.
19114 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
19115 	 * non-MAYBE_NULL registers as well.
19116 	 */
19117 	if (rold->type != rcur->type)
19118 		return false;
19119 
19120 	switch (base_type(rold->type)) {
19121 	case SCALAR_VALUE:
19122 		if (env->explore_alu_limits) {
19123 			/* explore_alu_limits disables tnum_in() and range_within()
19124 			 * logic and requires everything to be strict
19125 			 */
19126 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
19127 			       check_scalar_ids(rold->id, rcur->id, idmap);
19128 		}
19129 		if (!rold->precise && exact == NOT_EXACT)
19130 			return true;
19131 		if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
19132 			return false;
19133 		if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
19134 			return false;
19135 		/* Why check_ids() for scalar registers?
19136 		 *
19137 		 * Consider the following BPF code:
19138 		 *   1: r6 = ... unbound scalar, ID=a ...
19139 		 *   2: r7 = ... unbound scalar, ID=b ...
19140 		 *   3: if (r6 > r7) goto +1
19141 		 *   4: r6 = r7
19142 		 *   5: if (r6 > X) goto ...
19143 		 *   6: ... memory operation using r7 ...
19144 		 *
19145 		 * First verification path is [1-6]:
19146 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
19147 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
19148 		 *   r7 <= X, because r6 and r7 share same id.
19149 		 * Next verification path is [1-4, 6].
19150 		 *
19151 		 * Instruction (6) would be reached in two states:
19152 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
19153 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
19154 		 *
19155 		 * Use check_ids() to distinguish these states.
19156 		 * ---
19157 		 * Also verify that new value satisfies old value range knowledge.
19158 		 */
19159 		return range_within(rold, rcur) &&
19160 		       tnum_in(rold->var_off, rcur->var_off) &&
19161 		       check_scalar_ids(rold->id, rcur->id, idmap);
19162 	case PTR_TO_MAP_KEY:
19163 	case PTR_TO_MAP_VALUE:
19164 	case PTR_TO_MEM:
19165 	case PTR_TO_BUF:
19166 	case PTR_TO_TP_BUFFER:
19167 		/* If the new min/max/var_off satisfy the old ones and
19168 		 * everything else matches, we are OK.
19169 		 */
19170 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
19171 		       range_within(rold, rcur) &&
19172 		       tnum_in(rold->var_off, rcur->var_off) &&
19173 		       check_ids(rold->id, rcur->id, idmap) &&
19174 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
19175 	case PTR_TO_PACKET_META:
19176 	case PTR_TO_PACKET:
19177 		/* We must have at least as much range as the old ptr
19178 		 * did, so that any accesses which were safe before are
19179 		 * still safe.  This is true even if old range < old off,
19180 		 * since someone could have accessed through (ptr - k), or
19181 		 * even done ptr -= k in a register, to get a safe access.
19182 		 */
19183 		if (rold->range > rcur->range)
19184 			return false;
19185 		/* If the offsets don't match, we can't trust our alignment;
19186 		 * nor can we be sure that we won't fall out of range.
19187 		 */
19188 		if (rold->off != rcur->off)
19189 			return false;
19190 		/* id relations must be preserved */
19191 		if (!check_ids(rold->id, rcur->id, idmap))
19192 			return false;
19193 		/* new val must satisfy old val knowledge */
19194 		return range_within(rold, rcur) &&
19195 		       tnum_in(rold->var_off, rcur->var_off);
19196 	case PTR_TO_STACK:
19197 		/* two stack pointers are equal only if they're pointing to
19198 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
19199 		 */
19200 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
19201 	case PTR_TO_ARENA:
19202 		return true;
19203 	case PTR_TO_INSN:
19204 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
19205 			rold->off == rcur->off && range_within(rold, rcur) &&
19206 			tnum_in(rold->var_off, rcur->var_off);
19207 	default:
19208 		return regs_exact(rold, rcur, idmap);
19209 	}
19210 }
19211 
19212 static struct bpf_reg_state unbound_reg;
19213 
19214 static __init int unbound_reg_init(void)
19215 {
19216 	__mark_reg_unknown_imprecise(&unbound_reg);
19217 	return 0;
19218 }
19219 late_initcall(unbound_reg_init);
19220 
19221 static bool is_stack_all_misc(struct bpf_verifier_env *env,
19222 			      struct bpf_stack_state *stack)
19223 {
19224 	u32 i;
19225 
19226 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
19227 		if ((stack->slot_type[i] == STACK_MISC) ||
19228 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
19229 			continue;
19230 		return false;
19231 	}
19232 
19233 	return true;
19234 }
19235 
19236 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
19237 						  struct bpf_stack_state *stack)
19238 {
19239 	if (is_spilled_scalar_reg64(stack))
19240 		return &stack->spilled_ptr;
19241 
19242 	if (is_stack_all_misc(env, stack))
19243 		return &unbound_reg;
19244 
19245 	return NULL;
19246 }
19247 
19248 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
19249 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
19250 		      enum exact_level exact)
19251 {
19252 	int i, spi;
19253 
19254 	/* walk slots of the explored stack and ignore any additional
19255 	 * slots in the current stack, since explored(safe) state
19256 	 * didn't use them
19257 	 */
19258 	for (i = 0; i < old->allocated_stack; i++) {
19259 		struct bpf_reg_state *old_reg, *cur_reg;
19260 
19261 		spi = i / BPF_REG_SIZE;
19262 
19263 		if (exact != NOT_EXACT &&
19264 		    (i >= cur->allocated_stack ||
19265 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
19266 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
19267 			return false;
19268 
19269 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
19270 			continue;
19271 
19272 		if (env->allow_uninit_stack &&
19273 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
19274 			continue;
19275 
19276 		/* explored stack has more populated slots than current stack
19277 		 * and these slots were used
19278 		 */
19279 		if (i >= cur->allocated_stack)
19280 			return false;
19281 
19282 		/* 64-bit scalar spill vs all slots MISC and vice versa.
19283 		 * Load from all slots MISC produces unbound scalar.
19284 		 * Construct a fake register for such stack and call
19285 		 * regsafe() to ensure scalar ids are compared.
19286 		 */
19287 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
19288 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
19289 		if (old_reg && cur_reg) {
19290 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
19291 				return false;
19292 			i += BPF_REG_SIZE - 1;
19293 			continue;
19294 		}
19295 
19296 		/* if old state was safe with misc data in the stack
19297 		 * it will be safe with zero-initialized stack.
19298 		 * The opposite is not true
19299 		 */
19300 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
19301 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
19302 			continue;
19303 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
19304 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
19305 			/* Ex: old explored (safe) state has STACK_SPILL in
19306 			 * this stack slot, but current has STACK_MISC ->
19307 			 * this verifier states are not equivalent,
19308 			 * return false to continue verification of this path
19309 			 */
19310 			return false;
19311 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
19312 			continue;
19313 		/* Both old and cur are having same slot_type */
19314 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
19315 		case STACK_SPILL:
19316 			/* when explored and current stack slot are both storing
19317 			 * spilled registers, check that stored pointers types
19318 			 * are the same as well.
19319 			 * Ex: explored safe path could have stored
19320 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
19321 			 * but current path has stored:
19322 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
19323 			 * such verifier states are not equivalent.
19324 			 * return false to continue verification of this path
19325 			 */
19326 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
19327 				     &cur->stack[spi].spilled_ptr, idmap, exact))
19328 				return false;
19329 			break;
19330 		case STACK_DYNPTR:
19331 			old_reg = &old->stack[spi].spilled_ptr;
19332 			cur_reg = &cur->stack[spi].spilled_ptr;
19333 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
19334 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
19335 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
19336 				return false;
19337 			break;
19338 		case STACK_ITER:
19339 			old_reg = &old->stack[spi].spilled_ptr;
19340 			cur_reg = &cur->stack[spi].spilled_ptr;
19341 			/* iter.depth is not compared between states as it
19342 			 * doesn't matter for correctness and would otherwise
19343 			 * prevent convergence; we maintain it only to prevent
19344 			 * infinite loop check triggering, see
19345 			 * iter_active_depths_differ()
19346 			 */
19347 			if (old_reg->iter.btf != cur_reg->iter.btf ||
19348 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
19349 			    old_reg->iter.state != cur_reg->iter.state ||
19350 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
19351 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
19352 				return false;
19353 			break;
19354 		case STACK_IRQ_FLAG:
19355 			old_reg = &old->stack[spi].spilled_ptr;
19356 			cur_reg = &cur->stack[spi].spilled_ptr;
19357 			if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) ||
19358 			    old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class)
19359 				return false;
19360 			break;
19361 		case STACK_MISC:
19362 		case STACK_ZERO:
19363 		case STACK_INVALID:
19364 			continue;
19365 		/* Ensure that new unhandled slot types return false by default */
19366 		default:
19367 			return false;
19368 		}
19369 	}
19370 	return true;
19371 }
19372 
19373 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
19374 		    struct bpf_idmap *idmap)
19375 {
19376 	int i;
19377 
19378 	if (old->acquired_refs != cur->acquired_refs)
19379 		return false;
19380 
19381 	if (old->active_locks != cur->active_locks)
19382 		return false;
19383 
19384 	if (old->active_preempt_locks != cur->active_preempt_locks)
19385 		return false;
19386 
19387 	if (old->active_rcu_locks != cur->active_rcu_locks)
19388 		return false;
19389 
19390 	if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
19391 		return false;
19392 
19393 	if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) ||
19394 	    old->active_lock_ptr != cur->active_lock_ptr)
19395 		return false;
19396 
19397 	for (i = 0; i < old->acquired_refs; i++) {
19398 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
19399 		    old->refs[i].type != cur->refs[i].type)
19400 			return false;
19401 		switch (old->refs[i].type) {
19402 		case REF_TYPE_PTR:
19403 		case REF_TYPE_IRQ:
19404 			break;
19405 		case REF_TYPE_LOCK:
19406 		case REF_TYPE_RES_LOCK:
19407 		case REF_TYPE_RES_LOCK_IRQ:
19408 			if (old->refs[i].ptr != cur->refs[i].ptr)
19409 				return false;
19410 			break;
19411 		default:
19412 			WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
19413 			return false;
19414 		}
19415 	}
19416 
19417 	return true;
19418 }
19419 
19420 /* compare two verifier states
19421  *
19422  * all states stored in state_list are known to be valid, since
19423  * verifier reached 'bpf_exit' instruction through them
19424  *
19425  * this function is called when verifier exploring different branches of
19426  * execution popped from the state stack. If it sees an old state that has
19427  * more strict register state and more strict stack state then this execution
19428  * branch doesn't need to be explored further, since verifier already
19429  * concluded that more strict state leads to valid finish.
19430  *
19431  * Therefore two states are equivalent if register state is more conservative
19432  * and explored stack state is more conservative than the current one.
19433  * Example:
19434  *       explored                   current
19435  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
19436  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
19437  *
19438  * In other words if current stack state (one being explored) has more
19439  * valid slots than old one that already passed validation, it means
19440  * the verifier can stop exploring and conclude that current state is valid too
19441  *
19442  * Similarly with registers. If explored state has register type as invalid
19443  * whereas register type in current state is meaningful, it means that
19444  * the current state will reach 'bpf_exit' instruction safely
19445  */
19446 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
19447 			      struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact)
19448 {
19449 	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
19450 	u16 i;
19451 
19452 	if (old->callback_depth > cur->callback_depth)
19453 		return false;
19454 
19455 	for (i = 0; i < MAX_BPF_REG; i++)
19456 		if (((1 << i) & live_regs) &&
19457 		    !regsafe(env, &old->regs[i], &cur->regs[i],
19458 			     &env->idmap_scratch, exact))
19459 			return false;
19460 
19461 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
19462 		return false;
19463 
19464 	return true;
19465 }
19466 
19467 static void reset_idmap_scratch(struct bpf_verifier_env *env)
19468 {
19469 	env->idmap_scratch.tmp_id_gen = env->id_gen;
19470 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
19471 }
19472 
19473 static bool states_equal(struct bpf_verifier_env *env,
19474 			 struct bpf_verifier_state *old,
19475 			 struct bpf_verifier_state *cur,
19476 			 enum exact_level exact)
19477 {
19478 	u32 insn_idx;
19479 	int i;
19480 
19481 	if (old->curframe != cur->curframe)
19482 		return false;
19483 
19484 	reset_idmap_scratch(env);
19485 
19486 	/* Verification state from speculative execution simulation
19487 	 * must never prune a non-speculative execution one.
19488 	 */
19489 	if (old->speculative && !cur->speculative)
19490 		return false;
19491 
19492 	if (old->in_sleepable != cur->in_sleepable)
19493 		return false;
19494 
19495 	if (!refsafe(old, cur, &env->idmap_scratch))
19496 		return false;
19497 
19498 	/* for states to be equal callsites have to be the same
19499 	 * and all frame states need to be equivalent
19500 	 */
19501 	for (i = 0; i <= old->curframe; i++) {
19502 		insn_idx = frame_insn_idx(old, i);
19503 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
19504 			return false;
19505 		if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
19506 			return false;
19507 	}
19508 	return true;
19509 }
19510 
19511 /* find precise scalars in the previous equivalent state and
19512  * propagate them into the current state
19513  */
19514 static int propagate_precision(struct bpf_verifier_env *env,
19515 			       const struct bpf_verifier_state *old,
19516 			       struct bpf_verifier_state *cur,
19517 			       bool *changed)
19518 {
19519 	struct bpf_reg_state *state_reg;
19520 	struct bpf_func_state *state;
19521 	int i, err = 0, fr;
19522 	bool first;
19523 
19524 	for (fr = old->curframe; fr >= 0; fr--) {
19525 		state = old->frame[fr];
19526 		state_reg = state->regs;
19527 		first = true;
19528 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
19529 			if (state_reg->type != SCALAR_VALUE ||
19530 			    !state_reg->precise)
19531 				continue;
19532 			if (env->log.level & BPF_LOG_LEVEL2) {
19533 				if (first)
19534 					verbose(env, "frame %d: propagating r%d", fr, i);
19535 				else
19536 					verbose(env, ",r%d", i);
19537 			}
19538 			bt_set_frame_reg(&env->bt, fr, i);
19539 			first = false;
19540 		}
19541 
19542 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19543 			if (!is_spilled_reg(&state->stack[i]))
19544 				continue;
19545 			state_reg = &state->stack[i].spilled_ptr;
19546 			if (state_reg->type != SCALAR_VALUE ||
19547 			    !state_reg->precise)
19548 				continue;
19549 			if (env->log.level & BPF_LOG_LEVEL2) {
19550 				if (first)
19551 					verbose(env, "frame %d: propagating fp%d",
19552 						fr, (-i - 1) * BPF_REG_SIZE);
19553 				else
19554 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
19555 			}
19556 			bt_set_frame_slot(&env->bt, fr, i);
19557 			first = false;
19558 		}
19559 		if (!first && (env->log.level & BPF_LOG_LEVEL2))
19560 			verbose(env, "\n");
19561 	}
19562 
19563 	err = __mark_chain_precision(env, cur, -1, changed);
19564 	if (err < 0)
19565 		return err;
19566 
19567 	return 0;
19568 }
19569 
19570 #define MAX_BACKEDGE_ITERS 64
19571 
19572 /* Propagate read and precision marks from visit->backedges[*].state->equal_state
19573  * to corresponding parent states of visit->backedges[*].state until fixed point is reached,
19574  * then free visit->backedges.
19575  * After execution of this function incomplete_read_marks() will return false
19576  * for all states corresponding to @visit->callchain.
19577  */
19578 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit)
19579 {
19580 	struct bpf_scc_backedge *backedge;
19581 	struct bpf_verifier_state *st;
19582 	bool changed;
19583 	int i, err;
19584 
19585 	i = 0;
19586 	do {
19587 		if (i++ > MAX_BACKEDGE_ITERS) {
19588 			if (env->log.level & BPF_LOG_LEVEL2)
19589 				verbose(env, "%s: too many iterations\n", __func__);
19590 			for (backedge = visit->backedges; backedge; backedge = backedge->next)
19591 				mark_all_scalars_precise(env, &backedge->state);
19592 			break;
19593 		}
19594 		changed = false;
19595 		for (backedge = visit->backedges; backedge; backedge = backedge->next) {
19596 			st = &backedge->state;
19597 			err = propagate_precision(env, st->equal_state, st, &changed);
19598 			if (err)
19599 				return err;
19600 		}
19601 	} while (changed);
19602 
19603 	free_backedges(visit);
19604 	return 0;
19605 }
19606 
19607 static bool states_maybe_looping(struct bpf_verifier_state *old,
19608 				 struct bpf_verifier_state *cur)
19609 {
19610 	struct bpf_func_state *fold, *fcur;
19611 	int i, fr = cur->curframe;
19612 
19613 	if (old->curframe != fr)
19614 		return false;
19615 
19616 	fold = old->frame[fr];
19617 	fcur = cur->frame[fr];
19618 	for (i = 0; i < MAX_BPF_REG; i++)
19619 		if (memcmp(&fold->regs[i], &fcur->regs[i],
19620 			   offsetof(struct bpf_reg_state, frameno)))
19621 			return false;
19622 	return true;
19623 }
19624 
19625 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
19626 {
19627 	return env->insn_aux_data[insn_idx].is_iter_next;
19628 }
19629 
19630 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
19631  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
19632  * states to match, which otherwise would look like an infinite loop. So while
19633  * iter_next() calls are taken care of, we still need to be careful and
19634  * prevent erroneous and too eager declaration of "infinite loop", when
19635  * iterators are involved.
19636  *
19637  * Here's a situation in pseudo-BPF assembly form:
19638  *
19639  *   0: again:                          ; set up iter_next() call args
19640  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
19641  *   2:   call bpf_iter_num_next        ; this is iter_next() call
19642  *   3:   if r0 == 0 goto done
19643  *   4:   ... something useful here ...
19644  *   5:   goto again                    ; another iteration
19645  *   6: done:
19646  *   7:   r1 = &it
19647  *   8:   call bpf_iter_num_destroy     ; clean up iter state
19648  *   9:   exit
19649  *
19650  * This is a typical loop. Let's assume that we have a prune point at 1:,
19651  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
19652  * again`, assuming other heuristics don't get in a way).
19653  *
19654  * When we first time come to 1:, let's say we have some state X. We proceed
19655  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
19656  * Now we come back to validate that forked ACTIVE state. We proceed through
19657  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
19658  * are converging. But the problem is that we don't know that yet, as this
19659  * convergence has to happen at iter_next() call site only. So if nothing is
19660  * done, at 1: verifier will use bounded loop logic and declare infinite
19661  * looping (and would be *technically* correct, if not for iterator's
19662  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
19663  * don't want that. So what we do in process_iter_next_call() when we go on
19664  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
19665  * a different iteration. So when we suspect an infinite loop, we additionally
19666  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
19667  * pretend we are not looping and wait for next iter_next() call.
19668  *
19669  * This only applies to ACTIVE state. In DRAINED state we don't expect to
19670  * loop, because that would actually mean infinite loop, as DRAINED state is
19671  * "sticky", and so we'll keep returning into the same instruction with the
19672  * same state (at least in one of possible code paths).
19673  *
19674  * This approach allows to keep infinite loop heuristic even in the face of
19675  * active iterator. E.g., C snippet below is and will be detected as
19676  * infinitely looping:
19677  *
19678  *   struct bpf_iter_num it;
19679  *   int *p, x;
19680  *
19681  *   bpf_iter_num_new(&it, 0, 10);
19682  *   while ((p = bpf_iter_num_next(&t))) {
19683  *       x = p;
19684  *       while (x--) {} // <<-- infinite loop here
19685  *   }
19686  *
19687  */
19688 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
19689 {
19690 	struct bpf_reg_state *slot, *cur_slot;
19691 	struct bpf_func_state *state;
19692 	int i, fr;
19693 
19694 	for (fr = old->curframe; fr >= 0; fr--) {
19695 		state = old->frame[fr];
19696 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19697 			if (state->stack[i].slot_type[0] != STACK_ITER)
19698 				continue;
19699 
19700 			slot = &state->stack[i].spilled_ptr;
19701 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
19702 				continue;
19703 
19704 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
19705 			if (cur_slot->iter.depth != slot->iter.depth)
19706 				return true;
19707 		}
19708 	}
19709 	return false;
19710 }
19711 
19712 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
19713 {
19714 	struct bpf_verifier_state_list *new_sl;
19715 	struct bpf_verifier_state_list *sl;
19716 	struct bpf_verifier_state *cur = env->cur_state, *new;
19717 	bool force_new_state, add_new_state, loop;
19718 	int n, err, states_cnt = 0;
19719 	struct list_head *pos, *tmp, *head;
19720 
19721 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
19722 			  /* Avoid accumulating infinitely long jmp history */
19723 			  cur->jmp_history_cnt > 40;
19724 
19725 	/* bpf progs typically have pruning point every 4 instructions
19726 	 * http://vger.kernel.org/bpfconf2019.html#session-1
19727 	 * Do not add new state for future pruning if the verifier hasn't seen
19728 	 * at least 2 jumps and at least 8 instructions.
19729 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
19730 	 * In tests that amounts to up to 50% reduction into total verifier
19731 	 * memory consumption and 20% verifier time speedup.
19732 	 */
19733 	add_new_state = force_new_state;
19734 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
19735 	    env->insn_processed - env->prev_insn_processed >= 8)
19736 		add_new_state = true;
19737 
19738 	clean_live_states(env, insn_idx, cur);
19739 
19740 	loop = false;
19741 	head = explored_state(env, insn_idx);
19742 	list_for_each_safe(pos, tmp, head) {
19743 		sl = container_of(pos, struct bpf_verifier_state_list, node);
19744 		states_cnt++;
19745 		if (sl->state.insn_idx != insn_idx)
19746 			continue;
19747 
19748 		if (sl->state.branches) {
19749 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
19750 
19751 			if (frame->in_async_callback_fn &&
19752 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
19753 				/* Different async_entry_cnt means that the verifier is
19754 				 * processing another entry into async callback.
19755 				 * Seeing the same state is not an indication of infinite
19756 				 * loop or infinite recursion.
19757 				 * But finding the same state doesn't mean that it's safe
19758 				 * to stop processing the current state. The previous state
19759 				 * hasn't yet reached bpf_exit, since state.branches > 0.
19760 				 * Checking in_async_callback_fn alone is not enough either.
19761 				 * Since the verifier still needs to catch infinite loops
19762 				 * inside async callbacks.
19763 				 */
19764 				goto skip_inf_loop_check;
19765 			}
19766 			/* BPF open-coded iterators loop detection is special.
19767 			 * states_maybe_looping() logic is too simplistic in detecting
19768 			 * states that *might* be equivalent, because it doesn't know
19769 			 * about ID remapping, so don't even perform it.
19770 			 * See process_iter_next_call() and iter_active_depths_differ()
19771 			 * for overview of the logic. When current and one of parent
19772 			 * states are detected as equivalent, it's a good thing: we prove
19773 			 * convergence and can stop simulating further iterations.
19774 			 * It's safe to assume that iterator loop will finish, taking into
19775 			 * account iter_next() contract of eventually returning
19776 			 * sticky NULL result.
19777 			 *
19778 			 * Note, that states have to be compared exactly in this case because
19779 			 * read and precision marks might not be finalized inside the loop.
19780 			 * E.g. as in the program below:
19781 			 *
19782 			 *     1. r7 = -16
19783 			 *     2. r6 = bpf_get_prandom_u32()
19784 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
19785 			 *     4.   if (r6 != 42) {
19786 			 *     5.     r7 = -32
19787 			 *     6.     r6 = bpf_get_prandom_u32()
19788 			 *     7.     continue
19789 			 *     8.   }
19790 			 *     9.   r0 = r10
19791 			 *    10.   r0 += r7
19792 			 *    11.   r8 = *(u64 *)(r0 + 0)
19793 			 *    12.   r6 = bpf_get_prandom_u32()
19794 			 *    13. }
19795 			 *
19796 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
19797 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
19798 			 * not have read or precision mark for r7 yet, thus inexact states
19799 			 * comparison would discard current state with r7=-32
19800 			 * => unsafe memory access at 11 would not be caught.
19801 			 */
19802 			if (is_iter_next_insn(env, insn_idx)) {
19803 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19804 					struct bpf_func_state *cur_frame;
19805 					struct bpf_reg_state *iter_state, *iter_reg;
19806 					int spi;
19807 
19808 					cur_frame = cur->frame[cur->curframe];
19809 					/* btf_check_iter_kfuncs() enforces that
19810 					 * iter state pointer is always the first arg
19811 					 */
19812 					iter_reg = &cur_frame->regs[BPF_REG_1];
19813 					/* current state is valid due to states_equal(),
19814 					 * so we can assume valid iter and reg state,
19815 					 * no need for extra (re-)validations
19816 					 */
19817 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
19818 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
19819 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
19820 						loop = true;
19821 						goto hit;
19822 					}
19823 				}
19824 				goto skip_inf_loop_check;
19825 			}
19826 			if (is_may_goto_insn_at(env, insn_idx)) {
19827 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
19828 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19829 					loop = true;
19830 					goto hit;
19831 				}
19832 			}
19833 			if (bpf_calls_callback(env, insn_idx)) {
19834 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
19835 					goto hit;
19836 				goto skip_inf_loop_check;
19837 			}
19838 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
19839 			if (states_maybe_looping(&sl->state, cur) &&
19840 			    states_equal(env, &sl->state, cur, EXACT) &&
19841 			    !iter_active_depths_differ(&sl->state, cur) &&
19842 			    sl->state.may_goto_depth == cur->may_goto_depth &&
19843 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
19844 				verbose_linfo(env, insn_idx, "; ");
19845 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
19846 				verbose(env, "cur state:");
19847 				print_verifier_state(env, cur, cur->curframe, true);
19848 				verbose(env, "old state:");
19849 				print_verifier_state(env, &sl->state, cur->curframe, true);
19850 				return -EINVAL;
19851 			}
19852 			/* if the verifier is processing a loop, avoid adding new state
19853 			 * too often, since different loop iterations have distinct
19854 			 * states and may not help future pruning.
19855 			 * This threshold shouldn't be too low to make sure that
19856 			 * a loop with large bound will be rejected quickly.
19857 			 * The most abusive loop will be:
19858 			 * r1 += 1
19859 			 * if r1 < 1000000 goto pc-2
19860 			 * 1M insn_procssed limit / 100 == 10k peak states.
19861 			 * This threshold shouldn't be too high either, since states
19862 			 * at the end of the loop are likely to be useful in pruning.
19863 			 */
19864 skip_inf_loop_check:
19865 			if (!force_new_state &&
19866 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
19867 			    env->insn_processed - env->prev_insn_processed < 100)
19868 				add_new_state = false;
19869 			goto miss;
19870 		}
19871 		/* See comments for mark_all_regs_read_and_precise() */
19872 		loop = incomplete_read_marks(env, &sl->state);
19873 		if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) {
19874 hit:
19875 			sl->hit_cnt++;
19876 
19877 			/* if previous state reached the exit with precision and
19878 			 * current state is equivalent to it (except precision marks)
19879 			 * the precision needs to be propagated back in
19880 			 * the current state.
19881 			 */
19882 			err = 0;
19883 			if (is_jmp_point(env, env->insn_idx))
19884 				err = push_jmp_history(env, cur, 0, 0);
19885 			err = err ? : propagate_precision(env, &sl->state, cur, NULL);
19886 			if (err)
19887 				return err;
19888 			/* When processing iterator based loops above propagate_liveness and
19889 			 * propagate_precision calls are not sufficient to transfer all relevant
19890 			 * read and precision marks. E.g. consider the following case:
19891 			 *
19892 			 *  .-> A --.  Assume the states are visited in the order A, B, C.
19893 			 *  |   |   |  Assume that state B reaches a state equivalent to state A.
19894 			 *  |   v   v  At this point, state C is not processed yet, so state A
19895 			 *  '-- B   C  has not received any read or precision marks from C.
19896 			 *             Thus, marks propagated from A to B are incomplete.
19897 			 *
19898 			 * The verifier mitigates this by performing the following steps:
19899 			 *
19900 			 * - Prior to the main verification pass, strongly connected components
19901 			 *   (SCCs) are computed over the program's control flow graph,
19902 			 *   intraprocedurally.
19903 			 *
19904 			 * - During the main verification pass, `maybe_enter_scc()` checks
19905 			 *   whether the current verifier state is entering an SCC. If so, an
19906 			 *   instance of a `bpf_scc_visit` object is created, and the state
19907 			 *   entering the SCC is recorded as the entry state.
19908 			 *
19909 			 * - This instance is associated not with the SCC itself, but with a
19910 			 *   `bpf_scc_callchain`: a tuple consisting of the call sites leading to
19911 			 *   the SCC and the SCC id. See `compute_scc_callchain()`.
19912 			 *
19913 			 * - When a verification path encounters a `states_equal(...,
19914 			 *   RANGE_WITHIN)` condition, there exists a call chain describing the
19915 			 *   current state and a corresponding `bpf_scc_visit` instance. A copy
19916 			 *   of the current state is created and added to
19917 			 *   `bpf_scc_visit->backedges`.
19918 			 *
19919 			 * - When a verification path terminates, `maybe_exit_scc()` is called
19920 			 *   from `update_branch_counts()`. For states with `branches == 0`, it
19921 			 *   checks whether the state is the entry state of any `bpf_scc_visit`
19922 			 *   instance. If it is, this indicates that all paths originating from
19923 			 *   this SCC visit have been explored. `propagate_backedges()` is then
19924 			 *   called, which propagates read and precision marks through the
19925 			 *   backedges until a fixed point is reached.
19926 			 *   (In the earlier example, this would propagate marks from A to B,
19927 			 *    from C to A, and then again from A to B.)
19928 			 *
19929 			 * A note on callchains
19930 			 * --------------------
19931 			 *
19932 			 * Consider the following example:
19933 			 *
19934 			 *     void foo() { loop { ... SCC#1 ... } }
19935 			 *     void main() {
19936 			 *       A: foo();
19937 			 *       B: ...
19938 			 *       C: foo();
19939 			 *     }
19940 			 *
19941 			 * Here, there are two distinct callchains leading to SCC#1:
19942 			 * - (A, SCC#1)
19943 			 * - (C, SCC#1)
19944 			 *
19945 			 * Each callchain identifies a separate `bpf_scc_visit` instance that
19946 			 * accumulates backedge states. The `propagate_{liveness,precision}()`
19947 			 * functions traverse the parent state of each backedge state, which
19948 			 * means these parent states must remain valid (i.e., not freed) while
19949 			 * the corresponding `bpf_scc_visit` instance exists.
19950 			 *
19951 			 * Associating `bpf_scc_visit` instances directly with SCCs instead of
19952 			 * callchains would break this invariant:
19953 			 * - States explored during `C: foo()` would contribute backedges to
19954 			 *   SCC#1, but SCC#1 would only be exited once the exploration of
19955 			 *   `A: foo()` completes.
19956 			 * - By that time, the states explored between `A: foo()` and `C: foo()`
19957 			 *   (i.e., `B: ...`) may have already been freed, causing the parent
19958 			 *   links for states from `C: foo()` to become invalid.
19959 			 */
19960 			if (loop) {
19961 				struct bpf_scc_backedge *backedge;
19962 
19963 				backedge = kzalloc(sizeof(*backedge), GFP_KERNEL_ACCOUNT);
19964 				if (!backedge)
19965 					return -ENOMEM;
19966 				err = copy_verifier_state(&backedge->state, cur);
19967 				backedge->state.equal_state = &sl->state;
19968 				backedge->state.insn_idx = insn_idx;
19969 				err = err ?: add_scc_backedge(env, &sl->state, backedge);
19970 				if (err) {
19971 					free_verifier_state(&backedge->state, false);
19972 					kfree(backedge);
19973 					return err;
19974 				}
19975 			}
19976 			return 1;
19977 		}
19978 miss:
19979 		/* when new state is not going to be added do not increase miss count.
19980 		 * Otherwise several loop iterations will remove the state
19981 		 * recorded earlier. The goal of these heuristics is to have
19982 		 * states from some iterations of the loop (some in the beginning
19983 		 * and some at the end) to help pruning.
19984 		 */
19985 		if (add_new_state)
19986 			sl->miss_cnt++;
19987 		/* heuristic to determine whether this state is beneficial
19988 		 * to keep checking from state equivalence point of view.
19989 		 * Higher numbers increase max_states_per_insn and verification time,
19990 		 * but do not meaningfully decrease insn_processed.
19991 		 * 'n' controls how many times state could miss before eviction.
19992 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
19993 		 * too early would hinder iterator convergence.
19994 		 */
19995 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
19996 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
19997 			/* the state is unlikely to be useful. Remove it to
19998 			 * speed up verification
19999 			 */
20000 			sl->in_free_list = true;
20001 			list_del(&sl->node);
20002 			list_add(&sl->node, &env->free_list);
20003 			env->free_list_size++;
20004 			env->explored_states_size--;
20005 			maybe_free_verifier_state(env, sl);
20006 		}
20007 	}
20008 
20009 	if (env->max_states_per_insn < states_cnt)
20010 		env->max_states_per_insn = states_cnt;
20011 
20012 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
20013 		return 0;
20014 
20015 	if (!add_new_state)
20016 		return 0;
20017 
20018 	/* There were no equivalent states, remember the current one.
20019 	 * Technically the current state is not proven to be safe yet,
20020 	 * but it will either reach outer most bpf_exit (which means it's safe)
20021 	 * or it will be rejected. When there are no loops the verifier won't be
20022 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
20023 	 * again on the way to bpf_exit.
20024 	 * When looping the sl->state.branches will be > 0 and this state
20025 	 * will not be considered for equivalence until branches == 0.
20026 	 */
20027 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL_ACCOUNT);
20028 	if (!new_sl)
20029 		return -ENOMEM;
20030 	env->total_states++;
20031 	env->explored_states_size++;
20032 	update_peak_states(env);
20033 	env->prev_jmps_processed = env->jmps_processed;
20034 	env->prev_insn_processed = env->insn_processed;
20035 
20036 	/* forget precise markings we inherited, see __mark_chain_precision */
20037 	if (env->bpf_capable)
20038 		mark_all_scalars_imprecise(env, cur);
20039 
20040 	/* add new state to the head of linked list */
20041 	new = &new_sl->state;
20042 	err = copy_verifier_state(new, cur);
20043 	if (err) {
20044 		free_verifier_state(new, false);
20045 		kfree(new_sl);
20046 		return err;
20047 	}
20048 	new->insn_idx = insn_idx;
20049 	verifier_bug_if(new->branches != 1, env,
20050 			"%s:branches_to_explore=%d insn %d",
20051 			__func__, new->branches, insn_idx);
20052 	err = maybe_enter_scc(env, new);
20053 	if (err) {
20054 		free_verifier_state(new, false);
20055 		kfree(new_sl);
20056 		return err;
20057 	}
20058 
20059 	cur->parent = new;
20060 	cur->first_insn_idx = insn_idx;
20061 	cur->dfs_depth = new->dfs_depth + 1;
20062 	clear_jmp_history(cur);
20063 	list_add(&new_sl->node, head);
20064 	return 0;
20065 }
20066 
20067 /* Return true if it's OK to have the same insn return a different type. */
20068 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
20069 {
20070 	switch (base_type(type)) {
20071 	case PTR_TO_CTX:
20072 	case PTR_TO_SOCKET:
20073 	case PTR_TO_SOCK_COMMON:
20074 	case PTR_TO_TCP_SOCK:
20075 	case PTR_TO_XDP_SOCK:
20076 	case PTR_TO_BTF_ID:
20077 	case PTR_TO_ARENA:
20078 		return false;
20079 	default:
20080 		return true;
20081 	}
20082 }
20083 
20084 /* If an instruction was previously used with particular pointer types, then we
20085  * need to be careful to avoid cases such as the below, where it may be ok
20086  * for one branch accessing the pointer, but not ok for the other branch:
20087  *
20088  * R1 = sock_ptr
20089  * goto X;
20090  * ...
20091  * R1 = some_other_valid_ptr;
20092  * goto X;
20093  * ...
20094  * R2 = *(u32 *)(R1 + 0);
20095  */
20096 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
20097 {
20098 	return src != prev && (!reg_type_mismatch_ok(src) ||
20099 			       !reg_type_mismatch_ok(prev));
20100 }
20101 
20102 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
20103 {
20104 	switch (base_type(type)) {
20105 	case PTR_TO_MEM:
20106 	case PTR_TO_BTF_ID:
20107 		return true;
20108 	default:
20109 		return false;
20110 	}
20111 }
20112 
20113 static bool is_ptr_to_mem(enum bpf_reg_type type)
20114 {
20115 	return base_type(type) == PTR_TO_MEM;
20116 }
20117 
20118 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
20119 			     bool allow_trust_mismatch)
20120 {
20121 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
20122 	enum bpf_reg_type merged_type;
20123 
20124 	if (*prev_type == NOT_INIT) {
20125 		/* Saw a valid insn
20126 		 * dst_reg = *(u32 *)(src_reg + off)
20127 		 * save type to validate intersecting paths
20128 		 */
20129 		*prev_type = type;
20130 	} else if (reg_type_mismatch(type, *prev_type)) {
20131 		/* Abuser program is trying to use the same insn
20132 		 * dst_reg = *(u32*) (src_reg + off)
20133 		 * with different pointer types:
20134 		 * src_reg == ctx in one branch and
20135 		 * src_reg == stack|map in some other branch.
20136 		 * Reject it.
20137 		 */
20138 		if (allow_trust_mismatch &&
20139 		    is_ptr_to_mem_or_btf_id(type) &&
20140 		    is_ptr_to_mem_or_btf_id(*prev_type)) {
20141 			/*
20142 			 * Have to support a use case when one path through
20143 			 * the program yields TRUSTED pointer while another
20144 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
20145 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
20146 			 * Same behavior of MEM_RDONLY flag.
20147 			 */
20148 			if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type))
20149 				merged_type = PTR_TO_MEM;
20150 			else
20151 				merged_type = PTR_TO_BTF_ID;
20152 			if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED))
20153 				merged_type |= PTR_UNTRUSTED;
20154 			if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY))
20155 				merged_type |= MEM_RDONLY;
20156 			*prev_type = merged_type;
20157 		} else {
20158 			verbose(env, "same insn cannot be used with different pointers\n");
20159 			return -EINVAL;
20160 		}
20161 	}
20162 
20163 	return 0;
20164 }
20165 
20166 enum {
20167 	PROCESS_BPF_EXIT = 1
20168 };
20169 
20170 static int process_bpf_exit_full(struct bpf_verifier_env *env,
20171 				 bool *do_print_state,
20172 				 bool exception_exit)
20173 {
20174 	/* We must do check_reference_leak here before
20175 	 * prepare_func_exit to handle the case when
20176 	 * state->curframe > 0, it may be a callback function,
20177 	 * for which reference_state must match caller reference
20178 	 * state when it exits.
20179 	 */
20180 	int err = check_resource_leak(env, exception_exit,
20181 				      !env->cur_state->curframe,
20182 				      "BPF_EXIT instruction in main prog");
20183 	if (err)
20184 		return err;
20185 
20186 	/* The side effect of the prepare_func_exit which is
20187 	 * being skipped is that it frees bpf_func_state.
20188 	 * Typically, process_bpf_exit will only be hit with
20189 	 * outermost exit. copy_verifier_state in pop_stack will
20190 	 * handle freeing of any extra bpf_func_state left over
20191 	 * from not processing all nested function exits. We
20192 	 * also skip return code checks as they are not needed
20193 	 * for exceptional exits.
20194 	 */
20195 	if (exception_exit)
20196 		return PROCESS_BPF_EXIT;
20197 
20198 	if (env->cur_state->curframe) {
20199 		/* exit from nested function */
20200 		err = prepare_func_exit(env, &env->insn_idx);
20201 		if (err)
20202 			return err;
20203 		*do_print_state = true;
20204 		return 0;
20205 	}
20206 
20207 	err = check_return_code(env, BPF_REG_0, "R0");
20208 	if (err)
20209 		return err;
20210 	return PROCESS_BPF_EXIT;
20211 }
20212 
20213 static int indirect_jump_min_max_index(struct bpf_verifier_env *env,
20214 				       int regno,
20215 				       struct bpf_map *map,
20216 				       u32 *pmin_index, u32 *pmax_index)
20217 {
20218 	struct bpf_reg_state *reg = reg_state(env, regno);
20219 	u64 min_index, max_index;
20220 	const u32 size = 8;
20221 
20222 	if (check_add_overflow(reg->umin_value, reg->off, &min_index) ||
20223 		(min_index > (u64) U32_MAX * size)) {
20224 		verbose(env, "the sum of R%u umin_value %llu and off %u is too big\n",
20225 			     regno, reg->umin_value, reg->off);
20226 		return -ERANGE;
20227 	}
20228 	if (check_add_overflow(reg->umax_value, reg->off, &max_index) ||
20229 		(max_index > (u64) U32_MAX * size)) {
20230 		verbose(env, "the sum of R%u umax_value %llu and off %u is too big\n",
20231 			     regno, reg->umax_value, reg->off);
20232 		return -ERANGE;
20233 	}
20234 
20235 	min_index /= size;
20236 	max_index /= size;
20237 
20238 	if (max_index >= map->max_entries) {
20239 		verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n",
20240 			     regno, min_index, max_index, map->max_entries);
20241 		return -EINVAL;
20242 	}
20243 
20244 	*pmin_index = min_index;
20245 	*pmax_index = max_index;
20246 	return 0;
20247 }
20248 
20249 /* gotox *dst_reg */
20250 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
20251 {
20252 	struct bpf_verifier_state *other_branch;
20253 	struct bpf_reg_state *dst_reg;
20254 	struct bpf_map *map;
20255 	u32 min_index, max_index;
20256 	int err = 0;
20257 	int n;
20258 	int i;
20259 
20260 	dst_reg = reg_state(env, insn->dst_reg);
20261 	if (dst_reg->type != PTR_TO_INSN) {
20262 		verbose(env, "R%d has type %s, expected PTR_TO_INSN\n",
20263 			     insn->dst_reg, reg_type_str(env, dst_reg->type));
20264 		return -EINVAL;
20265 	}
20266 
20267 	map = dst_reg->map_ptr;
20268 	if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg))
20269 		return -EFAULT;
20270 
20271 	if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env,
20272 			    "R%d has incorrect map type %d", insn->dst_reg, map->map_type))
20273 		return -EFAULT;
20274 
20275 	err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
20276 	if (err)
20277 		return err;
20278 
20279 	/* Ensure that the buffer is large enough */
20280 	if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) {
20281 		env->gotox_tmp_buf = iarray_realloc(env->gotox_tmp_buf,
20282 						    max_index - min_index + 1);
20283 		if (!env->gotox_tmp_buf)
20284 			return -ENOMEM;
20285 	}
20286 
20287 	n = copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items);
20288 	if (n < 0)
20289 		return n;
20290 	if (n == 0) {
20291 		verbose(env, "register R%d doesn't point to any offset in map id=%d\n",
20292 			     insn->dst_reg, map->id);
20293 		return -EINVAL;
20294 	}
20295 
20296 	for (i = 0; i < n - 1; i++) {
20297 		other_branch = push_stack(env, env->gotox_tmp_buf->items[i],
20298 					  env->insn_idx, env->cur_state->speculative);
20299 		if (IS_ERR(other_branch))
20300 			return PTR_ERR(other_branch);
20301 	}
20302 	env->insn_idx = env->gotox_tmp_buf->items[n-1];
20303 	return 0;
20304 }
20305 
20306 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
20307 {
20308 	int err;
20309 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
20310 	u8 class = BPF_CLASS(insn->code);
20311 
20312 	if (class == BPF_ALU || class == BPF_ALU64) {
20313 		err = check_alu_op(env, insn);
20314 		if (err)
20315 			return err;
20316 
20317 	} else if (class == BPF_LDX) {
20318 		bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX;
20319 
20320 		/* Check for reserved fields is already done in
20321 		 * resolve_pseudo_ldimm64().
20322 		 */
20323 		err = check_load_mem(env, insn, false, is_ldsx, true, "ldx");
20324 		if (err)
20325 			return err;
20326 	} else if (class == BPF_STX) {
20327 		if (BPF_MODE(insn->code) == BPF_ATOMIC) {
20328 			err = check_atomic(env, insn);
20329 			if (err)
20330 				return err;
20331 			env->insn_idx++;
20332 			return 0;
20333 		}
20334 
20335 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
20336 			verbose(env, "BPF_STX uses reserved fields\n");
20337 			return -EINVAL;
20338 		}
20339 
20340 		err = check_store_reg(env, insn, false);
20341 		if (err)
20342 			return err;
20343 	} else if (class == BPF_ST) {
20344 		enum bpf_reg_type dst_reg_type;
20345 
20346 		if (BPF_MODE(insn->code) != BPF_MEM ||
20347 		    insn->src_reg != BPF_REG_0) {
20348 			verbose(env, "BPF_ST uses reserved fields\n");
20349 			return -EINVAL;
20350 		}
20351 		/* check src operand */
20352 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
20353 		if (err)
20354 			return err;
20355 
20356 		dst_reg_type = cur_regs(env)[insn->dst_reg].type;
20357 
20358 		/* check that memory (dst_reg + off) is writeable */
20359 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
20360 				       insn->off, BPF_SIZE(insn->code),
20361 				       BPF_WRITE, -1, false, false);
20362 		if (err)
20363 			return err;
20364 
20365 		err = save_aux_ptr_type(env, dst_reg_type, false);
20366 		if (err)
20367 			return err;
20368 	} else if (class == BPF_JMP || class == BPF_JMP32) {
20369 		u8 opcode = BPF_OP(insn->code);
20370 
20371 		env->jmps_processed++;
20372 		if (opcode == BPF_CALL) {
20373 			if (BPF_SRC(insn->code) != BPF_K ||
20374 			    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL &&
20375 			     insn->off != 0) ||
20376 			    (insn->src_reg != BPF_REG_0 &&
20377 			     insn->src_reg != BPF_PSEUDO_CALL &&
20378 			     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
20379 			    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
20380 				verbose(env, "BPF_CALL uses reserved fields\n");
20381 				return -EINVAL;
20382 			}
20383 
20384 			if (env->cur_state->active_locks) {
20385 				if ((insn->src_reg == BPF_REG_0 &&
20386 				     insn->imm != BPF_FUNC_spin_unlock) ||
20387 				    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
20388 				     (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
20389 					verbose(env,
20390 						"function calls are not allowed while holding a lock\n");
20391 					return -EINVAL;
20392 				}
20393 			}
20394 			if (insn->src_reg == BPF_PSEUDO_CALL) {
20395 				err = check_func_call(env, insn, &env->insn_idx);
20396 			} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
20397 				err = check_kfunc_call(env, insn, &env->insn_idx);
20398 				if (!err && is_bpf_throw_kfunc(insn))
20399 					return process_bpf_exit_full(env, do_print_state, true);
20400 			} else {
20401 				err = check_helper_call(env, insn, &env->insn_idx);
20402 			}
20403 			if (err)
20404 				return err;
20405 
20406 			mark_reg_scratched(env, BPF_REG_0);
20407 		} else if (opcode == BPF_JA) {
20408 			if (BPF_SRC(insn->code) == BPF_X) {
20409 				if (insn->src_reg != BPF_REG_0 ||
20410 				    insn->imm != 0 || insn->off != 0) {
20411 					verbose(env, "BPF_JA|BPF_X uses reserved fields\n");
20412 					return -EINVAL;
20413 				}
20414 				return check_indirect_jump(env, insn);
20415 			}
20416 
20417 			if (BPF_SRC(insn->code) != BPF_K ||
20418 			    insn->src_reg != BPF_REG_0 ||
20419 			    insn->dst_reg != BPF_REG_0 ||
20420 			    (class == BPF_JMP && insn->imm != 0) ||
20421 			    (class == BPF_JMP32 && insn->off != 0)) {
20422 				verbose(env, "BPF_JA uses reserved fields\n");
20423 				return -EINVAL;
20424 			}
20425 
20426 			if (class == BPF_JMP)
20427 				env->insn_idx += insn->off + 1;
20428 			else
20429 				env->insn_idx += insn->imm + 1;
20430 			return 0;
20431 		} else if (opcode == BPF_EXIT) {
20432 			if (BPF_SRC(insn->code) != BPF_K ||
20433 			    insn->imm != 0 ||
20434 			    insn->src_reg != BPF_REG_0 ||
20435 			    insn->dst_reg != BPF_REG_0 ||
20436 			    class == BPF_JMP32) {
20437 				verbose(env, "BPF_EXIT uses reserved fields\n");
20438 				return -EINVAL;
20439 			}
20440 			return process_bpf_exit_full(env, do_print_state, false);
20441 		} else {
20442 			err = check_cond_jmp_op(env, insn, &env->insn_idx);
20443 			if (err)
20444 				return err;
20445 		}
20446 	} else if (class == BPF_LD) {
20447 		u8 mode = BPF_MODE(insn->code);
20448 
20449 		if (mode == BPF_ABS || mode == BPF_IND) {
20450 			err = check_ld_abs(env, insn);
20451 			if (err)
20452 				return err;
20453 
20454 		} else if (mode == BPF_IMM) {
20455 			err = check_ld_imm(env, insn);
20456 			if (err)
20457 				return err;
20458 
20459 			env->insn_idx++;
20460 			sanitize_mark_insn_seen(env);
20461 		} else {
20462 			verbose(env, "invalid BPF_LD mode\n");
20463 			return -EINVAL;
20464 		}
20465 	} else {
20466 		verbose(env, "unknown insn class %d\n", class);
20467 		return -EINVAL;
20468 	}
20469 
20470 	env->insn_idx++;
20471 	return 0;
20472 }
20473 
20474 static int do_check(struct bpf_verifier_env *env)
20475 {
20476 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20477 	struct bpf_verifier_state *state = env->cur_state;
20478 	struct bpf_insn *insns = env->prog->insnsi;
20479 	int insn_cnt = env->prog->len;
20480 	bool do_print_state = false;
20481 	int prev_insn_idx = -1;
20482 
20483 	for (;;) {
20484 		struct bpf_insn *insn;
20485 		struct bpf_insn_aux_data *insn_aux;
20486 		int err, marks_err;
20487 
20488 		/* reset current history entry on each new instruction */
20489 		env->cur_hist_ent = NULL;
20490 
20491 		env->prev_insn_idx = prev_insn_idx;
20492 		if (env->insn_idx >= insn_cnt) {
20493 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
20494 				env->insn_idx, insn_cnt);
20495 			return -EFAULT;
20496 		}
20497 
20498 		insn = &insns[env->insn_idx];
20499 		insn_aux = &env->insn_aux_data[env->insn_idx];
20500 
20501 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
20502 			verbose(env,
20503 				"BPF program is too large. Processed %d insn\n",
20504 				env->insn_processed);
20505 			return -E2BIG;
20506 		}
20507 
20508 		state->last_insn_idx = env->prev_insn_idx;
20509 		state->insn_idx = env->insn_idx;
20510 
20511 		if (is_prune_point(env, env->insn_idx)) {
20512 			err = is_state_visited(env, env->insn_idx);
20513 			if (err < 0)
20514 				return err;
20515 			if (err == 1) {
20516 				/* found equivalent state, can prune the search */
20517 				if (env->log.level & BPF_LOG_LEVEL) {
20518 					if (do_print_state)
20519 						verbose(env, "\nfrom %d to %d%s: safe\n",
20520 							env->prev_insn_idx, env->insn_idx,
20521 							env->cur_state->speculative ?
20522 							" (speculative execution)" : "");
20523 					else
20524 						verbose(env, "%d: safe\n", env->insn_idx);
20525 				}
20526 				goto process_bpf_exit;
20527 			}
20528 		}
20529 
20530 		if (is_jmp_point(env, env->insn_idx)) {
20531 			err = push_jmp_history(env, state, 0, 0);
20532 			if (err)
20533 				return err;
20534 		}
20535 
20536 		if (signal_pending(current))
20537 			return -EAGAIN;
20538 
20539 		if (need_resched())
20540 			cond_resched();
20541 
20542 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
20543 			verbose(env, "\nfrom %d to %d%s:",
20544 				env->prev_insn_idx, env->insn_idx,
20545 				env->cur_state->speculative ?
20546 				" (speculative execution)" : "");
20547 			print_verifier_state(env, state, state->curframe, true);
20548 			do_print_state = false;
20549 		}
20550 
20551 		if (env->log.level & BPF_LOG_LEVEL) {
20552 			if (verifier_state_scratched(env))
20553 				print_insn_state(env, state, state->curframe);
20554 
20555 			verbose_linfo(env, env->insn_idx, "; ");
20556 			env->prev_log_pos = env->log.end_pos;
20557 			verbose(env, "%d: ", env->insn_idx);
20558 			verbose_insn(env, insn);
20559 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
20560 			env->prev_log_pos = env->log.end_pos;
20561 		}
20562 
20563 		if (bpf_prog_is_offloaded(env->prog->aux)) {
20564 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
20565 							   env->prev_insn_idx);
20566 			if (err)
20567 				return err;
20568 		}
20569 
20570 		sanitize_mark_insn_seen(env);
20571 		prev_insn_idx = env->insn_idx;
20572 
20573 		/* Reduce verification complexity by stopping speculative path
20574 		 * verification when a nospec is encountered.
20575 		 */
20576 		if (state->speculative && insn_aux->nospec)
20577 			goto process_bpf_exit;
20578 
20579 		err = bpf_reset_stack_write_marks(env, env->insn_idx);
20580 		if (err)
20581 			return err;
20582 		err = do_check_insn(env, &do_print_state);
20583 		if (err >= 0 || error_recoverable_with_nospec(err)) {
20584 			marks_err = bpf_commit_stack_write_marks(env);
20585 			if (marks_err)
20586 				return marks_err;
20587 		}
20588 		if (error_recoverable_with_nospec(err) && state->speculative) {
20589 			/* Prevent this speculative path from ever reaching the
20590 			 * insn that would have been unsafe to execute.
20591 			 */
20592 			insn_aux->nospec = true;
20593 			/* If it was an ADD/SUB insn, potentially remove any
20594 			 * markings for alu sanitization.
20595 			 */
20596 			insn_aux->alu_state = 0;
20597 			goto process_bpf_exit;
20598 		} else if (err < 0) {
20599 			return err;
20600 		} else if (err == PROCESS_BPF_EXIT) {
20601 			goto process_bpf_exit;
20602 		}
20603 		WARN_ON_ONCE(err);
20604 
20605 		if (state->speculative && insn_aux->nospec_result) {
20606 			/* If we are on a path that performed a jump-op, this
20607 			 * may skip a nospec patched-in after the jump. This can
20608 			 * currently never happen because nospec_result is only
20609 			 * used for the write-ops
20610 			 * `*(size*)(dst_reg+off)=src_reg|imm32` which must
20611 			 * never skip the following insn. Still, add a warning
20612 			 * to document this in case nospec_result is used
20613 			 * elsewhere in the future.
20614 			 *
20615 			 * All non-branch instructions have a single
20616 			 * fall-through edge. For these, nospec_result should
20617 			 * already work.
20618 			 */
20619 			if (verifier_bug_if(BPF_CLASS(insn->code) == BPF_JMP ||
20620 					    BPF_CLASS(insn->code) == BPF_JMP32, env,
20621 					    "speculation barrier after jump instruction may not have the desired effect"))
20622 				return -EFAULT;
20623 process_bpf_exit:
20624 			mark_verifier_state_scratched(env);
20625 			err = update_branch_counts(env, env->cur_state);
20626 			if (err)
20627 				return err;
20628 			err = bpf_update_live_stack(env);
20629 			if (err)
20630 				return err;
20631 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
20632 					pop_log);
20633 			if (err < 0) {
20634 				if (err != -ENOENT)
20635 					return err;
20636 				break;
20637 			} else {
20638 				do_print_state = true;
20639 				continue;
20640 			}
20641 		}
20642 	}
20643 
20644 	return 0;
20645 }
20646 
20647 static int find_btf_percpu_datasec(struct btf *btf)
20648 {
20649 	const struct btf_type *t;
20650 	const char *tname;
20651 	int i, n;
20652 
20653 	/*
20654 	 * Both vmlinux and module each have their own ".data..percpu"
20655 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
20656 	 * types to look at only module's own BTF types.
20657 	 */
20658 	n = btf_nr_types(btf);
20659 	if (btf_is_module(btf))
20660 		i = btf_nr_types(btf_vmlinux);
20661 	else
20662 		i = 1;
20663 
20664 	for(; i < n; i++) {
20665 		t = btf_type_by_id(btf, i);
20666 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
20667 			continue;
20668 
20669 		tname = btf_name_by_offset(btf, t->name_off);
20670 		if (!strcmp(tname, ".data..percpu"))
20671 			return i;
20672 	}
20673 
20674 	return -ENOENT;
20675 }
20676 
20677 /*
20678  * Add btf to the used_btfs array and return the index. (If the btf was
20679  * already added, then just return the index.) Upon successful insertion
20680  * increase btf refcnt, and, if present, also refcount the corresponding
20681  * kernel module.
20682  */
20683 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
20684 {
20685 	struct btf_mod_pair *btf_mod;
20686 	int i;
20687 
20688 	/* check whether we recorded this BTF (and maybe module) already */
20689 	for (i = 0; i < env->used_btf_cnt; i++)
20690 		if (env->used_btfs[i].btf == btf)
20691 			return i;
20692 
20693 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
20694 		verbose(env, "The total number of btfs per program has reached the limit of %u\n",
20695 			MAX_USED_BTFS);
20696 		return -E2BIG;
20697 	}
20698 
20699 	btf_get(btf);
20700 
20701 	btf_mod = &env->used_btfs[env->used_btf_cnt];
20702 	btf_mod->btf = btf;
20703 	btf_mod->module = NULL;
20704 
20705 	/* if we reference variables from kernel module, bump its refcount */
20706 	if (btf_is_module(btf)) {
20707 		btf_mod->module = btf_try_get_module(btf);
20708 		if (!btf_mod->module) {
20709 			btf_put(btf);
20710 			return -ENXIO;
20711 		}
20712 	}
20713 
20714 	return env->used_btf_cnt++;
20715 }
20716 
20717 /* replace pseudo btf_id with kernel symbol address */
20718 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
20719 				 struct bpf_insn *insn,
20720 				 struct bpf_insn_aux_data *aux,
20721 				 struct btf *btf)
20722 {
20723 	const struct btf_var_secinfo *vsi;
20724 	const struct btf_type *datasec;
20725 	const struct btf_type *t;
20726 	const char *sym_name;
20727 	bool percpu = false;
20728 	u32 type, id = insn->imm;
20729 	s32 datasec_id;
20730 	u64 addr;
20731 	int i;
20732 
20733 	t = btf_type_by_id(btf, id);
20734 	if (!t) {
20735 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
20736 		return -ENOENT;
20737 	}
20738 
20739 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
20740 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
20741 		return -EINVAL;
20742 	}
20743 
20744 	sym_name = btf_name_by_offset(btf, t->name_off);
20745 	addr = kallsyms_lookup_name(sym_name);
20746 	if (!addr) {
20747 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
20748 			sym_name);
20749 		return -ENOENT;
20750 	}
20751 	insn[0].imm = (u32)addr;
20752 	insn[1].imm = addr >> 32;
20753 
20754 	if (btf_type_is_func(t)) {
20755 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20756 		aux->btf_var.mem_size = 0;
20757 		return 0;
20758 	}
20759 
20760 	datasec_id = find_btf_percpu_datasec(btf);
20761 	if (datasec_id > 0) {
20762 		datasec = btf_type_by_id(btf, datasec_id);
20763 		for_each_vsi(i, datasec, vsi) {
20764 			if (vsi->type == id) {
20765 				percpu = true;
20766 				break;
20767 			}
20768 		}
20769 	}
20770 
20771 	type = t->type;
20772 	t = btf_type_skip_modifiers(btf, type, NULL);
20773 	if (percpu) {
20774 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
20775 		aux->btf_var.btf = btf;
20776 		aux->btf_var.btf_id = type;
20777 	} else if (!btf_type_is_struct(t)) {
20778 		const struct btf_type *ret;
20779 		const char *tname;
20780 		u32 tsize;
20781 
20782 		/* resolve the type size of ksym. */
20783 		ret = btf_resolve_size(btf, t, &tsize);
20784 		if (IS_ERR(ret)) {
20785 			tname = btf_name_by_offset(btf, t->name_off);
20786 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
20787 				tname, PTR_ERR(ret));
20788 			return -EINVAL;
20789 		}
20790 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20791 		aux->btf_var.mem_size = tsize;
20792 	} else {
20793 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
20794 		aux->btf_var.btf = btf;
20795 		aux->btf_var.btf_id = type;
20796 	}
20797 
20798 	return 0;
20799 }
20800 
20801 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
20802 			       struct bpf_insn *insn,
20803 			       struct bpf_insn_aux_data *aux)
20804 {
20805 	struct btf *btf;
20806 	int btf_fd;
20807 	int err;
20808 
20809 	btf_fd = insn[1].imm;
20810 	if (btf_fd) {
20811 		CLASS(fd, f)(btf_fd);
20812 
20813 		btf = __btf_get_by_fd(f);
20814 		if (IS_ERR(btf)) {
20815 			verbose(env, "invalid module BTF object FD specified.\n");
20816 			return -EINVAL;
20817 		}
20818 	} else {
20819 		if (!btf_vmlinux) {
20820 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
20821 			return -EINVAL;
20822 		}
20823 		btf = btf_vmlinux;
20824 	}
20825 
20826 	err = __check_pseudo_btf_id(env, insn, aux, btf);
20827 	if (err)
20828 		return err;
20829 
20830 	err = __add_used_btf(env, btf);
20831 	if (err < 0)
20832 		return err;
20833 	return 0;
20834 }
20835 
20836 static bool is_tracing_prog_type(enum bpf_prog_type type)
20837 {
20838 	switch (type) {
20839 	case BPF_PROG_TYPE_KPROBE:
20840 	case BPF_PROG_TYPE_TRACEPOINT:
20841 	case BPF_PROG_TYPE_PERF_EVENT:
20842 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
20843 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
20844 		return true;
20845 	default:
20846 		return false;
20847 	}
20848 }
20849 
20850 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
20851 {
20852 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
20853 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
20854 }
20855 
20856 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
20857 					struct bpf_map *map,
20858 					struct bpf_prog *prog)
20859 
20860 {
20861 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
20862 
20863 	if (map->excl_prog_sha &&
20864 	    memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) {
20865 		verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
20866 		return -EACCES;
20867 	}
20868 
20869 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
20870 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
20871 		if (is_tracing_prog_type(prog_type)) {
20872 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
20873 			return -EINVAL;
20874 		}
20875 	}
20876 
20877 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
20878 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
20879 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
20880 			return -EINVAL;
20881 		}
20882 
20883 		if (is_tracing_prog_type(prog_type)) {
20884 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
20885 			return -EINVAL;
20886 		}
20887 	}
20888 
20889 	if (btf_record_has_field(map->record, BPF_TIMER)) {
20890 		if (is_tracing_prog_type(prog_type)) {
20891 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
20892 			return -EINVAL;
20893 		}
20894 	}
20895 
20896 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
20897 		if (is_tracing_prog_type(prog_type)) {
20898 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
20899 			return -EINVAL;
20900 		}
20901 	}
20902 
20903 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
20904 	    !bpf_offload_prog_map_match(prog, map)) {
20905 		verbose(env, "offload device mismatch between prog and map\n");
20906 		return -EINVAL;
20907 	}
20908 
20909 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
20910 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
20911 		return -EINVAL;
20912 	}
20913 
20914 	if (prog->sleepable)
20915 		switch (map->map_type) {
20916 		case BPF_MAP_TYPE_HASH:
20917 		case BPF_MAP_TYPE_LRU_HASH:
20918 		case BPF_MAP_TYPE_ARRAY:
20919 		case BPF_MAP_TYPE_PERCPU_HASH:
20920 		case BPF_MAP_TYPE_PERCPU_ARRAY:
20921 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
20922 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
20923 		case BPF_MAP_TYPE_HASH_OF_MAPS:
20924 		case BPF_MAP_TYPE_RINGBUF:
20925 		case BPF_MAP_TYPE_USER_RINGBUF:
20926 		case BPF_MAP_TYPE_INODE_STORAGE:
20927 		case BPF_MAP_TYPE_SK_STORAGE:
20928 		case BPF_MAP_TYPE_TASK_STORAGE:
20929 		case BPF_MAP_TYPE_CGRP_STORAGE:
20930 		case BPF_MAP_TYPE_QUEUE:
20931 		case BPF_MAP_TYPE_STACK:
20932 		case BPF_MAP_TYPE_ARENA:
20933 		case BPF_MAP_TYPE_INSN_ARRAY:
20934 			break;
20935 		default:
20936 			verbose(env,
20937 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
20938 			return -EINVAL;
20939 		}
20940 
20941 	if (bpf_map_is_cgroup_storage(map) &&
20942 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
20943 		verbose(env, "only one cgroup storage of each type is allowed\n");
20944 		return -EBUSY;
20945 	}
20946 
20947 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
20948 		if (env->prog->aux->arena) {
20949 			verbose(env, "Only one arena per program\n");
20950 			return -EBUSY;
20951 		}
20952 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
20953 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
20954 			return -EPERM;
20955 		}
20956 		if (!env->prog->jit_requested) {
20957 			verbose(env, "JIT is required to use arena\n");
20958 			return -EOPNOTSUPP;
20959 		}
20960 		if (!bpf_jit_supports_arena()) {
20961 			verbose(env, "JIT doesn't support arena\n");
20962 			return -EOPNOTSUPP;
20963 		}
20964 		env->prog->aux->arena = (void *)map;
20965 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
20966 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
20967 			return -EINVAL;
20968 		}
20969 	}
20970 
20971 	return 0;
20972 }
20973 
20974 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
20975 {
20976 	int i, err;
20977 
20978 	/* check whether we recorded this map already */
20979 	for (i = 0; i < env->used_map_cnt; i++)
20980 		if (env->used_maps[i] == map)
20981 			return i;
20982 
20983 	if (env->used_map_cnt >= MAX_USED_MAPS) {
20984 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
20985 			MAX_USED_MAPS);
20986 		return -E2BIG;
20987 	}
20988 
20989 	err = check_map_prog_compatibility(env, map, env->prog);
20990 	if (err)
20991 		return err;
20992 
20993 	if (env->prog->sleepable)
20994 		atomic64_inc(&map->sleepable_refcnt);
20995 
20996 	/* hold the map. If the program is rejected by verifier,
20997 	 * the map will be released by release_maps() or it
20998 	 * will be used by the valid program until it's unloaded
20999 	 * and all maps are released in bpf_free_used_maps()
21000 	 */
21001 	bpf_map_inc(map);
21002 
21003 	env->used_maps[env->used_map_cnt++] = map;
21004 
21005 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
21006 		err = bpf_insn_array_init(map, env->prog);
21007 		if (err) {
21008 			verbose(env, "Failed to properly initialize insn array\n");
21009 			return err;
21010 		}
21011 		env->insn_array_maps[env->insn_array_map_cnt++] = map;
21012 	}
21013 
21014 	return env->used_map_cnt - 1;
21015 }
21016 
21017 /* Add map behind fd to used maps list, if it's not already there, and return
21018  * its index.
21019  * Returns <0 on error, or >= 0 index, on success.
21020  */
21021 static int add_used_map(struct bpf_verifier_env *env, int fd)
21022 {
21023 	struct bpf_map *map;
21024 	CLASS(fd, f)(fd);
21025 
21026 	map = __bpf_map_get(f);
21027 	if (IS_ERR(map)) {
21028 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
21029 		return PTR_ERR(map);
21030 	}
21031 
21032 	return __add_used_map(env, map);
21033 }
21034 
21035 /* find and rewrite pseudo imm in ld_imm64 instructions:
21036  *
21037  * 1. if it accesses map FD, replace it with actual map pointer.
21038  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
21039  *
21040  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
21041  */
21042 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
21043 {
21044 	struct bpf_insn *insn = env->prog->insnsi;
21045 	int insn_cnt = env->prog->len;
21046 	int i, err;
21047 
21048 	err = bpf_prog_calc_tag(env->prog);
21049 	if (err)
21050 		return err;
21051 
21052 	for (i = 0; i < insn_cnt; i++, insn++) {
21053 		if (BPF_CLASS(insn->code) == BPF_LDX &&
21054 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
21055 		    insn->imm != 0)) {
21056 			verbose(env, "BPF_LDX uses reserved fields\n");
21057 			return -EINVAL;
21058 		}
21059 
21060 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
21061 			struct bpf_insn_aux_data *aux;
21062 			struct bpf_map *map;
21063 			int map_idx;
21064 			u64 addr;
21065 			u32 fd;
21066 
21067 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
21068 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
21069 			    insn[1].off != 0) {
21070 				verbose(env, "invalid bpf_ld_imm64 insn\n");
21071 				return -EINVAL;
21072 			}
21073 
21074 			if (insn[0].src_reg == 0)
21075 				/* valid generic load 64-bit imm */
21076 				goto next_insn;
21077 
21078 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
21079 				aux = &env->insn_aux_data[i];
21080 				err = check_pseudo_btf_id(env, insn, aux);
21081 				if (err)
21082 					return err;
21083 				goto next_insn;
21084 			}
21085 
21086 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
21087 				aux = &env->insn_aux_data[i];
21088 				aux->ptr_type = PTR_TO_FUNC;
21089 				goto next_insn;
21090 			}
21091 
21092 			/* In final convert_pseudo_ld_imm64() step, this is
21093 			 * converted into regular 64-bit imm load insn.
21094 			 */
21095 			switch (insn[0].src_reg) {
21096 			case BPF_PSEUDO_MAP_VALUE:
21097 			case BPF_PSEUDO_MAP_IDX_VALUE:
21098 				break;
21099 			case BPF_PSEUDO_MAP_FD:
21100 			case BPF_PSEUDO_MAP_IDX:
21101 				if (insn[1].imm == 0)
21102 					break;
21103 				fallthrough;
21104 			default:
21105 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
21106 				return -EINVAL;
21107 			}
21108 
21109 			switch (insn[0].src_reg) {
21110 			case BPF_PSEUDO_MAP_IDX_VALUE:
21111 			case BPF_PSEUDO_MAP_IDX:
21112 				if (bpfptr_is_null(env->fd_array)) {
21113 					verbose(env, "fd_idx without fd_array is invalid\n");
21114 					return -EPROTO;
21115 				}
21116 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
21117 							    insn[0].imm * sizeof(fd),
21118 							    sizeof(fd)))
21119 					return -EFAULT;
21120 				break;
21121 			default:
21122 				fd = insn[0].imm;
21123 				break;
21124 			}
21125 
21126 			map_idx = add_used_map(env, fd);
21127 			if (map_idx < 0)
21128 				return map_idx;
21129 			map = env->used_maps[map_idx];
21130 
21131 			aux = &env->insn_aux_data[i];
21132 			aux->map_index = map_idx;
21133 
21134 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
21135 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
21136 				addr = (unsigned long)map;
21137 			} else {
21138 				u32 off = insn[1].imm;
21139 
21140 				if (off >= BPF_MAX_VAR_OFF) {
21141 					verbose(env, "direct value offset of %u is not allowed\n", off);
21142 					return -EINVAL;
21143 				}
21144 
21145 				if (!map->ops->map_direct_value_addr) {
21146 					verbose(env, "no direct value access support for this map type\n");
21147 					return -EINVAL;
21148 				}
21149 
21150 				err = map->ops->map_direct_value_addr(map, &addr, off);
21151 				if (err) {
21152 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
21153 						map->value_size, off);
21154 					return err;
21155 				}
21156 
21157 				aux->map_off = off;
21158 				addr += off;
21159 			}
21160 
21161 			insn[0].imm = (u32)addr;
21162 			insn[1].imm = addr >> 32;
21163 
21164 next_insn:
21165 			insn++;
21166 			i++;
21167 			continue;
21168 		}
21169 
21170 		/* Basic sanity check before we invest more work here. */
21171 		if (!bpf_opcode_in_insntable(insn->code)) {
21172 			verbose(env, "unknown opcode %02x\n", insn->code);
21173 			return -EINVAL;
21174 		}
21175 	}
21176 
21177 	/* now all pseudo BPF_LD_IMM64 instructions load valid
21178 	 * 'struct bpf_map *' into a register instead of user map_fd.
21179 	 * These pointers will be used later by verifier to validate map access.
21180 	 */
21181 	return 0;
21182 }
21183 
21184 /* drop refcnt of maps used by the rejected program */
21185 static void release_maps(struct bpf_verifier_env *env)
21186 {
21187 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
21188 			     env->used_map_cnt);
21189 }
21190 
21191 /* drop refcnt of maps used by the rejected program */
21192 static void release_btfs(struct bpf_verifier_env *env)
21193 {
21194 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
21195 }
21196 
21197 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
21198 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
21199 {
21200 	struct bpf_insn *insn = env->prog->insnsi;
21201 	int insn_cnt = env->prog->len;
21202 	int i;
21203 
21204 	for (i = 0; i < insn_cnt; i++, insn++) {
21205 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
21206 			continue;
21207 		if (insn->src_reg == BPF_PSEUDO_FUNC)
21208 			continue;
21209 		insn->src_reg = 0;
21210 	}
21211 }
21212 
21213 /* single env->prog->insni[off] instruction was replaced with the range
21214  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
21215  * [0, off) and [off, end) to new locations, so the patched range stays zero
21216  */
21217 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
21218 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
21219 {
21220 	struct bpf_insn_aux_data *data = env->insn_aux_data;
21221 	struct bpf_insn *insn = new_prog->insnsi;
21222 	u32 old_seen = data[off].seen;
21223 	u32 prog_len;
21224 	int i;
21225 
21226 	/* aux info at OFF always needs adjustment, no matter fast path
21227 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
21228 	 * original insn at old prog.
21229 	 */
21230 	data[off].zext_dst = insn_has_def32(insn + off + cnt - 1);
21231 
21232 	if (cnt == 1)
21233 		return;
21234 	prog_len = new_prog->len;
21235 
21236 	memmove(data + off + cnt - 1, data + off,
21237 		sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
21238 	memset(data + off, 0, sizeof(struct bpf_insn_aux_data) * (cnt - 1));
21239 	for (i = off; i < off + cnt - 1; i++) {
21240 		/* Expand insni[off]'s seen count to the patched range. */
21241 		data[i].seen = old_seen;
21242 		data[i].zext_dst = insn_has_def32(insn + i);
21243 	}
21244 }
21245 
21246 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
21247 {
21248 	int i;
21249 
21250 	if (len == 1)
21251 		return;
21252 	/* NOTE: fake 'exit' subprog should be updated as well. */
21253 	for (i = 0; i <= env->subprog_cnt; i++) {
21254 		if (env->subprog_info[i].start <= off)
21255 			continue;
21256 		env->subprog_info[i].start += len - 1;
21257 	}
21258 }
21259 
21260 static void release_insn_arrays(struct bpf_verifier_env *env)
21261 {
21262 	int i;
21263 
21264 	for (i = 0; i < env->insn_array_map_cnt; i++)
21265 		bpf_insn_array_release(env->insn_array_maps[i]);
21266 }
21267 
21268 static void adjust_insn_arrays(struct bpf_verifier_env *env, u32 off, u32 len)
21269 {
21270 	int i;
21271 
21272 	if (len == 1)
21273 		return;
21274 
21275 	for (i = 0; i < env->insn_array_map_cnt; i++)
21276 		bpf_insn_array_adjust(env->insn_array_maps[i], off, len);
21277 }
21278 
21279 static void adjust_insn_arrays_after_remove(struct bpf_verifier_env *env, u32 off, u32 len)
21280 {
21281 	int i;
21282 
21283 	for (i = 0; i < env->insn_array_map_cnt; i++)
21284 		bpf_insn_array_adjust_after_remove(env->insn_array_maps[i], off, len);
21285 }
21286 
21287 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
21288 {
21289 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
21290 	int i, sz = prog->aux->size_poke_tab;
21291 	struct bpf_jit_poke_descriptor *desc;
21292 
21293 	for (i = 0; i < sz; i++) {
21294 		desc = &tab[i];
21295 		if (desc->insn_idx <= off)
21296 			continue;
21297 		desc->insn_idx += len - 1;
21298 	}
21299 }
21300 
21301 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
21302 					    const struct bpf_insn *patch, u32 len)
21303 {
21304 	struct bpf_prog *new_prog;
21305 	struct bpf_insn_aux_data *new_data = NULL;
21306 
21307 	if (len > 1) {
21308 		new_data = vrealloc(env->insn_aux_data,
21309 				    array_size(env->prog->len + len - 1,
21310 					       sizeof(struct bpf_insn_aux_data)),
21311 				    GFP_KERNEL_ACCOUNT | __GFP_ZERO);
21312 		if (!new_data)
21313 			return NULL;
21314 
21315 		env->insn_aux_data = new_data;
21316 	}
21317 
21318 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
21319 	if (IS_ERR(new_prog)) {
21320 		if (PTR_ERR(new_prog) == -ERANGE)
21321 			verbose(env,
21322 				"insn %d cannot be patched due to 16-bit range\n",
21323 				env->insn_aux_data[off].orig_idx);
21324 		return NULL;
21325 	}
21326 	adjust_insn_aux_data(env, new_prog, off, len);
21327 	adjust_subprog_starts(env, off, len);
21328 	adjust_insn_arrays(env, off, len);
21329 	adjust_poke_descs(new_prog, off, len);
21330 	return new_prog;
21331 }
21332 
21333 /*
21334  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
21335  * jump offset by 'delta'.
21336  */
21337 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
21338 {
21339 	struct bpf_insn *insn = prog->insnsi;
21340 	u32 insn_cnt = prog->len, i;
21341 	s32 imm;
21342 	s16 off;
21343 
21344 	for (i = 0; i < insn_cnt; i++, insn++) {
21345 		u8 code = insn->code;
21346 
21347 		if (tgt_idx <= i && i < tgt_idx + delta)
21348 			continue;
21349 
21350 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
21351 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
21352 			continue;
21353 
21354 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
21355 			if (i + 1 + insn->imm != tgt_idx)
21356 				continue;
21357 			if (check_add_overflow(insn->imm, delta, &imm))
21358 				return -ERANGE;
21359 			insn->imm = imm;
21360 		} else {
21361 			if (i + 1 + insn->off != tgt_idx)
21362 				continue;
21363 			if (check_add_overflow(insn->off, delta, &off))
21364 				return -ERANGE;
21365 			insn->off = off;
21366 		}
21367 	}
21368 	return 0;
21369 }
21370 
21371 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
21372 					      u32 off, u32 cnt)
21373 {
21374 	int i, j;
21375 
21376 	/* find first prog starting at or after off (first to remove) */
21377 	for (i = 0; i < env->subprog_cnt; i++)
21378 		if (env->subprog_info[i].start >= off)
21379 			break;
21380 	/* find first prog starting at or after off + cnt (first to stay) */
21381 	for (j = i; j < env->subprog_cnt; j++)
21382 		if (env->subprog_info[j].start >= off + cnt)
21383 			break;
21384 	/* if j doesn't start exactly at off + cnt, we are just removing
21385 	 * the front of previous prog
21386 	 */
21387 	if (env->subprog_info[j].start != off + cnt)
21388 		j--;
21389 
21390 	if (j > i) {
21391 		struct bpf_prog_aux *aux = env->prog->aux;
21392 		int move;
21393 
21394 		/* move fake 'exit' subprog as well */
21395 		move = env->subprog_cnt + 1 - j;
21396 
21397 		memmove(env->subprog_info + i,
21398 			env->subprog_info + j,
21399 			sizeof(*env->subprog_info) * move);
21400 		env->subprog_cnt -= j - i;
21401 
21402 		/* remove func_info */
21403 		if (aux->func_info) {
21404 			move = aux->func_info_cnt - j;
21405 
21406 			memmove(aux->func_info + i,
21407 				aux->func_info + j,
21408 				sizeof(*aux->func_info) * move);
21409 			aux->func_info_cnt -= j - i;
21410 			/* func_info->insn_off is set after all code rewrites,
21411 			 * in adjust_btf_func() - no need to adjust
21412 			 */
21413 		}
21414 	} else {
21415 		/* convert i from "first prog to remove" to "first to adjust" */
21416 		if (env->subprog_info[i].start == off)
21417 			i++;
21418 	}
21419 
21420 	/* update fake 'exit' subprog as well */
21421 	for (; i <= env->subprog_cnt; i++)
21422 		env->subprog_info[i].start -= cnt;
21423 
21424 	return 0;
21425 }
21426 
21427 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
21428 				      u32 cnt)
21429 {
21430 	struct bpf_prog *prog = env->prog;
21431 	u32 i, l_off, l_cnt, nr_linfo;
21432 	struct bpf_line_info *linfo;
21433 
21434 	nr_linfo = prog->aux->nr_linfo;
21435 	if (!nr_linfo)
21436 		return 0;
21437 
21438 	linfo = prog->aux->linfo;
21439 
21440 	/* find first line info to remove, count lines to be removed */
21441 	for (i = 0; i < nr_linfo; i++)
21442 		if (linfo[i].insn_off >= off)
21443 			break;
21444 
21445 	l_off = i;
21446 	l_cnt = 0;
21447 	for (; i < nr_linfo; i++)
21448 		if (linfo[i].insn_off < off + cnt)
21449 			l_cnt++;
21450 		else
21451 			break;
21452 
21453 	/* First live insn doesn't match first live linfo, it needs to "inherit"
21454 	 * last removed linfo.  prog is already modified, so prog->len == off
21455 	 * means no live instructions after (tail of the program was removed).
21456 	 */
21457 	if (prog->len != off && l_cnt &&
21458 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
21459 		l_cnt--;
21460 		linfo[--i].insn_off = off + cnt;
21461 	}
21462 
21463 	/* remove the line info which refer to the removed instructions */
21464 	if (l_cnt) {
21465 		memmove(linfo + l_off, linfo + i,
21466 			sizeof(*linfo) * (nr_linfo - i));
21467 
21468 		prog->aux->nr_linfo -= l_cnt;
21469 		nr_linfo = prog->aux->nr_linfo;
21470 	}
21471 
21472 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
21473 	for (i = l_off; i < nr_linfo; i++)
21474 		linfo[i].insn_off -= cnt;
21475 
21476 	/* fix up all subprogs (incl. 'exit') which start >= off */
21477 	for (i = 0; i <= env->subprog_cnt; i++)
21478 		if (env->subprog_info[i].linfo_idx > l_off) {
21479 			/* program may have started in the removed region but
21480 			 * may not be fully removed
21481 			 */
21482 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
21483 				env->subprog_info[i].linfo_idx -= l_cnt;
21484 			else
21485 				env->subprog_info[i].linfo_idx = l_off;
21486 		}
21487 
21488 	return 0;
21489 }
21490 
21491 /*
21492  * Clean up dynamically allocated fields of aux data for instructions [start, ...]
21493  */
21494 static void clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
21495 {
21496 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21497 	struct bpf_insn *insns = env->prog->insnsi;
21498 	int end = start + len;
21499 	int i;
21500 
21501 	for (i = start; i < end; i++) {
21502 		if (aux_data[i].jt) {
21503 			kvfree(aux_data[i].jt);
21504 			aux_data[i].jt = NULL;
21505 		}
21506 
21507 		if (bpf_is_ldimm64(&insns[i]))
21508 			i++;
21509 	}
21510 }
21511 
21512 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
21513 {
21514 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21515 	unsigned int orig_prog_len = env->prog->len;
21516 	int err;
21517 
21518 	if (bpf_prog_is_offloaded(env->prog->aux))
21519 		bpf_prog_offload_remove_insns(env, off, cnt);
21520 
21521 	/* Should be called before bpf_remove_insns, as it uses prog->insnsi */
21522 	clear_insn_aux_data(env, off, cnt);
21523 
21524 	err = bpf_remove_insns(env->prog, off, cnt);
21525 	if (err)
21526 		return err;
21527 
21528 	err = adjust_subprog_starts_after_remove(env, off, cnt);
21529 	if (err)
21530 		return err;
21531 
21532 	err = bpf_adj_linfo_after_remove(env, off, cnt);
21533 	if (err)
21534 		return err;
21535 
21536 	adjust_insn_arrays_after_remove(env, off, cnt);
21537 
21538 	memmove(aux_data + off,	aux_data + off + cnt,
21539 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
21540 
21541 	return 0;
21542 }
21543 
21544 /* The verifier does more data flow analysis than llvm and will not
21545  * explore branches that are dead at run time. Malicious programs can
21546  * have dead code too. Therefore replace all dead at-run-time code
21547  * with 'ja -1'.
21548  *
21549  * Just nops are not optimal, e.g. if they would sit at the end of the
21550  * program and through another bug we would manage to jump there, then
21551  * we'd execute beyond program memory otherwise. Returning exception
21552  * code also wouldn't work since we can have subprogs where the dead
21553  * code could be located.
21554  */
21555 static void sanitize_dead_code(struct bpf_verifier_env *env)
21556 {
21557 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21558 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
21559 	struct bpf_insn *insn = env->prog->insnsi;
21560 	const int insn_cnt = env->prog->len;
21561 	int i;
21562 
21563 	for (i = 0; i < insn_cnt; i++) {
21564 		if (aux_data[i].seen)
21565 			continue;
21566 		memcpy(insn + i, &trap, sizeof(trap));
21567 		aux_data[i].zext_dst = false;
21568 	}
21569 }
21570 
21571 static bool insn_is_cond_jump(u8 code)
21572 {
21573 	u8 op;
21574 
21575 	op = BPF_OP(code);
21576 	if (BPF_CLASS(code) == BPF_JMP32)
21577 		return op != BPF_JA;
21578 
21579 	if (BPF_CLASS(code) != BPF_JMP)
21580 		return false;
21581 
21582 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
21583 }
21584 
21585 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
21586 {
21587 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21588 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21589 	struct bpf_insn *insn = env->prog->insnsi;
21590 	const int insn_cnt = env->prog->len;
21591 	int i;
21592 
21593 	for (i = 0; i < insn_cnt; i++, insn++) {
21594 		if (!insn_is_cond_jump(insn->code))
21595 			continue;
21596 
21597 		if (!aux_data[i + 1].seen)
21598 			ja.off = insn->off;
21599 		else if (!aux_data[i + 1 + insn->off].seen)
21600 			ja.off = 0;
21601 		else
21602 			continue;
21603 
21604 		if (bpf_prog_is_offloaded(env->prog->aux))
21605 			bpf_prog_offload_replace_insn(env, i, &ja);
21606 
21607 		memcpy(insn, &ja, sizeof(ja));
21608 	}
21609 }
21610 
21611 static int opt_remove_dead_code(struct bpf_verifier_env *env)
21612 {
21613 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21614 	int insn_cnt = env->prog->len;
21615 	int i, err;
21616 
21617 	for (i = 0; i < insn_cnt; i++) {
21618 		int j;
21619 
21620 		j = 0;
21621 		while (i + j < insn_cnt && !aux_data[i + j].seen)
21622 			j++;
21623 		if (!j)
21624 			continue;
21625 
21626 		err = verifier_remove_insns(env, i, j);
21627 		if (err)
21628 			return err;
21629 		insn_cnt = env->prog->len;
21630 	}
21631 
21632 	return 0;
21633 }
21634 
21635 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21636 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0);
21637 
21638 static int opt_remove_nops(struct bpf_verifier_env *env)
21639 {
21640 	struct bpf_insn *insn = env->prog->insnsi;
21641 	int insn_cnt = env->prog->len;
21642 	bool is_may_goto_0, is_ja;
21643 	int i, err;
21644 
21645 	for (i = 0; i < insn_cnt; i++) {
21646 		is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
21647 		is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP));
21648 
21649 		if (!is_may_goto_0 && !is_ja)
21650 			continue;
21651 
21652 		err = verifier_remove_insns(env, i, 1);
21653 		if (err)
21654 			return err;
21655 		insn_cnt--;
21656 		/* Go back one insn to catch may_goto +1; may_goto +0 sequence */
21657 		i -= (is_may_goto_0 && i > 0) ? 2 : 1;
21658 	}
21659 
21660 	return 0;
21661 }
21662 
21663 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
21664 					 const union bpf_attr *attr)
21665 {
21666 	struct bpf_insn *patch;
21667 	/* use env->insn_buf as two independent buffers */
21668 	struct bpf_insn *zext_patch = env->insn_buf;
21669 	struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2];
21670 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
21671 	int i, patch_len, delta = 0, len = env->prog->len;
21672 	struct bpf_insn *insns = env->prog->insnsi;
21673 	struct bpf_prog *new_prog;
21674 	bool rnd_hi32;
21675 
21676 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
21677 	zext_patch[1] = BPF_ZEXT_REG(0);
21678 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
21679 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
21680 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
21681 	for (i = 0; i < len; i++) {
21682 		int adj_idx = i + delta;
21683 		struct bpf_insn insn;
21684 		int load_reg;
21685 
21686 		insn = insns[adj_idx];
21687 		load_reg = insn_def_regno(&insn);
21688 		if (!aux[adj_idx].zext_dst) {
21689 			u8 code, class;
21690 			u32 imm_rnd;
21691 
21692 			if (!rnd_hi32)
21693 				continue;
21694 
21695 			code = insn.code;
21696 			class = BPF_CLASS(code);
21697 			if (load_reg == -1)
21698 				continue;
21699 
21700 			/* NOTE: arg "reg" (the fourth one) is only used for
21701 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
21702 			 *       here.
21703 			 */
21704 			if (is_reg64(&insn, load_reg, NULL, DST_OP)) {
21705 				if (class == BPF_LD &&
21706 				    BPF_MODE(code) == BPF_IMM)
21707 					i++;
21708 				continue;
21709 			}
21710 
21711 			/* ctx load could be transformed into wider load. */
21712 			if (class == BPF_LDX &&
21713 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
21714 				continue;
21715 
21716 			imm_rnd = get_random_u32();
21717 			rnd_hi32_patch[0] = insn;
21718 			rnd_hi32_patch[1].imm = imm_rnd;
21719 			rnd_hi32_patch[3].dst_reg = load_reg;
21720 			patch = rnd_hi32_patch;
21721 			patch_len = 4;
21722 			goto apply_patch_buffer;
21723 		}
21724 
21725 		/* Add in an zero-extend instruction if a) the JIT has requested
21726 		 * it or b) it's a CMPXCHG.
21727 		 *
21728 		 * The latter is because: BPF_CMPXCHG always loads a value into
21729 		 * R0, therefore always zero-extends. However some archs'
21730 		 * equivalent instruction only does this load when the
21731 		 * comparison is successful. This detail of CMPXCHG is
21732 		 * orthogonal to the general zero-extension behaviour of the
21733 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
21734 		 */
21735 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
21736 			continue;
21737 
21738 		/* Zero-extension is done by the caller. */
21739 		if (bpf_pseudo_kfunc_call(&insn))
21740 			continue;
21741 
21742 		if (verifier_bug_if(load_reg == -1, env,
21743 				    "zext_dst is set, but no reg is defined"))
21744 			return -EFAULT;
21745 
21746 		zext_patch[0] = insn;
21747 		zext_patch[1].dst_reg = load_reg;
21748 		zext_patch[1].src_reg = load_reg;
21749 		patch = zext_patch;
21750 		patch_len = 2;
21751 apply_patch_buffer:
21752 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
21753 		if (!new_prog)
21754 			return -ENOMEM;
21755 		env->prog = new_prog;
21756 		insns = new_prog->insnsi;
21757 		aux = env->insn_aux_data;
21758 		delta += patch_len - 1;
21759 	}
21760 
21761 	return 0;
21762 }
21763 
21764 /* convert load instructions that access fields of a context type into a
21765  * sequence of instructions that access fields of the underlying structure:
21766  *     struct __sk_buff    -> struct sk_buff
21767  *     struct bpf_sock_ops -> struct sock
21768  */
21769 static int convert_ctx_accesses(struct bpf_verifier_env *env)
21770 {
21771 	struct bpf_subprog_info *subprogs = env->subprog_info;
21772 	const struct bpf_verifier_ops *ops = env->ops;
21773 	int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
21774 	const int insn_cnt = env->prog->len;
21775 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
21776 	struct bpf_insn *insn_buf = env->insn_buf;
21777 	struct bpf_insn *insn;
21778 	u32 target_size, size_default, off;
21779 	struct bpf_prog *new_prog;
21780 	enum bpf_access_type type;
21781 	bool is_narrower_load;
21782 	int epilogue_idx = 0;
21783 
21784 	if (ops->gen_epilogue) {
21785 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
21786 						 -(subprogs[0].stack_depth + 8));
21787 		if (epilogue_cnt >= INSN_BUF_SIZE) {
21788 			verifier_bug(env, "epilogue is too long");
21789 			return -EFAULT;
21790 		} else if (epilogue_cnt) {
21791 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
21792 			cnt = 0;
21793 			subprogs[0].stack_depth += 8;
21794 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
21795 						      -subprogs[0].stack_depth);
21796 			insn_buf[cnt++] = env->prog->insnsi[0];
21797 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21798 			if (!new_prog)
21799 				return -ENOMEM;
21800 			env->prog = new_prog;
21801 			delta += cnt - 1;
21802 
21803 			ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
21804 			if (ret < 0)
21805 				return ret;
21806 		}
21807 	}
21808 
21809 	if (ops->gen_prologue || env->seen_direct_write) {
21810 		if (!ops->gen_prologue) {
21811 			verifier_bug(env, "gen_prologue is null");
21812 			return -EFAULT;
21813 		}
21814 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
21815 					env->prog);
21816 		if (cnt >= INSN_BUF_SIZE) {
21817 			verifier_bug(env, "prologue is too long");
21818 			return -EFAULT;
21819 		} else if (cnt) {
21820 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21821 			if (!new_prog)
21822 				return -ENOMEM;
21823 
21824 			env->prog = new_prog;
21825 			delta += cnt - 1;
21826 
21827 			ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
21828 			if (ret < 0)
21829 				return ret;
21830 		}
21831 	}
21832 
21833 	if (delta)
21834 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
21835 
21836 	if (bpf_prog_is_offloaded(env->prog->aux))
21837 		return 0;
21838 
21839 	insn = env->prog->insnsi + delta;
21840 
21841 	for (i = 0; i < insn_cnt; i++, insn++) {
21842 		bpf_convert_ctx_access_t convert_ctx_access;
21843 		u8 mode;
21844 
21845 		if (env->insn_aux_data[i + delta].nospec) {
21846 			WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state);
21847 			struct bpf_insn *patch = insn_buf;
21848 
21849 			*patch++ = BPF_ST_NOSPEC();
21850 			*patch++ = *insn;
21851 			cnt = patch - insn_buf;
21852 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21853 			if (!new_prog)
21854 				return -ENOMEM;
21855 
21856 			delta    += cnt - 1;
21857 			env->prog = new_prog;
21858 			insn      = new_prog->insnsi + i + delta;
21859 			/* This can not be easily merged with the
21860 			 * nospec_result-case, because an insn may require a
21861 			 * nospec before and after itself. Therefore also do not
21862 			 * 'continue' here but potentially apply further
21863 			 * patching to insn. *insn should equal patch[1] now.
21864 			 */
21865 		}
21866 
21867 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
21868 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
21869 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
21870 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
21871 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
21872 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
21873 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
21874 			type = BPF_READ;
21875 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
21876 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
21877 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
21878 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
21879 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
21880 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
21881 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
21882 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
21883 			type = BPF_WRITE;
21884 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) ||
21885 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) ||
21886 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
21887 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
21888 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
21889 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
21890 			env->prog->aux->num_exentries++;
21891 			continue;
21892 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
21893 			   epilogue_cnt &&
21894 			   i + delta < subprogs[1].start) {
21895 			/* Generate epilogue for the main prog */
21896 			if (epilogue_idx) {
21897 				/* jump back to the earlier generated epilogue */
21898 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
21899 				cnt = 1;
21900 			} else {
21901 				memcpy(insn_buf, epilogue_buf,
21902 				       epilogue_cnt * sizeof(*epilogue_buf));
21903 				cnt = epilogue_cnt;
21904 				/* epilogue_idx cannot be 0. It must have at
21905 				 * least one ctx ptr saving insn before the
21906 				 * epilogue.
21907 				 */
21908 				epilogue_idx = i + delta;
21909 			}
21910 			goto patch_insn_buf;
21911 		} else {
21912 			continue;
21913 		}
21914 
21915 		if (type == BPF_WRITE &&
21916 		    env->insn_aux_data[i + delta].nospec_result) {
21917 			/* nospec_result is only used to mitigate Spectre v4 and
21918 			 * to limit verification-time for Spectre v1.
21919 			 */
21920 			struct bpf_insn *patch = insn_buf;
21921 
21922 			*patch++ = *insn;
21923 			*patch++ = BPF_ST_NOSPEC();
21924 			cnt = patch - insn_buf;
21925 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21926 			if (!new_prog)
21927 				return -ENOMEM;
21928 
21929 			delta    += cnt - 1;
21930 			env->prog = new_prog;
21931 			insn      = new_prog->insnsi + i + delta;
21932 			continue;
21933 		}
21934 
21935 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
21936 		case PTR_TO_CTX:
21937 			if (!ops->convert_ctx_access)
21938 				continue;
21939 			convert_ctx_access = ops->convert_ctx_access;
21940 			break;
21941 		case PTR_TO_SOCKET:
21942 		case PTR_TO_SOCK_COMMON:
21943 			convert_ctx_access = bpf_sock_convert_ctx_access;
21944 			break;
21945 		case PTR_TO_TCP_SOCK:
21946 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
21947 			break;
21948 		case PTR_TO_XDP_SOCK:
21949 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
21950 			break;
21951 		case PTR_TO_BTF_ID:
21952 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
21953 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
21954 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
21955 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
21956 		 * any faults for loads into such types. BPF_WRITE is disallowed
21957 		 * for this case.
21958 		 */
21959 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
21960 		case PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED:
21961 			if (type == BPF_READ) {
21962 				if (BPF_MODE(insn->code) == BPF_MEM)
21963 					insn->code = BPF_LDX | BPF_PROBE_MEM |
21964 						     BPF_SIZE((insn)->code);
21965 				else
21966 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
21967 						     BPF_SIZE((insn)->code);
21968 				env->prog->aux->num_exentries++;
21969 			}
21970 			continue;
21971 		case PTR_TO_ARENA:
21972 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
21973 				if (!bpf_jit_supports_insn(insn, true)) {
21974 					verbose(env, "sign extending loads from arena are not supported yet\n");
21975 					return -EOPNOTSUPP;
21976 				}
21977 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32SX | BPF_SIZE(insn->code);
21978 			} else {
21979 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
21980 			}
21981 			env->prog->aux->num_exentries++;
21982 			continue;
21983 		default:
21984 			continue;
21985 		}
21986 
21987 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
21988 		size = BPF_LDST_BYTES(insn);
21989 		mode = BPF_MODE(insn->code);
21990 
21991 		/* If the read access is a narrower load of the field,
21992 		 * convert to a 4/8-byte load, to minimum program type specific
21993 		 * convert_ctx_access changes. If conversion is successful,
21994 		 * we will apply proper mask to the result.
21995 		 */
21996 		is_narrower_load = size < ctx_field_size;
21997 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
21998 		off = insn->off;
21999 		if (is_narrower_load) {
22000 			u8 size_code;
22001 
22002 			if (type == BPF_WRITE) {
22003 				verifier_bug(env, "narrow ctx access misconfigured");
22004 				return -EFAULT;
22005 			}
22006 
22007 			size_code = BPF_H;
22008 			if (ctx_field_size == 4)
22009 				size_code = BPF_W;
22010 			else if (ctx_field_size == 8)
22011 				size_code = BPF_DW;
22012 
22013 			insn->off = off & ~(size_default - 1);
22014 			insn->code = BPF_LDX | BPF_MEM | size_code;
22015 		}
22016 
22017 		target_size = 0;
22018 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
22019 					 &target_size);
22020 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
22021 		    (ctx_field_size && !target_size)) {
22022 			verifier_bug(env, "error during ctx access conversion (%d)", cnt);
22023 			return -EFAULT;
22024 		}
22025 
22026 		if (is_narrower_load && size < target_size) {
22027 			u8 shift = bpf_ctx_narrow_access_offset(
22028 				off, size, size_default) * 8;
22029 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
22030 				verifier_bug(env, "narrow ctx load misconfigured");
22031 				return -EFAULT;
22032 			}
22033 			if (ctx_field_size <= 4) {
22034 				if (shift)
22035 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
22036 									insn->dst_reg,
22037 									shift);
22038 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
22039 								(1 << size * 8) - 1);
22040 			} else {
22041 				if (shift)
22042 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
22043 									insn->dst_reg,
22044 									shift);
22045 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
22046 								(1ULL << size * 8) - 1);
22047 			}
22048 		}
22049 		if (mode == BPF_MEMSX)
22050 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
22051 						       insn->dst_reg, insn->dst_reg,
22052 						       size * 8, 0);
22053 
22054 patch_insn_buf:
22055 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22056 		if (!new_prog)
22057 			return -ENOMEM;
22058 
22059 		delta += cnt - 1;
22060 
22061 		/* keep walking new program and skip insns we just inserted */
22062 		env->prog = new_prog;
22063 		insn      = new_prog->insnsi + i + delta;
22064 	}
22065 
22066 	return 0;
22067 }
22068 
22069 static int jit_subprogs(struct bpf_verifier_env *env)
22070 {
22071 	struct bpf_prog *prog = env->prog, **func, *tmp;
22072 	int i, j, subprog_start, subprog_end = 0, len, subprog;
22073 	struct bpf_map *map_ptr;
22074 	struct bpf_insn *insn;
22075 	void *old_bpf_func;
22076 	int err, num_exentries;
22077 	int old_len, subprog_start_adjustment = 0;
22078 
22079 	if (env->subprog_cnt <= 1)
22080 		return 0;
22081 
22082 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22083 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
22084 			continue;
22085 
22086 		/* Upon error here we cannot fall back to interpreter but
22087 		 * need a hard reject of the program. Thus -EFAULT is
22088 		 * propagated in any case.
22089 		 */
22090 		subprog = find_subprog(env, i + insn->imm + 1);
22091 		if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d",
22092 				    i + insn->imm + 1))
22093 			return -EFAULT;
22094 		/* temporarily remember subprog id inside insn instead of
22095 		 * aux_data, since next loop will split up all insns into funcs
22096 		 */
22097 		insn->off = subprog;
22098 		/* remember original imm in case JIT fails and fallback
22099 		 * to interpreter will be needed
22100 		 */
22101 		env->insn_aux_data[i].call_imm = insn->imm;
22102 		/* point imm to __bpf_call_base+1 from JITs point of view */
22103 		insn->imm = 1;
22104 		if (bpf_pseudo_func(insn)) {
22105 #if defined(MODULES_VADDR)
22106 			u64 addr = MODULES_VADDR;
22107 #else
22108 			u64 addr = VMALLOC_START;
22109 #endif
22110 			/* jit (e.g. x86_64) may emit fewer instructions
22111 			 * if it learns a u32 imm is the same as a u64 imm.
22112 			 * Set close enough to possible prog address.
22113 			 */
22114 			insn[0].imm = (u32)addr;
22115 			insn[1].imm = addr >> 32;
22116 		}
22117 	}
22118 
22119 	err = bpf_prog_alloc_jited_linfo(prog);
22120 	if (err)
22121 		goto out_undo_insn;
22122 
22123 	err = -ENOMEM;
22124 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
22125 	if (!func)
22126 		goto out_undo_insn;
22127 
22128 	for (i = 0; i < env->subprog_cnt; i++) {
22129 		subprog_start = subprog_end;
22130 		subprog_end = env->subprog_info[i + 1].start;
22131 
22132 		len = subprog_end - subprog_start;
22133 		/* bpf_prog_run() doesn't call subprogs directly,
22134 		 * hence main prog stats include the runtime of subprogs.
22135 		 * subprogs don't have IDs and not reachable via prog_get_next_id
22136 		 * func[i]->stats will never be accessed and stays NULL
22137 		 */
22138 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
22139 		if (!func[i])
22140 			goto out_free;
22141 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
22142 		       len * sizeof(struct bpf_insn));
22143 		func[i]->type = prog->type;
22144 		func[i]->len = len;
22145 		if (bpf_prog_calc_tag(func[i]))
22146 			goto out_free;
22147 		func[i]->is_func = 1;
22148 		func[i]->sleepable = prog->sleepable;
22149 		func[i]->aux->func_idx = i;
22150 		/* Below members will be freed only at prog->aux */
22151 		func[i]->aux->btf = prog->aux->btf;
22152 		func[i]->aux->subprog_start = subprog_start + subprog_start_adjustment;
22153 		func[i]->aux->func_info = prog->aux->func_info;
22154 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
22155 		func[i]->aux->poke_tab = prog->aux->poke_tab;
22156 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
22157 		func[i]->aux->main_prog_aux = prog->aux;
22158 
22159 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
22160 			struct bpf_jit_poke_descriptor *poke;
22161 
22162 			poke = &prog->aux->poke_tab[j];
22163 			if (poke->insn_idx < subprog_end &&
22164 			    poke->insn_idx >= subprog_start)
22165 				poke->aux = func[i]->aux;
22166 		}
22167 
22168 		func[i]->aux->name[0] = 'F';
22169 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
22170 		if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
22171 			func[i]->aux->jits_use_priv_stack = true;
22172 
22173 		func[i]->jit_requested = 1;
22174 		func[i]->blinding_requested = prog->blinding_requested;
22175 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
22176 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
22177 		func[i]->aux->linfo = prog->aux->linfo;
22178 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
22179 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
22180 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
22181 		func[i]->aux->arena = prog->aux->arena;
22182 		func[i]->aux->used_maps = env->used_maps;
22183 		func[i]->aux->used_map_cnt = env->used_map_cnt;
22184 		num_exentries = 0;
22185 		insn = func[i]->insnsi;
22186 		for (j = 0; j < func[i]->len; j++, insn++) {
22187 			if (BPF_CLASS(insn->code) == BPF_LDX &&
22188 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22189 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
22190 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32SX ||
22191 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
22192 				num_exentries++;
22193 			if ((BPF_CLASS(insn->code) == BPF_STX ||
22194 			     BPF_CLASS(insn->code) == BPF_ST) &&
22195 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
22196 				num_exentries++;
22197 			if (BPF_CLASS(insn->code) == BPF_STX &&
22198 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
22199 				num_exentries++;
22200 		}
22201 		func[i]->aux->num_exentries = num_exentries;
22202 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
22203 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
22204 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
22205 		func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
22206 		if (!i)
22207 			func[i]->aux->exception_boundary = env->seen_exception;
22208 
22209 		/*
22210 		 * To properly pass the absolute subprog start to jit
22211 		 * all instruction adjustments should be accumulated
22212 		 */
22213 		old_len = func[i]->len;
22214 		func[i] = bpf_int_jit_compile(func[i]);
22215 		subprog_start_adjustment += func[i]->len - old_len;
22216 
22217 		if (!func[i]->jited) {
22218 			err = -ENOTSUPP;
22219 			goto out_free;
22220 		}
22221 		cond_resched();
22222 	}
22223 
22224 	/* at this point all bpf functions were successfully JITed
22225 	 * now populate all bpf_calls with correct addresses and
22226 	 * run last pass of JIT
22227 	 */
22228 	for (i = 0; i < env->subprog_cnt; i++) {
22229 		insn = func[i]->insnsi;
22230 		for (j = 0; j < func[i]->len; j++, insn++) {
22231 			if (bpf_pseudo_func(insn)) {
22232 				subprog = insn->off;
22233 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
22234 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
22235 				continue;
22236 			}
22237 			if (!bpf_pseudo_call(insn))
22238 				continue;
22239 			subprog = insn->off;
22240 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
22241 		}
22242 
22243 		/* we use the aux data to keep a list of the start addresses
22244 		 * of the JITed images for each function in the program
22245 		 *
22246 		 * for some architectures, such as powerpc64, the imm field
22247 		 * might not be large enough to hold the offset of the start
22248 		 * address of the callee's JITed image from __bpf_call_base
22249 		 *
22250 		 * in such cases, we can lookup the start address of a callee
22251 		 * by using its subprog id, available from the off field of
22252 		 * the call instruction, as an index for this list
22253 		 */
22254 		func[i]->aux->func = func;
22255 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
22256 		func[i]->aux->real_func_cnt = env->subprog_cnt;
22257 	}
22258 	for (i = 0; i < env->subprog_cnt; i++) {
22259 		old_bpf_func = func[i]->bpf_func;
22260 		tmp = bpf_int_jit_compile(func[i]);
22261 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
22262 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
22263 			err = -ENOTSUPP;
22264 			goto out_free;
22265 		}
22266 		cond_resched();
22267 	}
22268 
22269 	/*
22270 	 * Cleanup func[i]->aux fields which aren't required
22271 	 * or can become invalid in future
22272 	 */
22273 	for (i = 0; i < env->subprog_cnt; i++) {
22274 		func[i]->aux->used_maps = NULL;
22275 		func[i]->aux->used_map_cnt = 0;
22276 	}
22277 
22278 	/* finally lock prog and jit images for all functions and
22279 	 * populate kallsysm. Begin at the first subprogram, since
22280 	 * bpf_prog_load will add the kallsyms for the main program.
22281 	 */
22282 	for (i = 1; i < env->subprog_cnt; i++) {
22283 		err = bpf_prog_lock_ro(func[i]);
22284 		if (err)
22285 			goto out_free;
22286 	}
22287 
22288 	for (i = 1; i < env->subprog_cnt; i++)
22289 		bpf_prog_kallsyms_add(func[i]);
22290 
22291 	/* Last step: make now unused interpreter insns from main
22292 	 * prog consistent for later dump requests, so they can
22293 	 * later look the same as if they were interpreted only.
22294 	 */
22295 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22296 		if (bpf_pseudo_func(insn)) {
22297 			insn[0].imm = env->insn_aux_data[i].call_imm;
22298 			insn[1].imm = insn->off;
22299 			insn->off = 0;
22300 			continue;
22301 		}
22302 		if (!bpf_pseudo_call(insn))
22303 			continue;
22304 		insn->off = env->insn_aux_data[i].call_imm;
22305 		subprog = find_subprog(env, i + insn->off + 1);
22306 		insn->imm = subprog;
22307 	}
22308 
22309 	prog->jited = 1;
22310 	prog->bpf_func = func[0]->bpf_func;
22311 	prog->jited_len = func[0]->jited_len;
22312 	prog->aux->extable = func[0]->aux->extable;
22313 	prog->aux->num_exentries = func[0]->aux->num_exentries;
22314 	prog->aux->func = func;
22315 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
22316 	prog->aux->real_func_cnt = env->subprog_cnt;
22317 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
22318 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
22319 	bpf_prog_jit_attempt_done(prog);
22320 	return 0;
22321 out_free:
22322 	/* We failed JIT'ing, so at this point we need to unregister poke
22323 	 * descriptors from subprogs, so that kernel is not attempting to
22324 	 * patch it anymore as we're freeing the subprog JIT memory.
22325 	 */
22326 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
22327 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
22328 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
22329 	}
22330 	/* At this point we're guaranteed that poke descriptors are not
22331 	 * live anymore. We can just unlink its descriptor table as it's
22332 	 * released with the main prog.
22333 	 */
22334 	for (i = 0; i < env->subprog_cnt; i++) {
22335 		if (!func[i])
22336 			continue;
22337 		func[i]->aux->poke_tab = NULL;
22338 		bpf_jit_free(func[i]);
22339 	}
22340 	kfree(func);
22341 out_undo_insn:
22342 	/* cleanup main prog to be interpreted */
22343 	prog->jit_requested = 0;
22344 	prog->blinding_requested = 0;
22345 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22346 		if (!bpf_pseudo_call(insn))
22347 			continue;
22348 		insn->off = 0;
22349 		insn->imm = env->insn_aux_data[i].call_imm;
22350 	}
22351 	bpf_prog_jit_attempt_done(prog);
22352 	return err;
22353 }
22354 
22355 static int fixup_call_args(struct bpf_verifier_env *env)
22356 {
22357 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
22358 	struct bpf_prog *prog = env->prog;
22359 	struct bpf_insn *insn = prog->insnsi;
22360 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
22361 	int i, depth;
22362 #endif
22363 	int err = 0;
22364 
22365 	if (env->prog->jit_requested &&
22366 	    !bpf_prog_is_offloaded(env->prog->aux)) {
22367 		err = jit_subprogs(env);
22368 		if (err == 0)
22369 			return 0;
22370 		if (err == -EFAULT)
22371 			return err;
22372 	}
22373 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
22374 	if (has_kfunc_call) {
22375 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
22376 		return -EINVAL;
22377 	}
22378 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
22379 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
22380 		 * have to be rejected, since interpreter doesn't support them yet.
22381 		 */
22382 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
22383 		return -EINVAL;
22384 	}
22385 	for (i = 0; i < prog->len; i++, insn++) {
22386 		if (bpf_pseudo_func(insn)) {
22387 			/* When JIT fails the progs with callback calls
22388 			 * have to be rejected, since interpreter doesn't support them yet.
22389 			 */
22390 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
22391 			return -EINVAL;
22392 		}
22393 
22394 		if (!bpf_pseudo_call(insn))
22395 			continue;
22396 		depth = get_callee_stack_depth(env, insn, i);
22397 		if (depth < 0)
22398 			return depth;
22399 		bpf_patch_call_args(insn, depth);
22400 	}
22401 	err = 0;
22402 #endif
22403 	return err;
22404 }
22405 
22406 /* replace a generic kfunc with a specialized version if necessary */
22407 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)
22408 {
22409 	struct bpf_prog *prog = env->prog;
22410 	bool seen_direct_write;
22411 	void *xdp_kfunc;
22412 	bool is_rdonly;
22413 	u32 func_id = desc->func_id;
22414 	u16 offset = desc->offset;
22415 	unsigned long addr = desc->addr;
22416 
22417 	if (offset) /* return if module BTF is used */
22418 		return 0;
22419 
22420 	if (bpf_dev_bound_kfunc_id(func_id)) {
22421 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
22422 		if (xdp_kfunc)
22423 			addr = (unsigned long)xdp_kfunc;
22424 		/* fallback to default kfunc when not supported by netdev */
22425 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
22426 		seen_direct_write = env->seen_direct_write;
22427 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
22428 
22429 		if (is_rdonly)
22430 			addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
22431 
22432 		/* restore env->seen_direct_write to its original value, since
22433 		 * may_access_direct_pkt_data mutates it
22434 		 */
22435 		env->seen_direct_write = seen_direct_write;
22436 	} else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {
22437 		if (bpf_lsm_has_d_inode_locked(prog))
22438 			addr = (unsigned long)bpf_set_dentry_xattr_locked;
22439 	} else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
22440 		if (bpf_lsm_has_d_inode_locked(prog))
22441 			addr = (unsigned long)bpf_remove_dentry_xattr_locked;
22442 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
22443 		if (!env->insn_aux_data[insn_idx].non_sleepable)
22444 			addr = (unsigned long)bpf_dynptr_from_file_sleepable;
22445 	}
22446 	desc->addr = addr;
22447 	return 0;
22448 }
22449 
22450 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
22451 					    u16 struct_meta_reg,
22452 					    u16 node_offset_reg,
22453 					    struct bpf_insn *insn,
22454 					    struct bpf_insn *insn_buf,
22455 					    int *cnt)
22456 {
22457 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
22458 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
22459 
22460 	insn_buf[0] = addr[0];
22461 	insn_buf[1] = addr[1];
22462 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
22463 	insn_buf[3] = *insn;
22464 	*cnt = 4;
22465 }
22466 
22467 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
22468 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
22469 {
22470 	struct bpf_kfunc_desc *desc;
22471 	int err;
22472 
22473 	if (!insn->imm) {
22474 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
22475 		return -EINVAL;
22476 	}
22477 
22478 	*cnt = 0;
22479 
22480 	/* insn->imm has the btf func_id. Replace it with an offset relative to
22481 	 * __bpf_call_base, unless the JIT needs to call functions that are
22482 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
22483 	 */
22484 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
22485 	if (!desc) {
22486 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
22487 			     insn->imm);
22488 		return -EFAULT;
22489 	}
22490 
22491 	err = specialize_kfunc(env, desc, insn_idx);
22492 	if (err)
22493 		return err;
22494 
22495 	if (!bpf_jit_supports_far_kfunc_call())
22496 		insn->imm = BPF_CALL_IMM(desc->addr);
22497 	if (insn->off)
22498 		return 0;
22499 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
22500 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
22501 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22502 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
22503 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
22504 
22505 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
22506 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
22507 				     insn_idx);
22508 			return -EFAULT;
22509 		}
22510 
22511 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
22512 		insn_buf[1] = addr[0];
22513 		insn_buf[2] = addr[1];
22514 		insn_buf[3] = *insn;
22515 		*cnt = 4;
22516 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
22517 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
22518 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
22519 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22520 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
22521 
22522 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
22523 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
22524 				     insn_idx);
22525 			return -EFAULT;
22526 		}
22527 
22528 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
22529 		    !kptr_struct_meta) {
22530 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
22531 				     insn_idx);
22532 			return -EFAULT;
22533 		}
22534 
22535 		insn_buf[0] = addr[0];
22536 		insn_buf[1] = addr[1];
22537 		insn_buf[2] = *insn;
22538 		*cnt = 3;
22539 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
22540 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
22541 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
22542 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22543 		int struct_meta_reg = BPF_REG_3;
22544 		int node_offset_reg = BPF_REG_4;
22545 
22546 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
22547 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
22548 			struct_meta_reg = BPF_REG_4;
22549 			node_offset_reg = BPF_REG_5;
22550 		}
22551 
22552 		if (!kptr_struct_meta) {
22553 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
22554 				     insn_idx);
22555 			return -EFAULT;
22556 		}
22557 
22558 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
22559 						node_offset_reg, insn, insn_buf, cnt);
22560 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
22561 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
22562 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
22563 		*cnt = 1;
22564 	}
22565 
22566 	if (env->insn_aux_data[insn_idx].arg_prog) {
22567 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
22568 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
22569 		int idx = *cnt;
22570 
22571 		insn_buf[idx++] = ld_addrs[0];
22572 		insn_buf[idx++] = ld_addrs[1];
22573 		insn_buf[idx++] = *insn;
22574 		*cnt = idx;
22575 	}
22576 	return 0;
22577 }
22578 
22579 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
22580 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
22581 {
22582 	struct bpf_subprog_info *info = env->subprog_info;
22583 	int cnt = env->subprog_cnt;
22584 	struct bpf_prog *prog;
22585 
22586 	/* We only reserve one slot for hidden subprogs in subprog_info. */
22587 	if (env->hidden_subprog_cnt) {
22588 		verifier_bug(env, "only one hidden subprog supported");
22589 		return -EFAULT;
22590 	}
22591 	/* We're not patching any existing instruction, just appending the new
22592 	 * ones for the hidden subprog. Hence all of the adjustment operations
22593 	 * in bpf_patch_insn_data are no-ops.
22594 	 */
22595 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
22596 	if (!prog)
22597 		return -ENOMEM;
22598 	env->prog = prog;
22599 	info[cnt + 1].start = info[cnt].start;
22600 	info[cnt].start = prog->len - len + 1;
22601 	env->subprog_cnt++;
22602 	env->hidden_subprog_cnt++;
22603 	return 0;
22604 }
22605 
22606 /* Do various post-verification rewrites in a single program pass.
22607  * These rewrites simplify JIT and interpreter implementations.
22608  */
22609 static int do_misc_fixups(struct bpf_verifier_env *env)
22610 {
22611 	struct bpf_prog *prog = env->prog;
22612 	enum bpf_attach_type eatype = prog->expected_attach_type;
22613 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
22614 	struct bpf_insn *insn = prog->insnsi;
22615 	const struct bpf_func_proto *fn;
22616 	const int insn_cnt = prog->len;
22617 	const struct bpf_map_ops *ops;
22618 	struct bpf_insn_aux_data *aux;
22619 	struct bpf_insn *insn_buf = env->insn_buf;
22620 	struct bpf_prog *new_prog;
22621 	struct bpf_map *map_ptr;
22622 	int i, ret, cnt, delta = 0, cur_subprog = 0;
22623 	struct bpf_subprog_info *subprogs = env->subprog_info;
22624 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
22625 	u16 stack_depth_extra = 0;
22626 
22627 	if (env->seen_exception && !env->exception_callback_subprog) {
22628 		struct bpf_insn *patch = insn_buf;
22629 
22630 		*patch++ = env->prog->insnsi[insn_cnt - 1];
22631 		*patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
22632 		*patch++ = BPF_EXIT_INSN();
22633 		ret = add_hidden_subprog(env, insn_buf, patch - insn_buf);
22634 		if (ret < 0)
22635 			return ret;
22636 		prog = env->prog;
22637 		insn = prog->insnsi;
22638 
22639 		env->exception_callback_subprog = env->subprog_cnt - 1;
22640 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
22641 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
22642 	}
22643 
22644 	for (i = 0; i < insn_cnt;) {
22645 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
22646 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
22647 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
22648 				/* convert to 32-bit mov that clears upper 32-bit */
22649 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
22650 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
22651 				insn->off = 0;
22652 				insn->imm = 0;
22653 			} /* cast from as(0) to as(1) should be handled by JIT */
22654 			goto next_insn;
22655 		}
22656 
22657 		if (env->insn_aux_data[i + delta].needs_zext)
22658 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
22659 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
22660 
22661 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
22662 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
22663 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
22664 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
22665 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
22666 		    insn->off == 1 && insn->imm == -1) {
22667 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22668 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22669 			struct bpf_insn *patch = insn_buf;
22670 
22671 			if (isdiv)
22672 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22673 							BPF_NEG | BPF_K, insn->dst_reg,
22674 							0, 0, 0);
22675 			else
22676 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22677 
22678 			cnt = patch - insn_buf;
22679 
22680 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22681 			if (!new_prog)
22682 				return -ENOMEM;
22683 
22684 			delta    += cnt - 1;
22685 			env->prog = prog = new_prog;
22686 			insn      = new_prog->insnsi + i + delta;
22687 			goto next_insn;
22688 		}
22689 
22690 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
22691 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
22692 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
22693 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
22694 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
22695 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22696 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22697 			bool is_sdiv = isdiv && insn->off == 1;
22698 			bool is_smod = !isdiv && insn->off == 1;
22699 			struct bpf_insn *patch = insn_buf;
22700 
22701 			if (is_sdiv) {
22702 				/* [R,W]x sdiv 0 -> 0
22703 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
22704 				 * INT_MIN sdiv -1 -> INT_MIN
22705 				 */
22706 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22707 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22708 							BPF_ADD | BPF_K, BPF_REG_AX,
22709 							0, 0, 1);
22710 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22711 							BPF_JGT | BPF_K, BPF_REG_AX,
22712 							0, 4, 1);
22713 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22714 							BPF_JEQ | BPF_K, BPF_REG_AX,
22715 							0, 1, 0);
22716 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22717 							BPF_MOV | BPF_K, insn->dst_reg,
22718 							0, 0, 0);
22719 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
22720 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22721 							BPF_NEG | BPF_K, insn->dst_reg,
22722 							0, 0, 0);
22723 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22724 				*patch++ = *insn;
22725 				cnt = patch - insn_buf;
22726 			} else if (is_smod) {
22727 				/* [R,W]x mod 0 -> [R,W]x */
22728 				/* [R,W]x mod -1 -> 0 */
22729 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22730 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22731 							BPF_ADD | BPF_K, BPF_REG_AX,
22732 							0, 0, 1);
22733 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22734 							BPF_JGT | BPF_K, BPF_REG_AX,
22735 							0, 3, 1);
22736 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22737 							BPF_JEQ | BPF_K, BPF_REG_AX,
22738 							0, 3 + (is64 ? 0 : 1), 1);
22739 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22740 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22741 				*patch++ = *insn;
22742 
22743 				if (!is64) {
22744 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22745 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22746 				}
22747 				cnt = patch - insn_buf;
22748 			} else if (isdiv) {
22749 				/* [R,W]x div 0 -> 0 */
22750 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22751 							BPF_JNE | BPF_K, insn->src_reg,
22752 							0, 2, 0);
22753 				*patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg);
22754 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22755 				*patch++ = *insn;
22756 				cnt = patch - insn_buf;
22757 			} else {
22758 				/* [R,W]x mod 0 -> [R,W]x */
22759 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22760 							BPF_JEQ | BPF_K, insn->src_reg,
22761 							0, 1 + (is64 ? 0 : 1), 0);
22762 				*patch++ = *insn;
22763 
22764 				if (!is64) {
22765 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22766 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22767 				}
22768 				cnt = patch - insn_buf;
22769 			}
22770 
22771 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22772 			if (!new_prog)
22773 				return -ENOMEM;
22774 
22775 			delta    += cnt - 1;
22776 			env->prog = prog = new_prog;
22777 			insn      = new_prog->insnsi + i + delta;
22778 			goto next_insn;
22779 		}
22780 
22781 		/* Make it impossible to de-reference a userspace address */
22782 		if (BPF_CLASS(insn->code) == BPF_LDX &&
22783 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22784 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
22785 			struct bpf_insn *patch = insn_buf;
22786 			u64 uaddress_limit = bpf_arch_uaddress_limit();
22787 
22788 			if (!uaddress_limit)
22789 				goto next_insn;
22790 
22791 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22792 			if (insn->off)
22793 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
22794 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
22795 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
22796 			*patch++ = *insn;
22797 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22798 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
22799 
22800 			cnt = patch - insn_buf;
22801 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22802 			if (!new_prog)
22803 				return -ENOMEM;
22804 
22805 			delta    += cnt - 1;
22806 			env->prog = prog = new_prog;
22807 			insn      = new_prog->insnsi + i + delta;
22808 			goto next_insn;
22809 		}
22810 
22811 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
22812 		if (BPF_CLASS(insn->code) == BPF_LD &&
22813 		    (BPF_MODE(insn->code) == BPF_ABS ||
22814 		     BPF_MODE(insn->code) == BPF_IND)) {
22815 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
22816 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
22817 				verifier_bug(env, "%d insns generated for ld_abs", cnt);
22818 				return -EFAULT;
22819 			}
22820 
22821 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22822 			if (!new_prog)
22823 				return -ENOMEM;
22824 
22825 			delta    += cnt - 1;
22826 			env->prog = prog = new_prog;
22827 			insn      = new_prog->insnsi + i + delta;
22828 			goto next_insn;
22829 		}
22830 
22831 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
22832 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
22833 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
22834 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
22835 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
22836 			struct bpf_insn *patch = insn_buf;
22837 			bool issrc, isneg, isimm;
22838 			u32 off_reg;
22839 
22840 			aux = &env->insn_aux_data[i + delta];
22841 			if (!aux->alu_state ||
22842 			    aux->alu_state == BPF_ALU_NON_POINTER)
22843 				goto next_insn;
22844 
22845 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
22846 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
22847 				BPF_ALU_SANITIZE_SRC;
22848 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
22849 
22850 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
22851 			if (isimm) {
22852 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22853 			} else {
22854 				if (isneg)
22855 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22856 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22857 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
22858 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
22859 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
22860 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
22861 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
22862 			}
22863 			if (!issrc)
22864 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
22865 			insn->src_reg = BPF_REG_AX;
22866 			if (isneg)
22867 				insn->code = insn->code == code_add ?
22868 					     code_sub : code_add;
22869 			*patch++ = *insn;
22870 			if (issrc && isneg && !isimm)
22871 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22872 			cnt = patch - insn_buf;
22873 
22874 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22875 			if (!new_prog)
22876 				return -ENOMEM;
22877 
22878 			delta    += cnt - 1;
22879 			env->prog = prog = new_prog;
22880 			insn      = new_prog->insnsi + i + delta;
22881 			goto next_insn;
22882 		}
22883 
22884 		if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) {
22885 			int stack_off_cnt = -stack_depth - 16;
22886 
22887 			/*
22888 			 * Two 8 byte slots, depth-16 stores the count, and
22889 			 * depth-8 stores the start timestamp of the loop.
22890 			 *
22891 			 * The starting value of count is BPF_MAX_TIMED_LOOPS
22892 			 * (0xffff).  Every iteration loads it and subs it by 1,
22893 			 * until the value becomes 0 in AX (thus, 1 in stack),
22894 			 * after which we call arch_bpf_timed_may_goto, which
22895 			 * either sets AX to 0xffff to keep looping, or to 0
22896 			 * upon timeout. AX is then stored into the stack. In
22897 			 * the next iteration, we either see 0 and break out, or
22898 			 * continue iterating until the next time value is 0
22899 			 * after subtraction, rinse and repeat.
22900 			 */
22901 			stack_depth_extra = 16;
22902 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt);
22903 			if (insn->off >= 0)
22904 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5);
22905 			else
22906 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22907 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22908 			insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
22909 			/*
22910 			 * AX is used as an argument to pass in stack_off_cnt
22911 			 * (to add to r10/fp), and also as the return value of
22912 			 * the call to arch_bpf_timed_may_goto.
22913 			 */
22914 			insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt);
22915 			insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
22916 			insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt);
22917 			cnt = 7;
22918 
22919 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22920 			if (!new_prog)
22921 				return -ENOMEM;
22922 
22923 			delta += cnt - 1;
22924 			env->prog = prog = new_prog;
22925 			insn = new_prog->insnsi + i + delta;
22926 			goto next_insn;
22927 		} else if (is_may_goto_insn(insn)) {
22928 			int stack_off = -stack_depth - 8;
22929 
22930 			stack_depth_extra = 8;
22931 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
22932 			if (insn->off >= 0)
22933 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
22934 			else
22935 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22936 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22937 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
22938 			cnt = 4;
22939 
22940 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22941 			if (!new_prog)
22942 				return -ENOMEM;
22943 
22944 			delta += cnt - 1;
22945 			env->prog = prog = new_prog;
22946 			insn = new_prog->insnsi + i + delta;
22947 			goto next_insn;
22948 		}
22949 
22950 		if (insn->code != (BPF_JMP | BPF_CALL))
22951 			goto next_insn;
22952 		if (insn->src_reg == BPF_PSEUDO_CALL)
22953 			goto next_insn;
22954 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
22955 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
22956 			if (ret)
22957 				return ret;
22958 			if (cnt == 0)
22959 				goto next_insn;
22960 
22961 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22962 			if (!new_prog)
22963 				return -ENOMEM;
22964 
22965 			delta	 += cnt - 1;
22966 			env->prog = prog = new_prog;
22967 			insn	  = new_prog->insnsi + i + delta;
22968 			goto next_insn;
22969 		}
22970 
22971 		/* Skip inlining the helper call if the JIT does it. */
22972 		if (bpf_jit_inlines_helper_call(insn->imm))
22973 			goto next_insn;
22974 
22975 		if (insn->imm == BPF_FUNC_get_route_realm)
22976 			prog->dst_needed = 1;
22977 		if (insn->imm == BPF_FUNC_get_prandom_u32)
22978 			bpf_user_rnd_init_once();
22979 		if (insn->imm == BPF_FUNC_override_return)
22980 			prog->kprobe_override = 1;
22981 		if (insn->imm == BPF_FUNC_tail_call) {
22982 			/* If we tail call into other programs, we
22983 			 * cannot make any assumptions since they can
22984 			 * be replaced dynamically during runtime in
22985 			 * the program array.
22986 			 */
22987 			prog->cb_access = 1;
22988 			if (!allow_tail_call_in_subprogs(env))
22989 				prog->aux->stack_depth = MAX_BPF_STACK;
22990 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
22991 
22992 			/* mark bpf_tail_call as different opcode to avoid
22993 			 * conditional branch in the interpreter for every normal
22994 			 * call and to prevent accidental JITing by JIT compiler
22995 			 * that doesn't support bpf_tail_call yet
22996 			 */
22997 			insn->imm = 0;
22998 			insn->code = BPF_JMP | BPF_TAIL_CALL;
22999 
23000 			aux = &env->insn_aux_data[i + delta];
23001 			if (env->bpf_capable && !prog->blinding_requested &&
23002 			    prog->jit_requested &&
23003 			    !bpf_map_key_poisoned(aux) &&
23004 			    !bpf_map_ptr_poisoned(aux) &&
23005 			    !bpf_map_ptr_unpriv(aux)) {
23006 				struct bpf_jit_poke_descriptor desc = {
23007 					.reason = BPF_POKE_REASON_TAIL_CALL,
23008 					.tail_call.map = aux->map_ptr_state.map_ptr,
23009 					.tail_call.key = bpf_map_key_immediate(aux),
23010 					.insn_idx = i + delta,
23011 				};
23012 
23013 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
23014 				if (ret < 0) {
23015 					verbose(env, "adding tail call poke descriptor failed\n");
23016 					return ret;
23017 				}
23018 
23019 				insn->imm = ret + 1;
23020 				goto next_insn;
23021 			}
23022 
23023 			if (!bpf_map_ptr_unpriv(aux))
23024 				goto next_insn;
23025 
23026 			/* instead of changing every JIT dealing with tail_call
23027 			 * emit two extra insns:
23028 			 * if (index >= max_entries) goto out;
23029 			 * index &= array->index_mask;
23030 			 * to avoid out-of-bounds cpu speculation
23031 			 */
23032 			if (bpf_map_ptr_poisoned(aux)) {
23033 				verbose(env, "tail_call abusing map_ptr\n");
23034 				return -EINVAL;
23035 			}
23036 
23037 			map_ptr = aux->map_ptr_state.map_ptr;
23038 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
23039 						  map_ptr->max_entries, 2);
23040 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
23041 						    container_of(map_ptr,
23042 								 struct bpf_array,
23043 								 map)->index_mask);
23044 			insn_buf[2] = *insn;
23045 			cnt = 3;
23046 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23047 			if (!new_prog)
23048 				return -ENOMEM;
23049 
23050 			delta    += cnt - 1;
23051 			env->prog = prog = new_prog;
23052 			insn      = new_prog->insnsi + i + delta;
23053 			goto next_insn;
23054 		}
23055 
23056 		if (insn->imm == BPF_FUNC_timer_set_callback) {
23057 			/* The verifier will process callback_fn as many times as necessary
23058 			 * with different maps and the register states prepared by
23059 			 * set_timer_callback_state will be accurate.
23060 			 *
23061 			 * The following use case is valid:
23062 			 *   map1 is shared by prog1, prog2, prog3.
23063 			 *   prog1 calls bpf_timer_init for some map1 elements
23064 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
23065 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
23066 			 *   prog3 calls bpf_timer_start for some map1 elements.
23067 			 *     Those that were not both bpf_timer_init-ed and
23068 			 *     bpf_timer_set_callback-ed will return -EINVAL.
23069 			 */
23070 			struct bpf_insn ld_addrs[2] = {
23071 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
23072 			};
23073 
23074 			insn_buf[0] = ld_addrs[0];
23075 			insn_buf[1] = ld_addrs[1];
23076 			insn_buf[2] = *insn;
23077 			cnt = 3;
23078 
23079 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23080 			if (!new_prog)
23081 				return -ENOMEM;
23082 
23083 			delta    += cnt - 1;
23084 			env->prog = prog = new_prog;
23085 			insn      = new_prog->insnsi + i + delta;
23086 			goto patch_call_imm;
23087 		}
23088 
23089 		if (is_storage_get_function(insn->imm)) {
23090 			if (env->insn_aux_data[i + delta].non_sleepable)
23091 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
23092 			else
23093 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
23094 			insn_buf[1] = *insn;
23095 			cnt = 2;
23096 
23097 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23098 			if (!new_prog)
23099 				return -ENOMEM;
23100 
23101 			delta += cnt - 1;
23102 			env->prog = prog = new_prog;
23103 			insn = new_prog->insnsi + i + delta;
23104 			goto patch_call_imm;
23105 		}
23106 
23107 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
23108 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
23109 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
23110 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
23111 			 */
23112 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
23113 			insn_buf[1] = *insn;
23114 			cnt = 2;
23115 
23116 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23117 			if (!new_prog)
23118 				return -ENOMEM;
23119 
23120 			delta += cnt - 1;
23121 			env->prog = prog = new_prog;
23122 			insn = new_prog->insnsi + i + delta;
23123 			goto patch_call_imm;
23124 		}
23125 
23126 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
23127 		 * and other inlining handlers are currently limited to 64 bit
23128 		 * only.
23129 		 */
23130 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
23131 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
23132 		     insn->imm == BPF_FUNC_map_update_elem ||
23133 		     insn->imm == BPF_FUNC_map_delete_elem ||
23134 		     insn->imm == BPF_FUNC_map_push_elem   ||
23135 		     insn->imm == BPF_FUNC_map_pop_elem    ||
23136 		     insn->imm == BPF_FUNC_map_peek_elem   ||
23137 		     insn->imm == BPF_FUNC_redirect_map    ||
23138 		     insn->imm == BPF_FUNC_for_each_map_elem ||
23139 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
23140 			aux = &env->insn_aux_data[i + delta];
23141 			if (bpf_map_ptr_poisoned(aux))
23142 				goto patch_call_imm;
23143 
23144 			map_ptr = aux->map_ptr_state.map_ptr;
23145 			ops = map_ptr->ops;
23146 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
23147 			    ops->map_gen_lookup) {
23148 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
23149 				if (cnt == -EOPNOTSUPP)
23150 					goto patch_map_ops_generic;
23151 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
23152 					verifier_bug(env, "%d insns generated for map lookup", cnt);
23153 					return -EFAULT;
23154 				}
23155 
23156 				new_prog = bpf_patch_insn_data(env, i + delta,
23157 							       insn_buf, cnt);
23158 				if (!new_prog)
23159 					return -ENOMEM;
23160 
23161 				delta    += cnt - 1;
23162 				env->prog = prog = new_prog;
23163 				insn      = new_prog->insnsi + i + delta;
23164 				goto next_insn;
23165 			}
23166 
23167 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
23168 				     (void *(*)(struct bpf_map *map, void *key))NULL));
23169 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
23170 				     (long (*)(struct bpf_map *map, void *key))NULL));
23171 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
23172 				     (long (*)(struct bpf_map *map, void *key, void *value,
23173 					      u64 flags))NULL));
23174 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
23175 				     (long (*)(struct bpf_map *map, void *value,
23176 					      u64 flags))NULL));
23177 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
23178 				     (long (*)(struct bpf_map *map, void *value))NULL));
23179 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
23180 				     (long (*)(struct bpf_map *map, void *value))NULL));
23181 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
23182 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
23183 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
23184 				     (long (*)(struct bpf_map *map,
23185 					      bpf_callback_t callback_fn,
23186 					      void *callback_ctx,
23187 					      u64 flags))NULL));
23188 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
23189 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
23190 
23191 patch_map_ops_generic:
23192 			switch (insn->imm) {
23193 			case BPF_FUNC_map_lookup_elem:
23194 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
23195 				goto next_insn;
23196 			case BPF_FUNC_map_update_elem:
23197 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
23198 				goto next_insn;
23199 			case BPF_FUNC_map_delete_elem:
23200 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
23201 				goto next_insn;
23202 			case BPF_FUNC_map_push_elem:
23203 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
23204 				goto next_insn;
23205 			case BPF_FUNC_map_pop_elem:
23206 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
23207 				goto next_insn;
23208 			case BPF_FUNC_map_peek_elem:
23209 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
23210 				goto next_insn;
23211 			case BPF_FUNC_redirect_map:
23212 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
23213 				goto next_insn;
23214 			case BPF_FUNC_for_each_map_elem:
23215 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
23216 				goto next_insn;
23217 			case BPF_FUNC_map_lookup_percpu_elem:
23218 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
23219 				goto next_insn;
23220 			}
23221 
23222 			goto patch_call_imm;
23223 		}
23224 
23225 		/* Implement bpf_jiffies64 inline. */
23226 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
23227 		    insn->imm == BPF_FUNC_jiffies64) {
23228 			struct bpf_insn ld_jiffies_addr[2] = {
23229 				BPF_LD_IMM64(BPF_REG_0,
23230 					     (unsigned long)&jiffies),
23231 			};
23232 
23233 			insn_buf[0] = ld_jiffies_addr[0];
23234 			insn_buf[1] = ld_jiffies_addr[1];
23235 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
23236 						  BPF_REG_0, 0);
23237 			cnt = 3;
23238 
23239 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
23240 						       cnt);
23241 			if (!new_prog)
23242 				return -ENOMEM;
23243 
23244 			delta    += cnt - 1;
23245 			env->prog = prog = new_prog;
23246 			insn      = new_prog->insnsi + i + delta;
23247 			goto next_insn;
23248 		}
23249 
23250 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
23251 		/* Implement bpf_get_smp_processor_id() inline. */
23252 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
23253 		    verifier_inlines_helper_call(env, insn->imm)) {
23254 			/* BPF_FUNC_get_smp_processor_id inlining is an
23255 			 * optimization, so if cpu_number is ever
23256 			 * changed in some incompatible and hard to support
23257 			 * way, it's fine to back out this inlining logic
23258 			 */
23259 #ifdef CONFIG_SMP
23260 			insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number);
23261 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
23262 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
23263 			cnt = 3;
23264 #else
23265 			insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
23266 			cnt = 1;
23267 #endif
23268 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23269 			if (!new_prog)
23270 				return -ENOMEM;
23271 
23272 			delta    += cnt - 1;
23273 			env->prog = prog = new_prog;
23274 			insn      = new_prog->insnsi + i + delta;
23275 			goto next_insn;
23276 		}
23277 #endif
23278 		/* Implement bpf_get_func_arg inline. */
23279 		if (prog_type == BPF_PROG_TYPE_TRACING &&
23280 		    insn->imm == BPF_FUNC_get_func_arg) {
23281 			/* Load nr_args from ctx - 8 */
23282 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23283 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
23284 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
23285 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
23286 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
23287 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
23288 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
23289 			insn_buf[7] = BPF_JMP_A(1);
23290 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
23291 			cnt = 9;
23292 
23293 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23294 			if (!new_prog)
23295 				return -ENOMEM;
23296 
23297 			delta    += cnt - 1;
23298 			env->prog = prog = new_prog;
23299 			insn      = new_prog->insnsi + i + delta;
23300 			goto next_insn;
23301 		}
23302 
23303 		/* Implement bpf_get_func_ret inline. */
23304 		if (prog_type == BPF_PROG_TYPE_TRACING &&
23305 		    insn->imm == BPF_FUNC_get_func_ret) {
23306 			if (eatype == BPF_TRACE_FEXIT ||
23307 			    eatype == BPF_MODIFY_RETURN) {
23308 				/* Load nr_args from ctx - 8 */
23309 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23310 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
23311 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
23312 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
23313 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
23314 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
23315 				cnt = 6;
23316 			} else {
23317 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
23318 				cnt = 1;
23319 			}
23320 
23321 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23322 			if (!new_prog)
23323 				return -ENOMEM;
23324 
23325 			delta    += cnt - 1;
23326 			env->prog = prog = new_prog;
23327 			insn      = new_prog->insnsi + i + delta;
23328 			goto next_insn;
23329 		}
23330 
23331 		/* Implement get_func_arg_cnt inline. */
23332 		if (prog_type == BPF_PROG_TYPE_TRACING &&
23333 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
23334 			/* Load nr_args from ctx - 8 */
23335 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23336 
23337 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
23338 			if (!new_prog)
23339 				return -ENOMEM;
23340 
23341 			env->prog = prog = new_prog;
23342 			insn      = new_prog->insnsi + i + delta;
23343 			goto next_insn;
23344 		}
23345 
23346 		/* Implement bpf_get_func_ip inline. */
23347 		if (prog_type == BPF_PROG_TYPE_TRACING &&
23348 		    insn->imm == BPF_FUNC_get_func_ip) {
23349 			/* Load IP address from ctx - 16 */
23350 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
23351 
23352 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
23353 			if (!new_prog)
23354 				return -ENOMEM;
23355 
23356 			env->prog = prog = new_prog;
23357 			insn      = new_prog->insnsi + i + delta;
23358 			goto next_insn;
23359 		}
23360 
23361 		/* Implement bpf_get_branch_snapshot inline. */
23362 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
23363 		    prog->jit_requested && BITS_PER_LONG == 64 &&
23364 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
23365 			/* We are dealing with the following func protos:
23366 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
23367 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
23368 			 */
23369 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
23370 
23371 			/* struct perf_branch_entry is part of UAPI and is
23372 			 * used as an array element, so extremely unlikely to
23373 			 * ever grow or shrink
23374 			 */
23375 			BUILD_BUG_ON(br_entry_size != 24);
23376 
23377 			/* if (unlikely(flags)) return -EINVAL */
23378 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
23379 
23380 			/* Transform size (bytes) into number of entries (cnt = size / 24).
23381 			 * But to avoid expensive division instruction, we implement
23382 			 * divide-by-3 through multiplication, followed by further
23383 			 * division by 8 through 3-bit right shift.
23384 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
23385 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
23386 			 *
23387 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
23388 			 */
23389 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
23390 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
23391 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
23392 
23393 			/* call perf_snapshot_branch_stack implementation */
23394 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
23395 			/* if (entry_cnt == 0) return -ENOENT */
23396 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
23397 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
23398 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
23399 			insn_buf[7] = BPF_JMP_A(3);
23400 			/* return -EINVAL; */
23401 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
23402 			insn_buf[9] = BPF_JMP_A(1);
23403 			/* return -ENOENT; */
23404 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
23405 			cnt = 11;
23406 
23407 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23408 			if (!new_prog)
23409 				return -ENOMEM;
23410 
23411 			delta    += cnt - 1;
23412 			env->prog = prog = new_prog;
23413 			insn      = new_prog->insnsi + i + delta;
23414 			goto next_insn;
23415 		}
23416 
23417 		/* Implement bpf_kptr_xchg inline */
23418 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
23419 		    insn->imm == BPF_FUNC_kptr_xchg &&
23420 		    bpf_jit_supports_ptr_xchg()) {
23421 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
23422 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
23423 			cnt = 2;
23424 
23425 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23426 			if (!new_prog)
23427 				return -ENOMEM;
23428 
23429 			delta    += cnt - 1;
23430 			env->prog = prog = new_prog;
23431 			insn      = new_prog->insnsi + i + delta;
23432 			goto next_insn;
23433 		}
23434 patch_call_imm:
23435 		fn = env->ops->get_func_proto(insn->imm, env->prog);
23436 		/* all functions that have prototype and verifier allowed
23437 		 * programs to call them, must be real in-kernel functions
23438 		 */
23439 		if (!fn->func) {
23440 			verifier_bug(env,
23441 				     "not inlined functions %s#%d is missing func",
23442 				     func_id_name(insn->imm), insn->imm);
23443 			return -EFAULT;
23444 		}
23445 		insn->imm = fn->func - __bpf_call_base;
23446 next_insn:
23447 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
23448 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
23449 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
23450 
23451 			stack_depth = subprogs[cur_subprog].stack_depth;
23452 			if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) {
23453 				verbose(env, "stack size %d(extra %d) is too large\n",
23454 					stack_depth, stack_depth_extra);
23455 				return -EINVAL;
23456 			}
23457 			cur_subprog++;
23458 			stack_depth = subprogs[cur_subprog].stack_depth;
23459 			stack_depth_extra = 0;
23460 		}
23461 		i++;
23462 		insn++;
23463 	}
23464 
23465 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
23466 	for (i = 0; i < env->subprog_cnt; i++) {
23467 		int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1;
23468 		int subprog_start = subprogs[i].start;
23469 		int stack_slots = subprogs[i].stack_extra / 8;
23470 		int slots = delta, cnt = 0;
23471 
23472 		if (!stack_slots)
23473 			continue;
23474 		/* We need two slots in case timed may_goto is supported. */
23475 		if (stack_slots > slots) {
23476 			verifier_bug(env, "stack_slots supports may_goto only");
23477 			return -EFAULT;
23478 		}
23479 
23480 		stack_depth = subprogs[i].stack_depth;
23481 		if (bpf_jit_supports_timed_may_goto()) {
23482 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
23483 						     BPF_MAX_TIMED_LOOPS);
23484 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0);
23485 		} else {
23486 			/* Add ST insn to subprog prologue to init extra stack */
23487 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
23488 						     BPF_MAX_LOOPS);
23489 		}
23490 		/* Copy first actual insn to preserve it */
23491 		insn_buf[cnt++] = env->prog->insnsi[subprog_start];
23492 
23493 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt);
23494 		if (!new_prog)
23495 			return -ENOMEM;
23496 		env->prog = prog = new_prog;
23497 		/*
23498 		 * If may_goto is a first insn of a prog there could be a jmp
23499 		 * insn that points to it, hence adjust all such jmps to point
23500 		 * to insn after BPF_ST that inits may_goto count.
23501 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
23502 		 */
23503 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta));
23504 	}
23505 
23506 	/* Since poke tab is now finalized, publish aux to tracker. */
23507 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
23508 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
23509 		if (!map_ptr->ops->map_poke_track ||
23510 		    !map_ptr->ops->map_poke_untrack ||
23511 		    !map_ptr->ops->map_poke_run) {
23512 			verifier_bug(env, "poke tab is misconfigured");
23513 			return -EFAULT;
23514 		}
23515 
23516 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
23517 		if (ret < 0) {
23518 			verbose(env, "tracking tail call prog failed\n");
23519 			return ret;
23520 		}
23521 	}
23522 
23523 	ret = sort_kfunc_descs_by_imm_off(env);
23524 	if (ret)
23525 		return ret;
23526 
23527 	return 0;
23528 }
23529 
23530 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
23531 					int position,
23532 					s32 stack_base,
23533 					u32 callback_subprogno,
23534 					u32 *total_cnt)
23535 {
23536 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
23537 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
23538 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
23539 	int reg_loop_max = BPF_REG_6;
23540 	int reg_loop_cnt = BPF_REG_7;
23541 	int reg_loop_ctx = BPF_REG_8;
23542 
23543 	struct bpf_insn *insn_buf = env->insn_buf;
23544 	struct bpf_prog *new_prog;
23545 	u32 callback_start;
23546 	u32 call_insn_offset;
23547 	s32 callback_offset;
23548 	u32 cnt = 0;
23549 
23550 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
23551 	 * be careful to modify this code in sync.
23552 	 */
23553 
23554 	/* Return error and jump to the end of the patch if
23555 	 * expected number of iterations is too big.
23556 	 */
23557 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
23558 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
23559 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
23560 	/* spill R6, R7, R8 to use these as loop vars */
23561 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
23562 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
23563 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
23564 	/* initialize loop vars */
23565 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
23566 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
23567 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
23568 	/* loop header,
23569 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
23570 	 */
23571 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
23572 	/* callback call,
23573 	 * correct callback offset would be set after patching
23574 	 */
23575 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
23576 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
23577 	insn_buf[cnt++] = BPF_CALL_REL(0);
23578 	/* increment loop counter */
23579 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
23580 	/* jump to loop header if callback returned 0 */
23581 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
23582 	/* return value of bpf_loop,
23583 	 * set R0 to the number of iterations
23584 	 */
23585 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
23586 	/* restore original values of R6, R7, R8 */
23587 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
23588 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
23589 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
23590 
23591 	*total_cnt = cnt;
23592 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
23593 	if (!new_prog)
23594 		return new_prog;
23595 
23596 	/* callback start is known only after patching */
23597 	callback_start = env->subprog_info[callback_subprogno].start;
23598 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
23599 	call_insn_offset = position + 12;
23600 	callback_offset = callback_start - call_insn_offset - 1;
23601 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
23602 
23603 	return new_prog;
23604 }
23605 
23606 static bool is_bpf_loop_call(struct bpf_insn *insn)
23607 {
23608 	return insn->code == (BPF_JMP | BPF_CALL) &&
23609 		insn->src_reg == 0 &&
23610 		insn->imm == BPF_FUNC_loop;
23611 }
23612 
23613 /* For all sub-programs in the program (including main) check
23614  * insn_aux_data to see if there are bpf_loop calls that require
23615  * inlining. If such calls are found the calls are replaced with a
23616  * sequence of instructions produced by `inline_bpf_loop` function and
23617  * subprog stack_depth is increased by the size of 3 registers.
23618  * This stack space is used to spill values of the R6, R7, R8.  These
23619  * registers are used to store the loop bound, counter and context
23620  * variables.
23621  */
23622 static int optimize_bpf_loop(struct bpf_verifier_env *env)
23623 {
23624 	struct bpf_subprog_info *subprogs = env->subprog_info;
23625 	int i, cur_subprog = 0, cnt, delta = 0;
23626 	struct bpf_insn *insn = env->prog->insnsi;
23627 	int insn_cnt = env->prog->len;
23628 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
23629 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23630 	u16 stack_depth_extra = 0;
23631 
23632 	for (i = 0; i < insn_cnt; i++, insn++) {
23633 		struct bpf_loop_inline_state *inline_state =
23634 			&env->insn_aux_data[i + delta].loop_inline_state;
23635 
23636 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
23637 			struct bpf_prog *new_prog;
23638 
23639 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
23640 			new_prog = inline_bpf_loop(env,
23641 						   i + delta,
23642 						   -(stack_depth + stack_depth_extra),
23643 						   inline_state->callback_subprogno,
23644 						   &cnt);
23645 			if (!new_prog)
23646 				return -ENOMEM;
23647 
23648 			delta     += cnt - 1;
23649 			env->prog  = new_prog;
23650 			insn       = new_prog->insnsi + i + delta;
23651 		}
23652 
23653 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
23654 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
23655 			cur_subprog++;
23656 			stack_depth = subprogs[cur_subprog].stack_depth;
23657 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23658 			stack_depth_extra = 0;
23659 		}
23660 	}
23661 
23662 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23663 
23664 	return 0;
23665 }
23666 
23667 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
23668  * adjust subprograms stack depth when possible.
23669  */
23670 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
23671 {
23672 	struct bpf_subprog_info *subprog = env->subprog_info;
23673 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
23674 	struct bpf_insn *insn = env->prog->insnsi;
23675 	int insn_cnt = env->prog->len;
23676 	u32 spills_num;
23677 	bool modified = false;
23678 	int i, j;
23679 
23680 	for (i = 0; i < insn_cnt; i++, insn++) {
23681 		if (aux[i].fastcall_spills_num > 0) {
23682 			spills_num = aux[i].fastcall_spills_num;
23683 			/* NOPs would be removed by opt_remove_nops() */
23684 			for (j = 1; j <= spills_num; ++j) {
23685 				*(insn - j) = NOP;
23686 				*(insn + j) = NOP;
23687 			}
23688 			modified = true;
23689 		}
23690 		if ((subprog + 1)->start == i + 1) {
23691 			if (modified && !subprog->keep_fastcall_stack)
23692 				subprog->stack_depth = -subprog->fastcall_stack_off;
23693 			subprog++;
23694 			modified = false;
23695 		}
23696 	}
23697 
23698 	return 0;
23699 }
23700 
23701 static void free_states(struct bpf_verifier_env *env)
23702 {
23703 	struct bpf_verifier_state_list *sl;
23704 	struct list_head *head, *pos, *tmp;
23705 	struct bpf_scc_info *info;
23706 	int i, j;
23707 
23708 	free_verifier_state(env->cur_state, true);
23709 	env->cur_state = NULL;
23710 	while (!pop_stack(env, NULL, NULL, false));
23711 
23712 	list_for_each_safe(pos, tmp, &env->free_list) {
23713 		sl = container_of(pos, struct bpf_verifier_state_list, node);
23714 		free_verifier_state(&sl->state, false);
23715 		kfree(sl);
23716 	}
23717 	INIT_LIST_HEAD(&env->free_list);
23718 
23719 	for (i = 0; i < env->scc_cnt; ++i) {
23720 		info = env->scc_info[i];
23721 		if (!info)
23722 			continue;
23723 		for (j = 0; j < info->num_visits; j++)
23724 			free_backedges(&info->visits[j]);
23725 		kvfree(info);
23726 		env->scc_info[i] = NULL;
23727 	}
23728 
23729 	if (!env->explored_states)
23730 		return;
23731 
23732 	for (i = 0; i < state_htab_size(env); i++) {
23733 		head = &env->explored_states[i];
23734 
23735 		list_for_each_safe(pos, tmp, head) {
23736 			sl = container_of(pos, struct bpf_verifier_state_list, node);
23737 			free_verifier_state(&sl->state, false);
23738 			kfree(sl);
23739 		}
23740 		INIT_LIST_HEAD(&env->explored_states[i]);
23741 	}
23742 }
23743 
23744 static int do_check_common(struct bpf_verifier_env *env, int subprog)
23745 {
23746 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
23747 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
23748 	struct bpf_prog_aux *aux = env->prog->aux;
23749 	struct bpf_verifier_state *state;
23750 	struct bpf_reg_state *regs;
23751 	int ret, i;
23752 
23753 	env->prev_linfo = NULL;
23754 	env->pass_cnt++;
23755 
23756 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL_ACCOUNT);
23757 	if (!state)
23758 		return -ENOMEM;
23759 	state->curframe = 0;
23760 	state->speculative = false;
23761 	state->branches = 1;
23762 	state->in_sleepable = env->prog->sleepable;
23763 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL_ACCOUNT);
23764 	if (!state->frame[0]) {
23765 		kfree(state);
23766 		return -ENOMEM;
23767 	}
23768 	env->cur_state = state;
23769 	init_func_state(env, state->frame[0],
23770 			BPF_MAIN_FUNC /* callsite */,
23771 			0 /* frameno */,
23772 			subprog);
23773 	state->first_insn_idx = env->subprog_info[subprog].start;
23774 	state->last_insn_idx = -1;
23775 
23776 	regs = state->frame[state->curframe]->regs;
23777 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
23778 		const char *sub_name = subprog_name(env, subprog);
23779 		struct bpf_subprog_arg_info *arg;
23780 		struct bpf_reg_state *reg;
23781 
23782 		if (env->log.level & BPF_LOG_LEVEL)
23783 			verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
23784 		ret = btf_prepare_func_args(env, subprog);
23785 		if (ret)
23786 			goto out;
23787 
23788 		if (subprog_is_exc_cb(env, subprog)) {
23789 			state->frame[0]->in_exception_callback_fn = true;
23790 			/* We have already ensured that the callback returns an integer, just
23791 			 * like all global subprogs. We need to determine it only has a single
23792 			 * scalar argument.
23793 			 */
23794 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
23795 				verbose(env, "exception cb only supports single integer argument\n");
23796 				ret = -EINVAL;
23797 				goto out;
23798 			}
23799 		}
23800 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
23801 			arg = &sub->args[i - BPF_REG_1];
23802 			reg = &regs[i];
23803 
23804 			if (arg->arg_type == ARG_PTR_TO_CTX) {
23805 				reg->type = PTR_TO_CTX;
23806 				mark_reg_known_zero(env, regs, i);
23807 			} else if (arg->arg_type == ARG_ANYTHING) {
23808 				reg->type = SCALAR_VALUE;
23809 				mark_reg_unknown(env, regs, i);
23810 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
23811 				/* assume unspecial LOCAL dynptr type */
23812 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
23813 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
23814 				reg->type = PTR_TO_MEM;
23815 				reg->type |= arg->arg_type &
23816 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
23817 				mark_reg_known_zero(env, regs, i);
23818 				reg->mem_size = arg->mem_size;
23819 				if (arg->arg_type & PTR_MAYBE_NULL)
23820 					reg->id = ++env->id_gen;
23821 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
23822 				reg->type = PTR_TO_BTF_ID;
23823 				if (arg->arg_type & PTR_MAYBE_NULL)
23824 					reg->type |= PTR_MAYBE_NULL;
23825 				if (arg->arg_type & PTR_UNTRUSTED)
23826 					reg->type |= PTR_UNTRUSTED;
23827 				if (arg->arg_type & PTR_TRUSTED)
23828 					reg->type |= PTR_TRUSTED;
23829 				mark_reg_known_zero(env, regs, i);
23830 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
23831 				reg->btf_id = arg->btf_id;
23832 				reg->id = ++env->id_gen;
23833 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
23834 				/* caller can pass either PTR_TO_ARENA or SCALAR */
23835 				mark_reg_unknown(env, regs, i);
23836 			} else {
23837 				verifier_bug(env, "unhandled arg#%d type %d",
23838 					     i - BPF_REG_1, arg->arg_type);
23839 				ret = -EFAULT;
23840 				goto out;
23841 			}
23842 		}
23843 	} else {
23844 		/* if main BPF program has associated BTF info, validate that
23845 		 * it's matching expected signature, and otherwise mark BTF
23846 		 * info for main program as unreliable
23847 		 */
23848 		if (env->prog->aux->func_info_aux) {
23849 			ret = btf_prepare_func_args(env, 0);
23850 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
23851 				env->prog->aux->func_info_aux[0].unreliable = true;
23852 		}
23853 
23854 		/* 1st arg to a function */
23855 		regs[BPF_REG_1].type = PTR_TO_CTX;
23856 		mark_reg_known_zero(env, regs, BPF_REG_1);
23857 	}
23858 
23859 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
23860 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
23861 		for (i = 0; i < aux->ctx_arg_info_size; i++)
23862 			aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ?
23863 							  acquire_reference(env, 0) : 0;
23864 	}
23865 
23866 	ret = do_check(env);
23867 out:
23868 	if (!ret && pop_log)
23869 		bpf_vlog_reset(&env->log, 0);
23870 	free_states(env);
23871 	return ret;
23872 }
23873 
23874 /* Lazily verify all global functions based on their BTF, if they are called
23875  * from main BPF program or any of subprograms transitively.
23876  * BPF global subprogs called from dead code are not validated.
23877  * All callable global functions must pass verification.
23878  * Otherwise the whole program is rejected.
23879  * Consider:
23880  * int bar(int);
23881  * int foo(int f)
23882  * {
23883  *    return bar(f);
23884  * }
23885  * int bar(int b)
23886  * {
23887  *    ...
23888  * }
23889  * foo() will be verified first for R1=any_scalar_value. During verification it
23890  * will be assumed that bar() already verified successfully and call to bar()
23891  * from foo() will be checked for type match only. Later bar() will be verified
23892  * independently to check that it's safe for R1=any_scalar_value.
23893  */
23894 static int do_check_subprogs(struct bpf_verifier_env *env)
23895 {
23896 	struct bpf_prog_aux *aux = env->prog->aux;
23897 	struct bpf_func_info_aux *sub_aux;
23898 	int i, ret, new_cnt;
23899 
23900 	if (!aux->func_info)
23901 		return 0;
23902 
23903 	/* exception callback is presumed to be always called */
23904 	if (env->exception_callback_subprog)
23905 		subprog_aux(env, env->exception_callback_subprog)->called = true;
23906 
23907 again:
23908 	new_cnt = 0;
23909 	for (i = 1; i < env->subprog_cnt; i++) {
23910 		if (!subprog_is_global(env, i))
23911 			continue;
23912 
23913 		sub_aux = subprog_aux(env, i);
23914 		if (!sub_aux->called || sub_aux->verified)
23915 			continue;
23916 
23917 		env->insn_idx = env->subprog_info[i].start;
23918 		WARN_ON_ONCE(env->insn_idx == 0);
23919 		ret = do_check_common(env, i);
23920 		if (ret) {
23921 			return ret;
23922 		} else if (env->log.level & BPF_LOG_LEVEL) {
23923 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
23924 				i, subprog_name(env, i));
23925 		}
23926 
23927 		/* We verified new global subprog, it might have called some
23928 		 * more global subprogs that we haven't verified yet, so we
23929 		 * need to do another pass over subprogs to verify those.
23930 		 */
23931 		sub_aux->verified = true;
23932 		new_cnt++;
23933 	}
23934 
23935 	/* We can't loop forever as we verify at least one global subprog on
23936 	 * each pass.
23937 	 */
23938 	if (new_cnt)
23939 		goto again;
23940 
23941 	return 0;
23942 }
23943 
23944 static int do_check_main(struct bpf_verifier_env *env)
23945 {
23946 	int ret;
23947 
23948 	env->insn_idx = 0;
23949 	ret = do_check_common(env, 0);
23950 	if (!ret)
23951 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23952 	return ret;
23953 }
23954 
23955 
23956 static void print_verification_stats(struct bpf_verifier_env *env)
23957 {
23958 	int i;
23959 
23960 	if (env->log.level & BPF_LOG_STATS) {
23961 		verbose(env, "verification time %lld usec\n",
23962 			div_u64(env->verification_time, 1000));
23963 		verbose(env, "stack depth ");
23964 		for (i = 0; i < env->subprog_cnt; i++) {
23965 			u32 depth = env->subprog_info[i].stack_depth;
23966 
23967 			verbose(env, "%d", depth);
23968 			if (i + 1 < env->subprog_cnt)
23969 				verbose(env, "+");
23970 		}
23971 		verbose(env, "\n");
23972 	}
23973 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
23974 		"total_states %d peak_states %d mark_read %d\n",
23975 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
23976 		env->max_states_per_insn, env->total_states,
23977 		env->peak_states, env->longest_mark_read_walk);
23978 }
23979 
23980 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
23981 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
23982 {
23983 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
23984 	prog->aux->ctx_arg_info_size = cnt;
23985 
23986 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
23987 }
23988 
23989 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
23990 {
23991 	const struct btf_type *t, *func_proto;
23992 	const struct bpf_struct_ops_desc *st_ops_desc;
23993 	const struct bpf_struct_ops *st_ops;
23994 	const struct btf_member *member;
23995 	struct bpf_prog *prog = env->prog;
23996 	bool has_refcounted_arg = false;
23997 	u32 btf_id, member_idx, member_off;
23998 	struct btf *btf;
23999 	const char *mname;
24000 	int i, err;
24001 
24002 	if (!prog->gpl_compatible) {
24003 		verbose(env, "struct ops programs must have a GPL compatible license\n");
24004 		return -EINVAL;
24005 	}
24006 
24007 	if (!prog->aux->attach_btf_id)
24008 		return -ENOTSUPP;
24009 
24010 	btf = prog->aux->attach_btf;
24011 	if (btf_is_module(btf)) {
24012 		/* Make sure st_ops is valid through the lifetime of env */
24013 		env->attach_btf_mod = btf_try_get_module(btf);
24014 		if (!env->attach_btf_mod) {
24015 			verbose(env, "struct_ops module %s is not found\n",
24016 				btf_get_name(btf));
24017 			return -ENOTSUPP;
24018 		}
24019 	}
24020 
24021 	btf_id = prog->aux->attach_btf_id;
24022 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
24023 	if (!st_ops_desc) {
24024 		verbose(env, "attach_btf_id %u is not a supported struct\n",
24025 			btf_id);
24026 		return -ENOTSUPP;
24027 	}
24028 	st_ops = st_ops_desc->st_ops;
24029 
24030 	t = st_ops_desc->type;
24031 	member_idx = prog->expected_attach_type;
24032 	if (member_idx >= btf_type_vlen(t)) {
24033 		verbose(env, "attach to invalid member idx %u of struct %s\n",
24034 			member_idx, st_ops->name);
24035 		return -EINVAL;
24036 	}
24037 
24038 	member = &btf_type_member(t)[member_idx];
24039 	mname = btf_name_by_offset(btf, member->name_off);
24040 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
24041 					       NULL);
24042 	if (!func_proto) {
24043 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
24044 			mname, member_idx, st_ops->name);
24045 		return -EINVAL;
24046 	}
24047 
24048 	member_off = __btf_member_bit_offset(t, member) / 8;
24049 	err = bpf_struct_ops_supported(st_ops, member_off);
24050 	if (err) {
24051 		verbose(env, "attach to unsupported member %s of struct %s\n",
24052 			mname, st_ops->name);
24053 		return err;
24054 	}
24055 
24056 	if (st_ops->check_member) {
24057 		err = st_ops->check_member(t, member, prog);
24058 
24059 		if (err) {
24060 			verbose(env, "attach to unsupported member %s of struct %s\n",
24061 				mname, st_ops->name);
24062 			return err;
24063 		}
24064 	}
24065 
24066 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
24067 		verbose(env, "Private stack not supported by jit\n");
24068 		return -EACCES;
24069 	}
24070 
24071 	for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) {
24072 		if (st_ops_desc->arg_info[member_idx].info->refcounted) {
24073 			has_refcounted_arg = true;
24074 			break;
24075 		}
24076 	}
24077 
24078 	/* Tail call is not allowed for programs with refcounted arguments since we
24079 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
24080 	 */
24081 	for (i = 0; i < env->subprog_cnt; i++) {
24082 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
24083 			verbose(env, "program with __ref argument cannot tail call\n");
24084 			return -EINVAL;
24085 		}
24086 	}
24087 
24088 	prog->aux->st_ops = st_ops;
24089 	prog->aux->attach_st_ops_member_off = member_off;
24090 
24091 	prog->aux->attach_func_proto = func_proto;
24092 	prog->aux->attach_func_name = mname;
24093 	env->ops = st_ops->verifier_ops;
24094 
24095 	return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info,
24096 					  st_ops_desc->arg_info[member_idx].cnt);
24097 }
24098 #define SECURITY_PREFIX "security_"
24099 
24100 static int check_attach_modify_return(unsigned long addr, const char *func_name)
24101 {
24102 	if (within_error_injection_list(addr) ||
24103 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
24104 		return 0;
24105 
24106 	return -EINVAL;
24107 }
24108 
24109 /* list of non-sleepable functions that are otherwise on
24110  * ALLOW_ERROR_INJECTION list
24111  */
24112 BTF_SET_START(btf_non_sleepable_error_inject)
24113 /* Three functions below can be called from sleepable and non-sleepable context.
24114  * Assume non-sleepable from bpf safety point of view.
24115  */
24116 BTF_ID(func, __filemap_add_folio)
24117 #ifdef CONFIG_FAIL_PAGE_ALLOC
24118 BTF_ID(func, should_fail_alloc_page)
24119 #endif
24120 #ifdef CONFIG_FAILSLAB
24121 BTF_ID(func, should_failslab)
24122 #endif
24123 BTF_SET_END(btf_non_sleepable_error_inject)
24124 
24125 static int check_non_sleepable_error_inject(u32 btf_id)
24126 {
24127 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
24128 }
24129 
24130 int bpf_check_attach_target(struct bpf_verifier_log *log,
24131 			    const struct bpf_prog *prog,
24132 			    const struct bpf_prog *tgt_prog,
24133 			    u32 btf_id,
24134 			    struct bpf_attach_target_info *tgt_info)
24135 {
24136 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
24137 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
24138 	char trace_symbol[KSYM_SYMBOL_LEN];
24139 	const char prefix[] = "btf_trace_";
24140 	struct bpf_raw_event_map *btp;
24141 	int ret = 0, subprog = -1, i;
24142 	const struct btf_type *t;
24143 	bool conservative = true;
24144 	const char *tname, *fname;
24145 	struct btf *btf;
24146 	long addr = 0;
24147 	struct module *mod = NULL;
24148 
24149 	if (!btf_id) {
24150 		bpf_log(log, "Tracing programs must provide btf_id\n");
24151 		return -EINVAL;
24152 	}
24153 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
24154 	if (!btf) {
24155 		bpf_log(log,
24156 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
24157 		return -EINVAL;
24158 	}
24159 	t = btf_type_by_id(btf, btf_id);
24160 	if (!t) {
24161 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
24162 		return -EINVAL;
24163 	}
24164 	tname = btf_name_by_offset(btf, t->name_off);
24165 	if (!tname) {
24166 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
24167 		return -EINVAL;
24168 	}
24169 	if (tgt_prog) {
24170 		struct bpf_prog_aux *aux = tgt_prog->aux;
24171 		bool tgt_changes_pkt_data;
24172 		bool tgt_might_sleep;
24173 
24174 		if (bpf_prog_is_dev_bound(prog->aux) &&
24175 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
24176 			bpf_log(log, "Target program bound device mismatch");
24177 			return -EINVAL;
24178 		}
24179 
24180 		for (i = 0; i < aux->func_info_cnt; i++)
24181 			if (aux->func_info[i].type_id == btf_id) {
24182 				subprog = i;
24183 				break;
24184 			}
24185 		if (subprog == -1) {
24186 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
24187 			return -EINVAL;
24188 		}
24189 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
24190 			bpf_log(log,
24191 				"%s programs cannot attach to exception callback\n",
24192 				prog_extension ? "Extension" : "FENTRY/FEXIT");
24193 			return -EINVAL;
24194 		}
24195 		conservative = aux->func_info_aux[subprog].unreliable;
24196 		if (prog_extension) {
24197 			if (conservative) {
24198 				bpf_log(log,
24199 					"Cannot replace static functions\n");
24200 				return -EINVAL;
24201 			}
24202 			if (!prog->jit_requested) {
24203 				bpf_log(log,
24204 					"Extension programs should be JITed\n");
24205 				return -EINVAL;
24206 			}
24207 			tgt_changes_pkt_data = aux->func
24208 					       ? aux->func[subprog]->aux->changes_pkt_data
24209 					       : aux->changes_pkt_data;
24210 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
24211 				bpf_log(log,
24212 					"Extension program changes packet data, while original does not\n");
24213 				return -EINVAL;
24214 			}
24215 
24216 			tgt_might_sleep = aux->func
24217 					  ? aux->func[subprog]->aux->might_sleep
24218 					  : aux->might_sleep;
24219 			if (prog->aux->might_sleep && !tgt_might_sleep) {
24220 				bpf_log(log,
24221 					"Extension program may sleep, while original does not\n");
24222 				return -EINVAL;
24223 			}
24224 		}
24225 		if (!tgt_prog->jited) {
24226 			bpf_log(log, "Can attach to only JITed progs\n");
24227 			return -EINVAL;
24228 		}
24229 		if (prog_tracing) {
24230 			if (aux->attach_tracing_prog) {
24231 				/*
24232 				 * Target program is an fentry/fexit which is already attached
24233 				 * to another tracing program. More levels of nesting
24234 				 * attachment are not allowed.
24235 				 */
24236 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
24237 				return -EINVAL;
24238 			}
24239 		} else if (tgt_prog->type == prog->type) {
24240 			/*
24241 			 * To avoid potential call chain cycles, prevent attaching of a
24242 			 * program extension to another extension. It's ok to attach
24243 			 * fentry/fexit to extension program.
24244 			 */
24245 			bpf_log(log, "Cannot recursively attach\n");
24246 			return -EINVAL;
24247 		}
24248 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
24249 		    prog_extension &&
24250 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
24251 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
24252 			/* Program extensions can extend all program types
24253 			 * except fentry/fexit. The reason is the following.
24254 			 * The fentry/fexit programs are used for performance
24255 			 * analysis, stats and can be attached to any program
24256 			 * type. When extension program is replacing XDP function
24257 			 * it is necessary to allow performance analysis of all
24258 			 * functions. Both original XDP program and its program
24259 			 * extension. Hence attaching fentry/fexit to
24260 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
24261 			 * fentry/fexit was allowed it would be possible to create
24262 			 * long call chain fentry->extension->fentry->extension
24263 			 * beyond reasonable stack size. Hence extending fentry
24264 			 * is not allowed.
24265 			 */
24266 			bpf_log(log, "Cannot extend fentry/fexit\n");
24267 			return -EINVAL;
24268 		}
24269 	} else {
24270 		if (prog_extension) {
24271 			bpf_log(log, "Cannot replace kernel functions\n");
24272 			return -EINVAL;
24273 		}
24274 	}
24275 
24276 	switch (prog->expected_attach_type) {
24277 	case BPF_TRACE_RAW_TP:
24278 		if (tgt_prog) {
24279 			bpf_log(log,
24280 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
24281 			return -EINVAL;
24282 		}
24283 		if (!btf_type_is_typedef(t)) {
24284 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
24285 				btf_id);
24286 			return -EINVAL;
24287 		}
24288 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
24289 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
24290 				btf_id, tname);
24291 			return -EINVAL;
24292 		}
24293 		tname += sizeof(prefix) - 1;
24294 
24295 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
24296 		 * names. Thus using bpf_raw_event_map to get argument names.
24297 		 */
24298 		btp = bpf_get_raw_tracepoint(tname);
24299 		if (!btp)
24300 			return -EINVAL;
24301 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
24302 					trace_symbol);
24303 		bpf_put_raw_tracepoint(btp);
24304 
24305 		if (fname)
24306 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
24307 
24308 		if (!fname || ret < 0) {
24309 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
24310 				prefix, tname);
24311 			t = btf_type_by_id(btf, t->type);
24312 			if (!btf_type_is_ptr(t))
24313 				/* should never happen in valid vmlinux build */
24314 				return -EINVAL;
24315 		} else {
24316 			t = btf_type_by_id(btf, ret);
24317 			if (!btf_type_is_func(t))
24318 				/* should never happen in valid vmlinux build */
24319 				return -EINVAL;
24320 		}
24321 
24322 		t = btf_type_by_id(btf, t->type);
24323 		if (!btf_type_is_func_proto(t))
24324 			/* should never happen in valid vmlinux build */
24325 			return -EINVAL;
24326 
24327 		break;
24328 	case BPF_TRACE_ITER:
24329 		if (!btf_type_is_func(t)) {
24330 			bpf_log(log, "attach_btf_id %u is not a function\n",
24331 				btf_id);
24332 			return -EINVAL;
24333 		}
24334 		t = btf_type_by_id(btf, t->type);
24335 		if (!btf_type_is_func_proto(t))
24336 			return -EINVAL;
24337 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
24338 		if (ret)
24339 			return ret;
24340 		break;
24341 	default:
24342 		if (!prog_extension)
24343 			return -EINVAL;
24344 		fallthrough;
24345 	case BPF_MODIFY_RETURN:
24346 	case BPF_LSM_MAC:
24347 	case BPF_LSM_CGROUP:
24348 	case BPF_TRACE_FENTRY:
24349 	case BPF_TRACE_FEXIT:
24350 		if (!btf_type_is_func(t)) {
24351 			bpf_log(log, "attach_btf_id %u is not a function\n",
24352 				btf_id);
24353 			return -EINVAL;
24354 		}
24355 		if (prog_extension &&
24356 		    btf_check_type_match(log, prog, btf, t))
24357 			return -EINVAL;
24358 		t = btf_type_by_id(btf, t->type);
24359 		if (!btf_type_is_func_proto(t))
24360 			return -EINVAL;
24361 
24362 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
24363 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
24364 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
24365 			return -EINVAL;
24366 
24367 		if (tgt_prog && conservative)
24368 			t = NULL;
24369 
24370 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
24371 		if (ret < 0)
24372 			return ret;
24373 
24374 		if (tgt_prog) {
24375 			if (subprog == 0)
24376 				addr = (long) tgt_prog->bpf_func;
24377 			else
24378 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
24379 		} else {
24380 			if (btf_is_module(btf)) {
24381 				mod = btf_try_get_module(btf);
24382 				if (mod)
24383 					addr = find_kallsyms_symbol_value(mod, tname);
24384 				else
24385 					addr = 0;
24386 			} else {
24387 				addr = kallsyms_lookup_name(tname);
24388 			}
24389 			if (!addr) {
24390 				module_put(mod);
24391 				bpf_log(log,
24392 					"The address of function %s cannot be found\n",
24393 					tname);
24394 				return -ENOENT;
24395 			}
24396 		}
24397 
24398 		if (prog->sleepable) {
24399 			ret = -EINVAL;
24400 			switch (prog->type) {
24401 			case BPF_PROG_TYPE_TRACING:
24402 
24403 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
24404 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
24405 				 */
24406 				if (!check_non_sleepable_error_inject(btf_id) &&
24407 				    within_error_injection_list(addr))
24408 					ret = 0;
24409 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
24410 				 * in the fmodret id set with the KF_SLEEPABLE flag.
24411 				 */
24412 				else {
24413 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
24414 										prog);
24415 
24416 					if (flags && (*flags & KF_SLEEPABLE))
24417 						ret = 0;
24418 				}
24419 				break;
24420 			case BPF_PROG_TYPE_LSM:
24421 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
24422 				 * Only some of them are sleepable.
24423 				 */
24424 				if (bpf_lsm_is_sleepable_hook(btf_id))
24425 					ret = 0;
24426 				break;
24427 			default:
24428 				break;
24429 			}
24430 			if (ret) {
24431 				module_put(mod);
24432 				bpf_log(log, "%s is not sleepable\n", tname);
24433 				return ret;
24434 			}
24435 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
24436 			if (tgt_prog) {
24437 				module_put(mod);
24438 				bpf_log(log, "can't modify return codes of BPF programs\n");
24439 				return -EINVAL;
24440 			}
24441 			ret = -EINVAL;
24442 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
24443 			    !check_attach_modify_return(addr, tname))
24444 				ret = 0;
24445 			if (ret) {
24446 				module_put(mod);
24447 				bpf_log(log, "%s() is not modifiable\n", tname);
24448 				return ret;
24449 			}
24450 		}
24451 
24452 		break;
24453 	}
24454 	tgt_info->tgt_addr = addr;
24455 	tgt_info->tgt_name = tname;
24456 	tgt_info->tgt_type = t;
24457 	tgt_info->tgt_mod = mod;
24458 	return 0;
24459 }
24460 
24461 BTF_SET_START(btf_id_deny)
24462 BTF_ID_UNUSED
24463 #ifdef CONFIG_SMP
24464 BTF_ID(func, ___migrate_enable)
24465 BTF_ID(func, migrate_disable)
24466 BTF_ID(func, migrate_enable)
24467 #endif
24468 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
24469 BTF_ID(func, rcu_read_unlock_strict)
24470 #endif
24471 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
24472 BTF_ID(func, preempt_count_add)
24473 BTF_ID(func, preempt_count_sub)
24474 #endif
24475 #ifdef CONFIG_PREEMPT_RCU
24476 BTF_ID(func, __rcu_read_lock)
24477 BTF_ID(func, __rcu_read_unlock)
24478 #endif
24479 BTF_SET_END(btf_id_deny)
24480 
24481 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
24482  * Currently, we must manually list all __noreturn functions here. Once a more
24483  * robust solution is implemented, this workaround can be removed.
24484  */
24485 BTF_SET_START(noreturn_deny)
24486 #ifdef CONFIG_IA32_EMULATION
24487 BTF_ID(func, __ia32_sys_exit)
24488 BTF_ID(func, __ia32_sys_exit_group)
24489 #endif
24490 #ifdef CONFIG_KUNIT
24491 BTF_ID(func, __kunit_abort)
24492 BTF_ID(func, kunit_try_catch_throw)
24493 #endif
24494 #ifdef CONFIG_MODULES
24495 BTF_ID(func, __module_put_and_kthread_exit)
24496 #endif
24497 #ifdef CONFIG_X86_64
24498 BTF_ID(func, __x64_sys_exit)
24499 BTF_ID(func, __x64_sys_exit_group)
24500 #endif
24501 BTF_ID(func, do_exit)
24502 BTF_ID(func, do_group_exit)
24503 BTF_ID(func, kthread_complete_and_exit)
24504 BTF_ID(func, kthread_exit)
24505 BTF_ID(func, make_task_dead)
24506 BTF_SET_END(noreturn_deny)
24507 
24508 static bool can_be_sleepable(struct bpf_prog *prog)
24509 {
24510 	if (prog->type == BPF_PROG_TYPE_TRACING) {
24511 		switch (prog->expected_attach_type) {
24512 		case BPF_TRACE_FENTRY:
24513 		case BPF_TRACE_FEXIT:
24514 		case BPF_MODIFY_RETURN:
24515 		case BPF_TRACE_ITER:
24516 			return true;
24517 		default:
24518 			return false;
24519 		}
24520 	}
24521 	return prog->type == BPF_PROG_TYPE_LSM ||
24522 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
24523 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
24524 }
24525 
24526 static int check_attach_btf_id(struct bpf_verifier_env *env)
24527 {
24528 	struct bpf_prog *prog = env->prog;
24529 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
24530 	struct bpf_attach_target_info tgt_info = {};
24531 	u32 btf_id = prog->aux->attach_btf_id;
24532 	struct bpf_trampoline *tr;
24533 	int ret;
24534 	u64 key;
24535 
24536 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
24537 		if (prog->sleepable)
24538 			/* attach_btf_id checked to be zero already */
24539 			return 0;
24540 		verbose(env, "Syscall programs can only be sleepable\n");
24541 		return -EINVAL;
24542 	}
24543 
24544 	if (prog->sleepable && !can_be_sleepable(prog)) {
24545 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
24546 		return -EINVAL;
24547 	}
24548 
24549 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
24550 		return check_struct_ops_btf_id(env);
24551 
24552 	if (prog->type != BPF_PROG_TYPE_TRACING &&
24553 	    prog->type != BPF_PROG_TYPE_LSM &&
24554 	    prog->type != BPF_PROG_TYPE_EXT)
24555 		return 0;
24556 
24557 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
24558 	if (ret)
24559 		return ret;
24560 
24561 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
24562 		/* to make freplace equivalent to their targets, they need to
24563 		 * inherit env->ops and expected_attach_type for the rest of the
24564 		 * verification
24565 		 */
24566 		env->ops = bpf_verifier_ops[tgt_prog->type];
24567 		prog->expected_attach_type = tgt_prog->expected_attach_type;
24568 	}
24569 
24570 	/* store info about the attachment target that will be used later */
24571 	prog->aux->attach_func_proto = tgt_info.tgt_type;
24572 	prog->aux->attach_func_name = tgt_info.tgt_name;
24573 	prog->aux->mod = tgt_info.tgt_mod;
24574 
24575 	if (tgt_prog) {
24576 		prog->aux->saved_dst_prog_type = tgt_prog->type;
24577 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
24578 	}
24579 
24580 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
24581 		prog->aux->attach_btf_trace = true;
24582 		return 0;
24583 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
24584 		return bpf_iter_prog_supported(prog);
24585 	}
24586 
24587 	if (prog->type == BPF_PROG_TYPE_LSM) {
24588 		ret = bpf_lsm_verify_prog(&env->log, prog);
24589 		if (ret < 0)
24590 			return ret;
24591 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
24592 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
24593 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
24594 			tgt_info.tgt_name);
24595 		return -EINVAL;
24596 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
24597 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
24598 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
24599 		verbose(env, "Attaching fexit/fmod_ret to __noreturn function '%s' is rejected.\n",
24600 			tgt_info.tgt_name);
24601 		return -EINVAL;
24602 	}
24603 
24604 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
24605 	tr = bpf_trampoline_get(key, &tgt_info);
24606 	if (!tr)
24607 		return -ENOMEM;
24608 
24609 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
24610 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
24611 
24612 	prog->aux->dst_trampoline = tr;
24613 	return 0;
24614 }
24615 
24616 struct btf *bpf_get_btf_vmlinux(void)
24617 {
24618 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
24619 		mutex_lock(&bpf_verifier_lock);
24620 		if (!btf_vmlinux)
24621 			btf_vmlinux = btf_parse_vmlinux();
24622 		mutex_unlock(&bpf_verifier_lock);
24623 	}
24624 	return btf_vmlinux;
24625 }
24626 
24627 /*
24628  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
24629  * this case expect that every file descriptor in the array is either a map or
24630  * a BTF. Everything else is considered to be trash.
24631  */
24632 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
24633 {
24634 	struct bpf_map *map;
24635 	struct btf *btf;
24636 	CLASS(fd, f)(fd);
24637 	int err;
24638 
24639 	map = __bpf_map_get(f);
24640 	if (!IS_ERR(map)) {
24641 		err = __add_used_map(env, map);
24642 		if (err < 0)
24643 			return err;
24644 		return 0;
24645 	}
24646 
24647 	btf = __btf_get_by_fd(f);
24648 	if (!IS_ERR(btf)) {
24649 		err = __add_used_btf(env, btf);
24650 		if (err < 0)
24651 			return err;
24652 		return 0;
24653 	}
24654 
24655 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
24656 	return PTR_ERR(map);
24657 }
24658 
24659 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
24660 {
24661 	size_t size = sizeof(int);
24662 	int ret;
24663 	int fd;
24664 	u32 i;
24665 
24666 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
24667 
24668 	/*
24669 	 * The only difference between old (no fd_array_cnt is given) and new
24670 	 * APIs is that in the latter case the fd_array is expected to be
24671 	 * continuous and is scanned for map fds right away
24672 	 */
24673 	if (!attr->fd_array_cnt)
24674 		return 0;
24675 
24676 	/* Check for integer overflow */
24677 	if (attr->fd_array_cnt >= (U32_MAX / size)) {
24678 		verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
24679 		return -EINVAL;
24680 	}
24681 
24682 	for (i = 0; i < attr->fd_array_cnt; i++) {
24683 		if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
24684 			return -EFAULT;
24685 
24686 		ret = add_fd_from_fd_array(env, fd);
24687 		if (ret)
24688 			return ret;
24689 	}
24690 
24691 	return 0;
24692 }
24693 
24694 /* Each field is a register bitmask */
24695 struct insn_live_regs {
24696 	u16 use;	/* registers read by instruction */
24697 	u16 def;	/* registers written by instruction */
24698 	u16 in;		/* registers that may be alive before instruction */
24699 	u16 out;	/* registers that may be alive after instruction */
24700 };
24701 
24702 /* Bitmask with 1s for all caller saved registers */
24703 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
24704 
24705 /* Compute info->{use,def} fields for the instruction */
24706 static void compute_insn_live_regs(struct bpf_verifier_env *env,
24707 				   struct bpf_insn *insn,
24708 				   struct insn_live_regs *info)
24709 {
24710 	struct call_summary cs;
24711 	u8 class = BPF_CLASS(insn->code);
24712 	u8 code = BPF_OP(insn->code);
24713 	u8 mode = BPF_MODE(insn->code);
24714 	u16 src = BIT(insn->src_reg);
24715 	u16 dst = BIT(insn->dst_reg);
24716 	u16 r0  = BIT(0);
24717 	u16 def = 0;
24718 	u16 use = 0xffff;
24719 
24720 	switch (class) {
24721 	case BPF_LD:
24722 		switch (mode) {
24723 		case BPF_IMM:
24724 			if (BPF_SIZE(insn->code) == BPF_DW) {
24725 				def = dst;
24726 				use = 0;
24727 			}
24728 			break;
24729 		case BPF_LD | BPF_ABS:
24730 		case BPF_LD | BPF_IND:
24731 			/* stick with defaults */
24732 			break;
24733 		}
24734 		break;
24735 	case BPF_LDX:
24736 		switch (mode) {
24737 		case BPF_MEM:
24738 		case BPF_MEMSX:
24739 			def = dst;
24740 			use = src;
24741 			break;
24742 		}
24743 		break;
24744 	case BPF_ST:
24745 		switch (mode) {
24746 		case BPF_MEM:
24747 			def = 0;
24748 			use = dst;
24749 			break;
24750 		}
24751 		break;
24752 	case BPF_STX:
24753 		switch (mode) {
24754 		case BPF_MEM:
24755 			def = 0;
24756 			use = dst | src;
24757 			break;
24758 		case BPF_ATOMIC:
24759 			switch (insn->imm) {
24760 			case BPF_CMPXCHG:
24761 				use = r0 | dst | src;
24762 				def = r0;
24763 				break;
24764 			case BPF_LOAD_ACQ:
24765 				def = dst;
24766 				use = src;
24767 				break;
24768 			case BPF_STORE_REL:
24769 				def = 0;
24770 				use = dst | src;
24771 				break;
24772 			default:
24773 				use = dst | src;
24774 				if (insn->imm & BPF_FETCH)
24775 					def = src;
24776 				else
24777 					def = 0;
24778 			}
24779 			break;
24780 		}
24781 		break;
24782 	case BPF_ALU:
24783 	case BPF_ALU64:
24784 		switch (code) {
24785 		case BPF_END:
24786 			use = dst;
24787 			def = dst;
24788 			break;
24789 		case BPF_MOV:
24790 			def = dst;
24791 			if (BPF_SRC(insn->code) == BPF_K)
24792 				use = 0;
24793 			else
24794 				use = src;
24795 			break;
24796 		default:
24797 			def = dst;
24798 			if (BPF_SRC(insn->code) == BPF_K)
24799 				use = dst;
24800 			else
24801 				use = dst | src;
24802 		}
24803 		break;
24804 	case BPF_JMP:
24805 	case BPF_JMP32:
24806 		switch (code) {
24807 		case BPF_JA:
24808 		case BPF_JCOND:
24809 			def = 0;
24810 			use = 0;
24811 			break;
24812 		case BPF_EXIT:
24813 			def = 0;
24814 			use = r0;
24815 			break;
24816 		case BPF_CALL:
24817 			def = ALL_CALLER_SAVED_REGS;
24818 			use = def & ~BIT(BPF_REG_0);
24819 			if (get_call_summary(env, insn, &cs))
24820 				use = GENMASK(cs.num_params, 1);
24821 			break;
24822 		default:
24823 			def = 0;
24824 			if (BPF_SRC(insn->code) == BPF_K)
24825 				use = dst;
24826 			else
24827 				use = dst | src;
24828 		}
24829 		break;
24830 	}
24831 
24832 	info->def = def;
24833 	info->use = use;
24834 }
24835 
24836 /* Compute may-live registers after each instruction in the program.
24837  * The register is live after the instruction I if it is read by some
24838  * instruction S following I during program execution and is not
24839  * overwritten between I and S.
24840  *
24841  * Store result in env->insn_aux_data[i].live_regs.
24842  */
24843 static int compute_live_registers(struct bpf_verifier_env *env)
24844 {
24845 	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
24846 	struct bpf_insn *insns = env->prog->insnsi;
24847 	struct insn_live_regs *state;
24848 	int insn_cnt = env->prog->len;
24849 	int err = 0, i, j;
24850 	bool changed;
24851 
24852 	/* Use the following algorithm:
24853 	 * - define the following:
24854 	 *   - I.use : a set of all registers read by instruction I;
24855 	 *   - I.def : a set of all registers written by instruction I;
24856 	 *   - I.in  : a set of all registers that may be alive before I execution;
24857 	 *   - I.out : a set of all registers that may be alive after I execution;
24858 	 *   - insn_successors(I): a set of instructions S that might immediately
24859 	 *                         follow I for some program execution;
24860 	 * - associate separate empty sets 'I.in' and 'I.out' with each instruction;
24861 	 * - visit each instruction in a postorder and update
24862 	 *   state[i].in, state[i].out as follows:
24863 	 *
24864 	 *       state[i].out = U [state[s].in for S in insn_successors(i)]
24865 	 *       state[i].in  = (state[i].out / state[i].def) U state[i].use
24866 	 *
24867 	 *   (where U stands for set union, / stands for set difference)
24868 	 * - repeat the computation while {in,out} fields changes for
24869 	 *   any instruction.
24870 	 */
24871 	state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL_ACCOUNT);
24872 	if (!state) {
24873 		err = -ENOMEM;
24874 		goto out;
24875 	}
24876 
24877 	for (i = 0; i < insn_cnt; ++i)
24878 		compute_insn_live_regs(env, &insns[i], &state[i]);
24879 
24880 	changed = true;
24881 	while (changed) {
24882 		changed = false;
24883 		for (i = 0; i < env->cfg.cur_postorder; ++i) {
24884 			int insn_idx = env->cfg.insn_postorder[i];
24885 			struct insn_live_regs *live = &state[insn_idx];
24886 			struct bpf_iarray *succ;
24887 			u16 new_out = 0;
24888 			u16 new_in = 0;
24889 
24890 			succ = bpf_insn_successors(env, insn_idx);
24891 			for (int s = 0; s < succ->cnt; ++s)
24892 				new_out |= state[succ->items[s]].in;
24893 			new_in = (new_out & ~live->def) | live->use;
24894 			if (new_out != live->out || new_in != live->in) {
24895 				live->in = new_in;
24896 				live->out = new_out;
24897 				changed = true;
24898 			}
24899 		}
24900 	}
24901 
24902 	for (i = 0; i < insn_cnt; ++i)
24903 		insn_aux[i].live_regs_before = state[i].in;
24904 
24905 	if (env->log.level & BPF_LOG_LEVEL2) {
24906 		verbose(env, "Live regs before insn:\n");
24907 		for (i = 0; i < insn_cnt; ++i) {
24908 			if (env->insn_aux_data[i].scc)
24909 				verbose(env, "%3d ", env->insn_aux_data[i].scc);
24910 			else
24911 				verbose(env, "    ");
24912 			verbose(env, "%3d: ", i);
24913 			for (j = BPF_REG_0; j < BPF_REG_10; ++j)
24914 				if (insn_aux[i].live_regs_before & BIT(j))
24915 					verbose(env, "%d", j);
24916 				else
24917 					verbose(env, ".");
24918 			verbose(env, " ");
24919 			verbose_insn(env, &insns[i]);
24920 			if (bpf_is_ldimm64(&insns[i]))
24921 				i++;
24922 		}
24923 	}
24924 
24925 out:
24926 	kvfree(state);
24927 	return err;
24928 }
24929 
24930 /*
24931  * Compute strongly connected components (SCCs) on the CFG.
24932  * Assign an SCC number to each instruction, recorded in env->insn_aux[*].scc.
24933  * If instruction is a sole member of its SCC and there are no self edges,
24934  * assign it SCC number of zero.
24935  * Uses a non-recursive adaptation of Tarjan's algorithm for SCC computation.
24936  */
24937 static int compute_scc(struct bpf_verifier_env *env)
24938 {
24939 	const u32 NOT_ON_STACK = U32_MAX;
24940 
24941 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
24942 	const u32 insn_cnt = env->prog->len;
24943 	int stack_sz, dfs_sz, err = 0;
24944 	u32 *stack, *pre, *low, *dfs;
24945 	u32 i, j, t, w;
24946 	u32 next_preorder_num;
24947 	u32 next_scc_id;
24948 	bool assign_scc;
24949 	struct bpf_iarray *succ;
24950 
24951 	next_preorder_num = 1;
24952 	next_scc_id = 1;
24953 	/*
24954 	 * - 'stack' accumulates vertices in DFS order, see invariant comment below;
24955 	 * - 'pre[t] == p' => preorder number of vertex 't' is 'p';
24956 	 * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n';
24957 	 * - 'dfs' DFS traversal stack, used to emulate explicit recursion.
24958 	 */
24959 	stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24960 	pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24961 	low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24962 	dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT);
24963 	if (!stack || !pre || !low || !dfs) {
24964 		err = -ENOMEM;
24965 		goto exit;
24966 	}
24967 	/*
24968 	 * References:
24969 	 * [1] R. Tarjan "Depth-First Search and Linear Graph Algorithms"
24970 	 * [2] D. J. Pearce "A Space-Efficient Algorithm for Finding Strongly Connected Components"
24971 	 *
24972 	 * The algorithm maintains the following invariant:
24973 	 * - suppose there is a path 'u' ~> 'v', such that 'pre[v] < pre[u]';
24974 	 * - then, vertex 'u' remains on stack while vertex 'v' is on stack.
24975 	 *
24976 	 * Consequently:
24977 	 * - If 'low[v] < pre[v]', there is a path from 'v' to some vertex 'u',
24978 	 *   such that 'pre[u] == low[v]'; vertex 'u' is currently on the stack,
24979 	 *   and thus there is an SCC (loop) containing both 'u' and 'v'.
24980 	 * - If 'low[v] == pre[v]', loops containing 'v' have been explored,
24981 	 *   and 'v' can be considered the root of some SCC.
24982 	 *
24983 	 * Here is a pseudo-code for an explicitly recursive version of the algorithm:
24984 	 *
24985 	 *    NOT_ON_STACK = insn_cnt + 1
24986 	 *    pre = [0] * insn_cnt
24987 	 *    low = [0] * insn_cnt
24988 	 *    scc = [0] * insn_cnt
24989 	 *    stack = []
24990 	 *
24991 	 *    next_preorder_num = 1
24992 	 *    next_scc_id = 1
24993 	 *
24994 	 *    def recur(w):
24995 	 *        nonlocal next_preorder_num
24996 	 *        nonlocal next_scc_id
24997 	 *
24998 	 *        pre[w] = next_preorder_num
24999 	 *        low[w] = next_preorder_num
25000 	 *        next_preorder_num += 1
25001 	 *        stack.append(w)
25002 	 *        for s in successors(w):
25003 	 *            # Note: for classic algorithm the block below should look as:
25004 	 *            #
25005 	 *            # if pre[s] == 0:
25006 	 *            #     recur(s)
25007 	 *            #	    low[w] = min(low[w], low[s])
25008 	 *            # elif low[s] != NOT_ON_STACK:
25009 	 *            #     low[w] = min(low[w], pre[s])
25010 	 *            #
25011 	 *            # But replacing both 'min' instructions with 'low[w] = min(low[w], low[s])'
25012 	 *            # does not break the invariant and makes itartive version of the algorithm
25013 	 *            # simpler. See 'Algorithm #3' from [2].
25014 	 *
25015 	 *            # 's' not yet visited
25016 	 *            if pre[s] == 0:
25017 	 *                recur(s)
25018 	 *            # if 's' is on stack, pick lowest reachable preorder number from it;
25019 	 *            # if 's' is not on stack 'low[s] == NOT_ON_STACK > low[w]',
25020 	 *            # so 'min' would be a noop.
25021 	 *            low[w] = min(low[w], low[s])
25022 	 *
25023 	 *        if low[w] == pre[w]:
25024 	 *            # 'w' is the root of an SCC, pop all vertices
25025 	 *            # below 'w' on stack and assign same SCC to them.
25026 	 *            while True:
25027 	 *                t = stack.pop()
25028 	 *                low[t] = NOT_ON_STACK
25029 	 *                scc[t] = next_scc_id
25030 	 *                if t == w:
25031 	 *                    break
25032 	 *            next_scc_id += 1
25033 	 *
25034 	 *    for i in range(0, insn_cnt):
25035 	 *        if pre[i] == 0:
25036 	 *            recur(i)
25037 	 *
25038 	 * Below implementation replaces explicit recursion with array 'dfs'.
25039 	 */
25040 	for (i = 0; i < insn_cnt; i++) {
25041 		if (pre[i])
25042 			continue;
25043 		stack_sz = 0;
25044 		dfs_sz = 1;
25045 		dfs[0] = i;
25046 dfs_continue:
25047 		while (dfs_sz) {
25048 			w = dfs[dfs_sz - 1];
25049 			if (pre[w] == 0) {
25050 				low[w] = next_preorder_num;
25051 				pre[w] = next_preorder_num;
25052 				next_preorder_num++;
25053 				stack[stack_sz++] = w;
25054 			}
25055 			/* Visit 'w' successors */
25056 			succ = bpf_insn_successors(env, w);
25057 			for (j = 0; j < succ->cnt; ++j) {
25058 				if (pre[succ->items[j]]) {
25059 					low[w] = min(low[w], low[succ->items[j]]);
25060 				} else {
25061 					dfs[dfs_sz++] = succ->items[j];
25062 					goto dfs_continue;
25063 				}
25064 			}
25065 			/*
25066 			 * Preserve the invariant: if some vertex above in the stack
25067 			 * is reachable from 'w', keep 'w' on the stack.
25068 			 */
25069 			if (low[w] < pre[w]) {
25070 				dfs_sz--;
25071 				goto dfs_continue;
25072 			}
25073 			/*
25074 			 * Assign SCC number only if component has two or more elements,
25075 			 * or if component has a self reference.
25076 			 */
25077 			assign_scc = stack[stack_sz - 1] != w;
25078 			for (j = 0; j < succ->cnt; ++j) {
25079 				if (succ->items[j] == w) {
25080 					assign_scc = true;
25081 					break;
25082 				}
25083 			}
25084 			/* Pop component elements from stack */
25085 			do {
25086 				t = stack[--stack_sz];
25087 				low[t] = NOT_ON_STACK;
25088 				if (assign_scc)
25089 					aux[t].scc = next_scc_id;
25090 			} while (t != w);
25091 			if (assign_scc)
25092 				next_scc_id++;
25093 			dfs_sz--;
25094 		}
25095 	}
25096 	env->scc_info = kvcalloc(next_scc_id, sizeof(*env->scc_info), GFP_KERNEL_ACCOUNT);
25097 	if (!env->scc_info) {
25098 		err = -ENOMEM;
25099 		goto exit;
25100 	}
25101 	env->scc_cnt = next_scc_id;
25102 exit:
25103 	kvfree(stack);
25104 	kvfree(pre);
25105 	kvfree(low);
25106 	kvfree(dfs);
25107 	return err;
25108 }
25109 
25110 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
25111 {
25112 	u64 start_time = ktime_get_ns();
25113 	struct bpf_verifier_env *env;
25114 	int i, len, ret = -EINVAL, err;
25115 	u32 log_true_size;
25116 	bool is_priv;
25117 
25118 	BTF_TYPE_EMIT(enum bpf_features);
25119 
25120 	/* no program is valid */
25121 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
25122 		return -EINVAL;
25123 
25124 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
25125 	 * allocate/free it every time bpf_check() is called
25126 	 */
25127 	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL_ACCOUNT);
25128 	if (!env)
25129 		return -ENOMEM;
25130 
25131 	env->bt.env = env;
25132 
25133 	len = (*prog)->len;
25134 	env->insn_aux_data =
25135 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
25136 	ret = -ENOMEM;
25137 	if (!env->insn_aux_data)
25138 		goto err_free_env;
25139 	for (i = 0; i < len; i++)
25140 		env->insn_aux_data[i].orig_idx = i;
25141 	env->succ = iarray_realloc(NULL, 2);
25142 	if (!env->succ)
25143 		goto err_free_env;
25144 	env->prog = *prog;
25145 	env->ops = bpf_verifier_ops[env->prog->type];
25146 
25147 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
25148 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
25149 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
25150 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
25151 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
25152 
25153 	bpf_get_btf_vmlinux();
25154 
25155 	/* grab the mutex to protect few globals used by verifier */
25156 	if (!is_priv)
25157 		mutex_lock(&bpf_verifier_lock);
25158 
25159 	/* user could have requested verbose verifier output
25160 	 * and supplied buffer to store the verification trace
25161 	 */
25162 	ret = bpf_vlog_init(&env->log, attr->log_level,
25163 			    (char __user *) (unsigned long) attr->log_buf,
25164 			    attr->log_size);
25165 	if (ret)
25166 		goto err_unlock;
25167 
25168 	ret = process_fd_array(env, attr, uattr);
25169 	if (ret)
25170 		goto skip_full_check;
25171 
25172 	mark_verifier_state_clean(env);
25173 
25174 	if (IS_ERR(btf_vmlinux)) {
25175 		/* Either gcc or pahole or kernel are broken. */
25176 		verbose(env, "in-kernel BTF is malformed\n");
25177 		ret = PTR_ERR(btf_vmlinux);
25178 		goto skip_full_check;
25179 	}
25180 
25181 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
25182 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
25183 		env->strict_alignment = true;
25184 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
25185 		env->strict_alignment = false;
25186 
25187 	if (is_priv)
25188 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
25189 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
25190 
25191 	env->explored_states = kvcalloc(state_htab_size(env),
25192 				       sizeof(struct list_head),
25193 				       GFP_KERNEL_ACCOUNT);
25194 	ret = -ENOMEM;
25195 	if (!env->explored_states)
25196 		goto skip_full_check;
25197 
25198 	for (i = 0; i < state_htab_size(env); i++)
25199 		INIT_LIST_HEAD(&env->explored_states[i]);
25200 	INIT_LIST_HEAD(&env->free_list);
25201 
25202 	ret = check_btf_info_early(env, attr, uattr);
25203 	if (ret < 0)
25204 		goto skip_full_check;
25205 
25206 	ret = add_subprog_and_kfunc(env);
25207 	if (ret < 0)
25208 		goto skip_full_check;
25209 
25210 	ret = check_subprogs(env);
25211 	if (ret < 0)
25212 		goto skip_full_check;
25213 
25214 	ret = check_btf_info(env, attr, uattr);
25215 	if (ret < 0)
25216 		goto skip_full_check;
25217 
25218 	ret = resolve_pseudo_ldimm64(env);
25219 	if (ret < 0)
25220 		goto skip_full_check;
25221 
25222 	if (bpf_prog_is_offloaded(env->prog->aux)) {
25223 		ret = bpf_prog_offload_verifier_prep(env->prog);
25224 		if (ret)
25225 			goto skip_full_check;
25226 	}
25227 
25228 	ret = check_cfg(env);
25229 	if (ret < 0)
25230 		goto skip_full_check;
25231 
25232 	ret = compute_postorder(env);
25233 	if (ret < 0)
25234 		goto skip_full_check;
25235 
25236 	ret = bpf_stack_liveness_init(env);
25237 	if (ret)
25238 		goto skip_full_check;
25239 
25240 	ret = check_attach_btf_id(env);
25241 	if (ret)
25242 		goto skip_full_check;
25243 
25244 	ret = compute_scc(env);
25245 	if (ret < 0)
25246 		goto skip_full_check;
25247 
25248 	ret = compute_live_registers(env);
25249 	if (ret < 0)
25250 		goto skip_full_check;
25251 
25252 	ret = mark_fastcall_patterns(env);
25253 	if (ret < 0)
25254 		goto skip_full_check;
25255 
25256 	ret = do_check_main(env);
25257 	ret = ret ?: do_check_subprogs(env);
25258 
25259 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
25260 		ret = bpf_prog_offload_finalize(env);
25261 
25262 skip_full_check:
25263 	kvfree(env->explored_states);
25264 
25265 	/* might decrease stack depth, keep it before passes that
25266 	 * allocate additional slots.
25267 	 */
25268 	if (ret == 0)
25269 		ret = remove_fastcall_spills_fills(env);
25270 
25271 	if (ret == 0)
25272 		ret = check_max_stack_depth(env);
25273 
25274 	/* instruction rewrites happen after this point */
25275 	if (ret == 0)
25276 		ret = optimize_bpf_loop(env);
25277 
25278 	if (is_priv) {
25279 		if (ret == 0)
25280 			opt_hard_wire_dead_code_branches(env);
25281 		if (ret == 0)
25282 			ret = opt_remove_dead_code(env);
25283 		if (ret == 0)
25284 			ret = opt_remove_nops(env);
25285 	} else {
25286 		if (ret == 0)
25287 			sanitize_dead_code(env);
25288 	}
25289 
25290 	if (ret == 0)
25291 		/* program is valid, convert *(u32*)(ctx + off) accesses */
25292 		ret = convert_ctx_accesses(env);
25293 
25294 	if (ret == 0)
25295 		ret = do_misc_fixups(env);
25296 
25297 	/* do 32-bit optimization after insn patching has done so those patched
25298 	 * insns could be handled correctly.
25299 	 */
25300 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
25301 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
25302 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
25303 								     : false;
25304 	}
25305 
25306 	if (ret == 0)
25307 		ret = fixup_call_args(env);
25308 
25309 	env->verification_time = ktime_get_ns() - start_time;
25310 	print_verification_stats(env);
25311 	env->prog->aux->verified_insns = env->insn_processed;
25312 
25313 	/* preserve original error even if log finalization is successful */
25314 	err = bpf_vlog_finalize(&env->log, &log_true_size);
25315 	if (err)
25316 		ret = err;
25317 
25318 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
25319 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
25320 				  &log_true_size, sizeof(log_true_size))) {
25321 		ret = -EFAULT;
25322 		goto err_release_maps;
25323 	}
25324 
25325 	if (ret)
25326 		goto err_release_maps;
25327 
25328 	if (env->used_map_cnt) {
25329 		/* if program passed verifier, update used_maps in bpf_prog_info */
25330 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
25331 							  sizeof(env->used_maps[0]),
25332 							  GFP_KERNEL_ACCOUNT);
25333 
25334 		if (!env->prog->aux->used_maps) {
25335 			ret = -ENOMEM;
25336 			goto err_release_maps;
25337 		}
25338 
25339 		memcpy(env->prog->aux->used_maps, env->used_maps,
25340 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
25341 		env->prog->aux->used_map_cnt = env->used_map_cnt;
25342 	}
25343 	if (env->used_btf_cnt) {
25344 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
25345 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
25346 							  sizeof(env->used_btfs[0]),
25347 							  GFP_KERNEL_ACCOUNT);
25348 		if (!env->prog->aux->used_btfs) {
25349 			ret = -ENOMEM;
25350 			goto err_release_maps;
25351 		}
25352 
25353 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
25354 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
25355 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
25356 	}
25357 	if (env->used_map_cnt || env->used_btf_cnt) {
25358 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
25359 		 * bpf_ld_imm64 instructions
25360 		 */
25361 		convert_pseudo_ld_imm64(env);
25362 	}
25363 
25364 	adjust_btf_func(env);
25365 
25366 err_release_maps:
25367 	if (ret)
25368 		release_insn_arrays(env);
25369 	if (!env->prog->aux->used_maps)
25370 		/* if we didn't copy map pointers into bpf_prog_info, release
25371 		 * them now. Otherwise free_used_maps() will release them.
25372 		 */
25373 		release_maps(env);
25374 	if (!env->prog->aux->used_btfs)
25375 		release_btfs(env);
25376 
25377 	/* extension progs temporarily inherit the attach_type of their targets
25378 	   for verification purposes, so set it back to zero before returning
25379 	 */
25380 	if (env->prog->type == BPF_PROG_TYPE_EXT)
25381 		env->prog->expected_attach_type = 0;
25382 
25383 	*prog = env->prog;
25384 
25385 	module_put(env->attach_btf_mod);
25386 err_unlock:
25387 	if (!is_priv)
25388 		mutex_unlock(&bpf_verifier_lock);
25389 	clear_insn_aux_data(env, 0, env->prog->len);
25390 	vfree(env->insn_aux_data);
25391 err_free_env:
25392 	bpf_stack_liveness_free(env);
25393 	kvfree(env->cfg.insn_postorder);
25394 	kvfree(env->scc_info);
25395 	kvfree(env->succ);
25396 	kvfree(env->gotox_tmp_buf);
25397 	kvfree(env);
25398 	return ret;
25399 }
25400