xref: /linux/kernel/bpf/verifier.c (revision 07fdad3a93756b872da7b53647715c48d0f4a2d0)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <linux/bpf_mem_alloc.h>
30 #include <net/xdp.h>
31 #include <linux/trace_events.h>
32 #include <linux/kallsyms.h>
33 
34 #include "disasm.h"
35 
36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
38 	[_id] = & _name ## _verifier_ops,
39 #define BPF_MAP_TYPE(_id, _ops)
40 #define BPF_LINK_TYPE(_id, _name)
41 #include <linux/bpf_types.h>
42 #undef BPF_PROG_TYPE
43 #undef BPF_MAP_TYPE
44 #undef BPF_LINK_TYPE
45 };
46 
47 enum bpf_features {
48 	BPF_FEAT_RDONLY_CAST_TO_VOID = 0,
49 	BPF_FEAT_STREAMS	     = 1,
50 	__MAX_BPF_FEAT,
51 };
52 
53 struct bpf_mem_alloc bpf_global_percpu_ma;
54 static bool bpf_global_percpu_ma_set;
55 
56 /* bpf_check() is a static code analyzer that walks eBPF program
57  * instruction by instruction and updates register/stack state.
58  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
59  *
60  * The first pass is depth-first-search to check that the program is a DAG.
61  * It rejects the following programs:
62  * - larger than BPF_MAXINSNS insns
63  * - if loop is present (detected via back-edge)
64  * - unreachable insns exist (shouldn't be a forest. program = one function)
65  * - out of bounds or malformed jumps
66  * The second pass is all possible path descent from the 1st insn.
67  * Since it's analyzing all paths through the program, the length of the
68  * analysis is limited to 64k insn, which may be hit even if total number of
69  * insn is less then 4K, but there are too many branches that change stack/regs.
70  * Number of 'branches to be analyzed' is limited to 1k
71  *
72  * On entry to each instruction, each register has a type, and the instruction
73  * changes the types of the registers depending on instruction semantics.
74  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
75  * copied to R1.
76  *
77  * All registers are 64-bit.
78  * R0 - return register
79  * R1-R5 argument passing registers
80  * R6-R9 callee saved registers
81  * R10 - frame pointer read-only
82  *
83  * At the start of BPF program the register R1 contains a pointer to bpf_context
84  * and has type PTR_TO_CTX.
85  *
86  * Verifier tracks arithmetic operations on pointers in case:
87  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
88  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
89  * 1st insn copies R10 (which has FRAME_PTR) type into R1
90  * and 2nd arithmetic instruction is pattern matched to recognize
91  * that it wants to construct a pointer to some element within stack.
92  * So after 2nd insn, the register R1 has type PTR_TO_STACK
93  * (and -20 constant is saved for further stack bounds checking).
94  * Meaning that this reg is a pointer to stack plus known immediate constant.
95  *
96  * Most of the time the registers have SCALAR_VALUE type, which
97  * means the register has some value, but it's not a valid pointer.
98  * (like pointer plus pointer becomes SCALAR_VALUE type)
99  *
100  * When verifier sees load or store instructions the type of base register
101  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
102  * four pointer types recognized by check_mem_access() function.
103  *
104  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
105  * and the range of [ptr, ptr + map's value_size) is accessible.
106  *
107  * registers used to pass values to function calls are checked against
108  * function argument constraints.
109  *
110  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
111  * It means that the register type passed to this function must be
112  * PTR_TO_STACK and it will be used inside the function as
113  * 'pointer to map element key'
114  *
115  * For example the argument constraints for bpf_map_lookup_elem():
116  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
117  *   .arg1_type = ARG_CONST_MAP_PTR,
118  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
119  *
120  * ret_type says that this function returns 'pointer to map elem value or null'
121  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
122  * 2nd argument should be a pointer to stack, which will be used inside
123  * the helper function as a pointer to map element key.
124  *
125  * On the kernel side the helper function looks like:
126  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
127  * {
128  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
129  *    void *key = (void *) (unsigned long) r2;
130  *    void *value;
131  *
132  *    here kernel can access 'key' and 'map' pointers safely, knowing that
133  *    [key, key + map->key_size) bytes are valid and were initialized on
134  *    the stack of eBPF program.
135  * }
136  *
137  * Corresponding eBPF program may look like:
138  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
139  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
140  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
141  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
142  * here verifier looks at prototype of map_lookup_elem() and sees:
143  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
144  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
145  *
146  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
147  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
148  * and were initialized prior to this call.
149  * If it's ok, then verifier allows this BPF_CALL insn and looks at
150  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
151  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
152  * returns either pointer to map value or NULL.
153  *
154  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
155  * insn, the register holding that pointer in the true branch changes state to
156  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
157  * branch. See check_cond_jmp_op().
158  *
159  * After the call R0 is set to return type of the function and registers R1-R5
160  * are set to NOT_INIT to indicate that they are no longer readable.
161  *
162  * The following reference types represent a potential reference to a kernel
163  * resource which, after first being allocated, must be checked and freed by
164  * the BPF program:
165  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
166  *
167  * When the verifier sees a helper call return a reference type, it allocates a
168  * pointer id for the reference and stores it in the current function state.
169  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
170  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
171  * passes through a NULL-check conditional. For the branch wherein the state is
172  * changed to CONST_IMM, the verifier releases the reference.
173  *
174  * For each helper function that allocates a reference, such as
175  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
176  * bpf_sk_release(). When a reference type passes into the release function,
177  * the verifier also releases the reference. If any unchecked or unreleased
178  * reference remains at the end of the program, the verifier rejects it.
179  */
180 
181 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
182 struct bpf_verifier_stack_elem {
183 	/* verifier state is 'st'
184 	 * before processing instruction 'insn_idx'
185 	 * and after processing instruction 'prev_insn_idx'
186 	 */
187 	struct bpf_verifier_state st;
188 	int insn_idx;
189 	int prev_insn_idx;
190 	struct bpf_verifier_stack_elem *next;
191 	/* length of verifier log at the time this state was pushed on stack */
192 	u32 log_pos;
193 };
194 
195 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
196 #define BPF_COMPLEXITY_LIMIT_STATES	64
197 
198 #define BPF_MAP_KEY_POISON	(1ULL << 63)
199 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
200 
201 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
202 
203 #define BPF_PRIV_STACK_MIN_SIZE		64
204 
205 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx);
206 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id);
207 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
208 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
209 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
210 static int ref_set_non_owning(struct bpf_verifier_env *env,
211 			      struct bpf_reg_state *reg);
212 static void specialize_kfunc(struct bpf_verifier_env *env,
213 			     u32 func_id, u16 offset, unsigned long *addr);
214 static bool is_trusted_reg(const struct bpf_reg_state *reg);
215 
216 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
217 {
218 	return aux->map_ptr_state.poison;
219 }
220 
221 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
222 {
223 	return aux->map_ptr_state.unpriv;
224 }
225 
226 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
227 			      struct bpf_map *map,
228 			      bool unpriv, bool poison)
229 {
230 	unpriv |= bpf_map_ptr_unpriv(aux);
231 	aux->map_ptr_state.unpriv = unpriv;
232 	aux->map_ptr_state.poison = poison;
233 	aux->map_ptr_state.map_ptr = map;
234 }
235 
236 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
237 {
238 	return aux->map_key_state & BPF_MAP_KEY_POISON;
239 }
240 
241 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
242 {
243 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
244 }
245 
246 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
247 {
248 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
249 }
250 
251 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
252 {
253 	bool poisoned = bpf_map_key_poisoned(aux);
254 
255 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
256 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
257 }
258 
259 static bool bpf_helper_call(const struct bpf_insn *insn)
260 {
261 	return insn->code == (BPF_JMP | BPF_CALL) &&
262 	       insn->src_reg == 0;
263 }
264 
265 static bool bpf_pseudo_call(const struct bpf_insn *insn)
266 {
267 	return insn->code == (BPF_JMP | BPF_CALL) &&
268 	       insn->src_reg == BPF_PSEUDO_CALL;
269 }
270 
271 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
272 {
273 	return insn->code == (BPF_JMP | BPF_CALL) &&
274 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
275 }
276 
277 struct bpf_call_arg_meta {
278 	struct bpf_map *map_ptr;
279 	bool raw_mode;
280 	bool pkt_access;
281 	u8 release_regno;
282 	int regno;
283 	int access_size;
284 	int mem_size;
285 	u64 msize_max_value;
286 	int ref_obj_id;
287 	int dynptr_id;
288 	int map_uid;
289 	int func_id;
290 	struct btf *btf;
291 	u32 btf_id;
292 	struct btf *ret_btf;
293 	u32 ret_btf_id;
294 	u32 subprogno;
295 	struct btf_field *kptr_field;
296 	s64 const_map_key;
297 };
298 
299 struct bpf_kfunc_call_arg_meta {
300 	/* In parameters */
301 	struct btf *btf;
302 	u32 func_id;
303 	u32 kfunc_flags;
304 	const struct btf_type *func_proto;
305 	const char *func_name;
306 	/* Out parameters */
307 	u32 ref_obj_id;
308 	u8 release_regno;
309 	bool r0_rdonly;
310 	u32 ret_btf_id;
311 	u64 r0_size;
312 	u32 subprogno;
313 	struct {
314 		u64 value;
315 		bool found;
316 	} arg_constant;
317 
318 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
319 	 * generally to pass info about user-defined local kptr types to later
320 	 * verification logic
321 	 *   bpf_obj_drop/bpf_percpu_obj_drop
322 	 *     Record the local kptr type to be drop'd
323 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
324 	 *     Record the local kptr type to be refcount_incr'd and use
325 	 *     arg_owning_ref to determine whether refcount_acquire should be
326 	 *     fallible
327 	 */
328 	struct btf *arg_btf;
329 	u32 arg_btf_id;
330 	bool arg_owning_ref;
331 	bool arg_prog;
332 
333 	struct {
334 		struct btf_field *field;
335 	} arg_list_head;
336 	struct {
337 		struct btf_field *field;
338 	} arg_rbtree_root;
339 	struct {
340 		enum bpf_dynptr_type type;
341 		u32 id;
342 		u32 ref_obj_id;
343 	} initialized_dynptr;
344 	struct {
345 		u8 spi;
346 		u8 frameno;
347 	} iter;
348 	struct {
349 		struct bpf_map *ptr;
350 		int uid;
351 	} map;
352 	u64 mem_size;
353 };
354 
355 struct btf *btf_vmlinux;
356 
357 static const char *btf_type_name(const struct btf *btf, u32 id)
358 {
359 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
360 }
361 
362 static DEFINE_MUTEX(bpf_verifier_lock);
363 static DEFINE_MUTEX(bpf_percpu_ma_lock);
364 
365 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
366 {
367 	struct bpf_verifier_env *env = private_data;
368 	va_list args;
369 
370 	if (!bpf_verifier_log_needed(&env->log))
371 		return;
372 
373 	va_start(args, fmt);
374 	bpf_verifier_vlog(&env->log, fmt, args);
375 	va_end(args);
376 }
377 
378 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
379 				   struct bpf_reg_state *reg,
380 				   struct bpf_retval_range range, const char *ctx,
381 				   const char *reg_name)
382 {
383 	bool unknown = true;
384 
385 	verbose(env, "%s the register %s has", ctx, reg_name);
386 	if (reg->smin_value > S64_MIN) {
387 		verbose(env, " smin=%lld", reg->smin_value);
388 		unknown = false;
389 	}
390 	if (reg->smax_value < S64_MAX) {
391 		verbose(env, " smax=%lld", reg->smax_value);
392 		unknown = false;
393 	}
394 	if (unknown)
395 		verbose(env, " unknown scalar value");
396 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
397 }
398 
399 static bool reg_not_null(const struct bpf_reg_state *reg)
400 {
401 	enum bpf_reg_type type;
402 
403 	type = reg->type;
404 	if (type_may_be_null(type))
405 		return false;
406 
407 	type = base_type(type);
408 	return type == PTR_TO_SOCKET ||
409 		type == PTR_TO_TCP_SOCK ||
410 		type == PTR_TO_MAP_VALUE ||
411 		type == PTR_TO_MAP_KEY ||
412 		type == PTR_TO_SOCK_COMMON ||
413 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
414 		(type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) ||
415 		type == CONST_PTR_TO_MAP;
416 }
417 
418 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
419 {
420 	struct btf_record *rec = NULL;
421 	struct btf_struct_meta *meta;
422 
423 	if (reg->type == PTR_TO_MAP_VALUE) {
424 		rec = reg->map_ptr->record;
425 	} else if (type_is_ptr_alloc_obj(reg->type)) {
426 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
427 		if (meta)
428 			rec = meta->record;
429 	}
430 	return rec;
431 }
432 
433 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
434 {
435 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
436 
437 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
438 }
439 
440 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
441 {
442 	struct bpf_func_info *info;
443 
444 	if (!env->prog->aux->func_info)
445 		return "";
446 
447 	info = &env->prog->aux->func_info[subprog];
448 	return btf_type_name(env->prog->aux->btf, info->type_id);
449 }
450 
451 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
452 {
453 	struct bpf_subprog_info *info = subprog_info(env, subprog);
454 
455 	info->is_cb = true;
456 	info->is_async_cb = true;
457 	info->is_exception_cb = true;
458 }
459 
460 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
461 {
462 	return subprog_info(env, subprog)->is_exception_cb;
463 }
464 
465 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
466 {
467 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
468 }
469 
470 static bool type_is_rdonly_mem(u32 type)
471 {
472 	return type & MEM_RDONLY;
473 }
474 
475 static bool is_acquire_function(enum bpf_func_id func_id,
476 				const struct bpf_map *map)
477 {
478 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
479 
480 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
481 	    func_id == BPF_FUNC_sk_lookup_udp ||
482 	    func_id == BPF_FUNC_skc_lookup_tcp ||
483 	    func_id == BPF_FUNC_ringbuf_reserve ||
484 	    func_id == BPF_FUNC_kptr_xchg)
485 		return true;
486 
487 	if (func_id == BPF_FUNC_map_lookup_elem &&
488 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
489 	     map_type == BPF_MAP_TYPE_SOCKHASH))
490 		return true;
491 
492 	return false;
493 }
494 
495 static bool is_ptr_cast_function(enum bpf_func_id func_id)
496 {
497 	return func_id == BPF_FUNC_tcp_sock ||
498 		func_id == BPF_FUNC_sk_fullsock ||
499 		func_id == BPF_FUNC_skc_to_tcp_sock ||
500 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
501 		func_id == BPF_FUNC_skc_to_udp6_sock ||
502 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
503 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
504 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
505 }
506 
507 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
508 {
509 	return func_id == BPF_FUNC_dynptr_data;
510 }
511 
512 static bool is_sync_callback_calling_kfunc(u32 btf_id);
513 static bool is_async_callback_calling_kfunc(u32 btf_id);
514 static bool is_callback_calling_kfunc(u32 btf_id);
515 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
516 
517 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
518 
519 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
520 {
521 	return func_id == BPF_FUNC_for_each_map_elem ||
522 	       func_id == BPF_FUNC_find_vma ||
523 	       func_id == BPF_FUNC_loop ||
524 	       func_id == BPF_FUNC_user_ringbuf_drain;
525 }
526 
527 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
528 {
529 	return func_id == BPF_FUNC_timer_set_callback;
530 }
531 
532 static bool is_callback_calling_function(enum bpf_func_id func_id)
533 {
534 	return is_sync_callback_calling_function(func_id) ||
535 	       is_async_callback_calling_function(func_id);
536 }
537 
538 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
539 {
540 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
541 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
542 }
543 
544 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
545 {
546 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
547 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
548 }
549 
550 static bool is_may_goto_insn(struct bpf_insn *insn)
551 {
552 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
553 }
554 
555 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
556 {
557 	return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
558 }
559 
560 static bool is_storage_get_function(enum bpf_func_id func_id)
561 {
562 	return func_id == BPF_FUNC_sk_storage_get ||
563 	       func_id == BPF_FUNC_inode_storage_get ||
564 	       func_id == BPF_FUNC_task_storage_get ||
565 	       func_id == BPF_FUNC_cgrp_storage_get;
566 }
567 
568 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
569 					const struct bpf_map *map)
570 {
571 	int ref_obj_uses = 0;
572 
573 	if (is_ptr_cast_function(func_id))
574 		ref_obj_uses++;
575 	if (is_acquire_function(func_id, map))
576 		ref_obj_uses++;
577 	if (is_dynptr_ref_function(func_id))
578 		ref_obj_uses++;
579 
580 	return ref_obj_uses > 1;
581 }
582 
583 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
584 {
585 	return BPF_CLASS(insn->code) == BPF_STX &&
586 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
587 	       insn->imm == BPF_CMPXCHG;
588 }
589 
590 static bool is_atomic_load_insn(const struct bpf_insn *insn)
591 {
592 	return BPF_CLASS(insn->code) == BPF_STX &&
593 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
594 	       insn->imm == BPF_LOAD_ACQ;
595 }
596 
597 static int __get_spi(s32 off)
598 {
599 	return (-off - 1) / BPF_REG_SIZE;
600 }
601 
602 static struct bpf_func_state *func(struct bpf_verifier_env *env,
603 				   const struct bpf_reg_state *reg)
604 {
605 	struct bpf_verifier_state *cur = env->cur_state;
606 
607 	return cur->frame[reg->frameno];
608 }
609 
610 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
611 {
612        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
613 
614        /* We need to check that slots between [spi - nr_slots + 1, spi] are
615 	* within [0, allocated_stack).
616 	*
617 	* Please note that the spi grows downwards. For example, a dynptr
618 	* takes the size of two stack slots; the first slot will be at
619 	* spi and the second slot will be at spi - 1.
620 	*/
621        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
622 }
623 
624 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
625 			          const char *obj_kind, int nr_slots)
626 {
627 	int off, spi;
628 
629 	if (!tnum_is_const(reg->var_off)) {
630 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
631 		return -EINVAL;
632 	}
633 
634 	off = reg->off + reg->var_off.value;
635 	if (off % BPF_REG_SIZE) {
636 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
637 		return -EINVAL;
638 	}
639 
640 	spi = __get_spi(off);
641 	if (spi + 1 < nr_slots) {
642 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
643 		return -EINVAL;
644 	}
645 
646 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
647 		return -ERANGE;
648 	return spi;
649 }
650 
651 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
652 {
653 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
654 }
655 
656 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
657 {
658 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
659 }
660 
661 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
662 {
663 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
664 }
665 
666 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
667 {
668 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
669 	case DYNPTR_TYPE_LOCAL:
670 		return BPF_DYNPTR_TYPE_LOCAL;
671 	case DYNPTR_TYPE_RINGBUF:
672 		return BPF_DYNPTR_TYPE_RINGBUF;
673 	case DYNPTR_TYPE_SKB:
674 		return BPF_DYNPTR_TYPE_SKB;
675 	case DYNPTR_TYPE_XDP:
676 		return BPF_DYNPTR_TYPE_XDP;
677 	case DYNPTR_TYPE_SKB_META:
678 		return BPF_DYNPTR_TYPE_SKB_META;
679 	default:
680 		return BPF_DYNPTR_TYPE_INVALID;
681 	}
682 }
683 
684 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
685 {
686 	switch (type) {
687 	case BPF_DYNPTR_TYPE_LOCAL:
688 		return DYNPTR_TYPE_LOCAL;
689 	case BPF_DYNPTR_TYPE_RINGBUF:
690 		return DYNPTR_TYPE_RINGBUF;
691 	case BPF_DYNPTR_TYPE_SKB:
692 		return DYNPTR_TYPE_SKB;
693 	case BPF_DYNPTR_TYPE_XDP:
694 		return DYNPTR_TYPE_XDP;
695 	case BPF_DYNPTR_TYPE_SKB_META:
696 		return DYNPTR_TYPE_SKB_META;
697 	default:
698 		return 0;
699 	}
700 }
701 
702 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
703 {
704 	return type == BPF_DYNPTR_TYPE_RINGBUF;
705 }
706 
707 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
708 			      enum bpf_dynptr_type type,
709 			      bool first_slot, int dynptr_id);
710 
711 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
712 				struct bpf_reg_state *reg);
713 
714 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
715 				   struct bpf_reg_state *sreg1,
716 				   struct bpf_reg_state *sreg2,
717 				   enum bpf_dynptr_type type)
718 {
719 	int id = ++env->id_gen;
720 
721 	__mark_dynptr_reg(sreg1, type, true, id);
722 	__mark_dynptr_reg(sreg2, type, false, id);
723 }
724 
725 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
726 			       struct bpf_reg_state *reg,
727 			       enum bpf_dynptr_type type)
728 {
729 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
730 }
731 
732 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
733 				        struct bpf_func_state *state, int spi);
734 
735 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
736 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
737 {
738 	struct bpf_func_state *state = func(env, reg);
739 	enum bpf_dynptr_type type;
740 	int spi, i, err;
741 
742 	spi = dynptr_get_spi(env, reg);
743 	if (spi < 0)
744 		return spi;
745 
746 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
747 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
748 	 * to ensure that for the following example:
749 	 *	[d1][d1][d2][d2]
750 	 * spi    3   2   1   0
751 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
752 	 * case they do belong to same dynptr, second call won't see slot_type
753 	 * as STACK_DYNPTR and will simply skip destruction.
754 	 */
755 	err = destroy_if_dynptr_stack_slot(env, state, spi);
756 	if (err)
757 		return err;
758 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
759 	if (err)
760 		return err;
761 
762 	for (i = 0; i < BPF_REG_SIZE; i++) {
763 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
764 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
765 	}
766 
767 	type = arg_to_dynptr_type(arg_type);
768 	if (type == BPF_DYNPTR_TYPE_INVALID)
769 		return -EINVAL;
770 
771 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
772 			       &state->stack[spi - 1].spilled_ptr, type);
773 
774 	if (dynptr_type_refcounted(type)) {
775 		/* The id is used to track proper releasing */
776 		int id;
777 
778 		if (clone_ref_obj_id)
779 			id = clone_ref_obj_id;
780 		else
781 			id = acquire_reference(env, insn_idx);
782 
783 		if (id < 0)
784 			return id;
785 
786 		state->stack[spi].spilled_ptr.ref_obj_id = id;
787 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
788 	}
789 
790 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
791 
792 	return 0;
793 }
794 
795 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
796 {
797 	int i;
798 
799 	for (i = 0; i < BPF_REG_SIZE; i++) {
800 		state->stack[spi].slot_type[i] = STACK_INVALID;
801 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
802 	}
803 
804 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
805 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
806 
807 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
808 }
809 
810 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
811 {
812 	struct bpf_func_state *state = func(env, reg);
813 	int spi, ref_obj_id, i;
814 
815 	spi = dynptr_get_spi(env, reg);
816 	if (spi < 0)
817 		return spi;
818 
819 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
820 		invalidate_dynptr(env, state, spi);
821 		return 0;
822 	}
823 
824 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
825 
826 	/* If the dynptr has a ref_obj_id, then we need to invalidate
827 	 * two things:
828 	 *
829 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
830 	 * 2) Any slices derived from this dynptr.
831 	 */
832 
833 	/* Invalidate any slices associated with this dynptr */
834 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
835 
836 	/* Invalidate any dynptr clones */
837 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
838 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
839 			continue;
840 
841 		/* it should always be the case that if the ref obj id
842 		 * matches then the stack slot also belongs to a
843 		 * dynptr
844 		 */
845 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
846 			verifier_bug(env, "misconfigured ref_obj_id");
847 			return -EFAULT;
848 		}
849 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
850 			invalidate_dynptr(env, state, i);
851 	}
852 
853 	return 0;
854 }
855 
856 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
857 			       struct bpf_reg_state *reg);
858 
859 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
860 {
861 	if (!env->allow_ptr_leaks)
862 		__mark_reg_not_init(env, reg);
863 	else
864 		__mark_reg_unknown(env, reg);
865 }
866 
867 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
868 				        struct bpf_func_state *state, int spi)
869 {
870 	struct bpf_func_state *fstate;
871 	struct bpf_reg_state *dreg;
872 	int i, dynptr_id;
873 
874 	/* We always ensure that STACK_DYNPTR is never set partially,
875 	 * hence just checking for slot_type[0] is enough. This is
876 	 * different for STACK_SPILL, where it may be only set for
877 	 * 1 byte, so code has to use is_spilled_reg.
878 	 */
879 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
880 		return 0;
881 
882 	/* Reposition spi to first slot */
883 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
884 		spi = spi + 1;
885 
886 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
887 		verbose(env, "cannot overwrite referenced dynptr\n");
888 		return -EINVAL;
889 	}
890 
891 	mark_stack_slot_scratched(env, spi);
892 	mark_stack_slot_scratched(env, spi - 1);
893 
894 	/* Writing partially to one dynptr stack slot destroys both. */
895 	for (i = 0; i < BPF_REG_SIZE; i++) {
896 		state->stack[spi].slot_type[i] = STACK_INVALID;
897 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
898 	}
899 
900 	dynptr_id = state->stack[spi].spilled_ptr.id;
901 	/* Invalidate any slices associated with this dynptr */
902 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
903 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
904 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
905 			continue;
906 		if (dreg->dynptr_id == dynptr_id)
907 			mark_reg_invalid(env, dreg);
908 	}));
909 
910 	/* Do not release reference state, we are destroying dynptr on stack,
911 	 * not using some helper to release it. Just reset register.
912 	 */
913 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
914 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
915 
916 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
917 
918 	return 0;
919 }
920 
921 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
922 {
923 	int spi;
924 
925 	if (reg->type == CONST_PTR_TO_DYNPTR)
926 		return false;
927 
928 	spi = dynptr_get_spi(env, reg);
929 
930 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
931 	 * error because this just means the stack state hasn't been updated yet.
932 	 * We will do check_mem_access to check and update stack bounds later.
933 	 */
934 	if (spi < 0 && spi != -ERANGE)
935 		return false;
936 
937 	/* We don't need to check if the stack slots are marked by previous
938 	 * dynptr initializations because we allow overwriting existing unreferenced
939 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
940 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
941 	 * touching are completely destructed before we reinitialize them for a new
942 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
943 	 * instead of delaying it until the end where the user will get "Unreleased
944 	 * reference" error.
945 	 */
946 	return true;
947 }
948 
949 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
950 {
951 	struct bpf_func_state *state = func(env, reg);
952 	int i, spi;
953 
954 	/* This already represents first slot of initialized bpf_dynptr.
955 	 *
956 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
957 	 * check_func_arg_reg_off's logic, so we don't need to check its
958 	 * offset and alignment.
959 	 */
960 	if (reg->type == CONST_PTR_TO_DYNPTR)
961 		return true;
962 
963 	spi = dynptr_get_spi(env, reg);
964 	if (spi < 0)
965 		return false;
966 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
967 		return false;
968 
969 	for (i = 0; i < BPF_REG_SIZE; i++) {
970 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
971 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
972 			return false;
973 	}
974 
975 	return true;
976 }
977 
978 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
979 				    enum bpf_arg_type arg_type)
980 {
981 	struct bpf_func_state *state = func(env, reg);
982 	enum bpf_dynptr_type dynptr_type;
983 	int spi;
984 
985 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
986 	if (arg_type == ARG_PTR_TO_DYNPTR)
987 		return true;
988 
989 	dynptr_type = arg_to_dynptr_type(arg_type);
990 	if (reg->type == CONST_PTR_TO_DYNPTR) {
991 		return reg->dynptr.type == dynptr_type;
992 	} else {
993 		spi = dynptr_get_spi(env, reg);
994 		if (spi < 0)
995 			return false;
996 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
997 	}
998 }
999 
1000 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1001 
1002 static bool in_rcu_cs(struct bpf_verifier_env *env);
1003 
1004 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1005 
1006 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1007 				 struct bpf_kfunc_call_arg_meta *meta,
1008 				 struct bpf_reg_state *reg, int insn_idx,
1009 				 struct btf *btf, u32 btf_id, int nr_slots)
1010 {
1011 	struct bpf_func_state *state = func(env, reg);
1012 	int spi, i, j, id;
1013 
1014 	spi = iter_get_spi(env, reg, nr_slots);
1015 	if (spi < 0)
1016 		return spi;
1017 
1018 	id = acquire_reference(env, insn_idx);
1019 	if (id < 0)
1020 		return id;
1021 
1022 	for (i = 0; i < nr_slots; i++) {
1023 		struct bpf_stack_state *slot = &state->stack[spi - i];
1024 		struct bpf_reg_state *st = &slot->spilled_ptr;
1025 
1026 		__mark_reg_known_zero(st);
1027 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1028 		if (is_kfunc_rcu_protected(meta)) {
1029 			if (in_rcu_cs(env))
1030 				st->type |= MEM_RCU;
1031 			else
1032 				st->type |= PTR_UNTRUSTED;
1033 		}
1034 		st->ref_obj_id = i == 0 ? id : 0;
1035 		st->iter.btf = btf;
1036 		st->iter.btf_id = btf_id;
1037 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1038 		st->iter.depth = 0;
1039 
1040 		for (j = 0; j < BPF_REG_SIZE; j++)
1041 			slot->slot_type[j] = STACK_ITER;
1042 
1043 		bpf_mark_stack_write(env, state->frameno, BIT(spi - i));
1044 		mark_stack_slot_scratched(env, spi - i);
1045 	}
1046 
1047 	return 0;
1048 }
1049 
1050 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1051 				   struct bpf_reg_state *reg, int nr_slots)
1052 {
1053 	struct bpf_func_state *state = func(env, reg);
1054 	int spi, i, j;
1055 
1056 	spi = iter_get_spi(env, reg, nr_slots);
1057 	if (spi < 0)
1058 		return spi;
1059 
1060 	for (i = 0; i < nr_slots; i++) {
1061 		struct bpf_stack_state *slot = &state->stack[spi - i];
1062 		struct bpf_reg_state *st = &slot->spilled_ptr;
1063 
1064 		if (i == 0)
1065 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1066 
1067 		__mark_reg_not_init(env, st);
1068 
1069 		for (j = 0; j < BPF_REG_SIZE; j++)
1070 			slot->slot_type[j] = STACK_INVALID;
1071 
1072 		bpf_mark_stack_write(env, state->frameno, BIT(spi - i));
1073 		mark_stack_slot_scratched(env, spi - i);
1074 	}
1075 
1076 	return 0;
1077 }
1078 
1079 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1080 				     struct bpf_reg_state *reg, int nr_slots)
1081 {
1082 	struct bpf_func_state *state = func(env, reg);
1083 	int spi, i, j;
1084 
1085 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1086 	 * will do check_mem_access to check and update stack bounds later, so
1087 	 * return true for that case.
1088 	 */
1089 	spi = iter_get_spi(env, reg, nr_slots);
1090 	if (spi == -ERANGE)
1091 		return true;
1092 	if (spi < 0)
1093 		return false;
1094 
1095 	for (i = 0; i < nr_slots; i++) {
1096 		struct bpf_stack_state *slot = &state->stack[spi - i];
1097 
1098 		for (j = 0; j < BPF_REG_SIZE; j++)
1099 			if (slot->slot_type[j] == STACK_ITER)
1100 				return false;
1101 	}
1102 
1103 	return true;
1104 }
1105 
1106 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1107 				   struct btf *btf, u32 btf_id, int nr_slots)
1108 {
1109 	struct bpf_func_state *state = func(env, reg);
1110 	int spi, i, j;
1111 
1112 	spi = iter_get_spi(env, reg, nr_slots);
1113 	if (spi < 0)
1114 		return -EINVAL;
1115 
1116 	for (i = 0; i < nr_slots; i++) {
1117 		struct bpf_stack_state *slot = &state->stack[spi - i];
1118 		struct bpf_reg_state *st = &slot->spilled_ptr;
1119 
1120 		if (st->type & PTR_UNTRUSTED)
1121 			return -EPROTO;
1122 		/* only main (first) slot has ref_obj_id set */
1123 		if (i == 0 && !st->ref_obj_id)
1124 			return -EINVAL;
1125 		if (i != 0 && st->ref_obj_id)
1126 			return -EINVAL;
1127 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1128 			return -EINVAL;
1129 
1130 		for (j = 0; j < BPF_REG_SIZE; j++)
1131 			if (slot->slot_type[j] != STACK_ITER)
1132 				return -EINVAL;
1133 	}
1134 
1135 	return 0;
1136 }
1137 
1138 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1139 static int release_irq_state(struct bpf_verifier_state *state, int id);
1140 
1141 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1142 				     struct bpf_kfunc_call_arg_meta *meta,
1143 				     struct bpf_reg_state *reg, int insn_idx,
1144 				     int kfunc_class)
1145 {
1146 	struct bpf_func_state *state = func(env, reg);
1147 	struct bpf_stack_state *slot;
1148 	struct bpf_reg_state *st;
1149 	int spi, i, id;
1150 
1151 	spi = irq_flag_get_spi(env, reg);
1152 	if (spi < 0)
1153 		return spi;
1154 
1155 	id = acquire_irq_state(env, insn_idx);
1156 	if (id < 0)
1157 		return id;
1158 
1159 	slot = &state->stack[spi];
1160 	st = &slot->spilled_ptr;
1161 
1162 	bpf_mark_stack_write(env, reg->frameno, BIT(spi));
1163 	__mark_reg_known_zero(st);
1164 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1165 	st->ref_obj_id = id;
1166 	st->irq.kfunc_class = kfunc_class;
1167 
1168 	for (i = 0; i < BPF_REG_SIZE; i++)
1169 		slot->slot_type[i] = STACK_IRQ_FLAG;
1170 
1171 	mark_stack_slot_scratched(env, spi);
1172 	return 0;
1173 }
1174 
1175 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1176 				      int kfunc_class)
1177 {
1178 	struct bpf_func_state *state = func(env, reg);
1179 	struct bpf_stack_state *slot;
1180 	struct bpf_reg_state *st;
1181 	int spi, i, err;
1182 
1183 	spi = irq_flag_get_spi(env, reg);
1184 	if (spi < 0)
1185 		return spi;
1186 
1187 	slot = &state->stack[spi];
1188 	st = &slot->spilled_ptr;
1189 
1190 	if (st->irq.kfunc_class != kfunc_class) {
1191 		const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1192 		const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1193 
1194 		verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1195 			flag_kfunc, used_kfunc);
1196 		return -EINVAL;
1197 	}
1198 
1199 	err = release_irq_state(env->cur_state, st->ref_obj_id);
1200 	WARN_ON_ONCE(err && err != -EACCES);
1201 	if (err) {
1202 		int insn_idx = 0;
1203 
1204 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1205 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1206 				insn_idx = env->cur_state->refs[i].insn_idx;
1207 				break;
1208 			}
1209 		}
1210 
1211 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1212 			env->cur_state->active_irq_id, insn_idx);
1213 		return err;
1214 	}
1215 
1216 	__mark_reg_not_init(env, st);
1217 
1218 	bpf_mark_stack_write(env, reg->frameno, BIT(spi));
1219 
1220 	for (i = 0; i < BPF_REG_SIZE; i++)
1221 		slot->slot_type[i] = STACK_INVALID;
1222 
1223 	mark_stack_slot_scratched(env, spi);
1224 	return 0;
1225 }
1226 
1227 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1228 {
1229 	struct bpf_func_state *state = func(env, reg);
1230 	struct bpf_stack_state *slot;
1231 	int spi, i;
1232 
1233 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1234 	 * will do check_mem_access to check and update stack bounds later, so
1235 	 * return true for that case.
1236 	 */
1237 	spi = irq_flag_get_spi(env, reg);
1238 	if (spi == -ERANGE)
1239 		return true;
1240 	if (spi < 0)
1241 		return false;
1242 
1243 	slot = &state->stack[spi];
1244 
1245 	for (i = 0; i < BPF_REG_SIZE; i++)
1246 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1247 			return false;
1248 	return true;
1249 }
1250 
1251 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1252 {
1253 	struct bpf_func_state *state = func(env, reg);
1254 	struct bpf_stack_state *slot;
1255 	struct bpf_reg_state *st;
1256 	int spi, i;
1257 
1258 	spi = irq_flag_get_spi(env, reg);
1259 	if (spi < 0)
1260 		return -EINVAL;
1261 
1262 	slot = &state->stack[spi];
1263 	st = &slot->spilled_ptr;
1264 
1265 	if (!st->ref_obj_id)
1266 		return -EINVAL;
1267 
1268 	for (i = 0; i < BPF_REG_SIZE; i++)
1269 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1270 			return -EINVAL;
1271 	return 0;
1272 }
1273 
1274 /* Check if given stack slot is "special":
1275  *   - spilled register state (STACK_SPILL);
1276  *   - dynptr state (STACK_DYNPTR);
1277  *   - iter state (STACK_ITER).
1278  *   - irq flag state (STACK_IRQ_FLAG)
1279  */
1280 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1281 {
1282 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1283 
1284 	switch (type) {
1285 	case STACK_SPILL:
1286 	case STACK_DYNPTR:
1287 	case STACK_ITER:
1288 	case STACK_IRQ_FLAG:
1289 		return true;
1290 	case STACK_INVALID:
1291 	case STACK_MISC:
1292 	case STACK_ZERO:
1293 		return false;
1294 	default:
1295 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1296 		return true;
1297 	}
1298 }
1299 
1300 /* The reg state of a pointer or a bounded scalar was saved when
1301  * it was spilled to the stack.
1302  */
1303 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1304 {
1305 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1306 }
1307 
1308 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1309 {
1310 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1311 	       stack->spilled_ptr.type == SCALAR_VALUE;
1312 }
1313 
1314 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1315 {
1316 	return stack->slot_type[0] == STACK_SPILL &&
1317 	       stack->spilled_ptr.type == SCALAR_VALUE;
1318 }
1319 
1320 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1321  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1322  * more precise STACK_ZERO.
1323  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1324  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1325  * unnecessary as both are considered equivalent when loading data and pruning,
1326  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1327  * slots.
1328  */
1329 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1330 {
1331 	if (*stype == STACK_ZERO)
1332 		return;
1333 	if (*stype == STACK_INVALID)
1334 		return;
1335 	*stype = STACK_MISC;
1336 }
1337 
1338 static void scrub_spilled_slot(u8 *stype)
1339 {
1340 	if (*stype != STACK_INVALID)
1341 		*stype = STACK_MISC;
1342 }
1343 
1344 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1345  * small to hold src. This is different from krealloc since we don't want to preserve
1346  * the contents of dst.
1347  *
1348  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1349  * not be allocated.
1350  */
1351 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1352 {
1353 	size_t alloc_bytes;
1354 	void *orig = dst;
1355 	size_t bytes;
1356 
1357 	if (ZERO_OR_NULL_PTR(src))
1358 		goto out;
1359 
1360 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1361 		return NULL;
1362 
1363 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1364 	dst = krealloc(orig, alloc_bytes, flags);
1365 	if (!dst) {
1366 		kfree(orig);
1367 		return NULL;
1368 	}
1369 
1370 	memcpy(dst, src, bytes);
1371 out:
1372 	return dst ? dst : ZERO_SIZE_PTR;
1373 }
1374 
1375 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1376  * small to hold new_n items. new items are zeroed out if the array grows.
1377  *
1378  * Contrary to krealloc_array, does not free arr if new_n is zero.
1379  */
1380 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1381 {
1382 	size_t alloc_size;
1383 	void *new_arr;
1384 
1385 	if (!new_n || old_n == new_n)
1386 		goto out;
1387 
1388 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1389 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1390 	if (!new_arr) {
1391 		kfree(arr);
1392 		return NULL;
1393 	}
1394 	arr = new_arr;
1395 
1396 	if (new_n > old_n)
1397 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1398 
1399 out:
1400 	return arr ? arr : ZERO_SIZE_PTR;
1401 }
1402 
1403 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1404 {
1405 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1406 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1407 	if (!dst->refs)
1408 		return -ENOMEM;
1409 
1410 	dst->acquired_refs = src->acquired_refs;
1411 	dst->active_locks = src->active_locks;
1412 	dst->active_preempt_locks = src->active_preempt_locks;
1413 	dst->active_rcu_lock = src->active_rcu_lock;
1414 	dst->active_irq_id = src->active_irq_id;
1415 	dst->active_lock_id = src->active_lock_id;
1416 	dst->active_lock_ptr = src->active_lock_ptr;
1417 	return 0;
1418 }
1419 
1420 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1421 {
1422 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1423 
1424 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1425 				GFP_KERNEL_ACCOUNT);
1426 	if (!dst->stack)
1427 		return -ENOMEM;
1428 
1429 	dst->allocated_stack = src->allocated_stack;
1430 	return 0;
1431 }
1432 
1433 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1434 {
1435 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1436 				    sizeof(struct bpf_reference_state));
1437 	if (!state->refs)
1438 		return -ENOMEM;
1439 
1440 	state->acquired_refs = n;
1441 	return 0;
1442 }
1443 
1444 /* Possibly update state->allocated_stack to be at least size bytes. Also
1445  * possibly update the function's high-water mark in its bpf_subprog_info.
1446  */
1447 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1448 {
1449 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1450 
1451 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1452 	size = round_up(size, BPF_REG_SIZE);
1453 	n = size / BPF_REG_SIZE;
1454 
1455 	if (old_n >= n)
1456 		return 0;
1457 
1458 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1459 	if (!state->stack)
1460 		return -ENOMEM;
1461 
1462 	state->allocated_stack = size;
1463 
1464 	/* update known max for given subprogram */
1465 	if (env->subprog_info[state->subprogno].stack_depth < size)
1466 		env->subprog_info[state->subprogno].stack_depth = size;
1467 
1468 	return 0;
1469 }
1470 
1471 /* Acquire a pointer id from the env and update the state->refs to include
1472  * this new pointer reference.
1473  * On success, returns a valid pointer id to associate with the register
1474  * On failure, returns a negative errno.
1475  */
1476 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1477 {
1478 	struct bpf_verifier_state *state = env->cur_state;
1479 	int new_ofs = state->acquired_refs;
1480 	int err;
1481 
1482 	err = resize_reference_state(state, state->acquired_refs + 1);
1483 	if (err)
1484 		return NULL;
1485 	state->refs[new_ofs].insn_idx = insn_idx;
1486 
1487 	return &state->refs[new_ofs];
1488 }
1489 
1490 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx)
1491 {
1492 	struct bpf_reference_state *s;
1493 
1494 	s = acquire_reference_state(env, insn_idx);
1495 	if (!s)
1496 		return -ENOMEM;
1497 	s->type = REF_TYPE_PTR;
1498 	s->id = ++env->id_gen;
1499 	return s->id;
1500 }
1501 
1502 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1503 			      int id, void *ptr)
1504 {
1505 	struct bpf_verifier_state *state = env->cur_state;
1506 	struct bpf_reference_state *s;
1507 
1508 	s = acquire_reference_state(env, insn_idx);
1509 	if (!s)
1510 		return -ENOMEM;
1511 	s->type = type;
1512 	s->id = id;
1513 	s->ptr = ptr;
1514 
1515 	state->active_locks++;
1516 	state->active_lock_id = id;
1517 	state->active_lock_ptr = ptr;
1518 	return 0;
1519 }
1520 
1521 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1522 {
1523 	struct bpf_verifier_state *state = env->cur_state;
1524 	struct bpf_reference_state *s;
1525 
1526 	s = acquire_reference_state(env, insn_idx);
1527 	if (!s)
1528 		return -ENOMEM;
1529 	s->type = REF_TYPE_IRQ;
1530 	s->id = ++env->id_gen;
1531 
1532 	state->active_irq_id = s->id;
1533 	return s->id;
1534 }
1535 
1536 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1537 {
1538 	int last_idx;
1539 	size_t rem;
1540 
1541 	/* IRQ state requires the relative ordering of elements remaining the
1542 	 * same, since it relies on the refs array to behave as a stack, so that
1543 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1544 	 * the array instead of swapping the final element into the deleted idx.
1545 	 */
1546 	last_idx = state->acquired_refs - 1;
1547 	rem = state->acquired_refs - idx - 1;
1548 	if (last_idx && idx != last_idx)
1549 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1550 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1551 	state->acquired_refs--;
1552 	return;
1553 }
1554 
1555 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id)
1556 {
1557 	int i;
1558 
1559 	for (i = 0; i < state->acquired_refs; i++)
1560 		if (state->refs[i].id == ptr_id)
1561 			return true;
1562 
1563 	return false;
1564 }
1565 
1566 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
1567 {
1568 	void *prev_ptr = NULL;
1569 	u32 prev_id = 0;
1570 	int i;
1571 
1572 	for (i = 0; i < state->acquired_refs; i++) {
1573 		if (state->refs[i].type == type && state->refs[i].id == id &&
1574 		    state->refs[i].ptr == ptr) {
1575 			release_reference_state(state, i);
1576 			state->active_locks--;
1577 			/* Reassign active lock (id, ptr). */
1578 			state->active_lock_id = prev_id;
1579 			state->active_lock_ptr = prev_ptr;
1580 			return 0;
1581 		}
1582 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1583 			prev_id = state->refs[i].id;
1584 			prev_ptr = state->refs[i].ptr;
1585 		}
1586 	}
1587 	return -EINVAL;
1588 }
1589 
1590 static int release_irq_state(struct bpf_verifier_state *state, int id)
1591 {
1592 	u32 prev_id = 0;
1593 	int i;
1594 
1595 	if (id != state->active_irq_id)
1596 		return -EACCES;
1597 
1598 	for (i = 0; i < state->acquired_refs; i++) {
1599 		if (state->refs[i].type != REF_TYPE_IRQ)
1600 			continue;
1601 		if (state->refs[i].id == id) {
1602 			release_reference_state(state, i);
1603 			state->active_irq_id = prev_id;
1604 			return 0;
1605 		} else {
1606 			prev_id = state->refs[i].id;
1607 		}
1608 	}
1609 	return -EINVAL;
1610 }
1611 
1612 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1613 						   int id, void *ptr)
1614 {
1615 	int i;
1616 
1617 	for (i = 0; i < state->acquired_refs; i++) {
1618 		struct bpf_reference_state *s = &state->refs[i];
1619 
1620 		if (!(s->type & type))
1621 			continue;
1622 
1623 		if (s->id == id && s->ptr == ptr)
1624 			return s;
1625 	}
1626 	return NULL;
1627 }
1628 
1629 static void update_peak_states(struct bpf_verifier_env *env)
1630 {
1631 	u32 cur_states;
1632 
1633 	cur_states = env->explored_states_size + env->free_list_size + env->num_backedges;
1634 	env->peak_states = max(env->peak_states, cur_states);
1635 }
1636 
1637 static void free_func_state(struct bpf_func_state *state)
1638 {
1639 	if (!state)
1640 		return;
1641 	kfree(state->stack);
1642 	kfree(state);
1643 }
1644 
1645 static void clear_jmp_history(struct bpf_verifier_state *state)
1646 {
1647 	kfree(state->jmp_history);
1648 	state->jmp_history = NULL;
1649 	state->jmp_history_cnt = 0;
1650 }
1651 
1652 static void free_verifier_state(struct bpf_verifier_state *state,
1653 				bool free_self)
1654 {
1655 	int i;
1656 
1657 	for (i = 0; i <= state->curframe; i++) {
1658 		free_func_state(state->frame[i]);
1659 		state->frame[i] = NULL;
1660 	}
1661 	kfree(state->refs);
1662 	clear_jmp_history(state);
1663 	if (free_self)
1664 		kfree(state);
1665 }
1666 
1667 /* struct bpf_verifier_state->parent refers to states
1668  * that are in either of env->{expored_states,free_list}.
1669  * In both cases the state is contained in struct bpf_verifier_state_list.
1670  */
1671 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st)
1672 {
1673 	if (st->parent)
1674 		return container_of(st->parent, struct bpf_verifier_state_list, state);
1675 	return NULL;
1676 }
1677 
1678 static bool incomplete_read_marks(struct bpf_verifier_env *env,
1679 				  struct bpf_verifier_state *st);
1680 
1681 /* A state can be freed if it is no longer referenced:
1682  * - is in the env->free_list;
1683  * - has no children states;
1684  */
1685 static void maybe_free_verifier_state(struct bpf_verifier_env *env,
1686 				      struct bpf_verifier_state_list *sl)
1687 {
1688 	if (!sl->in_free_list
1689 	    || sl->state.branches != 0
1690 	    || incomplete_read_marks(env, &sl->state))
1691 		return;
1692 	list_del(&sl->node);
1693 	free_verifier_state(&sl->state, false);
1694 	kfree(sl);
1695 	env->free_list_size--;
1696 }
1697 
1698 /* copy verifier state from src to dst growing dst stack space
1699  * when necessary to accommodate larger src stack
1700  */
1701 static int copy_func_state(struct bpf_func_state *dst,
1702 			   const struct bpf_func_state *src)
1703 {
1704 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1705 	return copy_stack_state(dst, src);
1706 }
1707 
1708 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1709 			       const struct bpf_verifier_state *src)
1710 {
1711 	struct bpf_func_state *dst;
1712 	int i, err;
1713 
1714 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1715 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1716 					  GFP_KERNEL_ACCOUNT);
1717 	if (!dst_state->jmp_history)
1718 		return -ENOMEM;
1719 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1720 
1721 	/* if dst has more stack frames then src frame, free them, this is also
1722 	 * necessary in case of exceptional exits using bpf_throw.
1723 	 */
1724 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1725 		free_func_state(dst_state->frame[i]);
1726 		dst_state->frame[i] = NULL;
1727 	}
1728 	err = copy_reference_state(dst_state, src);
1729 	if (err)
1730 		return err;
1731 	dst_state->speculative = src->speculative;
1732 	dst_state->in_sleepable = src->in_sleepable;
1733 	dst_state->cleaned = src->cleaned;
1734 	dst_state->curframe = src->curframe;
1735 	dst_state->branches = src->branches;
1736 	dst_state->parent = src->parent;
1737 	dst_state->first_insn_idx = src->first_insn_idx;
1738 	dst_state->last_insn_idx = src->last_insn_idx;
1739 	dst_state->dfs_depth = src->dfs_depth;
1740 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1741 	dst_state->may_goto_depth = src->may_goto_depth;
1742 	dst_state->equal_state = src->equal_state;
1743 	for (i = 0; i <= src->curframe; i++) {
1744 		dst = dst_state->frame[i];
1745 		if (!dst) {
1746 			dst = kzalloc(sizeof(*dst), GFP_KERNEL_ACCOUNT);
1747 			if (!dst)
1748 				return -ENOMEM;
1749 			dst_state->frame[i] = dst;
1750 		}
1751 		err = copy_func_state(dst, src->frame[i]);
1752 		if (err)
1753 			return err;
1754 	}
1755 	return 0;
1756 }
1757 
1758 static u32 state_htab_size(struct bpf_verifier_env *env)
1759 {
1760 	return env->prog->len;
1761 }
1762 
1763 static struct list_head *explored_state(struct bpf_verifier_env *env, int idx)
1764 {
1765 	struct bpf_verifier_state *cur = env->cur_state;
1766 	struct bpf_func_state *state = cur->frame[cur->curframe];
1767 
1768 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1769 }
1770 
1771 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1772 {
1773 	int fr;
1774 
1775 	if (a->curframe != b->curframe)
1776 		return false;
1777 
1778 	for (fr = a->curframe; fr >= 0; fr--)
1779 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1780 			return false;
1781 
1782 	return true;
1783 }
1784 
1785 /* Return IP for a given frame in a call stack */
1786 static u32 frame_insn_idx(struct bpf_verifier_state *st, u32 frame)
1787 {
1788 	return frame == st->curframe
1789 	       ? st->insn_idx
1790 	       : st->frame[frame + 1]->callsite;
1791 }
1792 
1793 /* For state @st look for a topmost frame with frame_insn_idx() in some SCC,
1794  * if such frame exists form a corresponding @callchain as an array of
1795  * call sites leading to this frame and SCC id.
1796  * E.g.:
1797  *
1798  *    void foo()  { A: loop {... SCC#1 ...}; }
1799  *    void bar()  { B: loop { C: foo(); ... SCC#2 ... }
1800  *                  D: loop { E: foo(); ... SCC#3 ... } }
1801  *    void main() { F: bar(); }
1802  *
1803  * @callchain at (A) would be either (F,SCC#2) or (F,SCC#3) depending
1804  * on @st frame call sites being (F,C,A) or (F,E,A).
1805  */
1806 static bool compute_scc_callchain(struct bpf_verifier_env *env,
1807 				  struct bpf_verifier_state *st,
1808 				  struct bpf_scc_callchain *callchain)
1809 {
1810 	u32 i, scc, insn_idx;
1811 
1812 	memset(callchain, 0, sizeof(*callchain));
1813 	for (i = 0; i <= st->curframe; i++) {
1814 		insn_idx = frame_insn_idx(st, i);
1815 		scc = env->insn_aux_data[insn_idx].scc;
1816 		if (scc) {
1817 			callchain->scc = scc;
1818 			break;
1819 		} else if (i < st->curframe) {
1820 			callchain->callsites[i] = insn_idx;
1821 		} else {
1822 			return false;
1823 		}
1824 	}
1825 	return true;
1826 }
1827 
1828 /* Check if bpf_scc_visit instance for @callchain exists. */
1829 static struct bpf_scc_visit *scc_visit_lookup(struct bpf_verifier_env *env,
1830 					      struct bpf_scc_callchain *callchain)
1831 {
1832 	struct bpf_scc_info *info = env->scc_info[callchain->scc];
1833 	struct bpf_scc_visit *visits = info->visits;
1834 	u32 i;
1835 
1836 	if (!info)
1837 		return NULL;
1838 	for (i = 0; i < info->num_visits; i++)
1839 		if (memcmp(callchain, &visits[i].callchain, sizeof(*callchain)) == 0)
1840 			return &visits[i];
1841 	return NULL;
1842 }
1843 
1844 /* Allocate a new bpf_scc_visit instance corresponding to @callchain.
1845  * Allocated instances are alive for a duration of the do_check_common()
1846  * call and are freed by free_states().
1847  */
1848 static struct bpf_scc_visit *scc_visit_alloc(struct bpf_verifier_env *env,
1849 					     struct bpf_scc_callchain *callchain)
1850 {
1851 	struct bpf_scc_visit *visit;
1852 	struct bpf_scc_info *info;
1853 	u32 scc, num_visits;
1854 	u64 new_sz;
1855 
1856 	scc = callchain->scc;
1857 	info = env->scc_info[scc];
1858 	num_visits = info ? info->num_visits : 0;
1859 	new_sz = sizeof(*info) + sizeof(struct bpf_scc_visit) * (num_visits + 1);
1860 	info = kvrealloc(env->scc_info[scc], new_sz, GFP_KERNEL_ACCOUNT);
1861 	if (!info)
1862 		return NULL;
1863 	env->scc_info[scc] = info;
1864 	info->num_visits = num_visits + 1;
1865 	visit = &info->visits[num_visits];
1866 	memset(visit, 0, sizeof(*visit));
1867 	memcpy(&visit->callchain, callchain, sizeof(*callchain));
1868 	return visit;
1869 }
1870 
1871 /* Form a string '(callsite#1,callsite#2,...,scc)' in env->tmp_str_buf */
1872 static char *format_callchain(struct bpf_verifier_env *env, struct bpf_scc_callchain *callchain)
1873 {
1874 	char *buf = env->tmp_str_buf;
1875 	int i, delta = 0;
1876 
1877 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "(");
1878 	for (i = 0; i < ARRAY_SIZE(callchain->callsites); i++) {
1879 		if (!callchain->callsites[i])
1880 			break;
1881 		delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u,",
1882 				  callchain->callsites[i]);
1883 	}
1884 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u)", callchain->scc);
1885 	return env->tmp_str_buf;
1886 }
1887 
1888 /* If callchain for @st exists (@st is in some SCC), ensure that
1889  * bpf_scc_visit instance for this callchain exists.
1890  * If instance does not exist or is empty, assign visit->entry_state to @st.
1891  */
1892 static int maybe_enter_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1893 {
1894 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1895 	struct bpf_scc_visit *visit;
1896 
1897 	if (!compute_scc_callchain(env, st, callchain))
1898 		return 0;
1899 	visit = scc_visit_lookup(env, callchain);
1900 	visit = visit ?: scc_visit_alloc(env, callchain);
1901 	if (!visit)
1902 		return -ENOMEM;
1903 	if (!visit->entry_state) {
1904 		visit->entry_state = st;
1905 		if (env->log.level & BPF_LOG_LEVEL2)
1906 			verbose(env, "SCC enter %s\n", format_callchain(env, callchain));
1907 	}
1908 	return 0;
1909 }
1910 
1911 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit);
1912 
1913 /* If callchain for @st exists (@st is in some SCC), make it empty:
1914  * - set visit->entry_state to NULL;
1915  * - flush accumulated backedges.
1916  */
1917 static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1918 {
1919 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1920 	struct bpf_scc_visit *visit;
1921 
1922 	if (!compute_scc_callchain(env, st, callchain))
1923 		return 0;
1924 	visit = scc_visit_lookup(env, callchain);
1925 	if (!visit) {
1926 		/*
1927 		 * If path traversal stops inside an SCC, corresponding bpf_scc_visit
1928 		 * must exist for non-speculative paths. For non-speculative paths
1929 		 * traversal stops when:
1930 		 * a. Verification error is found, maybe_exit_scc() is not called.
1931 		 * b. Top level BPF_EXIT is reached. Top level BPF_EXIT is not a member
1932 		 *    of any SCC.
1933 		 * c. A checkpoint is reached and matched. Checkpoints are created by
1934 		 *    is_state_visited(), which calls maybe_enter_scc(), which allocates
1935 		 *    bpf_scc_visit instances for checkpoints within SCCs.
1936 		 * (c) is the only case that can reach this point.
1937 		 */
1938 		if (!st->speculative) {
1939 			verifier_bug(env, "scc exit: no visit info for call chain %s",
1940 				     format_callchain(env, callchain));
1941 			return -EFAULT;
1942 		}
1943 		return 0;
1944 	}
1945 	if (visit->entry_state != st)
1946 		return 0;
1947 	if (env->log.level & BPF_LOG_LEVEL2)
1948 		verbose(env, "SCC exit %s\n", format_callchain(env, callchain));
1949 	visit->entry_state = NULL;
1950 	env->num_backedges -= visit->num_backedges;
1951 	visit->num_backedges = 0;
1952 	update_peak_states(env);
1953 	return propagate_backedges(env, visit);
1954 }
1955 
1956 /* Lookup an bpf_scc_visit instance corresponding to @st callchain
1957  * and add @backedge to visit->backedges. @st callchain must exist.
1958  */
1959 static int add_scc_backedge(struct bpf_verifier_env *env,
1960 			    struct bpf_verifier_state *st,
1961 			    struct bpf_scc_backedge *backedge)
1962 {
1963 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1964 	struct bpf_scc_visit *visit;
1965 
1966 	if (!compute_scc_callchain(env, st, callchain)) {
1967 		verifier_bug(env, "add backedge: no SCC in verification path, insn_idx %d",
1968 			     st->insn_idx);
1969 		return -EFAULT;
1970 	}
1971 	visit = scc_visit_lookup(env, callchain);
1972 	if (!visit) {
1973 		verifier_bug(env, "add backedge: no visit info for call chain %s",
1974 			     format_callchain(env, callchain));
1975 		return -EFAULT;
1976 	}
1977 	if (env->log.level & BPF_LOG_LEVEL2)
1978 		verbose(env, "SCC backedge %s\n", format_callchain(env, callchain));
1979 	backedge->next = visit->backedges;
1980 	visit->backedges = backedge;
1981 	visit->num_backedges++;
1982 	env->num_backedges++;
1983 	update_peak_states(env);
1984 	return 0;
1985 }
1986 
1987 /* bpf_reg_state->live marks for registers in a state @st are incomplete,
1988  * if state @st is in some SCC and not all execution paths starting at this
1989  * SCC are fully explored.
1990  */
1991 static bool incomplete_read_marks(struct bpf_verifier_env *env,
1992 				  struct bpf_verifier_state *st)
1993 {
1994 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1995 	struct bpf_scc_visit *visit;
1996 
1997 	if (!compute_scc_callchain(env, st, callchain))
1998 		return false;
1999 	visit = scc_visit_lookup(env, callchain);
2000 	if (!visit)
2001 		return false;
2002 	return !!visit->backedges;
2003 }
2004 
2005 static void free_backedges(struct bpf_scc_visit *visit)
2006 {
2007 	struct bpf_scc_backedge *backedge, *next;
2008 
2009 	for (backedge = visit->backedges; backedge; backedge = next) {
2010 		free_verifier_state(&backedge->state, false);
2011 		next = backedge->next;
2012 		kfree(backedge);
2013 	}
2014 	visit->backedges = NULL;
2015 }
2016 
2017 static int update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2018 {
2019 	struct bpf_verifier_state_list *sl = NULL, *parent_sl;
2020 	struct bpf_verifier_state *parent;
2021 	int err;
2022 
2023 	while (st) {
2024 		u32 br = --st->branches;
2025 
2026 		/* verifier_bug_if(br > 1, ...) technically makes sense here,
2027 		 * but see comment in push_stack(), hence:
2028 		 */
2029 		verifier_bug_if((int)br < 0, env, "%s:branches_to_explore=%d", __func__, br);
2030 		if (br)
2031 			break;
2032 		err = maybe_exit_scc(env, st);
2033 		if (err)
2034 			return err;
2035 		parent = st->parent;
2036 		parent_sl = state_parent_as_list(st);
2037 		if (sl)
2038 			maybe_free_verifier_state(env, sl);
2039 		st = parent;
2040 		sl = parent_sl;
2041 	}
2042 	return 0;
2043 }
2044 
2045 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2046 		     int *insn_idx, bool pop_log)
2047 {
2048 	struct bpf_verifier_state *cur = env->cur_state;
2049 	struct bpf_verifier_stack_elem *elem, *head = env->head;
2050 	int err;
2051 
2052 	if (env->head == NULL)
2053 		return -ENOENT;
2054 
2055 	if (cur) {
2056 		err = copy_verifier_state(cur, &head->st);
2057 		if (err)
2058 			return err;
2059 	}
2060 	if (pop_log)
2061 		bpf_vlog_reset(&env->log, head->log_pos);
2062 	if (insn_idx)
2063 		*insn_idx = head->insn_idx;
2064 	if (prev_insn_idx)
2065 		*prev_insn_idx = head->prev_insn_idx;
2066 	elem = head->next;
2067 	free_verifier_state(&head->st, false);
2068 	kfree(head);
2069 	env->head = elem;
2070 	env->stack_size--;
2071 	return 0;
2072 }
2073 
2074 static bool error_recoverable_with_nospec(int err)
2075 {
2076 	/* Should only return true for non-fatal errors that are allowed to
2077 	 * occur during speculative verification. For these we can insert a
2078 	 * nospec and the program might still be accepted. Do not include
2079 	 * something like ENOMEM because it is likely to re-occur for the next
2080 	 * architectural path once it has been recovered-from in all speculative
2081 	 * paths.
2082 	 */
2083 	return err == -EPERM || err == -EACCES || err == -EINVAL;
2084 }
2085 
2086 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2087 					     int insn_idx, int prev_insn_idx,
2088 					     bool speculative)
2089 {
2090 	struct bpf_verifier_state *cur = env->cur_state;
2091 	struct bpf_verifier_stack_elem *elem;
2092 	int err;
2093 
2094 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2095 	if (!elem)
2096 		return NULL;
2097 
2098 	elem->insn_idx = insn_idx;
2099 	elem->prev_insn_idx = prev_insn_idx;
2100 	elem->next = env->head;
2101 	elem->log_pos = env->log.end_pos;
2102 	env->head = elem;
2103 	env->stack_size++;
2104 	err = copy_verifier_state(&elem->st, cur);
2105 	if (err)
2106 		return NULL;
2107 	elem->st.speculative |= speculative;
2108 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2109 		verbose(env, "The sequence of %d jumps is too complex.\n",
2110 			env->stack_size);
2111 		return NULL;
2112 	}
2113 	if (elem->st.parent) {
2114 		++elem->st.parent->branches;
2115 		/* WARN_ON(branches > 2) technically makes sense here,
2116 		 * but
2117 		 * 1. speculative states will bump 'branches' for non-branch
2118 		 * instructions
2119 		 * 2. is_state_visited() heuristics may decide not to create
2120 		 * a new state for a sequence of branches and all such current
2121 		 * and cloned states will be pointing to a single parent state
2122 		 * which might have large 'branches' count.
2123 		 */
2124 	}
2125 	return &elem->st;
2126 }
2127 
2128 #define CALLER_SAVED_REGS 6
2129 static const int caller_saved[CALLER_SAVED_REGS] = {
2130 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2131 };
2132 
2133 /* This helper doesn't clear reg->id */
2134 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2135 {
2136 	reg->var_off = tnum_const(imm);
2137 	reg->smin_value = (s64)imm;
2138 	reg->smax_value = (s64)imm;
2139 	reg->umin_value = imm;
2140 	reg->umax_value = imm;
2141 
2142 	reg->s32_min_value = (s32)imm;
2143 	reg->s32_max_value = (s32)imm;
2144 	reg->u32_min_value = (u32)imm;
2145 	reg->u32_max_value = (u32)imm;
2146 }
2147 
2148 /* Mark the unknown part of a register (variable offset or scalar value) as
2149  * known to have the value @imm.
2150  */
2151 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2152 {
2153 	/* Clear off and union(map_ptr, range) */
2154 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2155 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2156 	reg->id = 0;
2157 	reg->ref_obj_id = 0;
2158 	___mark_reg_known(reg, imm);
2159 }
2160 
2161 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2162 {
2163 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2164 	reg->s32_min_value = (s32)imm;
2165 	reg->s32_max_value = (s32)imm;
2166 	reg->u32_min_value = (u32)imm;
2167 	reg->u32_max_value = (u32)imm;
2168 }
2169 
2170 /* Mark the 'variable offset' part of a register as zero.  This should be
2171  * used only on registers holding a pointer type.
2172  */
2173 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2174 {
2175 	__mark_reg_known(reg, 0);
2176 }
2177 
2178 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2179 {
2180 	__mark_reg_known(reg, 0);
2181 	reg->type = SCALAR_VALUE;
2182 	/* all scalars are assumed imprecise initially (unless unprivileged,
2183 	 * in which case everything is forced to be precise)
2184 	 */
2185 	reg->precise = !env->bpf_capable;
2186 }
2187 
2188 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2189 				struct bpf_reg_state *regs, u32 regno)
2190 {
2191 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2192 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2193 		/* Something bad happened, let's kill all regs */
2194 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2195 			__mark_reg_not_init(env, regs + regno);
2196 		return;
2197 	}
2198 	__mark_reg_known_zero(regs + regno);
2199 }
2200 
2201 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2202 			      bool first_slot, int dynptr_id)
2203 {
2204 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2205 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2206 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2207 	 */
2208 	__mark_reg_known_zero(reg);
2209 	reg->type = CONST_PTR_TO_DYNPTR;
2210 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2211 	reg->id = dynptr_id;
2212 	reg->dynptr.type = type;
2213 	reg->dynptr.first_slot = first_slot;
2214 }
2215 
2216 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2217 {
2218 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2219 		const struct bpf_map *map = reg->map_ptr;
2220 
2221 		if (map->inner_map_meta) {
2222 			reg->type = CONST_PTR_TO_MAP;
2223 			reg->map_ptr = map->inner_map_meta;
2224 			/* transfer reg's id which is unique for every map_lookup_elem
2225 			 * as UID of the inner map.
2226 			 */
2227 			if (btf_record_has_field(map->inner_map_meta->record,
2228 						 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) {
2229 				reg->map_uid = reg->id;
2230 			}
2231 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2232 			reg->type = PTR_TO_XDP_SOCK;
2233 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2234 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2235 			reg->type = PTR_TO_SOCKET;
2236 		} else {
2237 			reg->type = PTR_TO_MAP_VALUE;
2238 		}
2239 		return;
2240 	}
2241 
2242 	reg->type &= ~PTR_MAYBE_NULL;
2243 }
2244 
2245 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2246 				struct btf_field_graph_root *ds_head)
2247 {
2248 	__mark_reg_known_zero(&regs[regno]);
2249 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2250 	regs[regno].btf = ds_head->btf;
2251 	regs[regno].btf_id = ds_head->value_btf_id;
2252 	regs[regno].off = ds_head->node_offset;
2253 }
2254 
2255 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2256 {
2257 	return type_is_pkt_pointer(reg->type);
2258 }
2259 
2260 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2261 {
2262 	return reg_is_pkt_pointer(reg) ||
2263 	       reg->type == PTR_TO_PACKET_END;
2264 }
2265 
2266 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2267 {
2268 	return base_type(reg->type) == PTR_TO_MEM &&
2269 	       (reg->type &
2270 		(DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META));
2271 }
2272 
2273 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2274 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2275 				    enum bpf_reg_type which)
2276 {
2277 	/* The register can already have a range from prior markings.
2278 	 * This is fine as long as it hasn't been advanced from its
2279 	 * origin.
2280 	 */
2281 	return reg->type == which &&
2282 	       reg->id == 0 &&
2283 	       reg->off == 0 &&
2284 	       tnum_equals_const(reg->var_off, 0);
2285 }
2286 
2287 /* Reset the min/max bounds of a register */
2288 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2289 {
2290 	reg->smin_value = S64_MIN;
2291 	reg->smax_value = S64_MAX;
2292 	reg->umin_value = 0;
2293 	reg->umax_value = U64_MAX;
2294 
2295 	reg->s32_min_value = S32_MIN;
2296 	reg->s32_max_value = S32_MAX;
2297 	reg->u32_min_value = 0;
2298 	reg->u32_max_value = U32_MAX;
2299 }
2300 
2301 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2302 {
2303 	reg->smin_value = S64_MIN;
2304 	reg->smax_value = S64_MAX;
2305 	reg->umin_value = 0;
2306 	reg->umax_value = U64_MAX;
2307 }
2308 
2309 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2310 {
2311 	reg->s32_min_value = S32_MIN;
2312 	reg->s32_max_value = S32_MAX;
2313 	reg->u32_min_value = 0;
2314 	reg->u32_max_value = U32_MAX;
2315 }
2316 
2317 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2318 {
2319 	struct tnum var32_off = tnum_subreg(reg->var_off);
2320 
2321 	/* min signed is max(sign bit) | min(other bits) */
2322 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2323 			var32_off.value | (var32_off.mask & S32_MIN));
2324 	/* max signed is min(sign bit) | max(other bits) */
2325 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2326 			var32_off.value | (var32_off.mask & S32_MAX));
2327 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2328 	reg->u32_max_value = min(reg->u32_max_value,
2329 				 (u32)(var32_off.value | var32_off.mask));
2330 }
2331 
2332 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2333 {
2334 	/* min signed is max(sign bit) | min(other bits) */
2335 	reg->smin_value = max_t(s64, reg->smin_value,
2336 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2337 	/* max signed is min(sign bit) | max(other bits) */
2338 	reg->smax_value = min_t(s64, reg->smax_value,
2339 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2340 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2341 	reg->umax_value = min(reg->umax_value,
2342 			      reg->var_off.value | reg->var_off.mask);
2343 }
2344 
2345 static void __update_reg_bounds(struct bpf_reg_state *reg)
2346 {
2347 	__update_reg32_bounds(reg);
2348 	__update_reg64_bounds(reg);
2349 }
2350 
2351 /* Uses signed min/max values to inform unsigned, and vice-versa */
2352 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2353 {
2354 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
2355 	 * bits to improve our u32/s32 boundaries.
2356 	 *
2357 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
2358 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
2359 	 * [10, 20] range. But this property holds for any 64-bit range as
2360 	 * long as upper 32 bits in that entire range of values stay the same.
2361 	 *
2362 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
2363 	 * in decimal) has the same upper 32 bits throughout all the values in
2364 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
2365 	 * range.
2366 	 *
2367 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
2368 	 * following the rules outlined below about u64/s64 correspondence
2369 	 * (which equally applies to u32 vs s32 correspondence). In general it
2370 	 * depends on actual hexadecimal values of 32-bit range. They can form
2371 	 * only valid u32, or only valid s32 ranges in some cases.
2372 	 *
2373 	 * So we use all these insights to derive bounds for subregisters here.
2374 	 */
2375 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
2376 		/* u64 to u32 casting preserves validity of low 32 bits as
2377 		 * a range, if upper 32 bits are the same
2378 		 */
2379 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2380 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2381 
2382 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2383 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2384 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2385 		}
2386 	}
2387 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2388 		/* low 32 bits should form a proper u32 range */
2389 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2390 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2391 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2392 		}
2393 		/* low 32 bits should form a proper s32 range */
2394 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2395 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2396 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2397 		}
2398 	}
2399 	/* Special case where upper bits form a small sequence of two
2400 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2401 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2402 	 * going from negative numbers to positive numbers. E.g., let's say we
2403 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2404 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2405 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2406 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2407 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2408 	 * upper 32 bits. As a random example, s64 range
2409 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2410 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2411 	 */
2412 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2413 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2414 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2415 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2416 	}
2417 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2418 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2419 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2420 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2421 	}
2422 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2423 	 * try to learn from that
2424 	 */
2425 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2426 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2427 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2428 	}
2429 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2430 	 * are the same, so combine.  This works even in the negative case, e.g.
2431 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2432 	 */
2433 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2434 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2435 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2436 	}
2437 }
2438 
2439 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2440 {
2441 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2442 	 * try to learn from that. Let's do a bit of ASCII art to see when
2443 	 * this is happening. Let's take u64 range first:
2444 	 *
2445 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2446 	 * |-------------------------------|--------------------------------|
2447 	 *
2448 	 * Valid u64 range is formed when umin and umax are anywhere in the
2449 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2450 	 * straightforward. Let's see how s64 range maps onto the same range
2451 	 * of values, annotated below the line for comparison:
2452 	 *
2453 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2454 	 * |-------------------------------|--------------------------------|
2455 	 * 0                        S64_MAX S64_MIN                        -1
2456 	 *
2457 	 * So s64 values basically start in the middle and they are logically
2458 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2459 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2460 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2461 	 * more visually as mapped to sign-agnostic range of hex values.
2462 	 *
2463 	 *  u64 start                                               u64 end
2464 	 *  _______________________________________________________________
2465 	 * /                                                               \
2466 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2467 	 * |-------------------------------|--------------------------------|
2468 	 * 0                        S64_MAX S64_MIN                        -1
2469 	 *                                / \
2470 	 * >------------------------------   ------------------------------->
2471 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2472 	 *
2473 	 * What this means is that, in general, we can't always derive
2474 	 * something new about u64 from any random s64 range, and vice versa.
2475 	 *
2476 	 * But we can do that in two particular cases. One is when entire
2477 	 * u64/s64 range is *entirely* contained within left half of the above
2478 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2479 	 *
2480 	 * |-------------------------------|--------------------------------|
2481 	 *     ^                   ^            ^                 ^
2482 	 *     A                   B            C                 D
2483 	 *
2484 	 * [A, B] and [C, D] are contained entirely in their respective halves
2485 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2486 	 * will be non-negative both as u64 and s64 (and in fact it will be
2487 	 * identical ranges no matter the signedness). [C, D] treated as s64
2488 	 * will be a range of negative values, while in u64 it will be
2489 	 * non-negative range of values larger than 0x8000000000000000.
2490 	 *
2491 	 * Now, any other range here can't be represented in both u64 and s64
2492 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2493 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2494 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2495 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2496 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2497 	 * ranges as u64. Currently reg_state can't represent two segments per
2498 	 * numeric domain, so in such situations we can only derive maximal
2499 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2500 	 *
2501 	 * So we use these facts to derive umin/umax from smin/smax and vice
2502 	 * versa only if they stay within the same "half". This is equivalent
2503 	 * to checking sign bit: lower half will have sign bit as zero, upper
2504 	 * half have sign bit 1. Below in code we simplify this by just
2505 	 * casting umin/umax as smin/smax and checking if they form valid
2506 	 * range, and vice versa. Those are equivalent checks.
2507 	 */
2508 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2509 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2510 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2511 	}
2512 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2513 	 * are the same, so combine.  This works even in the negative case, e.g.
2514 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2515 	 */
2516 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2517 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2518 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2519 	} else {
2520 		/* If the s64 range crosses the sign boundary, then it's split
2521 		 * between the beginning and end of the U64 domain. In that
2522 		 * case, we can derive new bounds if the u64 range overlaps
2523 		 * with only one end of the s64 range.
2524 		 *
2525 		 * In the following example, the u64 range overlaps only with
2526 		 * positive portion of the s64 range.
2527 		 *
2528 		 * 0                                                   U64_MAX
2529 		 * |  [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]              |
2530 		 * |----------------------------|----------------------------|
2531 		 * |xxxxx s64 range xxxxxxxxx]                       [xxxxxxx|
2532 		 * 0                     S64_MAX S64_MIN                    -1
2533 		 *
2534 		 * We can thus derive the following new s64 and u64 ranges.
2535 		 *
2536 		 * 0                                                   U64_MAX
2537 		 * |  [xxxxxx u64 range xxxxx]                               |
2538 		 * |----------------------------|----------------------------|
2539 		 * |  [xxxxxx s64 range xxxxx]                               |
2540 		 * 0                     S64_MAX S64_MIN                    -1
2541 		 *
2542 		 * If they overlap in two places, we can't derive anything
2543 		 * because reg_state can't represent two ranges per numeric
2544 		 * domain.
2545 		 *
2546 		 * 0                                                   U64_MAX
2547 		 * |  [xxxxxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxxxxx]        |
2548 		 * |----------------------------|----------------------------|
2549 		 * |xxxxx s64 range xxxxxxxxx]                    [xxxxxxxxxx|
2550 		 * 0                     S64_MAX S64_MIN                    -1
2551 		 *
2552 		 * The first condition below corresponds to the first diagram
2553 		 * above.
2554 		 */
2555 		if (reg->umax_value < (u64)reg->smin_value) {
2556 			reg->smin_value = (s64)reg->umin_value;
2557 			reg->umax_value = min_t(u64, reg->umax_value, reg->smax_value);
2558 		} else if ((u64)reg->smax_value < reg->umin_value) {
2559 			/* This second condition considers the case where the u64 range
2560 			 * overlaps with the negative portion of the s64 range:
2561 			 *
2562 			 * 0                                                   U64_MAX
2563 			 * |              [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]  |
2564 			 * |----------------------------|----------------------------|
2565 			 * |xxxxxxxxx]                       [xxxxxxxxxxxx s64 range |
2566 			 * 0                     S64_MAX S64_MIN                    -1
2567 			 */
2568 			reg->smax_value = (s64)reg->umax_value;
2569 			reg->umin_value = max_t(u64, reg->umin_value, reg->smin_value);
2570 		}
2571 	}
2572 }
2573 
2574 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2575 {
2576 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2577 	 * values on both sides of 64-bit range in hope to have tighter range.
2578 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2579 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2580 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2581 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2582 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2583 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2584 	 * We just need to make sure that derived bounds we are intersecting
2585 	 * with are well-formed ranges in respective s64 or u64 domain, just
2586 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2587 	 */
2588 	__u64 new_umin, new_umax;
2589 	__s64 new_smin, new_smax;
2590 
2591 	/* u32 -> u64 tightening, it's always well-formed */
2592 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2593 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2594 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2595 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2596 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2597 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2598 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2599 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2600 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2601 
2602 	/* Here we would like to handle a special case after sign extending load,
2603 	 * when upper bits for a 64-bit range are all 1s or all 0s.
2604 	 *
2605 	 * Upper bits are all 1s when register is in a range:
2606 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2607 	 * Upper bits are all 0s when register is in a range:
2608 	 *   [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2609 	 * Together this forms are continuous range:
2610 	 *   [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2611 	 *
2612 	 * Now, suppose that register range is in fact tighter:
2613 	 *   [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2614 	 * Also suppose that it's 32-bit range is positive,
2615 	 * meaning that lower 32-bits of the full 64-bit register
2616 	 * are in the range:
2617 	 *   [0x0000_0000, 0x7fff_ffff] (W)
2618 	 *
2619 	 * If this happens, then any value in a range:
2620 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2621 	 * is smaller than a lowest bound of the range (R):
2622 	 *   0xffff_ffff_8000_0000
2623 	 * which means that upper bits of the full 64-bit register
2624 	 * can't be all 1s, when lower bits are in range (W).
2625 	 *
2626 	 * Note that:
2627 	 *  - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2628 	 *  - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2629 	 * These relations are used in the conditions below.
2630 	 */
2631 	if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2632 		reg->smin_value = reg->s32_min_value;
2633 		reg->smax_value = reg->s32_max_value;
2634 		reg->umin_value = reg->s32_min_value;
2635 		reg->umax_value = reg->s32_max_value;
2636 		reg->var_off = tnum_intersect(reg->var_off,
2637 					      tnum_range(reg->smin_value, reg->smax_value));
2638 	}
2639 }
2640 
2641 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2642 {
2643 	__reg32_deduce_bounds(reg);
2644 	__reg64_deduce_bounds(reg);
2645 	__reg_deduce_mixed_bounds(reg);
2646 }
2647 
2648 /* Attempts to improve var_off based on unsigned min/max information */
2649 static void __reg_bound_offset(struct bpf_reg_state *reg)
2650 {
2651 	struct tnum var64_off = tnum_intersect(reg->var_off,
2652 					       tnum_range(reg->umin_value,
2653 							  reg->umax_value));
2654 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2655 					       tnum_range(reg->u32_min_value,
2656 							  reg->u32_max_value));
2657 
2658 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2659 }
2660 
2661 static void reg_bounds_sync(struct bpf_reg_state *reg)
2662 {
2663 	/* We might have learned new bounds from the var_off. */
2664 	__update_reg_bounds(reg);
2665 	/* We might have learned something about the sign bit. */
2666 	__reg_deduce_bounds(reg);
2667 	__reg_deduce_bounds(reg);
2668 	__reg_deduce_bounds(reg);
2669 	/* We might have learned some bits from the bounds. */
2670 	__reg_bound_offset(reg);
2671 	/* Intersecting with the old var_off might have improved our bounds
2672 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2673 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2674 	 */
2675 	__update_reg_bounds(reg);
2676 }
2677 
2678 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2679 				   struct bpf_reg_state *reg, const char *ctx)
2680 {
2681 	const char *msg;
2682 
2683 	if (reg->umin_value > reg->umax_value ||
2684 	    reg->smin_value > reg->smax_value ||
2685 	    reg->u32_min_value > reg->u32_max_value ||
2686 	    reg->s32_min_value > reg->s32_max_value) {
2687 		    msg = "range bounds violation";
2688 		    goto out;
2689 	}
2690 
2691 	if (tnum_is_const(reg->var_off)) {
2692 		u64 uval = reg->var_off.value;
2693 		s64 sval = (s64)uval;
2694 
2695 		if (reg->umin_value != uval || reg->umax_value != uval ||
2696 		    reg->smin_value != sval || reg->smax_value != sval) {
2697 			msg = "const tnum out of sync with range bounds";
2698 			goto out;
2699 		}
2700 	}
2701 
2702 	if (tnum_subreg_is_const(reg->var_off)) {
2703 		u32 uval32 = tnum_subreg(reg->var_off).value;
2704 		s32 sval32 = (s32)uval32;
2705 
2706 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2707 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2708 			msg = "const subreg tnum out of sync with range bounds";
2709 			goto out;
2710 		}
2711 	}
2712 
2713 	return 0;
2714 out:
2715 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2716 		     "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)",
2717 		     ctx, msg, reg->umin_value, reg->umax_value,
2718 		     reg->smin_value, reg->smax_value,
2719 		     reg->u32_min_value, reg->u32_max_value,
2720 		     reg->s32_min_value, reg->s32_max_value,
2721 		     reg->var_off.value, reg->var_off.mask);
2722 	if (env->test_reg_invariants)
2723 		return -EFAULT;
2724 	__mark_reg_unbounded(reg);
2725 	return 0;
2726 }
2727 
2728 static bool __reg32_bound_s64(s32 a)
2729 {
2730 	return a >= 0 && a <= S32_MAX;
2731 }
2732 
2733 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2734 {
2735 	reg->umin_value = reg->u32_min_value;
2736 	reg->umax_value = reg->u32_max_value;
2737 
2738 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2739 	 * be positive otherwise set to worse case bounds and refine later
2740 	 * from tnum.
2741 	 */
2742 	if (__reg32_bound_s64(reg->s32_min_value) &&
2743 	    __reg32_bound_s64(reg->s32_max_value)) {
2744 		reg->smin_value = reg->s32_min_value;
2745 		reg->smax_value = reg->s32_max_value;
2746 	} else {
2747 		reg->smin_value = 0;
2748 		reg->smax_value = U32_MAX;
2749 	}
2750 }
2751 
2752 /* Mark a register as having a completely unknown (scalar) value. */
2753 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2754 {
2755 	/*
2756 	 * Clear type, off, and union(map_ptr, range) and
2757 	 * padding between 'type' and union
2758 	 */
2759 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2760 	reg->type = SCALAR_VALUE;
2761 	reg->id = 0;
2762 	reg->ref_obj_id = 0;
2763 	reg->var_off = tnum_unknown;
2764 	reg->frameno = 0;
2765 	reg->precise = false;
2766 	__mark_reg_unbounded(reg);
2767 }
2768 
2769 /* Mark a register as having a completely unknown (scalar) value,
2770  * initialize .precise as true when not bpf capable.
2771  */
2772 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2773 			       struct bpf_reg_state *reg)
2774 {
2775 	__mark_reg_unknown_imprecise(reg);
2776 	reg->precise = !env->bpf_capable;
2777 }
2778 
2779 static void mark_reg_unknown(struct bpf_verifier_env *env,
2780 			     struct bpf_reg_state *regs, u32 regno)
2781 {
2782 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2783 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2784 		/* Something bad happened, let's kill all regs except FP */
2785 		for (regno = 0; regno < BPF_REG_FP; regno++)
2786 			__mark_reg_not_init(env, regs + regno);
2787 		return;
2788 	}
2789 	__mark_reg_unknown(env, regs + regno);
2790 }
2791 
2792 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2793 				struct bpf_reg_state *regs,
2794 				u32 regno,
2795 				s32 s32_min,
2796 				s32 s32_max)
2797 {
2798 	struct bpf_reg_state *reg = regs + regno;
2799 
2800 	reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2801 	reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2802 
2803 	reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2804 	reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2805 
2806 	reg_bounds_sync(reg);
2807 
2808 	return reg_bounds_sanity_check(env, reg, "s32_range");
2809 }
2810 
2811 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2812 				struct bpf_reg_state *reg)
2813 {
2814 	__mark_reg_unknown(env, reg);
2815 	reg->type = NOT_INIT;
2816 }
2817 
2818 static void mark_reg_not_init(struct bpf_verifier_env *env,
2819 			      struct bpf_reg_state *regs, u32 regno)
2820 {
2821 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2822 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2823 		/* Something bad happened, let's kill all regs except FP */
2824 		for (regno = 0; regno < BPF_REG_FP; regno++)
2825 			__mark_reg_not_init(env, regs + regno);
2826 		return;
2827 	}
2828 	__mark_reg_not_init(env, regs + regno);
2829 }
2830 
2831 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2832 			   struct bpf_reg_state *regs, u32 regno,
2833 			   enum bpf_reg_type reg_type,
2834 			   struct btf *btf, u32 btf_id,
2835 			   enum bpf_type_flag flag)
2836 {
2837 	switch (reg_type) {
2838 	case SCALAR_VALUE:
2839 		mark_reg_unknown(env, regs, regno);
2840 		return 0;
2841 	case PTR_TO_BTF_ID:
2842 		mark_reg_known_zero(env, regs, regno);
2843 		regs[regno].type = PTR_TO_BTF_ID | flag;
2844 		regs[regno].btf = btf;
2845 		regs[regno].btf_id = btf_id;
2846 		if (type_may_be_null(flag))
2847 			regs[regno].id = ++env->id_gen;
2848 		return 0;
2849 	case PTR_TO_MEM:
2850 		mark_reg_known_zero(env, regs, regno);
2851 		regs[regno].type = PTR_TO_MEM | flag;
2852 		regs[regno].mem_size = 0;
2853 		return 0;
2854 	default:
2855 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2856 		return -EFAULT;
2857 	}
2858 }
2859 
2860 #define DEF_NOT_SUBREG	(0)
2861 static void init_reg_state(struct bpf_verifier_env *env,
2862 			   struct bpf_func_state *state)
2863 {
2864 	struct bpf_reg_state *regs = state->regs;
2865 	int i;
2866 
2867 	for (i = 0; i < MAX_BPF_REG; i++) {
2868 		mark_reg_not_init(env, regs, i);
2869 		regs[i].subreg_def = DEF_NOT_SUBREG;
2870 	}
2871 
2872 	/* frame pointer */
2873 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2874 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2875 	regs[BPF_REG_FP].frameno = state->frameno;
2876 }
2877 
2878 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2879 {
2880 	return (struct bpf_retval_range){ minval, maxval };
2881 }
2882 
2883 #define BPF_MAIN_FUNC (-1)
2884 static void init_func_state(struct bpf_verifier_env *env,
2885 			    struct bpf_func_state *state,
2886 			    int callsite, int frameno, int subprogno)
2887 {
2888 	state->callsite = callsite;
2889 	state->frameno = frameno;
2890 	state->subprogno = subprogno;
2891 	state->callback_ret_range = retval_range(0, 0);
2892 	init_reg_state(env, state);
2893 	mark_verifier_state_scratched(env);
2894 }
2895 
2896 /* Similar to push_stack(), but for async callbacks */
2897 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2898 						int insn_idx, int prev_insn_idx,
2899 						int subprog, bool is_sleepable)
2900 {
2901 	struct bpf_verifier_stack_elem *elem;
2902 	struct bpf_func_state *frame;
2903 
2904 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2905 	if (!elem)
2906 		return NULL;
2907 
2908 	elem->insn_idx = insn_idx;
2909 	elem->prev_insn_idx = prev_insn_idx;
2910 	elem->next = env->head;
2911 	elem->log_pos = env->log.end_pos;
2912 	env->head = elem;
2913 	env->stack_size++;
2914 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2915 		verbose(env,
2916 			"The sequence of %d jumps is too complex for async cb.\n",
2917 			env->stack_size);
2918 		return NULL;
2919 	}
2920 	/* Unlike push_stack() do not copy_verifier_state().
2921 	 * The caller state doesn't matter.
2922 	 * This is async callback. It starts in a fresh stack.
2923 	 * Initialize it similar to do_check_common().
2924 	 */
2925 	elem->st.branches = 1;
2926 	elem->st.in_sleepable = is_sleepable;
2927 	frame = kzalloc(sizeof(*frame), GFP_KERNEL_ACCOUNT);
2928 	if (!frame)
2929 		return NULL;
2930 	init_func_state(env, frame,
2931 			BPF_MAIN_FUNC /* callsite */,
2932 			0 /* frameno within this callchain */,
2933 			subprog /* subprog number within this prog */);
2934 	elem->st.frame[0] = frame;
2935 	return &elem->st;
2936 }
2937 
2938 
2939 enum reg_arg_type {
2940 	SRC_OP,		/* register is used as source operand */
2941 	DST_OP,		/* register is used as destination operand */
2942 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2943 };
2944 
2945 static int cmp_subprogs(const void *a, const void *b)
2946 {
2947 	return ((struct bpf_subprog_info *)a)->start -
2948 	       ((struct bpf_subprog_info *)b)->start;
2949 }
2950 
2951 /* Find subprogram that contains instruction at 'off' */
2952 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)
2953 {
2954 	struct bpf_subprog_info *vals = env->subprog_info;
2955 	int l, r, m;
2956 
2957 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2958 		return NULL;
2959 
2960 	l = 0;
2961 	r = env->subprog_cnt - 1;
2962 	while (l < r) {
2963 		m = l + (r - l + 1) / 2;
2964 		if (vals[m].start <= off)
2965 			l = m;
2966 		else
2967 			r = m - 1;
2968 	}
2969 	return &vals[l];
2970 }
2971 
2972 /* Find subprogram that starts exactly at 'off' */
2973 static int find_subprog(struct bpf_verifier_env *env, int off)
2974 {
2975 	struct bpf_subprog_info *p;
2976 
2977 	p = bpf_find_containing_subprog(env, off);
2978 	if (!p || p->start != off)
2979 		return -ENOENT;
2980 	return p - env->subprog_info;
2981 }
2982 
2983 static int add_subprog(struct bpf_verifier_env *env, int off)
2984 {
2985 	int insn_cnt = env->prog->len;
2986 	int ret;
2987 
2988 	if (off >= insn_cnt || off < 0) {
2989 		verbose(env, "call to invalid destination\n");
2990 		return -EINVAL;
2991 	}
2992 	ret = find_subprog(env, off);
2993 	if (ret >= 0)
2994 		return ret;
2995 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2996 		verbose(env, "too many subprograms\n");
2997 		return -E2BIG;
2998 	}
2999 	/* determine subprog starts. The end is one before the next starts */
3000 	env->subprog_info[env->subprog_cnt++].start = off;
3001 	sort(env->subprog_info, env->subprog_cnt,
3002 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
3003 	return env->subprog_cnt - 1;
3004 }
3005 
3006 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
3007 {
3008 	struct bpf_prog_aux *aux = env->prog->aux;
3009 	struct btf *btf = aux->btf;
3010 	const struct btf_type *t;
3011 	u32 main_btf_id, id;
3012 	const char *name;
3013 	int ret, i;
3014 
3015 	/* Non-zero func_info_cnt implies valid btf */
3016 	if (!aux->func_info_cnt)
3017 		return 0;
3018 	main_btf_id = aux->func_info[0].type_id;
3019 
3020 	t = btf_type_by_id(btf, main_btf_id);
3021 	if (!t) {
3022 		verbose(env, "invalid btf id for main subprog in func_info\n");
3023 		return -EINVAL;
3024 	}
3025 
3026 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
3027 	if (IS_ERR(name)) {
3028 		ret = PTR_ERR(name);
3029 		/* If there is no tag present, there is no exception callback */
3030 		if (ret == -ENOENT)
3031 			ret = 0;
3032 		else if (ret == -EEXIST)
3033 			verbose(env, "multiple exception callback tags for main subprog\n");
3034 		return ret;
3035 	}
3036 
3037 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
3038 	if (ret < 0) {
3039 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
3040 		return ret;
3041 	}
3042 	id = ret;
3043 	t = btf_type_by_id(btf, id);
3044 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3045 		verbose(env, "exception callback '%s' must have global linkage\n", name);
3046 		return -EINVAL;
3047 	}
3048 	ret = 0;
3049 	for (i = 0; i < aux->func_info_cnt; i++) {
3050 		if (aux->func_info[i].type_id != id)
3051 			continue;
3052 		ret = aux->func_info[i].insn_off;
3053 		/* Further func_info and subprog checks will also happen
3054 		 * later, so assume this is the right insn_off for now.
3055 		 */
3056 		if (!ret) {
3057 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
3058 			ret = -EINVAL;
3059 		}
3060 	}
3061 	if (!ret) {
3062 		verbose(env, "exception callback type id not found in func_info\n");
3063 		ret = -EINVAL;
3064 	}
3065 	return ret;
3066 }
3067 
3068 #define MAX_KFUNC_DESCS 256
3069 #define MAX_KFUNC_BTFS	256
3070 
3071 struct bpf_kfunc_desc {
3072 	struct btf_func_model func_model;
3073 	u32 func_id;
3074 	s32 imm;
3075 	u16 offset;
3076 	unsigned long addr;
3077 };
3078 
3079 struct bpf_kfunc_btf {
3080 	struct btf *btf;
3081 	struct module *module;
3082 	u16 offset;
3083 };
3084 
3085 struct bpf_kfunc_desc_tab {
3086 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
3087 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
3088 	 * available, therefore at the end of verification do_misc_fixups()
3089 	 * sorts this by imm and offset.
3090 	 */
3091 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
3092 	u32 nr_descs;
3093 };
3094 
3095 struct bpf_kfunc_btf_tab {
3096 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
3097 	u32 nr_descs;
3098 };
3099 
3100 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
3101 {
3102 	const struct bpf_kfunc_desc *d0 = a;
3103 	const struct bpf_kfunc_desc *d1 = b;
3104 
3105 	/* func_id is not greater than BTF_MAX_TYPE */
3106 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
3107 }
3108 
3109 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
3110 {
3111 	const struct bpf_kfunc_btf *d0 = a;
3112 	const struct bpf_kfunc_btf *d1 = b;
3113 
3114 	return d0->offset - d1->offset;
3115 }
3116 
3117 static const struct bpf_kfunc_desc *
3118 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
3119 {
3120 	struct bpf_kfunc_desc desc = {
3121 		.func_id = func_id,
3122 		.offset = offset,
3123 	};
3124 	struct bpf_kfunc_desc_tab *tab;
3125 
3126 	tab = prog->aux->kfunc_tab;
3127 	return bsearch(&desc, tab->descs, tab->nr_descs,
3128 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
3129 }
3130 
3131 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3132 		       u16 btf_fd_idx, u8 **func_addr)
3133 {
3134 	const struct bpf_kfunc_desc *desc;
3135 
3136 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
3137 	if (!desc)
3138 		return -EFAULT;
3139 
3140 	*func_addr = (u8 *)desc->addr;
3141 	return 0;
3142 }
3143 
3144 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
3145 					 s16 offset)
3146 {
3147 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
3148 	struct bpf_kfunc_btf_tab *tab;
3149 	struct bpf_kfunc_btf *b;
3150 	struct module *mod;
3151 	struct btf *btf;
3152 	int btf_fd;
3153 
3154 	tab = env->prog->aux->kfunc_btf_tab;
3155 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
3156 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
3157 	if (!b) {
3158 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
3159 			verbose(env, "too many different module BTFs\n");
3160 			return ERR_PTR(-E2BIG);
3161 		}
3162 
3163 		if (bpfptr_is_null(env->fd_array)) {
3164 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
3165 			return ERR_PTR(-EPROTO);
3166 		}
3167 
3168 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
3169 					    offset * sizeof(btf_fd),
3170 					    sizeof(btf_fd)))
3171 			return ERR_PTR(-EFAULT);
3172 
3173 		btf = btf_get_by_fd(btf_fd);
3174 		if (IS_ERR(btf)) {
3175 			verbose(env, "invalid module BTF fd specified\n");
3176 			return btf;
3177 		}
3178 
3179 		if (!btf_is_module(btf)) {
3180 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
3181 			btf_put(btf);
3182 			return ERR_PTR(-EINVAL);
3183 		}
3184 
3185 		mod = btf_try_get_module(btf);
3186 		if (!mod) {
3187 			btf_put(btf);
3188 			return ERR_PTR(-ENXIO);
3189 		}
3190 
3191 		b = &tab->descs[tab->nr_descs++];
3192 		b->btf = btf;
3193 		b->module = mod;
3194 		b->offset = offset;
3195 
3196 		/* sort() reorders entries by value, so b may no longer point
3197 		 * to the right entry after this
3198 		 */
3199 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3200 		     kfunc_btf_cmp_by_off, NULL);
3201 	} else {
3202 		btf = b->btf;
3203 	}
3204 
3205 	return btf;
3206 }
3207 
3208 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
3209 {
3210 	if (!tab)
3211 		return;
3212 
3213 	while (tab->nr_descs--) {
3214 		module_put(tab->descs[tab->nr_descs].module);
3215 		btf_put(tab->descs[tab->nr_descs].btf);
3216 	}
3217 	kfree(tab);
3218 }
3219 
3220 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
3221 {
3222 	if (offset) {
3223 		if (offset < 0) {
3224 			/* In the future, this can be allowed to increase limit
3225 			 * of fd index into fd_array, interpreted as u16.
3226 			 */
3227 			verbose(env, "negative offset disallowed for kernel module function call\n");
3228 			return ERR_PTR(-EINVAL);
3229 		}
3230 
3231 		return __find_kfunc_desc_btf(env, offset);
3232 	}
3233 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
3234 }
3235 
3236 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
3237 {
3238 	const struct btf_type *func, *func_proto;
3239 	struct bpf_kfunc_btf_tab *btf_tab;
3240 	struct bpf_kfunc_desc_tab *tab;
3241 	struct bpf_prog_aux *prog_aux;
3242 	struct bpf_kfunc_desc *desc;
3243 	const char *func_name;
3244 	struct btf *desc_btf;
3245 	unsigned long call_imm;
3246 	unsigned long addr;
3247 	int err;
3248 
3249 	prog_aux = env->prog->aux;
3250 	tab = prog_aux->kfunc_tab;
3251 	btf_tab = prog_aux->kfunc_btf_tab;
3252 	if (!tab) {
3253 		if (!btf_vmlinux) {
3254 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3255 			return -ENOTSUPP;
3256 		}
3257 
3258 		if (!env->prog->jit_requested) {
3259 			verbose(env, "JIT is required for calling kernel function\n");
3260 			return -ENOTSUPP;
3261 		}
3262 
3263 		if (!bpf_jit_supports_kfunc_call()) {
3264 			verbose(env, "JIT does not support calling kernel function\n");
3265 			return -ENOTSUPP;
3266 		}
3267 
3268 		if (!env->prog->gpl_compatible) {
3269 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3270 			return -EINVAL;
3271 		}
3272 
3273 		tab = kzalloc(sizeof(*tab), GFP_KERNEL_ACCOUNT);
3274 		if (!tab)
3275 			return -ENOMEM;
3276 		prog_aux->kfunc_tab = tab;
3277 	}
3278 
3279 	/* func_id == 0 is always invalid, but instead of returning an error, be
3280 	 * conservative and wait until the code elimination pass before returning
3281 	 * error, so that invalid calls that get pruned out can be in BPF programs
3282 	 * loaded from userspace.  It is also required that offset be untouched
3283 	 * for such calls.
3284 	 */
3285 	if (!func_id && !offset)
3286 		return 0;
3287 
3288 	if (!btf_tab && offset) {
3289 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL_ACCOUNT);
3290 		if (!btf_tab)
3291 			return -ENOMEM;
3292 		prog_aux->kfunc_btf_tab = btf_tab;
3293 	}
3294 
3295 	desc_btf = find_kfunc_desc_btf(env, offset);
3296 	if (IS_ERR(desc_btf)) {
3297 		verbose(env, "failed to find BTF for kernel function\n");
3298 		return PTR_ERR(desc_btf);
3299 	}
3300 
3301 	if (find_kfunc_desc(env->prog, func_id, offset))
3302 		return 0;
3303 
3304 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
3305 		verbose(env, "too many different kernel function calls\n");
3306 		return -E2BIG;
3307 	}
3308 
3309 	func = btf_type_by_id(desc_btf, func_id);
3310 	if (!func || !btf_type_is_func(func)) {
3311 		verbose(env, "kernel btf_id %u is not a function\n",
3312 			func_id);
3313 		return -EINVAL;
3314 	}
3315 	func_proto = btf_type_by_id(desc_btf, func->type);
3316 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3317 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
3318 			func_id);
3319 		return -EINVAL;
3320 	}
3321 
3322 	func_name = btf_name_by_offset(desc_btf, func->name_off);
3323 	addr = kallsyms_lookup_name(func_name);
3324 	if (!addr) {
3325 		verbose(env, "cannot find address for kernel function %s\n",
3326 			func_name);
3327 		return -EINVAL;
3328 	}
3329 	specialize_kfunc(env, func_id, offset, &addr);
3330 
3331 	if (bpf_jit_supports_far_kfunc_call()) {
3332 		call_imm = func_id;
3333 	} else {
3334 		call_imm = BPF_CALL_IMM(addr);
3335 		/* Check whether the relative offset overflows desc->imm */
3336 		if ((unsigned long)(s32)call_imm != call_imm) {
3337 			verbose(env, "address of kernel function %s is out of range\n",
3338 				func_name);
3339 			return -EINVAL;
3340 		}
3341 	}
3342 
3343 	if (bpf_dev_bound_kfunc_id(func_id)) {
3344 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3345 		if (err)
3346 			return err;
3347 	}
3348 
3349 	desc = &tab->descs[tab->nr_descs++];
3350 	desc->func_id = func_id;
3351 	desc->imm = call_imm;
3352 	desc->offset = offset;
3353 	desc->addr = addr;
3354 	err = btf_distill_func_proto(&env->log, desc_btf,
3355 				     func_proto, func_name,
3356 				     &desc->func_model);
3357 	if (!err)
3358 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3359 		     kfunc_desc_cmp_by_id_off, NULL);
3360 	return err;
3361 }
3362 
3363 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3364 {
3365 	const struct bpf_kfunc_desc *d0 = a;
3366 	const struct bpf_kfunc_desc *d1 = b;
3367 
3368 	if (d0->imm != d1->imm)
3369 		return d0->imm < d1->imm ? -1 : 1;
3370 	if (d0->offset != d1->offset)
3371 		return d0->offset < d1->offset ? -1 : 1;
3372 	return 0;
3373 }
3374 
3375 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
3376 {
3377 	struct bpf_kfunc_desc_tab *tab;
3378 
3379 	tab = prog->aux->kfunc_tab;
3380 	if (!tab)
3381 		return;
3382 
3383 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3384 	     kfunc_desc_cmp_by_imm_off, NULL);
3385 }
3386 
3387 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3388 {
3389 	return !!prog->aux->kfunc_tab;
3390 }
3391 
3392 const struct btf_func_model *
3393 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3394 			 const struct bpf_insn *insn)
3395 {
3396 	const struct bpf_kfunc_desc desc = {
3397 		.imm = insn->imm,
3398 		.offset = insn->off,
3399 	};
3400 	const struct bpf_kfunc_desc *res;
3401 	struct bpf_kfunc_desc_tab *tab;
3402 
3403 	tab = prog->aux->kfunc_tab;
3404 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3405 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3406 
3407 	return res ? &res->func_model : NULL;
3408 }
3409 
3410 static int add_kfunc_in_insns(struct bpf_verifier_env *env,
3411 			      struct bpf_insn *insn, int cnt)
3412 {
3413 	int i, ret;
3414 
3415 	for (i = 0; i < cnt; i++, insn++) {
3416 		if (bpf_pseudo_kfunc_call(insn)) {
3417 			ret = add_kfunc_call(env, insn->imm, insn->off);
3418 			if (ret < 0)
3419 				return ret;
3420 		}
3421 	}
3422 	return 0;
3423 }
3424 
3425 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3426 {
3427 	struct bpf_subprog_info *subprog = env->subprog_info;
3428 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3429 	struct bpf_insn *insn = env->prog->insnsi;
3430 
3431 	/* Add entry function. */
3432 	ret = add_subprog(env, 0);
3433 	if (ret)
3434 		return ret;
3435 
3436 	for (i = 0; i < insn_cnt; i++, insn++) {
3437 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3438 		    !bpf_pseudo_kfunc_call(insn))
3439 			continue;
3440 
3441 		if (!env->bpf_capable) {
3442 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3443 			return -EPERM;
3444 		}
3445 
3446 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3447 			ret = add_subprog(env, i + insn->imm + 1);
3448 		else
3449 			ret = add_kfunc_call(env, insn->imm, insn->off);
3450 
3451 		if (ret < 0)
3452 			return ret;
3453 	}
3454 
3455 	ret = bpf_find_exception_callback_insn_off(env);
3456 	if (ret < 0)
3457 		return ret;
3458 	ex_cb_insn = ret;
3459 
3460 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3461 	 * marked using BTF decl tag to serve as the exception callback.
3462 	 */
3463 	if (ex_cb_insn) {
3464 		ret = add_subprog(env, ex_cb_insn);
3465 		if (ret < 0)
3466 			return ret;
3467 		for (i = 1; i < env->subprog_cnt; i++) {
3468 			if (env->subprog_info[i].start != ex_cb_insn)
3469 				continue;
3470 			env->exception_callback_subprog = i;
3471 			mark_subprog_exc_cb(env, i);
3472 			break;
3473 		}
3474 	}
3475 
3476 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3477 	 * logic. 'subprog_cnt' should not be increased.
3478 	 */
3479 	subprog[env->subprog_cnt].start = insn_cnt;
3480 
3481 	if (env->log.level & BPF_LOG_LEVEL2)
3482 		for (i = 0; i < env->subprog_cnt; i++)
3483 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3484 
3485 	return 0;
3486 }
3487 
3488 static int check_subprogs(struct bpf_verifier_env *env)
3489 {
3490 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3491 	struct bpf_subprog_info *subprog = env->subprog_info;
3492 	struct bpf_insn *insn = env->prog->insnsi;
3493 	int insn_cnt = env->prog->len;
3494 
3495 	/* now check that all jumps are within the same subprog */
3496 	subprog_start = subprog[cur_subprog].start;
3497 	subprog_end = subprog[cur_subprog + 1].start;
3498 	for (i = 0; i < insn_cnt; i++) {
3499 		u8 code = insn[i].code;
3500 
3501 		if (code == (BPF_JMP | BPF_CALL) &&
3502 		    insn[i].src_reg == 0 &&
3503 		    insn[i].imm == BPF_FUNC_tail_call) {
3504 			subprog[cur_subprog].has_tail_call = true;
3505 			subprog[cur_subprog].tail_call_reachable = true;
3506 		}
3507 		if (BPF_CLASS(code) == BPF_LD &&
3508 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3509 			subprog[cur_subprog].has_ld_abs = true;
3510 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3511 			goto next;
3512 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3513 			goto next;
3514 		off = i + bpf_jmp_offset(&insn[i]) + 1;
3515 		if (off < subprog_start || off >= subprog_end) {
3516 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3517 			return -EINVAL;
3518 		}
3519 next:
3520 		if (i == subprog_end - 1) {
3521 			/* to avoid fall-through from one subprog into another
3522 			 * the last insn of the subprog should be either exit
3523 			 * or unconditional jump back or bpf_throw call
3524 			 */
3525 			if (code != (BPF_JMP | BPF_EXIT) &&
3526 			    code != (BPF_JMP32 | BPF_JA) &&
3527 			    code != (BPF_JMP | BPF_JA)) {
3528 				verbose(env, "last insn is not an exit or jmp\n");
3529 				return -EINVAL;
3530 			}
3531 			subprog_start = subprog_end;
3532 			cur_subprog++;
3533 			if (cur_subprog < env->subprog_cnt)
3534 				subprog_end = subprog[cur_subprog + 1].start;
3535 		}
3536 	}
3537 	return 0;
3538 }
3539 
3540 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3541 				    int spi, int nr_slots)
3542 {
3543 	int err, i;
3544 
3545 	for (i = 0; i < nr_slots; i++) {
3546 		err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi - i));
3547 		if (err)
3548 			return err;
3549 		mark_stack_slot_scratched(env, spi - i);
3550 	}
3551 	return 0;
3552 }
3553 
3554 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3555 {
3556 	int spi;
3557 
3558 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3559 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3560 	 * check_kfunc_call.
3561 	 */
3562 	if (reg->type == CONST_PTR_TO_DYNPTR)
3563 		return 0;
3564 	spi = dynptr_get_spi(env, reg);
3565 	if (spi < 0)
3566 		return spi;
3567 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3568 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3569 	 * read.
3570 	 */
3571 	return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS);
3572 }
3573 
3574 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3575 			  int spi, int nr_slots)
3576 {
3577 	return mark_stack_slot_obj_read(env, reg, spi, nr_slots);
3578 }
3579 
3580 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3581 {
3582 	int spi;
3583 
3584 	spi = irq_flag_get_spi(env, reg);
3585 	if (spi < 0)
3586 		return spi;
3587 	return mark_stack_slot_obj_read(env, reg, spi, 1);
3588 }
3589 
3590 /* This function is supposed to be used by the following 32-bit optimization
3591  * code only. It returns TRUE if the source or destination register operates
3592  * on 64-bit, otherwise return FALSE.
3593  */
3594 static bool is_reg64(struct bpf_insn *insn,
3595 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3596 {
3597 	u8 code, class, op;
3598 
3599 	code = insn->code;
3600 	class = BPF_CLASS(code);
3601 	op = BPF_OP(code);
3602 	if (class == BPF_JMP) {
3603 		/* BPF_EXIT for "main" will reach here. Return TRUE
3604 		 * conservatively.
3605 		 */
3606 		if (op == BPF_EXIT)
3607 			return true;
3608 		if (op == BPF_CALL) {
3609 			/* BPF to BPF call will reach here because of marking
3610 			 * caller saved clobber with DST_OP_NO_MARK for which we
3611 			 * don't care the register def because they are anyway
3612 			 * marked as NOT_INIT already.
3613 			 */
3614 			if (insn->src_reg == BPF_PSEUDO_CALL)
3615 				return false;
3616 			/* Helper call will reach here because of arg type
3617 			 * check, conservatively return TRUE.
3618 			 */
3619 			if (t == SRC_OP)
3620 				return true;
3621 
3622 			return false;
3623 		}
3624 	}
3625 
3626 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3627 		return false;
3628 
3629 	if (class == BPF_ALU64 || class == BPF_JMP ||
3630 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3631 		return true;
3632 
3633 	if (class == BPF_ALU || class == BPF_JMP32)
3634 		return false;
3635 
3636 	if (class == BPF_LDX) {
3637 		if (t != SRC_OP)
3638 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3639 		/* LDX source must be ptr. */
3640 		return true;
3641 	}
3642 
3643 	if (class == BPF_STX) {
3644 		/* BPF_STX (including atomic variants) has one or more source
3645 		 * operands, one of which is a ptr. Check whether the caller is
3646 		 * asking about it.
3647 		 */
3648 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3649 			return true;
3650 		return BPF_SIZE(code) == BPF_DW;
3651 	}
3652 
3653 	if (class == BPF_LD) {
3654 		u8 mode = BPF_MODE(code);
3655 
3656 		/* LD_IMM64 */
3657 		if (mode == BPF_IMM)
3658 			return true;
3659 
3660 		/* Both LD_IND and LD_ABS return 32-bit data. */
3661 		if (t != SRC_OP)
3662 			return  false;
3663 
3664 		/* Implicit ctx ptr. */
3665 		if (regno == BPF_REG_6)
3666 			return true;
3667 
3668 		/* Explicit source could be any width. */
3669 		return true;
3670 	}
3671 
3672 	if (class == BPF_ST)
3673 		/* The only source register for BPF_ST is a ptr. */
3674 		return true;
3675 
3676 	/* Conservatively return true at default. */
3677 	return true;
3678 }
3679 
3680 /* Return the regno defined by the insn, or -1. */
3681 static int insn_def_regno(const struct bpf_insn *insn)
3682 {
3683 	switch (BPF_CLASS(insn->code)) {
3684 	case BPF_JMP:
3685 	case BPF_JMP32:
3686 	case BPF_ST:
3687 		return -1;
3688 	case BPF_STX:
3689 		if (BPF_MODE(insn->code) == BPF_ATOMIC ||
3690 		    BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) {
3691 			if (insn->imm == BPF_CMPXCHG)
3692 				return BPF_REG_0;
3693 			else if (insn->imm == BPF_LOAD_ACQ)
3694 				return insn->dst_reg;
3695 			else if (insn->imm & BPF_FETCH)
3696 				return insn->src_reg;
3697 		}
3698 		return -1;
3699 	default:
3700 		return insn->dst_reg;
3701 	}
3702 }
3703 
3704 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3705 static bool insn_has_def32(struct bpf_insn *insn)
3706 {
3707 	int dst_reg = insn_def_regno(insn);
3708 
3709 	if (dst_reg == -1)
3710 		return false;
3711 
3712 	return !is_reg64(insn, dst_reg, NULL, DST_OP);
3713 }
3714 
3715 static void mark_insn_zext(struct bpf_verifier_env *env,
3716 			   struct bpf_reg_state *reg)
3717 {
3718 	s32 def_idx = reg->subreg_def;
3719 
3720 	if (def_idx == DEF_NOT_SUBREG)
3721 		return;
3722 
3723 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3724 	/* The dst will be zero extended, so won't be sub-register anymore. */
3725 	reg->subreg_def = DEF_NOT_SUBREG;
3726 }
3727 
3728 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3729 			   enum reg_arg_type t)
3730 {
3731 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3732 	struct bpf_reg_state *reg;
3733 	bool rw64;
3734 
3735 	if (regno >= MAX_BPF_REG) {
3736 		verbose(env, "R%d is invalid\n", regno);
3737 		return -EINVAL;
3738 	}
3739 
3740 	mark_reg_scratched(env, regno);
3741 
3742 	reg = &regs[regno];
3743 	rw64 = is_reg64(insn, regno, reg, t);
3744 	if (t == SRC_OP) {
3745 		/* check whether register used as source operand can be read */
3746 		if (reg->type == NOT_INIT) {
3747 			verbose(env, "R%d !read_ok\n", regno);
3748 			return -EACCES;
3749 		}
3750 		/* We don't need to worry about FP liveness because it's read-only */
3751 		if (regno == BPF_REG_FP)
3752 			return 0;
3753 
3754 		if (rw64)
3755 			mark_insn_zext(env, reg);
3756 
3757 		return 0;
3758 	} else {
3759 		/* check whether register used as dest operand can be written to */
3760 		if (regno == BPF_REG_FP) {
3761 			verbose(env, "frame pointer is read only\n");
3762 			return -EACCES;
3763 		}
3764 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3765 		if (t == DST_OP)
3766 			mark_reg_unknown(env, regs, regno);
3767 	}
3768 	return 0;
3769 }
3770 
3771 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3772 			 enum reg_arg_type t)
3773 {
3774 	struct bpf_verifier_state *vstate = env->cur_state;
3775 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3776 
3777 	return __check_reg_arg(env, state->regs, regno, t);
3778 }
3779 
3780 static int insn_stack_access_flags(int frameno, int spi)
3781 {
3782 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3783 }
3784 
3785 static int insn_stack_access_spi(int insn_flags)
3786 {
3787 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3788 }
3789 
3790 static int insn_stack_access_frameno(int insn_flags)
3791 {
3792 	return insn_flags & INSN_F_FRAMENO_MASK;
3793 }
3794 
3795 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3796 {
3797 	env->insn_aux_data[idx].jmp_point = true;
3798 }
3799 
3800 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3801 {
3802 	return env->insn_aux_data[insn_idx].jmp_point;
3803 }
3804 
3805 #define LR_FRAMENO_BITS	3
3806 #define LR_SPI_BITS	6
3807 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3808 #define LR_SIZE_BITS	4
3809 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3810 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3811 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3812 #define LR_SPI_OFF	LR_FRAMENO_BITS
3813 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3814 #define LINKED_REGS_MAX	6
3815 
3816 struct linked_reg {
3817 	u8 frameno;
3818 	union {
3819 		u8 spi;
3820 		u8 regno;
3821 	};
3822 	bool is_reg;
3823 };
3824 
3825 struct linked_regs {
3826 	int cnt;
3827 	struct linked_reg entries[LINKED_REGS_MAX];
3828 };
3829 
3830 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3831 {
3832 	if (s->cnt < LINKED_REGS_MAX)
3833 		return &s->entries[s->cnt++];
3834 
3835 	return NULL;
3836 }
3837 
3838 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3839  * number of elements currently in stack.
3840  * Pack one history entry for linked registers as 10 bits in the following format:
3841  * - 3-bits frameno
3842  * - 6-bits spi_or_reg
3843  * - 1-bit  is_reg
3844  */
3845 static u64 linked_regs_pack(struct linked_regs *s)
3846 {
3847 	u64 val = 0;
3848 	int i;
3849 
3850 	for (i = 0; i < s->cnt; ++i) {
3851 		struct linked_reg *e = &s->entries[i];
3852 		u64 tmp = 0;
3853 
3854 		tmp |= e->frameno;
3855 		tmp |= e->spi << LR_SPI_OFF;
3856 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3857 
3858 		val <<= LR_ENTRY_BITS;
3859 		val |= tmp;
3860 	}
3861 	val <<= LR_SIZE_BITS;
3862 	val |= s->cnt;
3863 	return val;
3864 }
3865 
3866 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3867 {
3868 	int i;
3869 
3870 	s->cnt = val & LR_SIZE_MASK;
3871 	val >>= LR_SIZE_BITS;
3872 
3873 	for (i = 0; i < s->cnt; ++i) {
3874 		struct linked_reg *e = &s->entries[i];
3875 
3876 		e->frameno =  val & LR_FRAMENO_MASK;
3877 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3878 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3879 		val >>= LR_ENTRY_BITS;
3880 	}
3881 }
3882 
3883 /* for any branch, call, exit record the history of jmps in the given state */
3884 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3885 			    int insn_flags, u64 linked_regs)
3886 {
3887 	u32 cnt = cur->jmp_history_cnt;
3888 	struct bpf_jmp_history_entry *p;
3889 	size_t alloc_size;
3890 
3891 	/* combine instruction flags if we already recorded this instruction */
3892 	if (env->cur_hist_ent) {
3893 		/* atomic instructions push insn_flags twice, for READ and
3894 		 * WRITE sides, but they should agree on stack slot
3895 		 */
3896 		verifier_bug_if((env->cur_hist_ent->flags & insn_flags) &&
3897 				(env->cur_hist_ent->flags & insn_flags) != insn_flags,
3898 				env, "insn history: insn_idx %d cur flags %x new flags %x",
3899 				env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3900 		env->cur_hist_ent->flags |= insn_flags;
3901 		verifier_bug_if(env->cur_hist_ent->linked_regs != 0, env,
3902 				"insn history: insn_idx %d linked_regs: %#llx",
3903 				env->insn_idx, env->cur_hist_ent->linked_regs);
3904 		env->cur_hist_ent->linked_regs = linked_regs;
3905 		return 0;
3906 	}
3907 
3908 	cnt++;
3909 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3910 	p = krealloc(cur->jmp_history, alloc_size, GFP_KERNEL_ACCOUNT);
3911 	if (!p)
3912 		return -ENOMEM;
3913 	cur->jmp_history = p;
3914 
3915 	p = &cur->jmp_history[cnt - 1];
3916 	p->idx = env->insn_idx;
3917 	p->prev_idx = env->prev_insn_idx;
3918 	p->flags = insn_flags;
3919 	p->linked_regs = linked_regs;
3920 	cur->jmp_history_cnt = cnt;
3921 	env->cur_hist_ent = p;
3922 
3923 	return 0;
3924 }
3925 
3926 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3927 						        u32 hist_end, int insn_idx)
3928 {
3929 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3930 		return &st->jmp_history[hist_end - 1];
3931 	return NULL;
3932 }
3933 
3934 /* Backtrack one insn at a time. If idx is not at the top of recorded
3935  * history then previous instruction came from straight line execution.
3936  * Return -ENOENT if we exhausted all instructions within given state.
3937  *
3938  * It's legal to have a bit of a looping with the same starting and ending
3939  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3940  * instruction index is the same as state's first_idx doesn't mean we are
3941  * done. If there is still some jump history left, we should keep going. We
3942  * need to take into account that we might have a jump history between given
3943  * state's parent and itself, due to checkpointing. In this case, we'll have
3944  * history entry recording a jump from last instruction of parent state and
3945  * first instruction of given state.
3946  */
3947 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3948 			     u32 *history)
3949 {
3950 	u32 cnt = *history;
3951 
3952 	if (i == st->first_insn_idx) {
3953 		if (cnt == 0)
3954 			return -ENOENT;
3955 		if (cnt == 1 && st->jmp_history[0].idx == i)
3956 			return -ENOENT;
3957 	}
3958 
3959 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3960 		i = st->jmp_history[cnt - 1].prev_idx;
3961 		(*history)--;
3962 	} else {
3963 		i--;
3964 	}
3965 	return i;
3966 }
3967 
3968 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3969 {
3970 	const struct btf_type *func;
3971 	struct btf *desc_btf;
3972 
3973 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3974 		return NULL;
3975 
3976 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3977 	if (IS_ERR(desc_btf))
3978 		return "<error>";
3979 
3980 	func = btf_type_by_id(desc_btf, insn->imm);
3981 	return btf_name_by_offset(desc_btf, func->name_off);
3982 }
3983 
3984 static void verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
3985 {
3986 	const struct bpf_insn_cbs cbs = {
3987 		.cb_call	= disasm_kfunc_name,
3988 		.cb_print	= verbose,
3989 		.private_data	= env,
3990 	};
3991 
3992 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3993 }
3994 
3995 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3996 {
3997 	bt->frame = frame;
3998 }
3999 
4000 static inline void bt_reset(struct backtrack_state *bt)
4001 {
4002 	struct bpf_verifier_env *env = bt->env;
4003 
4004 	memset(bt, 0, sizeof(*bt));
4005 	bt->env = env;
4006 }
4007 
4008 static inline u32 bt_empty(struct backtrack_state *bt)
4009 {
4010 	u64 mask = 0;
4011 	int i;
4012 
4013 	for (i = 0; i <= bt->frame; i++)
4014 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
4015 
4016 	return mask == 0;
4017 }
4018 
4019 static inline int bt_subprog_enter(struct backtrack_state *bt)
4020 {
4021 	if (bt->frame == MAX_CALL_FRAMES - 1) {
4022 		verifier_bug(bt->env, "subprog enter from frame %d", bt->frame);
4023 		return -EFAULT;
4024 	}
4025 	bt->frame++;
4026 	return 0;
4027 }
4028 
4029 static inline int bt_subprog_exit(struct backtrack_state *bt)
4030 {
4031 	if (bt->frame == 0) {
4032 		verifier_bug(bt->env, "subprog exit from frame 0");
4033 		return -EFAULT;
4034 	}
4035 	bt->frame--;
4036 	return 0;
4037 }
4038 
4039 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4040 {
4041 	bt->reg_masks[frame] |= 1 << reg;
4042 }
4043 
4044 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4045 {
4046 	bt->reg_masks[frame] &= ~(1 << reg);
4047 }
4048 
4049 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
4050 {
4051 	bt_set_frame_reg(bt, bt->frame, reg);
4052 }
4053 
4054 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
4055 {
4056 	bt_clear_frame_reg(bt, bt->frame, reg);
4057 }
4058 
4059 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4060 {
4061 	bt->stack_masks[frame] |= 1ull << slot;
4062 }
4063 
4064 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4065 {
4066 	bt->stack_masks[frame] &= ~(1ull << slot);
4067 }
4068 
4069 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
4070 {
4071 	return bt->reg_masks[frame];
4072 }
4073 
4074 static inline u32 bt_reg_mask(struct backtrack_state *bt)
4075 {
4076 	return bt->reg_masks[bt->frame];
4077 }
4078 
4079 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
4080 {
4081 	return bt->stack_masks[frame];
4082 }
4083 
4084 static inline u64 bt_stack_mask(struct backtrack_state *bt)
4085 {
4086 	return bt->stack_masks[bt->frame];
4087 }
4088 
4089 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
4090 {
4091 	return bt->reg_masks[bt->frame] & (1 << reg);
4092 }
4093 
4094 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
4095 {
4096 	return bt->reg_masks[frame] & (1 << reg);
4097 }
4098 
4099 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
4100 {
4101 	return bt->stack_masks[frame] & (1ull << slot);
4102 }
4103 
4104 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
4105 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
4106 {
4107 	DECLARE_BITMAP(mask, 64);
4108 	bool first = true;
4109 	int i, n;
4110 
4111 	buf[0] = '\0';
4112 
4113 	bitmap_from_u64(mask, reg_mask);
4114 	for_each_set_bit(i, mask, 32) {
4115 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
4116 		first = false;
4117 		buf += n;
4118 		buf_sz -= n;
4119 		if (buf_sz < 0)
4120 			break;
4121 	}
4122 }
4123 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
4124 void bpf_fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
4125 {
4126 	DECLARE_BITMAP(mask, 64);
4127 	bool first = true;
4128 	int i, n;
4129 
4130 	buf[0] = '\0';
4131 
4132 	bitmap_from_u64(mask, stack_mask);
4133 	for_each_set_bit(i, mask, 64) {
4134 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
4135 		first = false;
4136 		buf += n;
4137 		buf_sz -= n;
4138 		if (buf_sz < 0)
4139 			break;
4140 	}
4141 }
4142 
4143 /* If any register R in hist->linked_regs is marked as precise in bt,
4144  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
4145  */
4146 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
4147 {
4148 	struct linked_regs linked_regs;
4149 	bool some_precise = false;
4150 	int i;
4151 
4152 	if (!hist || hist->linked_regs == 0)
4153 		return;
4154 
4155 	linked_regs_unpack(hist->linked_regs, &linked_regs);
4156 	for (i = 0; i < linked_regs.cnt; ++i) {
4157 		struct linked_reg *e = &linked_regs.entries[i];
4158 
4159 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
4160 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
4161 			some_precise = true;
4162 			break;
4163 		}
4164 	}
4165 
4166 	if (!some_precise)
4167 		return;
4168 
4169 	for (i = 0; i < linked_regs.cnt; ++i) {
4170 		struct linked_reg *e = &linked_regs.entries[i];
4171 
4172 		if (e->is_reg)
4173 			bt_set_frame_reg(bt, e->frameno, e->regno);
4174 		else
4175 			bt_set_frame_slot(bt, e->frameno, e->spi);
4176 	}
4177 }
4178 
4179 /* For given verifier state backtrack_insn() is called from the last insn to
4180  * the first insn. Its purpose is to compute a bitmask of registers and
4181  * stack slots that needs precision in the parent verifier state.
4182  *
4183  * @idx is an index of the instruction we are currently processing;
4184  * @subseq_idx is an index of the subsequent instruction that:
4185  *   - *would be* executed next, if jump history is viewed in forward order;
4186  *   - *was* processed previously during backtracking.
4187  */
4188 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
4189 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
4190 {
4191 	struct bpf_insn *insn = env->prog->insnsi + idx;
4192 	u8 class = BPF_CLASS(insn->code);
4193 	u8 opcode = BPF_OP(insn->code);
4194 	u8 mode = BPF_MODE(insn->code);
4195 	u32 dreg = insn->dst_reg;
4196 	u32 sreg = insn->src_reg;
4197 	u32 spi, i, fr;
4198 
4199 	if (insn->code == 0)
4200 		return 0;
4201 	if (env->log.level & BPF_LOG_LEVEL2) {
4202 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
4203 		verbose(env, "mark_precise: frame%d: regs=%s ",
4204 			bt->frame, env->tmp_str_buf);
4205 		bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
4206 		verbose(env, "stack=%s before ", env->tmp_str_buf);
4207 		verbose(env, "%d: ", idx);
4208 		verbose_insn(env, insn);
4209 	}
4210 
4211 	/* If there is a history record that some registers gained range at this insn,
4212 	 * propagate precision marks to those registers, so that bt_is_reg_set()
4213 	 * accounts for these registers.
4214 	 */
4215 	bt_sync_linked_regs(bt, hist);
4216 
4217 	if (class == BPF_ALU || class == BPF_ALU64) {
4218 		if (!bt_is_reg_set(bt, dreg))
4219 			return 0;
4220 		if (opcode == BPF_END || opcode == BPF_NEG) {
4221 			/* sreg is reserved and unused
4222 			 * dreg still need precision before this insn
4223 			 */
4224 			return 0;
4225 		} else if (opcode == BPF_MOV) {
4226 			if (BPF_SRC(insn->code) == BPF_X) {
4227 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
4228 				 * dreg needs precision after this insn
4229 				 * sreg needs precision before this insn
4230 				 */
4231 				bt_clear_reg(bt, dreg);
4232 				if (sreg != BPF_REG_FP)
4233 					bt_set_reg(bt, sreg);
4234 			} else {
4235 				/* dreg = K
4236 				 * dreg needs precision after this insn.
4237 				 * Corresponding register is already marked
4238 				 * as precise=true in this verifier state.
4239 				 * No further markings in parent are necessary
4240 				 */
4241 				bt_clear_reg(bt, dreg);
4242 			}
4243 		} else {
4244 			if (BPF_SRC(insn->code) == BPF_X) {
4245 				/* dreg += sreg
4246 				 * both dreg and sreg need precision
4247 				 * before this insn
4248 				 */
4249 				if (sreg != BPF_REG_FP)
4250 					bt_set_reg(bt, sreg);
4251 			} /* else dreg += K
4252 			   * dreg still needs precision before this insn
4253 			   */
4254 		}
4255 	} else if (class == BPF_LDX || is_atomic_load_insn(insn)) {
4256 		if (!bt_is_reg_set(bt, dreg))
4257 			return 0;
4258 		bt_clear_reg(bt, dreg);
4259 
4260 		/* scalars can only be spilled into stack w/o losing precision.
4261 		 * Load from any other memory can be zero extended.
4262 		 * The desire to keep that precision is already indicated
4263 		 * by 'precise' mark in corresponding register of this state.
4264 		 * No further tracking necessary.
4265 		 */
4266 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4267 			return 0;
4268 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
4269 		 * that [fp - off] slot contains scalar that needs to be
4270 		 * tracked with precision
4271 		 */
4272 		spi = insn_stack_access_spi(hist->flags);
4273 		fr = insn_stack_access_frameno(hist->flags);
4274 		bt_set_frame_slot(bt, fr, spi);
4275 	} else if (class == BPF_STX || class == BPF_ST) {
4276 		if (bt_is_reg_set(bt, dreg))
4277 			/* stx & st shouldn't be using _scalar_ dst_reg
4278 			 * to access memory. It means backtracking
4279 			 * encountered a case of pointer subtraction.
4280 			 */
4281 			return -ENOTSUPP;
4282 		/* scalars can only be spilled into stack */
4283 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4284 			return 0;
4285 		spi = insn_stack_access_spi(hist->flags);
4286 		fr = insn_stack_access_frameno(hist->flags);
4287 		if (!bt_is_frame_slot_set(bt, fr, spi))
4288 			return 0;
4289 		bt_clear_frame_slot(bt, fr, spi);
4290 		if (class == BPF_STX)
4291 			bt_set_reg(bt, sreg);
4292 	} else if (class == BPF_JMP || class == BPF_JMP32) {
4293 		if (bpf_pseudo_call(insn)) {
4294 			int subprog_insn_idx, subprog;
4295 
4296 			subprog_insn_idx = idx + insn->imm + 1;
4297 			subprog = find_subprog(env, subprog_insn_idx);
4298 			if (subprog < 0)
4299 				return -EFAULT;
4300 
4301 			if (subprog_is_global(env, subprog)) {
4302 				/* check that jump history doesn't have any
4303 				 * extra instructions from subprog; the next
4304 				 * instruction after call to global subprog
4305 				 * should be literally next instruction in
4306 				 * caller program
4307 				 */
4308 				verifier_bug_if(idx + 1 != subseq_idx, env,
4309 						"extra insn from subprog");
4310 				/* r1-r5 are invalidated after subprog call,
4311 				 * so for global func call it shouldn't be set
4312 				 * anymore
4313 				 */
4314 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4315 					verifier_bug(env, "global subprog unexpected regs %x",
4316 						     bt_reg_mask(bt));
4317 					return -EFAULT;
4318 				}
4319 				/* global subprog always sets R0 */
4320 				bt_clear_reg(bt, BPF_REG_0);
4321 				return 0;
4322 			} else {
4323 				/* static subprog call instruction, which
4324 				 * means that we are exiting current subprog,
4325 				 * so only r1-r5 could be still requested as
4326 				 * precise, r0 and r6-r10 or any stack slot in
4327 				 * the current frame should be zero by now
4328 				 */
4329 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4330 					verifier_bug(env, "static subprog unexpected regs %x",
4331 						     bt_reg_mask(bt));
4332 					return -EFAULT;
4333 				}
4334 				/* we are now tracking register spills correctly,
4335 				 * so any instance of leftover slots is a bug
4336 				 */
4337 				if (bt_stack_mask(bt) != 0) {
4338 					verifier_bug(env,
4339 						     "static subprog leftover stack slots %llx",
4340 						     bt_stack_mask(bt));
4341 					return -EFAULT;
4342 				}
4343 				/* propagate r1-r5 to the caller */
4344 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
4345 					if (bt_is_reg_set(bt, i)) {
4346 						bt_clear_reg(bt, i);
4347 						bt_set_frame_reg(bt, bt->frame - 1, i);
4348 					}
4349 				}
4350 				if (bt_subprog_exit(bt))
4351 					return -EFAULT;
4352 				return 0;
4353 			}
4354 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
4355 			/* exit from callback subprog to callback-calling helper or
4356 			 * kfunc call. Use idx/subseq_idx check to discern it from
4357 			 * straight line code backtracking.
4358 			 * Unlike the subprog call handling above, we shouldn't
4359 			 * propagate precision of r1-r5 (if any requested), as they are
4360 			 * not actually arguments passed directly to callback subprogs
4361 			 */
4362 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4363 				verifier_bug(env, "callback unexpected regs %x",
4364 					     bt_reg_mask(bt));
4365 				return -EFAULT;
4366 			}
4367 			if (bt_stack_mask(bt) != 0) {
4368 				verifier_bug(env, "callback leftover stack slots %llx",
4369 					     bt_stack_mask(bt));
4370 				return -EFAULT;
4371 			}
4372 			/* clear r1-r5 in callback subprog's mask */
4373 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4374 				bt_clear_reg(bt, i);
4375 			if (bt_subprog_exit(bt))
4376 				return -EFAULT;
4377 			return 0;
4378 		} else if (opcode == BPF_CALL) {
4379 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
4380 			 * catch this error later. Make backtracking conservative
4381 			 * with ENOTSUPP.
4382 			 */
4383 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
4384 				return -ENOTSUPP;
4385 			/* regular helper call sets R0 */
4386 			bt_clear_reg(bt, BPF_REG_0);
4387 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4388 				/* if backtracking was looking for registers R1-R5
4389 				 * they should have been found already.
4390 				 */
4391 				verifier_bug(env, "backtracking call unexpected regs %x",
4392 					     bt_reg_mask(bt));
4393 				return -EFAULT;
4394 			}
4395 		} else if (opcode == BPF_EXIT) {
4396 			bool r0_precise;
4397 
4398 			/* Backtracking to a nested function call, 'idx' is a part of
4399 			 * the inner frame 'subseq_idx' is a part of the outer frame.
4400 			 * In case of a regular function call, instructions giving
4401 			 * precision to registers R1-R5 should have been found already.
4402 			 * In case of a callback, it is ok to have R1-R5 marked for
4403 			 * backtracking, as these registers are set by the function
4404 			 * invoking callback.
4405 			 */
4406 			if (subseq_idx >= 0 && bpf_calls_callback(env, subseq_idx))
4407 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4408 					bt_clear_reg(bt, i);
4409 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4410 				verifier_bug(env, "backtracking exit unexpected regs %x",
4411 					     bt_reg_mask(bt));
4412 				return -EFAULT;
4413 			}
4414 
4415 			/* BPF_EXIT in subprog or callback always returns
4416 			 * right after the call instruction, so by checking
4417 			 * whether the instruction at subseq_idx-1 is subprog
4418 			 * call or not we can distinguish actual exit from
4419 			 * *subprog* from exit from *callback*. In the former
4420 			 * case, we need to propagate r0 precision, if
4421 			 * necessary. In the former we never do that.
4422 			 */
4423 			r0_precise = subseq_idx - 1 >= 0 &&
4424 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4425 				     bt_is_reg_set(bt, BPF_REG_0);
4426 
4427 			bt_clear_reg(bt, BPF_REG_0);
4428 			if (bt_subprog_enter(bt))
4429 				return -EFAULT;
4430 
4431 			if (r0_precise)
4432 				bt_set_reg(bt, BPF_REG_0);
4433 			/* r6-r9 and stack slots will stay set in caller frame
4434 			 * bitmasks until we return back from callee(s)
4435 			 */
4436 			return 0;
4437 		} else if (BPF_SRC(insn->code) == BPF_X) {
4438 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4439 				return 0;
4440 			/* dreg <cond> sreg
4441 			 * Both dreg and sreg need precision before
4442 			 * this insn. If only sreg was marked precise
4443 			 * before it would be equally necessary to
4444 			 * propagate it to dreg.
4445 			 */
4446 			if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK))
4447 				bt_set_reg(bt, sreg);
4448 			if (!hist || !(hist->flags & INSN_F_DST_REG_STACK))
4449 				bt_set_reg(bt, dreg);
4450 		} else if (BPF_SRC(insn->code) == BPF_K) {
4451 			 /* dreg <cond> K
4452 			  * Only dreg still needs precision before
4453 			  * this insn, so for the K-based conditional
4454 			  * there is nothing new to be marked.
4455 			  */
4456 		}
4457 	} else if (class == BPF_LD) {
4458 		if (!bt_is_reg_set(bt, dreg))
4459 			return 0;
4460 		bt_clear_reg(bt, dreg);
4461 		/* It's ld_imm64 or ld_abs or ld_ind.
4462 		 * For ld_imm64 no further tracking of precision
4463 		 * into parent is necessary
4464 		 */
4465 		if (mode == BPF_IND || mode == BPF_ABS)
4466 			/* to be analyzed */
4467 			return -ENOTSUPP;
4468 	}
4469 	/* Propagate precision marks to linked registers, to account for
4470 	 * registers marked as precise in this function.
4471 	 */
4472 	bt_sync_linked_regs(bt, hist);
4473 	return 0;
4474 }
4475 
4476 /* the scalar precision tracking algorithm:
4477  * . at the start all registers have precise=false.
4478  * . scalar ranges are tracked as normal through alu and jmp insns.
4479  * . once precise value of the scalar register is used in:
4480  *   .  ptr + scalar alu
4481  *   . if (scalar cond K|scalar)
4482  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
4483  *   backtrack through the verifier states and mark all registers and
4484  *   stack slots with spilled constants that these scalar registers
4485  *   should be precise.
4486  * . during state pruning two registers (or spilled stack slots)
4487  *   are equivalent if both are not precise.
4488  *
4489  * Note the verifier cannot simply walk register parentage chain,
4490  * since many different registers and stack slots could have been
4491  * used to compute single precise scalar.
4492  *
4493  * The approach of starting with precise=true for all registers and then
4494  * backtrack to mark a register as not precise when the verifier detects
4495  * that program doesn't care about specific value (e.g., when helper
4496  * takes register as ARG_ANYTHING parameter) is not safe.
4497  *
4498  * It's ok to walk single parentage chain of the verifier states.
4499  * It's possible that this backtracking will go all the way till 1st insn.
4500  * All other branches will be explored for needing precision later.
4501  *
4502  * The backtracking needs to deal with cases like:
4503  *   R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
4504  * r9 -= r8
4505  * r5 = r9
4506  * if r5 > 0x79f goto pc+7
4507  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4508  * r5 += 1
4509  * ...
4510  * call bpf_perf_event_output#25
4511  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4512  *
4513  * and this case:
4514  * r6 = 1
4515  * call foo // uses callee's r6 inside to compute r0
4516  * r0 += r6
4517  * if r0 == 0 goto
4518  *
4519  * to track above reg_mask/stack_mask needs to be independent for each frame.
4520  *
4521  * Also if parent's curframe > frame where backtracking started,
4522  * the verifier need to mark registers in both frames, otherwise callees
4523  * may incorrectly prune callers. This is similar to
4524  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4525  *
4526  * For now backtracking falls back into conservative marking.
4527  */
4528 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4529 				     struct bpf_verifier_state *st)
4530 {
4531 	struct bpf_func_state *func;
4532 	struct bpf_reg_state *reg;
4533 	int i, j;
4534 
4535 	if (env->log.level & BPF_LOG_LEVEL2) {
4536 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4537 			st->curframe);
4538 	}
4539 
4540 	/* big hammer: mark all scalars precise in this path.
4541 	 * pop_stack may still get !precise scalars.
4542 	 * We also skip current state and go straight to first parent state,
4543 	 * because precision markings in current non-checkpointed state are
4544 	 * not needed. See why in the comment in __mark_chain_precision below.
4545 	 */
4546 	for (st = st->parent; st; st = st->parent) {
4547 		for (i = 0; i <= st->curframe; i++) {
4548 			func = st->frame[i];
4549 			for (j = 0; j < BPF_REG_FP; j++) {
4550 				reg = &func->regs[j];
4551 				if (reg->type != SCALAR_VALUE || reg->precise)
4552 					continue;
4553 				reg->precise = true;
4554 				if (env->log.level & BPF_LOG_LEVEL2) {
4555 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4556 						i, j);
4557 				}
4558 			}
4559 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4560 				if (!is_spilled_reg(&func->stack[j]))
4561 					continue;
4562 				reg = &func->stack[j].spilled_ptr;
4563 				if (reg->type != SCALAR_VALUE || reg->precise)
4564 					continue;
4565 				reg->precise = true;
4566 				if (env->log.level & BPF_LOG_LEVEL2) {
4567 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4568 						i, -(j + 1) * 8);
4569 				}
4570 			}
4571 		}
4572 	}
4573 }
4574 
4575 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4576 {
4577 	struct bpf_func_state *func;
4578 	struct bpf_reg_state *reg;
4579 	int i, j;
4580 
4581 	for (i = 0; i <= st->curframe; i++) {
4582 		func = st->frame[i];
4583 		for (j = 0; j < BPF_REG_FP; j++) {
4584 			reg = &func->regs[j];
4585 			if (reg->type != SCALAR_VALUE)
4586 				continue;
4587 			reg->precise = false;
4588 		}
4589 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4590 			if (!is_spilled_reg(&func->stack[j]))
4591 				continue;
4592 			reg = &func->stack[j].spilled_ptr;
4593 			if (reg->type != SCALAR_VALUE)
4594 				continue;
4595 			reg->precise = false;
4596 		}
4597 	}
4598 }
4599 
4600 /*
4601  * __mark_chain_precision() backtracks BPF program instruction sequence and
4602  * chain of verifier states making sure that register *regno* (if regno >= 0)
4603  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4604  * SCALARS, as well as any other registers and slots that contribute to
4605  * a tracked state of given registers/stack slots, depending on specific BPF
4606  * assembly instructions (see backtrack_insns() for exact instruction handling
4607  * logic). This backtracking relies on recorded jmp_history and is able to
4608  * traverse entire chain of parent states. This process ends only when all the
4609  * necessary registers/slots and their transitive dependencies are marked as
4610  * precise.
4611  *
4612  * One important and subtle aspect is that precise marks *do not matter* in
4613  * the currently verified state (current state). It is important to understand
4614  * why this is the case.
4615  *
4616  * First, note that current state is the state that is not yet "checkpointed",
4617  * i.e., it is not yet put into env->explored_states, and it has no children
4618  * states as well. It's ephemeral, and can end up either a) being discarded if
4619  * compatible explored state is found at some point or BPF_EXIT instruction is
4620  * reached or b) checkpointed and put into env->explored_states, branching out
4621  * into one or more children states.
4622  *
4623  * In the former case, precise markings in current state are completely
4624  * ignored by state comparison code (see regsafe() for details). Only
4625  * checkpointed ("old") state precise markings are important, and if old
4626  * state's register/slot is precise, regsafe() assumes current state's
4627  * register/slot as precise and checks value ranges exactly and precisely. If
4628  * states turn out to be compatible, current state's necessary precise
4629  * markings and any required parent states' precise markings are enforced
4630  * after the fact with propagate_precision() logic, after the fact. But it's
4631  * important to realize that in this case, even after marking current state
4632  * registers/slots as precise, we immediately discard current state. So what
4633  * actually matters is any of the precise markings propagated into current
4634  * state's parent states, which are always checkpointed (due to b) case above).
4635  * As such, for scenario a) it doesn't matter if current state has precise
4636  * markings set or not.
4637  *
4638  * Now, for the scenario b), checkpointing and forking into child(ren)
4639  * state(s). Note that before current state gets to checkpointing step, any
4640  * processed instruction always assumes precise SCALAR register/slot
4641  * knowledge: if precise value or range is useful to prune jump branch, BPF
4642  * verifier takes this opportunity enthusiastically. Similarly, when
4643  * register's value is used to calculate offset or memory address, exact
4644  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4645  * what we mentioned above about state comparison ignoring precise markings
4646  * during state comparison, BPF verifier ignores and also assumes precise
4647  * markings *at will* during instruction verification process. But as verifier
4648  * assumes precision, it also propagates any precision dependencies across
4649  * parent states, which are not yet finalized, so can be further restricted
4650  * based on new knowledge gained from restrictions enforced by their children
4651  * states. This is so that once those parent states are finalized, i.e., when
4652  * they have no more active children state, state comparison logic in
4653  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4654  * required for correctness.
4655  *
4656  * To build a bit more intuition, note also that once a state is checkpointed,
4657  * the path we took to get to that state is not important. This is crucial
4658  * property for state pruning. When state is checkpointed and finalized at
4659  * some instruction index, it can be correctly and safely used to "short
4660  * circuit" any *compatible* state that reaches exactly the same instruction
4661  * index. I.e., if we jumped to that instruction from a completely different
4662  * code path than original finalized state was derived from, it doesn't
4663  * matter, current state can be discarded because from that instruction
4664  * forward having a compatible state will ensure we will safely reach the
4665  * exit. States describe preconditions for further exploration, but completely
4666  * forget the history of how we got here.
4667  *
4668  * This also means that even if we needed precise SCALAR range to get to
4669  * finalized state, but from that point forward *that same* SCALAR register is
4670  * never used in a precise context (i.e., it's precise value is not needed for
4671  * correctness), it's correct and safe to mark such register as "imprecise"
4672  * (i.e., precise marking set to false). This is what we rely on when we do
4673  * not set precise marking in current state. If no child state requires
4674  * precision for any given SCALAR register, it's safe to dictate that it can
4675  * be imprecise. If any child state does require this register to be precise,
4676  * we'll mark it precise later retroactively during precise markings
4677  * propagation from child state to parent states.
4678  *
4679  * Skipping precise marking setting in current state is a mild version of
4680  * relying on the above observation. But we can utilize this property even
4681  * more aggressively by proactively forgetting any precise marking in the
4682  * current state (which we inherited from the parent state), right before we
4683  * checkpoint it and branch off into new child state. This is done by
4684  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4685  * finalized states which help in short circuiting more future states.
4686  */
4687 static int __mark_chain_precision(struct bpf_verifier_env *env,
4688 				  struct bpf_verifier_state *starting_state,
4689 				  int regno,
4690 				  bool *changed)
4691 {
4692 	struct bpf_verifier_state *st = starting_state;
4693 	struct backtrack_state *bt = &env->bt;
4694 	int first_idx = st->first_insn_idx;
4695 	int last_idx = starting_state->insn_idx;
4696 	int subseq_idx = -1;
4697 	struct bpf_func_state *func;
4698 	bool tmp, skip_first = true;
4699 	struct bpf_reg_state *reg;
4700 	int i, fr, err;
4701 
4702 	if (!env->bpf_capable)
4703 		return 0;
4704 
4705 	changed = changed ?: &tmp;
4706 	/* set frame number from which we are starting to backtrack */
4707 	bt_init(bt, starting_state->curframe);
4708 
4709 	/* Do sanity checks against current state of register and/or stack
4710 	 * slot, but don't set precise flag in current state, as precision
4711 	 * tracking in the current state is unnecessary.
4712 	 */
4713 	func = st->frame[bt->frame];
4714 	if (regno >= 0) {
4715 		reg = &func->regs[regno];
4716 		if (reg->type != SCALAR_VALUE) {
4717 			verifier_bug(env, "backtracking misuse");
4718 			return -EFAULT;
4719 		}
4720 		bt_set_reg(bt, regno);
4721 	}
4722 
4723 	if (bt_empty(bt))
4724 		return 0;
4725 
4726 	for (;;) {
4727 		DECLARE_BITMAP(mask, 64);
4728 		u32 history = st->jmp_history_cnt;
4729 		struct bpf_jmp_history_entry *hist;
4730 
4731 		if (env->log.level & BPF_LOG_LEVEL2) {
4732 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4733 				bt->frame, last_idx, first_idx, subseq_idx);
4734 		}
4735 
4736 		if (last_idx < 0) {
4737 			/* we are at the entry into subprog, which
4738 			 * is expected for global funcs, but only if
4739 			 * requested precise registers are R1-R5
4740 			 * (which are global func's input arguments)
4741 			 */
4742 			if (st->curframe == 0 &&
4743 			    st->frame[0]->subprogno > 0 &&
4744 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4745 			    bt_stack_mask(bt) == 0 &&
4746 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4747 				bitmap_from_u64(mask, bt_reg_mask(bt));
4748 				for_each_set_bit(i, mask, 32) {
4749 					reg = &st->frame[0]->regs[i];
4750 					bt_clear_reg(bt, i);
4751 					if (reg->type == SCALAR_VALUE) {
4752 						reg->precise = true;
4753 						*changed = true;
4754 					}
4755 				}
4756 				return 0;
4757 			}
4758 
4759 			verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %llx",
4760 				     st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4761 			return -EFAULT;
4762 		}
4763 
4764 		for (i = last_idx;;) {
4765 			if (skip_first) {
4766 				err = 0;
4767 				skip_first = false;
4768 			} else {
4769 				hist = get_jmp_hist_entry(st, history, i);
4770 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4771 			}
4772 			if (err == -ENOTSUPP) {
4773 				mark_all_scalars_precise(env, starting_state);
4774 				bt_reset(bt);
4775 				return 0;
4776 			} else if (err) {
4777 				return err;
4778 			}
4779 			if (bt_empty(bt))
4780 				/* Found assignment(s) into tracked register in this state.
4781 				 * Since this state is already marked, just return.
4782 				 * Nothing to be tracked further in the parent state.
4783 				 */
4784 				return 0;
4785 			subseq_idx = i;
4786 			i = get_prev_insn_idx(st, i, &history);
4787 			if (i == -ENOENT)
4788 				break;
4789 			if (i >= env->prog->len) {
4790 				/* This can happen if backtracking reached insn 0
4791 				 * and there are still reg_mask or stack_mask
4792 				 * to backtrack.
4793 				 * It means the backtracking missed the spot where
4794 				 * particular register was initialized with a constant.
4795 				 */
4796 				verifier_bug(env, "backtracking idx %d", i);
4797 				return -EFAULT;
4798 			}
4799 		}
4800 		st = st->parent;
4801 		if (!st)
4802 			break;
4803 
4804 		for (fr = bt->frame; fr >= 0; fr--) {
4805 			func = st->frame[fr];
4806 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4807 			for_each_set_bit(i, mask, 32) {
4808 				reg = &func->regs[i];
4809 				if (reg->type != SCALAR_VALUE) {
4810 					bt_clear_frame_reg(bt, fr, i);
4811 					continue;
4812 				}
4813 				if (reg->precise) {
4814 					bt_clear_frame_reg(bt, fr, i);
4815 				} else {
4816 					reg->precise = true;
4817 					*changed = true;
4818 				}
4819 			}
4820 
4821 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4822 			for_each_set_bit(i, mask, 64) {
4823 				if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE,
4824 						    env, "stack slot %d, total slots %d",
4825 						    i, func->allocated_stack / BPF_REG_SIZE))
4826 					return -EFAULT;
4827 
4828 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4829 					bt_clear_frame_slot(bt, fr, i);
4830 					continue;
4831 				}
4832 				reg = &func->stack[i].spilled_ptr;
4833 				if (reg->precise) {
4834 					bt_clear_frame_slot(bt, fr, i);
4835 				} else {
4836 					reg->precise = true;
4837 					*changed = true;
4838 				}
4839 			}
4840 			if (env->log.level & BPF_LOG_LEVEL2) {
4841 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4842 					     bt_frame_reg_mask(bt, fr));
4843 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4844 					fr, env->tmp_str_buf);
4845 				bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4846 					       bt_frame_stack_mask(bt, fr));
4847 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4848 				print_verifier_state(env, st, fr, true);
4849 			}
4850 		}
4851 
4852 		if (bt_empty(bt))
4853 			return 0;
4854 
4855 		subseq_idx = first_idx;
4856 		last_idx = st->last_insn_idx;
4857 		first_idx = st->first_insn_idx;
4858 	}
4859 
4860 	/* if we still have requested precise regs or slots, we missed
4861 	 * something (e.g., stack access through non-r10 register), so
4862 	 * fallback to marking all precise
4863 	 */
4864 	if (!bt_empty(bt)) {
4865 		mark_all_scalars_precise(env, starting_state);
4866 		bt_reset(bt);
4867 	}
4868 
4869 	return 0;
4870 }
4871 
4872 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4873 {
4874 	return __mark_chain_precision(env, env->cur_state, regno, NULL);
4875 }
4876 
4877 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4878  * desired reg and stack masks across all relevant frames
4879  */
4880 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
4881 				      struct bpf_verifier_state *starting_state)
4882 {
4883 	return __mark_chain_precision(env, starting_state, -1, NULL);
4884 }
4885 
4886 static bool is_spillable_regtype(enum bpf_reg_type type)
4887 {
4888 	switch (base_type(type)) {
4889 	case PTR_TO_MAP_VALUE:
4890 	case PTR_TO_STACK:
4891 	case PTR_TO_CTX:
4892 	case PTR_TO_PACKET:
4893 	case PTR_TO_PACKET_META:
4894 	case PTR_TO_PACKET_END:
4895 	case PTR_TO_FLOW_KEYS:
4896 	case CONST_PTR_TO_MAP:
4897 	case PTR_TO_SOCKET:
4898 	case PTR_TO_SOCK_COMMON:
4899 	case PTR_TO_TCP_SOCK:
4900 	case PTR_TO_XDP_SOCK:
4901 	case PTR_TO_BTF_ID:
4902 	case PTR_TO_BUF:
4903 	case PTR_TO_MEM:
4904 	case PTR_TO_FUNC:
4905 	case PTR_TO_MAP_KEY:
4906 	case PTR_TO_ARENA:
4907 		return true;
4908 	default:
4909 		return false;
4910 	}
4911 }
4912 
4913 /* Does this register contain a constant zero? */
4914 static bool register_is_null(struct bpf_reg_state *reg)
4915 {
4916 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4917 }
4918 
4919 /* check if register is a constant scalar value */
4920 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4921 {
4922 	return reg->type == SCALAR_VALUE &&
4923 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4924 }
4925 
4926 /* assuming is_reg_const() is true, return constant value of a register */
4927 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4928 {
4929 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4930 }
4931 
4932 static bool __is_pointer_value(bool allow_ptr_leaks,
4933 			       const struct bpf_reg_state *reg)
4934 {
4935 	if (allow_ptr_leaks)
4936 		return false;
4937 
4938 	return reg->type != SCALAR_VALUE;
4939 }
4940 
4941 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4942 					struct bpf_reg_state *src_reg)
4943 {
4944 	if (src_reg->type != SCALAR_VALUE)
4945 		return;
4946 
4947 	if (src_reg->id & BPF_ADD_CONST) {
4948 		/*
4949 		 * The verifier is processing rX = rY insn and
4950 		 * rY->id has special linked register already.
4951 		 * Cleared it, since multiple rX += const are not supported.
4952 		 */
4953 		src_reg->id = 0;
4954 		src_reg->off = 0;
4955 	}
4956 
4957 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
4958 		/* Ensure that src_reg has a valid ID that will be copied to
4959 		 * dst_reg and then will be used by sync_linked_regs() to
4960 		 * propagate min/max range.
4961 		 */
4962 		src_reg->id = ++env->id_gen;
4963 }
4964 
4965 /* Copy src state preserving dst->parent and dst->live fields */
4966 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4967 {
4968 	*dst = *src;
4969 }
4970 
4971 static void save_register_state(struct bpf_verifier_env *env,
4972 				struct bpf_func_state *state,
4973 				int spi, struct bpf_reg_state *reg,
4974 				int size)
4975 {
4976 	int i;
4977 
4978 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4979 
4980 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4981 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4982 
4983 	/* size < 8 bytes spill */
4984 	for (; i; i--)
4985 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4986 }
4987 
4988 static bool is_bpf_st_mem(struct bpf_insn *insn)
4989 {
4990 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4991 }
4992 
4993 static int get_reg_width(struct bpf_reg_state *reg)
4994 {
4995 	return fls64(reg->umax_value);
4996 }
4997 
4998 /* See comment for mark_fastcall_pattern_for_call() */
4999 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
5000 					  struct bpf_func_state *state, int insn_idx, int off)
5001 {
5002 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
5003 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
5004 	int i;
5005 
5006 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
5007 		return;
5008 	/* access to the region [max_stack_depth .. fastcall_stack_off)
5009 	 * from something that is not a part of the fastcall pattern,
5010 	 * disable fastcall rewrites for current subprogram by setting
5011 	 * fastcall_stack_off to a value smaller than any possible offset.
5012 	 */
5013 	subprog->fastcall_stack_off = S16_MIN;
5014 	/* reset fastcall aux flags within subprogram,
5015 	 * happens at most once per subprogram
5016 	 */
5017 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
5018 		aux[i].fastcall_spills_num = 0;
5019 		aux[i].fastcall_pattern = 0;
5020 	}
5021 }
5022 
5023 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
5024  * stack boundary and alignment are checked in check_mem_access()
5025  */
5026 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
5027 				       /* stack frame we're writing to */
5028 				       struct bpf_func_state *state,
5029 				       int off, int size, int value_regno,
5030 				       int insn_idx)
5031 {
5032 	struct bpf_func_state *cur; /* state of the current function */
5033 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
5034 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5035 	struct bpf_reg_state *reg = NULL;
5036 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
5037 
5038 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
5039 	 * so it's aligned access and [off, off + size) are within stack limits
5040 	 */
5041 	if (!env->allow_ptr_leaks &&
5042 	    is_spilled_reg(&state->stack[spi]) &&
5043 	    !is_spilled_scalar_reg(&state->stack[spi]) &&
5044 	    size != BPF_REG_SIZE) {
5045 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
5046 		return -EACCES;
5047 	}
5048 
5049 	cur = env->cur_state->frame[env->cur_state->curframe];
5050 	if (value_regno >= 0)
5051 		reg = &cur->regs[value_regno];
5052 	if (!env->bypass_spec_v4) {
5053 		bool sanitize = reg && is_spillable_regtype(reg->type);
5054 
5055 		for (i = 0; i < size; i++) {
5056 			u8 type = state->stack[spi].slot_type[i];
5057 
5058 			if (type != STACK_MISC && type != STACK_ZERO) {
5059 				sanitize = true;
5060 				break;
5061 			}
5062 		}
5063 
5064 		if (sanitize)
5065 			env->insn_aux_data[insn_idx].nospec_result = true;
5066 	}
5067 
5068 	err = destroy_if_dynptr_stack_slot(env, state, spi);
5069 	if (err)
5070 		return err;
5071 
5072 	if (!(off % BPF_REG_SIZE) && size == BPF_REG_SIZE) {
5073 		/* only mark the slot as written if all 8 bytes were written
5074 		 * otherwise read propagation may incorrectly stop too soon
5075 		 * when stack slots are partially written.
5076 		 * This heuristic means that read propagation will be
5077 		 * conservative, since it will add reg_live_read marks
5078 		 * to stack slots all the way to first state when programs
5079 		 * writes+reads less than 8 bytes
5080 		 */
5081 		bpf_mark_stack_write(env, state->frameno, BIT(spi));
5082 	}
5083 
5084 	check_fastcall_stack_contract(env, state, insn_idx, off);
5085 	mark_stack_slot_scratched(env, spi);
5086 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
5087 		bool reg_value_fits;
5088 
5089 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
5090 		/* Make sure that reg had an ID to build a relation on spill. */
5091 		if (reg_value_fits)
5092 			assign_scalar_id_before_mov(env, reg);
5093 		save_register_state(env, state, spi, reg, size);
5094 		/* Break the relation on a narrowing spill. */
5095 		if (!reg_value_fits)
5096 			state->stack[spi].spilled_ptr.id = 0;
5097 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
5098 		   env->bpf_capable) {
5099 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
5100 
5101 		memset(tmp_reg, 0, sizeof(*tmp_reg));
5102 		__mark_reg_known(tmp_reg, insn->imm);
5103 		tmp_reg->type = SCALAR_VALUE;
5104 		save_register_state(env, state, spi, tmp_reg, size);
5105 	} else if (reg && is_spillable_regtype(reg->type)) {
5106 		/* register containing pointer is being spilled into stack */
5107 		if (size != BPF_REG_SIZE) {
5108 			verbose_linfo(env, insn_idx, "; ");
5109 			verbose(env, "invalid size of register spill\n");
5110 			return -EACCES;
5111 		}
5112 		if (state != cur && reg->type == PTR_TO_STACK) {
5113 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
5114 			return -EINVAL;
5115 		}
5116 		save_register_state(env, state, spi, reg, size);
5117 	} else {
5118 		u8 type = STACK_MISC;
5119 
5120 		/* regular write of data into stack destroys any spilled ptr */
5121 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5122 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
5123 		if (is_stack_slot_special(&state->stack[spi]))
5124 			for (i = 0; i < BPF_REG_SIZE; i++)
5125 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
5126 
5127 		/* when we zero initialize stack slots mark them as such */
5128 		if ((reg && register_is_null(reg)) ||
5129 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
5130 			/* STACK_ZERO case happened because register spill
5131 			 * wasn't properly aligned at the stack slot boundary,
5132 			 * so it's not a register spill anymore; force
5133 			 * originating register to be precise to make
5134 			 * STACK_ZERO correct for subsequent states
5135 			 */
5136 			err = mark_chain_precision(env, value_regno);
5137 			if (err)
5138 				return err;
5139 			type = STACK_ZERO;
5140 		}
5141 
5142 		/* Mark slots affected by this stack write. */
5143 		for (i = 0; i < size; i++)
5144 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
5145 		insn_flags = 0; /* not a register spill */
5146 	}
5147 
5148 	if (insn_flags)
5149 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5150 	return 0;
5151 }
5152 
5153 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
5154  * known to contain a variable offset.
5155  * This function checks whether the write is permitted and conservatively
5156  * tracks the effects of the write, considering that each stack slot in the
5157  * dynamic range is potentially written to.
5158  *
5159  * 'off' includes 'regno->off'.
5160  * 'value_regno' can be -1, meaning that an unknown value is being written to
5161  * the stack.
5162  *
5163  * Spilled pointers in range are not marked as written because we don't know
5164  * what's going to be actually written. This means that read propagation for
5165  * future reads cannot be terminated by this write.
5166  *
5167  * For privileged programs, uninitialized stack slots are considered
5168  * initialized by this write (even though we don't know exactly what offsets
5169  * are going to be written to). The idea is that we don't want the verifier to
5170  * reject future reads that access slots written to through variable offsets.
5171  */
5172 static int check_stack_write_var_off(struct bpf_verifier_env *env,
5173 				     /* func where register points to */
5174 				     struct bpf_func_state *state,
5175 				     int ptr_regno, int off, int size,
5176 				     int value_regno, int insn_idx)
5177 {
5178 	struct bpf_func_state *cur; /* state of the current function */
5179 	int min_off, max_off;
5180 	int i, err;
5181 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
5182 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5183 	bool writing_zero = false;
5184 	/* set if the fact that we're writing a zero is used to let any
5185 	 * stack slots remain STACK_ZERO
5186 	 */
5187 	bool zero_used = false;
5188 
5189 	cur = env->cur_state->frame[env->cur_state->curframe];
5190 	ptr_reg = &cur->regs[ptr_regno];
5191 	min_off = ptr_reg->smin_value + off;
5192 	max_off = ptr_reg->smax_value + off + size;
5193 	if (value_regno >= 0)
5194 		value_reg = &cur->regs[value_regno];
5195 	if ((value_reg && register_is_null(value_reg)) ||
5196 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
5197 		writing_zero = true;
5198 
5199 	for (i = min_off; i < max_off; i++) {
5200 		int spi;
5201 
5202 		spi = __get_spi(i);
5203 		err = destroy_if_dynptr_stack_slot(env, state, spi);
5204 		if (err)
5205 			return err;
5206 	}
5207 
5208 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
5209 	/* Variable offset writes destroy any spilled pointers in range. */
5210 	for (i = min_off; i < max_off; i++) {
5211 		u8 new_type, *stype;
5212 		int slot, spi;
5213 
5214 		slot = -i - 1;
5215 		spi = slot / BPF_REG_SIZE;
5216 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5217 		mark_stack_slot_scratched(env, spi);
5218 
5219 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
5220 			/* Reject the write if range we may write to has not
5221 			 * been initialized beforehand. If we didn't reject
5222 			 * here, the ptr status would be erased below (even
5223 			 * though not all slots are actually overwritten),
5224 			 * possibly opening the door to leaks.
5225 			 *
5226 			 * We do however catch STACK_INVALID case below, and
5227 			 * only allow reading possibly uninitialized memory
5228 			 * later for CAP_PERFMON, as the write may not happen to
5229 			 * that slot.
5230 			 */
5231 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
5232 				insn_idx, i);
5233 			return -EINVAL;
5234 		}
5235 
5236 		/* If writing_zero and the spi slot contains a spill of value 0,
5237 		 * maintain the spill type.
5238 		 */
5239 		if (writing_zero && *stype == STACK_SPILL &&
5240 		    is_spilled_scalar_reg(&state->stack[spi])) {
5241 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
5242 
5243 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
5244 				zero_used = true;
5245 				continue;
5246 			}
5247 		}
5248 
5249 		/* Erase all other spilled pointers. */
5250 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5251 
5252 		/* Update the slot type. */
5253 		new_type = STACK_MISC;
5254 		if (writing_zero && *stype == STACK_ZERO) {
5255 			new_type = STACK_ZERO;
5256 			zero_used = true;
5257 		}
5258 		/* If the slot is STACK_INVALID, we check whether it's OK to
5259 		 * pretend that it will be initialized by this write. The slot
5260 		 * might not actually be written to, and so if we mark it as
5261 		 * initialized future reads might leak uninitialized memory.
5262 		 * For privileged programs, we will accept such reads to slots
5263 		 * that may or may not be written because, if we're reject
5264 		 * them, the error would be too confusing.
5265 		 */
5266 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
5267 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
5268 					insn_idx, i);
5269 			return -EINVAL;
5270 		}
5271 		*stype = new_type;
5272 	}
5273 	if (zero_used) {
5274 		/* backtracking doesn't work for STACK_ZERO yet. */
5275 		err = mark_chain_precision(env, value_regno);
5276 		if (err)
5277 			return err;
5278 	}
5279 	return 0;
5280 }
5281 
5282 /* When register 'dst_regno' is assigned some values from stack[min_off,
5283  * max_off), we set the register's type according to the types of the
5284  * respective stack slots. If all the stack values are known to be zeros, then
5285  * so is the destination reg. Otherwise, the register is considered to be
5286  * SCALAR. This function does not deal with register filling; the caller must
5287  * ensure that all spilled registers in the stack range have been marked as
5288  * read.
5289  */
5290 static void mark_reg_stack_read(struct bpf_verifier_env *env,
5291 				/* func where src register points to */
5292 				struct bpf_func_state *ptr_state,
5293 				int min_off, int max_off, int dst_regno)
5294 {
5295 	struct bpf_verifier_state *vstate = env->cur_state;
5296 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5297 	int i, slot, spi;
5298 	u8 *stype;
5299 	int zeros = 0;
5300 
5301 	for (i = min_off; i < max_off; i++) {
5302 		slot = -i - 1;
5303 		spi = slot / BPF_REG_SIZE;
5304 		mark_stack_slot_scratched(env, spi);
5305 		stype = ptr_state->stack[spi].slot_type;
5306 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
5307 			break;
5308 		zeros++;
5309 	}
5310 	if (zeros == max_off - min_off) {
5311 		/* Any access_size read into register is zero extended,
5312 		 * so the whole register == const_zero.
5313 		 */
5314 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
5315 	} else {
5316 		/* have read misc data from the stack */
5317 		mark_reg_unknown(env, state->regs, dst_regno);
5318 	}
5319 }
5320 
5321 /* Read the stack at 'off' and put the results into the register indicated by
5322  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
5323  * spilled reg.
5324  *
5325  * 'dst_regno' can be -1, meaning that the read value is not going to a
5326  * register.
5327  *
5328  * The access is assumed to be within the current stack bounds.
5329  */
5330 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
5331 				      /* func where src register points to */
5332 				      struct bpf_func_state *reg_state,
5333 				      int off, int size, int dst_regno)
5334 {
5335 	struct bpf_verifier_state *vstate = env->cur_state;
5336 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5337 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
5338 	struct bpf_reg_state *reg;
5339 	u8 *stype, type;
5340 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
5341 	int err;
5342 
5343 	stype = reg_state->stack[spi].slot_type;
5344 	reg = &reg_state->stack[spi].spilled_ptr;
5345 
5346 	mark_stack_slot_scratched(env, spi);
5347 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
5348 	err = bpf_mark_stack_read(env, reg_state->frameno, env->insn_idx, BIT(spi));
5349 	if (err)
5350 		return err;
5351 
5352 	if (is_spilled_reg(&reg_state->stack[spi])) {
5353 		u8 spill_size = 1;
5354 
5355 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
5356 			spill_size++;
5357 
5358 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
5359 			if (reg->type != SCALAR_VALUE) {
5360 				verbose_linfo(env, env->insn_idx, "; ");
5361 				verbose(env, "invalid size of register fill\n");
5362 				return -EACCES;
5363 			}
5364 
5365 			if (dst_regno < 0)
5366 				return 0;
5367 
5368 			if (size <= spill_size &&
5369 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
5370 				/* The earlier check_reg_arg() has decided the
5371 				 * subreg_def for this insn.  Save it first.
5372 				 */
5373 				s32 subreg_def = state->regs[dst_regno].subreg_def;
5374 
5375 				copy_register_state(&state->regs[dst_regno], reg);
5376 				state->regs[dst_regno].subreg_def = subreg_def;
5377 
5378 				/* Break the relation on a narrowing fill.
5379 				 * coerce_reg_to_size will adjust the boundaries.
5380 				 */
5381 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
5382 					state->regs[dst_regno].id = 0;
5383 			} else {
5384 				int spill_cnt = 0, zero_cnt = 0;
5385 
5386 				for (i = 0; i < size; i++) {
5387 					type = stype[(slot - i) % BPF_REG_SIZE];
5388 					if (type == STACK_SPILL) {
5389 						spill_cnt++;
5390 						continue;
5391 					}
5392 					if (type == STACK_MISC)
5393 						continue;
5394 					if (type == STACK_ZERO) {
5395 						zero_cnt++;
5396 						continue;
5397 					}
5398 					if (type == STACK_INVALID && env->allow_uninit_stack)
5399 						continue;
5400 					verbose(env, "invalid read from stack off %d+%d size %d\n",
5401 						off, i, size);
5402 					return -EACCES;
5403 				}
5404 
5405 				if (spill_cnt == size &&
5406 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
5407 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5408 					/* this IS register fill, so keep insn_flags */
5409 				} else if (zero_cnt == size) {
5410 					/* similarly to mark_reg_stack_read(), preserve zeroes */
5411 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5412 					insn_flags = 0; /* not restoring original register state */
5413 				} else {
5414 					mark_reg_unknown(env, state->regs, dst_regno);
5415 					insn_flags = 0; /* not restoring original register state */
5416 				}
5417 			}
5418 		} else if (dst_regno >= 0) {
5419 			/* restore register state from stack */
5420 			copy_register_state(&state->regs[dst_regno], reg);
5421 			/* mark reg as written since spilled pointer state likely
5422 			 * has its liveness marks cleared by is_state_visited()
5423 			 * which resets stack/reg liveness for state transitions
5424 			 */
5425 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5426 			/* If dst_regno==-1, the caller is asking us whether
5427 			 * it is acceptable to use this value as a SCALAR_VALUE
5428 			 * (e.g. for XADD).
5429 			 * We must not allow unprivileged callers to do that
5430 			 * with spilled pointers.
5431 			 */
5432 			verbose(env, "leaking pointer from stack off %d\n",
5433 				off);
5434 			return -EACCES;
5435 		}
5436 	} else {
5437 		for (i = 0; i < size; i++) {
5438 			type = stype[(slot - i) % BPF_REG_SIZE];
5439 			if (type == STACK_MISC)
5440 				continue;
5441 			if (type == STACK_ZERO)
5442 				continue;
5443 			if (type == STACK_INVALID && env->allow_uninit_stack)
5444 				continue;
5445 			verbose(env, "invalid read from stack off %d+%d size %d\n",
5446 				off, i, size);
5447 			return -EACCES;
5448 		}
5449 		if (dst_regno >= 0)
5450 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5451 		insn_flags = 0; /* we are not restoring spilled register */
5452 	}
5453 	if (insn_flags)
5454 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5455 	return 0;
5456 }
5457 
5458 enum bpf_access_src {
5459 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5460 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
5461 };
5462 
5463 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5464 					 int regno, int off, int access_size,
5465 					 bool zero_size_allowed,
5466 					 enum bpf_access_type type,
5467 					 struct bpf_call_arg_meta *meta);
5468 
5469 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5470 {
5471 	return cur_regs(env) + regno;
5472 }
5473 
5474 /* Read the stack at 'ptr_regno + off' and put the result into the register
5475  * 'dst_regno'.
5476  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5477  * but not its variable offset.
5478  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5479  *
5480  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5481  * filling registers (i.e. reads of spilled register cannot be detected when
5482  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5483  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5484  * offset; for a fixed offset check_stack_read_fixed_off should be used
5485  * instead.
5486  */
5487 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5488 				    int ptr_regno, int off, int size, int dst_regno)
5489 {
5490 	/* The state of the source register. */
5491 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5492 	struct bpf_func_state *ptr_state = func(env, reg);
5493 	int err;
5494 	int min_off, max_off;
5495 
5496 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5497 	 */
5498 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5499 					    false, BPF_READ, NULL);
5500 	if (err)
5501 		return err;
5502 
5503 	min_off = reg->smin_value + off;
5504 	max_off = reg->smax_value + off;
5505 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5506 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5507 	return 0;
5508 }
5509 
5510 /* check_stack_read dispatches to check_stack_read_fixed_off or
5511  * check_stack_read_var_off.
5512  *
5513  * The caller must ensure that the offset falls within the allocated stack
5514  * bounds.
5515  *
5516  * 'dst_regno' is a register which will receive the value from the stack. It
5517  * can be -1, meaning that the read value is not going to a register.
5518  */
5519 static int check_stack_read(struct bpf_verifier_env *env,
5520 			    int ptr_regno, int off, int size,
5521 			    int dst_regno)
5522 {
5523 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5524 	struct bpf_func_state *state = func(env, reg);
5525 	int err;
5526 	/* Some accesses are only permitted with a static offset. */
5527 	bool var_off = !tnum_is_const(reg->var_off);
5528 
5529 	/* The offset is required to be static when reads don't go to a
5530 	 * register, in order to not leak pointers (see
5531 	 * check_stack_read_fixed_off).
5532 	 */
5533 	if (dst_regno < 0 && var_off) {
5534 		char tn_buf[48];
5535 
5536 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5537 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5538 			tn_buf, off, size);
5539 		return -EACCES;
5540 	}
5541 	/* Variable offset is prohibited for unprivileged mode for simplicity
5542 	 * since it requires corresponding support in Spectre masking for stack
5543 	 * ALU. See also retrieve_ptr_limit(). The check in
5544 	 * check_stack_access_for_ptr_arithmetic() called by
5545 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5546 	 * with variable offsets, therefore no check is required here. Further,
5547 	 * just checking it here would be insufficient as speculative stack
5548 	 * writes could still lead to unsafe speculative behaviour.
5549 	 */
5550 	if (!var_off) {
5551 		off += reg->var_off.value;
5552 		err = check_stack_read_fixed_off(env, state, off, size,
5553 						 dst_regno);
5554 	} else {
5555 		/* Variable offset stack reads need more conservative handling
5556 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5557 		 * branch.
5558 		 */
5559 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5560 					       dst_regno);
5561 	}
5562 	return err;
5563 }
5564 
5565 
5566 /* check_stack_write dispatches to check_stack_write_fixed_off or
5567  * check_stack_write_var_off.
5568  *
5569  * 'ptr_regno' is the register used as a pointer into the stack.
5570  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5571  * 'value_regno' is the register whose value we're writing to the stack. It can
5572  * be -1, meaning that we're not writing from a register.
5573  *
5574  * The caller must ensure that the offset falls within the maximum stack size.
5575  */
5576 static int check_stack_write(struct bpf_verifier_env *env,
5577 			     int ptr_regno, int off, int size,
5578 			     int value_regno, int insn_idx)
5579 {
5580 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5581 	struct bpf_func_state *state = func(env, reg);
5582 	int err;
5583 
5584 	if (tnum_is_const(reg->var_off)) {
5585 		off += reg->var_off.value;
5586 		err = check_stack_write_fixed_off(env, state, off, size,
5587 						  value_regno, insn_idx);
5588 	} else {
5589 		/* Variable offset stack reads need more conservative handling
5590 		 * than fixed offset ones.
5591 		 */
5592 		err = check_stack_write_var_off(env, state,
5593 						ptr_regno, off, size,
5594 						value_regno, insn_idx);
5595 	}
5596 	return err;
5597 }
5598 
5599 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5600 				 int off, int size, enum bpf_access_type type)
5601 {
5602 	struct bpf_reg_state *regs = cur_regs(env);
5603 	struct bpf_map *map = regs[regno].map_ptr;
5604 	u32 cap = bpf_map_flags_to_cap(map);
5605 
5606 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5607 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5608 			map->value_size, off, size);
5609 		return -EACCES;
5610 	}
5611 
5612 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5613 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5614 			map->value_size, off, size);
5615 		return -EACCES;
5616 	}
5617 
5618 	return 0;
5619 }
5620 
5621 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5622 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5623 			      int off, int size, u32 mem_size,
5624 			      bool zero_size_allowed)
5625 {
5626 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5627 	struct bpf_reg_state *reg;
5628 
5629 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5630 		return 0;
5631 
5632 	reg = &cur_regs(env)[regno];
5633 	switch (reg->type) {
5634 	case PTR_TO_MAP_KEY:
5635 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5636 			mem_size, off, size);
5637 		break;
5638 	case PTR_TO_MAP_VALUE:
5639 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5640 			mem_size, off, size);
5641 		break;
5642 	case PTR_TO_PACKET:
5643 	case PTR_TO_PACKET_META:
5644 	case PTR_TO_PACKET_END:
5645 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5646 			off, size, regno, reg->id, off, mem_size);
5647 		break;
5648 	case PTR_TO_MEM:
5649 	default:
5650 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5651 			mem_size, off, size);
5652 	}
5653 
5654 	return -EACCES;
5655 }
5656 
5657 /* check read/write into a memory region with possible variable offset */
5658 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5659 				   int off, int size, u32 mem_size,
5660 				   bool zero_size_allowed)
5661 {
5662 	struct bpf_verifier_state *vstate = env->cur_state;
5663 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5664 	struct bpf_reg_state *reg = &state->regs[regno];
5665 	int err;
5666 
5667 	/* We may have adjusted the register pointing to memory region, so we
5668 	 * need to try adding each of min_value and max_value to off
5669 	 * to make sure our theoretical access will be safe.
5670 	 *
5671 	 * The minimum value is only important with signed
5672 	 * comparisons where we can't assume the floor of a
5673 	 * value is 0.  If we are using signed variables for our
5674 	 * index'es we need to make sure that whatever we use
5675 	 * will have a set floor within our range.
5676 	 */
5677 	if (reg->smin_value < 0 &&
5678 	    (reg->smin_value == S64_MIN ||
5679 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5680 	      reg->smin_value + off < 0)) {
5681 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5682 			regno);
5683 		return -EACCES;
5684 	}
5685 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5686 				 mem_size, zero_size_allowed);
5687 	if (err) {
5688 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5689 			regno);
5690 		return err;
5691 	}
5692 
5693 	/* If we haven't set a max value then we need to bail since we can't be
5694 	 * sure we won't do bad things.
5695 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5696 	 */
5697 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5698 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5699 			regno);
5700 		return -EACCES;
5701 	}
5702 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5703 				 mem_size, zero_size_allowed);
5704 	if (err) {
5705 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5706 			regno);
5707 		return err;
5708 	}
5709 
5710 	return 0;
5711 }
5712 
5713 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5714 			       const struct bpf_reg_state *reg, int regno,
5715 			       bool fixed_off_ok)
5716 {
5717 	/* Access to this pointer-typed register or passing it to a helper
5718 	 * is only allowed in its original, unmodified form.
5719 	 */
5720 
5721 	if (reg->off < 0) {
5722 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5723 			reg_type_str(env, reg->type), regno, reg->off);
5724 		return -EACCES;
5725 	}
5726 
5727 	if (!fixed_off_ok && reg->off) {
5728 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5729 			reg_type_str(env, reg->type), regno, reg->off);
5730 		return -EACCES;
5731 	}
5732 
5733 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5734 		char tn_buf[48];
5735 
5736 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5737 		verbose(env, "variable %s access var_off=%s disallowed\n",
5738 			reg_type_str(env, reg->type), tn_buf);
5739 		return -EACCES;
5740 	}
5741 
5742 	return 0;
5743 }
5744 
5745 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5746 		             const struct bpf_reg_state *reg, int regno)
5747 {
5748 	return __check_ptr_off_reg(env, reg, regno, false);
5749 }
5750 
5751 static int map_kptr_match_type(struct bpf_verifier_env *env,
5752 			       struct btf_field *kptr_field,
5753 			       struct bpf_reg_state *reg, u32 regno)
5754 {
5755 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5756 	int perm_flags;
5757 	const char *reg_name = "";
5758 
5759 	if (btf_is_kernel(reg->btf)) {
5760 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5761 
5762 		/* Only unreferenced case accepts untrusted pointers */
5763 		if (kptr_field->type == BPF_KPTR_UNREF)
5764 			perm_flags |= PTR_UNTRUSTED;
5765 	} else {
5766 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5767 		if (kptr_field->type == BPF_KPTR_PERCPU)
5768 			perm_flags |= MEM_PERCPU;
5769 	}
5770 
5771 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5772 		goto bad_type;
5773 
5774 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5775 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5776 
5777 	/* For ref_ptr case, release function check should ensure we get one
5778 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5779 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5780 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5781 	 * reg->off and reg->ref_obj_id are not needed here.
5782 	 */
5783 	if (__check_ptr_off_reg(env, reg, regno, true))
5784 		return -EACCES;
5785 
5786 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5787 	 * we also need to take into account the reg->off.
5788 	 *
5789 	 * We want to support cases like:
5790 	 *
5791 	 * struct foo {
5792 	 *         struct bar br;
5793 	 *         struct baz bz;
5794 	 * };
5795 	 *
5796 	 * struct foo *v;
5797 	 * v = func();	      // PTR_TO_BTF_ID
5798 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5799 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5800 	 *                    // first member type of struct after comparison fails
5801 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5802 	 *                    // to match type
5803 	 *
5804 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5805 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5806 	 * the struct to match type against first member of struct, i.e. reject
5807 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5808 	 * strict mode to true for type match.
5809 	 */
5810 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5811 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5812 				  kptr_field->type != BPF_KPTR_UNREF))
5813 		goto bad_type;
5814 	return 0;
5815 bad_type:
5816 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5817 		reg_type_str(env, reg->type), reg_name);
5818 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5819 	if (kptr_field->type == BPF_KPTR_UNREF)
5820 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5821 			targ_name);
5822 	else
5823 		verbose(env, "\n");
5824 	return -EINVAL;
5825 }
5826 
5827 static bool in_sleepable(struct bpf_verifier_env *env)
5828 {
5829 	return env->prog->sleepable ||
5830 	       (env->cur_state && env->cur_state->in_sleepable);
5831 }
5832 
5833 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5834  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5835  */
5836 static bool in_rcu_cs(struct bpf_verifier_env *env)
5837 {
5838 	return env->cur_state->active_rcu_lock ||
5839 	       env->cur_state->active_locks ||
5840 	       !in_sleepable(env);
5841 }
5842 
5843 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5844 BTF_SET_START(rcu_protected_types)
5845 #ifdef CONFIG_NET
5846 BTF_ID(struct, prog_test_ref_kfunc)
5847 #endif
5848 #ifdef CONFIG_CGROUPS
5849 BTF_ID(struct, cgroup)
5850 #endif
5851 #ifdef CONFIG_BPF_JIT
5852 BTF_ID(struct, bpf_cpumask)
5853 #endif
5854 BTF_ID(struct, task_struct)
5855 #ifdef CONFIG_CRYPTO
5856 BTF_ID(struct, bpf_crypto_ctx)
5857 #endif
5858 BTF_SET_END(rcu_protected_types)
5859 
5860 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5861 {
5862 	if (!btf_is_kernel(btf))
5863 		return true;
5864 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5865 }
5866 
5867 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5868 {
5869 	struct btf_struct_meta *meta;
5870 
5871 	if (btf_is_kernel(kptr_field->kptr.btf))
5872 		return NULL;
5873 
5874 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5875 				    kptr_field->kptr.btf_id);
5876 
5877 	return meta ? meta->record : NULL;
5878 }
5879 
5880 static bool rcu_safe_kptr(const struct btf_field *field)
5881 {
5882 	const struct btf_field_kptr *kptr = &field->kptr;
5883 
5884 	return field->type == BPF_KPTR_PERCPU ||
5885 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5886 }
5887 
5888 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5889 {
5890 	struct btf_record *rec;
5891 	u32 ret;
5892 
5893 	ret = PTR_MAYBE_NULL;
5894 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5895 		ret |= MEM_RCU;
5896 		if (kptr_field->type == BPF_KPTR_PERCPU)
5897 			ret |= MEM_PERCPU;
5898 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5899 			ret |= MEM_ALLOC;
5900 
5901 		rec = kptr_pointee_btf_record(kptr_field);
5902 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5903 			ret |= NON_OWN_REF;
5904 	} else {
5905 		ret |= PTR_UNTRUSTED;
5906 	}
5907 
5908 	return ret;
5909 }
5910 
5911 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
5912 			    struct btf_field *field)
5913 {
5914 	struct bpf_reg_state *reg;
5915 	const struct btf_type *t;
5916 
5917 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
5918 	mark_reg_known_zero(env, cur_regs(env), regno);
5919 	reg = reg_state(env, regno);
5920 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5921 	reg->mem_size = t->size;
5922 	reg->id = ++env->id_gen;
5923 
5924 	return 0;
5925 }
5926 
5927 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5928 				 int value_regno, int insn_idx,
5929 				 struct btf_field *kptr_field)
5930 {
5931 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5932 	int class = BPF_CLASS(insn->code);
5933 	struct bpf_reg_state *val_reg;
5934 	int ret;
5935 
5936 	/* Things we already checked for in check_map_access and caller:
5937 	 *  - Reject cases where variable offset may touch kptr
5938 	 *  - size of access (must be BPF_DW)
5939 	 *  - tnum_is_const(reg->var_off)
5940 	 *  - kptr_field->offset == off + reg->var_off.value
5941 	 */
5942 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5943 	if (BPF_MODE(insn->code) != BPF_MEM) {
5944 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5945 		return -EACCES;
5946 	}
5947 
5948 	/* We only allow loading referenced kptr, since it will be marked as
5949 	 * untrusted, similar to unreferenced kptr.
5950 	 */
5951 	if (class != BPF_LDX &&
5952 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5953 		verbose(env, "store to referenced kptr disallowed\n");
5954 		return -EACCES;
5955 	}
5956 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
5957 		verbose(env, "store to uptr disallowed\n");
5958 		return -EACCES;
5959 	}
5960 
5961 	if (class == BPF_LDX) {
5962 		if (kptr_field->type == BPF_UPTR)
5963 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
5964 
5965 		/* We can simply mark the value_regno receiving the pointer
5966 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5967 		 */
5968 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
5969 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5970 				      btf_ld_kptr_type(env, kptr_field));
5971 		if (ret < 0)
5972 			return ret;
5973 	} else if (class == BPF_STX) {
5974 		val_reg = reg_state(env, value_regno);
5975 		if (!register_is_null(val_reg) &&
5976 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5977 			return -EACCES;
5978 	} else if (class == BPF_ST) {
5979 		if (insn->imm) {
5980 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5981 				kptr_field->offset);
5982 			return -EACCES;
5983 		}
5984 	} else {
5985 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5986 		return -EACCES;
5987 	}
5988 	return 0;
5989 }
5990 
5991 /* check read/write into a map element with possible variable offset */
5992 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5993 			    int off, int size, bool zero_size_allowed,
5994 			    enum bpf_access_src src)
5995 {
5996 	struct bpf_verifier_state *vstate = env->cur_state;
5997 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5998 	struct bpf_reg_state *reg = &state->regs[regno];
5999 	struct bpf_map *map = reg->map_ptr;
6000 	struct btf_record *rec;
6001 	int err, i;
6002 
6003 	err = check_mem_region_access(env, regno, off, size, map->value_size,
6004 				      zero_size_allowed);
6005 	if (err)
6006 		return err;
6007 
6008 	if (IS_ERR_OR_NULL(map->record))
6009 		return 0;
6010 	rec = map->record;
6011 	for (i = 0; i < rec->cnt; i++) {
6012 		struct btf_field *field = &rec->fields[i];
6013 		u32 p = field->offset;
6014 
6015 		/* If any part of a field  can be touched by load/store, reject
6016 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
6017 		 * it is sufficient to check x1 < y2 && y1 < x2.
6018 		 */
6019 		if (reg->smin_value + off < p + field->size &&
6020 		    p < reg->umax_value + off + size) {
6021 			switch (field->type) {
6022 			case BPF_KPTR_UNREF:
6023 			case BPF_KPTR_REF:
6024 			case BPF_KPTR_PERCPU:
6025 			case BPF_UPTR:
6026 				if (src != ACCESS_DIRECT) {
6027 					verbose(env, "%s cannot be accessed indirectly by helper\n",
6028 						btf_field_type_name(field->type));
6029 					return -EACCES;
6030 				}
6031 				if (!tnum_is_const(reg->var_off)) {
6032 					verbose(env, "%s access cannot have variable offset\n",
6033 						btf_field_type_name(field->type));
6034 					return -EACCES;
6035 				}
6036 				if (p != off + reg->var_off.value) {
6037 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
6038 						btf_field_type_name(field->type),
6039 						p, off + reg->var_off.value);
6040 					return -EACCES;
6041 				}
6042 				if (size != bpf_size_to_bytes(BPF_DW)) {
6043 					verbose(env, "%s access size must be BPF_DW\n",
6044 						btf_field_type_name(field->type));
6045 					return -EACCES;
6046 				}
6047 				break;
6048 			default:
6049 				verbose(env, "%s cannot be accessed directly by load/store\n",
6050 					btf_field_type_name(field->type));
6051 				return -EACCES;
6052 			}
6053 		}
6054 	}
6055 	return 0;
6056 }
6057 
6058 #define MAX_PACKET_OFF 0xffff
6059 
6060 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
6061 				       const struct bpf_call_arg_meta *meta,
6062 				       enum bpf_access_type t)
6063 {
6064 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6065 
6066 	switch (prog_type) {
6067 	/* Program types only with direct read access go here! */
6068 	case BPF_PROG_TYPE_LWT_IN:
6069 	case BPF_PROG_TYPE_LWT_OUT:
6070 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
6071 	case BPF_PROG_TYPE_SK_REUSEPORT:
6072 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6073 	case BPF_PROG_TYPE_CGROUP_SKB:
6074 		if (t == BPF_WRITE)
6075 			return false;
6076 		fallthrough;
6077 
6078 	/* Program types with direct read + write access go here! */
6079 	case BPF_PROG_TYPE_SCHED_CLS:
6080 	case BPF_PROG_TYPE_SCHED_ACT:
6081 	case BPF_PROG_TYPE_XDP:
6082 	case BPF_PROG_TYPE_LWT_XMIT:
6083 	case BPF_PROG_TYPE_SK_SKB:
6084 	case BPF_PROG_TYPE_SK_MSG:
6085 		if (meta)
6086 			return meta->pkt_access;
6087 
6088 		env->seen_direct_write = true;
6089 		return true;
6090 
6091 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
6092 		if (t == BPF_WRITE)
6093 			env->seen_direct_write = true;
6094 
6095 		return true;
6096 
6097 	default:
6098 		return false;
6099 	}
6100 }
6101 
6102 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
6103 			       int size, bool zero_size_allowed)
6104 {
6105 	struct bpf_reg_state *regs = cur_regs(env);
6106 	struct bpf_reg_state *reg = &regs[regno];
6107 	int err;
6108 
6109 	/* We may have added a variable offset to the packet pointer; but any
6110 	 * reg->range we have comes after that.  We are only checking the fixed
6111 	 * offset.
6112 	 */
6113 
6114 	/* We don't allow negative numbers, because we aren't tracking enough
6115 	 * detail to prove they're safe.
6116 	 */
6117 	if (reg->smin_value < 0) {
6118 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6119 			regno);
6120 		return -EACCES;
6121 	}
6122 
6123 	err = reg->range < 0 ? -EINVAL :
6124 	      __check_mem_access(env, regno, off, size, reg->range,
6125 				 zero_size_allowed);
6126 	if (err) {
6127 		verbose(env, "R%d offset is outside of the packet\n", regno);
6128 		return err;
6129 	}
6130 
6131 	/* __check_mem_access has made sure "off + size - 1" is within u16.
6132 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
6133 	 * otherwise find_good_pkt_pointers would have refused to set range info
6134 	 * that __check_mem_access would have rejected this pkt access.
6135 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
6136 	 */
6137 	env->prog->aux->max_pkt_offset =
6138 		max_t(u32, env->prog->aux->max_pkt_offset,
6139 		      off + reg->umax_value + size - 1);
6140 
6141 	return err;
6142 }
6143 
6144 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
6145 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
6146 			    enum bpf_access_type t, struct bpf_insn_access_aux *info)
6147 {
6148 	if (env->ops->is_valid_access &&
6149 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
6150 		/* A non zero info.ctx_field_size indicates that this field is a
6151 		 * candidate for later verifier transformation to load the whole
6152 		 * field and then apply a mask when accessed with a narrower
6153 		 * access than actual ctx access size. A zero info.ctx_field_size
6154 		 * will only allow for whole field access and rejects any other
6155 		 * type of narrower access.
6156 		 */
6157 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
6158 			if (info->ref_obj_id &&
6159 			    !find_reference_state(env->cur_state, info->ref_obj_id)) {
6160 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
6161 					off);
6162 				return -EACCES;
6163 			}
6164 		} else {
6165 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
6166 		}
6167 		/* remember the offset of last byte accessed in ctx */
6168 		if (env->prog->aux->max_ctx_offset < off + size)
6169 			env->prog->aux->max_ctx_offset = off + size;
6170 		return 0;
6171 	}
6172 
6173 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
6174 	return -EACCES;
6175 }
6176 
6177 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
6178 				  int size)
6179 {
6180 	if (size < 0 || off < 0 ||
6181 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
6182 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
6183 			off, size);
6184 		return -EACCES;
6185 	}
6186 	return 0;
6187 }
6188 
6189 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
6190 			     u32 regno, int off, int size,
6191 			     enum bpf_access_type t)
6192 {
6193 	struct bpf_reg_state *regs = cur_regs(env);
6194 	struct bpf_reg_state *reg = &regs[regno];
6195 	struct bpf_insn_access_aux info = {};
6196 	bool valid;
6197 
6198 	if (reg->smin_value < 0) {
6199 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6200 			regno);
6201 		return -EACCES;
6202 	}
6203 
6204 	switch (reg->type) {
6205 	case PTR_TO_SOCK_COMMON:
6206 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
6207 		break;
6208 	case PTR_TO_SOCKET:
6209 		valid = bpf_sock_is_valid_access(off, size, t, &info);
6210 		break;
6211 	case PTR_TO_TCP_SOCK:
6212 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
6213 		break;
6214 	case PTR_TO_XDP_SOCK:
6215 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
6216 		break;
6217 	default:
6218 		valid = false;
6219 	}
6220 
6221 
6222 	if (valid) {
6223 		env->insn_aux_data[insn_idx].ctx_field_size =
6224 			info.ctx_field_size;
6225 		return 0;
6226 	}
6227 
6228 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
6229 		regno, reg_type_str(env, reg->type), off, size);
6230 
6231 	return -EACCES;
6232 }
6233 
6234 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
6235 {
6236 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
6237 }
6238 
6239 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
6240 {
6241 	const struct bpf_reg_state *reg = reg_state(env, regno);
6242 
6243 	return reg->type == PTR_TO_CTX;
6244 }
6245 
6246 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
6247 {
6248 	const struct bpf_reg_state *reg = reg_state(env, regno);
6249 
6250 	return type_is_sk_pointer(reg->type);
6251 }
6252 
6253 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
6254 {
6255 	const struct bpf_reg_state *reg = reg_state(env, regno);
6256 
6257 	return type_is_pkt_pointer(reg->type);
6258 }
6259 
6260 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
6261 {
6262 	const struct bpf_reg_state *reg = reg_state(env, regno);
6263 
6264 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
6265 	return reg->type == PTR_TO_FLOW_KEYS;
6266 }
6267 
6268 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
6269 {
6270 	const struct bpf_reg_state *reg = reg_state(env, regno);
6271 
6272 	return reg->type == PTR_TO_ARENA;
6273 }
6274 
6275 /* Return false if @regno contains a pointer whose type isn't supported for
6276  * atomic instruction @insn.
6277  */
6278 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
6279 			       struct bpf_insn *insn)
6280 {
6281 	if (is_ctx_reg(env, regno))
6282 		return false;
6283 	if (is_pkt_reg(env, regno))
6284 		return false;
6285 	if (is_flow_key_reg(env, regno))
6286 		return false;
6287 	if (is_sk_reg(env, regno))
6288 		return false;
6289 	if (is_arena_reg(env, regno))
6290 		return bpf_jit_supports_insn(insn, true);
6291 
6292 	return true;
6293 }
6294 
6295 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
6296 #ifdef CONFIG_NET
6297 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
6298 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6299 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
6300 #endif
6301 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
6302 };
6303 
6304 static bool is_trusted_reg(const struct bpf_reg_state *reg)
6305 {
6306 	/* A referenced register is always trusted. */
6307 	if (reg->ref_obj_id)
6308 		return true;
6309 
6310 	/* Types listed in the reg2btf_ids are always trusted */
6311 	if (reg2btf_ids[base_type(reg->type)] &&
6312 	    !bpf_type_has_unsafe_modifiers(reg->type))
6313 		return true;
6314 
6315 	/* If a register is not referenced, it is trusted if it has the
6316 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
6317 	 * other type modifiers may be safe, but we elect to take an opt-in
6318 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
6319 	 * not.
6320 	 *
6321 	 * Eventually, we should make PTR_TRUSTED the single source of truth
6322 	 * for whether a register is trusted.
6323 	 */
6324 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
6325 	       !bpf_type_has_unsafe_modifiers(reg->type);
6326 }
6327 
6328 static bool is_rcu_reg(const struct bpf_reg_state *reg)
6329 {
6330 	return reg->type & MEM_RCU;
6331 }
6332 
6333 static void clear_trusted_flags(enum bpf_type_flag *flag)
6334 {
6335 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
6336 }
6337 
6338 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
6339 				   const struct bpf_reg_state *reg,
6340 				   int off, int size, bool strict)
6341 {
6342 	struct tnum reg_off;
6343 	int ip_align;
6344 
6345 	/* Byte size accesses are always allowed. */
6346 	if (!strict || size == 1)
6347 		return 0;
6348 
6349 	/* For platforms that do not have a Kconfig enabling
6350 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
6351 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
6352 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
6353 	 * to this code only in strict mode where we want to emulate
6354 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
6355 	 * unconditional IP align value of '2'.
6356 	 */
6357 	ip_align = 2;
6358 
6359 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
6360 	if (!tnum_is_aligned(reg_off, size)) {
6361 		char tn_buf[48];
6362 
6363 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6364 		verbose(env,
6365 			"misaligned packet access off %d+%s+%d+%d size %d\n",
6366 			ip_align, tn_buf, reg->off, off, size);
6367 		return -EACCES;
6368 	}
6369 
6370 	return 0;
6371 }
6372 
6373 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
6374 				       const struct bpf_reg_state *reg,
6375 				       const char *pointer_desc,
6376 				       int off, int size, bool strict)
6377 {
6378 	struct tnum reg_off;
6379 
6380 	/* Byte size accesses are always allowed. */
6381 	if (!strict || size == 1)
6382 		return 0;
6383 
6384 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
6385 	if (!tnum_is_aligned(reg_off, size)) {
6386 		char tn_buf[48];
6387 
6388 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6389 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
6390 			pointer_desc, tn_buf, reg->off, off, size);
6391 		return -EACCES;
6392 	}
6393 
6394 	return 0;
6395 }
6396 
6397 static int check_ptr_alignment(struct bpf_verifier_env *env,
6398 			       const struct bpf_reg_state *reg, int off,
6399 			       int size, bool strict_alignment_once)
6400 {
6401 	bool strict = env->strict_alignment || strict_alignment_once;
6402 	const char *pointer_desc = "";
6403 
6404 	switch (reg->type) {
6405 	case PTR_TO_PACKET:
6406 	case PTR_TO_PACKET_META:
6407 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
6408 		 * right in front, treat it the very same way.
6409 		 */
6410 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
6411 	case PTR_TO_FLOW_KEYS:
6412 		pointer_desc = "flow keys ";
6413 		break;
6414 	case PTR_TO_MAP_KEY:
6415 		pointer_desc = "key ";
6416 		break;
6417 	case PTR_TO_MAP_VALUE:
6418 		pointer_desc = "value ";
6419 		break;
6420 	case PTR_TO_CTX:
6421 		pointer_desc = "context ";
6422 		break;
6423 	case PTR_TO_STACK:
6424 		pointer_desc = "stack ";
6425 		/* The stack spill tracking logic in check_stack_write_fixed_off()
6426 		 * and check_stack_read_fixed_off() relies on stack accesses being
6427 		 * aligned.
6428 		 */
6429 		strict = true;
6430 		break;
6431 	case PTR_TO_SOCKET:
6432 		pointer_desc = "sock ";
6433 		break;
6434 	case PTR_TO_SOCK_COMMON:
6435 		pointer_desc = "sock_common ";
6436 		break;
6437 	case PTR_TO_TCP_SOCK:
6438 		pointer_desc = "tcp_sock ";
6439 		break;
6440 	case PTR_TO_XDP_SOCK:
6441 		pointer_desc = "xdp_sock ";
6442 		break;
6443 	case PTR_TO_ARENA:
6444 		return 0;
6445 	default:
6446 		break;
6447 	}
6448 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
6449 					   strict);
6450 }
6451 
6452 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
6453 {
6454 	if (!bpf_jit_supports_private_stack())
6455 		return NO_PRIV_STACK;
6456 
6457 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
6458 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
6459 	 * explicitly.
6460 	 */
6461 	switch (prog->type) {
6462 	case BPF_PROG_TYPE_KPROBE:
6463 	case BPF_PROG_TYPE_TRACEPOINT:
6464 	case BPF_PROG_TYPE_PERF_EVENT:
6465 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6466 		return PRIV_STACK_ADAPTIVE;
6467 	case BPF_PROG_TYPE_TRACING:
6468 	case BPF_PROG_TYPE_LSM:
6469 	case BPF_PROG_TYPE_STRUCT_OPS:
6470 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
6471 			return PRIV_STACK_ADAPTIVE;
6472 		fallthrough;
6473 	default:
6474 		break;
6475 	}
6476 
6477 	return NO_PRIV_STACK;
6478 }
6479 
6480 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
6481 {
6482 	if (env->prog->jit_requested)
6483 		return round_up(stack_depth, 16);
6484 
6485 	/* round up to 32-bytes, since this is granularity
6486 	 * of interpreter stack size
6487 	 */
6488 	return round_up(max_t(u32, stack_depth, 1), 32);
6489 }
6490 
6491 /* starting from main bpf function walk all instructions of the function
6492  * and recursively walk all callees that given function can call.
6493  * Ignore jump and exit insns.
6494  * Since recursion is prevented by check_cfg() this algorithm
6495  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6496  */
6497 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
6498 					 bool priv_stack_supported)
6499 {
6500 	struct bpf_subprog_info *subprog = env->subprog_info;
6501 	struct bpf_insn *insn = env->prog->insnsi;
6502 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
6503 	bool tail_call_reachable = false;
6504 	int ret_insn[MAX_CALL_FRAMES];
6505 	int ret_prog[MAX_CALL_FRAMES];
6506 	int j;
6507 
6508 	i = subprog[idx].start;
6509 	if (!priv_stack_supported)
6510 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6511 process_func:
6512 	/* protect against potential stack overflow that might happen when
6513 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6514 	 * depth for such case down to 256 so that the worst case scenario
6515 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
6516 	 * 8k).
6517 	 *
6518 	 * To get the idea what might happen, see an example:
6519 	 * func1 -> sub rsp, 128
6520 	 *  subfunc1 -> sub rsp, 256
6521 	 *  tailcall1 -> add rsp, 256
6522 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6523 	 *   subfunc2 -> sub rsp, 64
6524 	 *   subfunc22 -> sub rsp, 128
6525 	 *   tailcall2 -> add rsp, 128
6526 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6527 	 *
6528 	 * tailcall will unwind the current stack frame but it will not get rid
6529 	 * of caller's stack as shown on the example above.
6530 	 */
6531 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
6532 		verbose(env,
6533 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6534 			depth);
6535 		return -EACCES;
6536 	}
6537 
6538 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
6539 	if (priv_stack_supported) {
6540 		/* Request private stack support only if the subprog stack
6541 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
6542 		 * avoid jit penalty if the stack usage is small.
6543 		 */
6544 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
6545 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
6546 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
6547 	}
6548 
6549 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6550 		if (subprog_depth > MAX_BPF_STACK) {
6551 			verbose(env, "stack size of subprog %d is %d. Too large\n",
6552 				idx, subprog_depth);
6553 			return -EACCES;
6554 		}
6555 	} else {
6556 		depth += subprog_depth;
6557 		if (depth > MAX_BPF_STACK) {
6558 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
6559 				frame + 1, depth);
6560 			return -EACCES;
6561 		}
6562 	}
6563 continue_func:
6564 	subprog_end = subprog[idx + 1].start;
6565 	for (; i < subprog_end; i++) {
6566 		int next_insn, sidx;
6567 
6568 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6569 			bool err = false;
6570 
6571 			if (!is_bpf_throw_kfunc(insn + i))
6572 				continue;
6573 			if (subprog[idx].is_cb)
6574 				err = true;
6575 			for (int c = 0; c < frame && !err; c++) {
6576 				if (subprog[ret_prog[c]].is_cb) {
6577 					err = true;
6578 					break;
6579 				}
6580 			}
6581 			if (!err)
6582 				continue;
6583 			verbose(env,
6584 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6585 				i, idx);
6586 			return -EINVAL;
6587 		}
6588 
6589 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6590 			continue;
6591 		/* remember insn and function to return to */
6592 		ret_insn[frame] = i + 1;
6593 		ret_prog[frame] = idx;
6594 
6595 		/* find the callee */
6596 		next_insn = i + insn[i].imm + 1;
6597 		sidx = find_subprog(env, next_insn);
6598 		if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
6599 			return -EFAULT;
6600 		if (subprog[sidx].is_async_cb) {
6601 			if (subprog[sidx].has_tail_call) {
6602 				verifier_bug(env, "subprog has tail_call and async cb");
6603 				return -EFAULT;
6604 			}
6605 			/* async callbacks don't increase bpf prog stack size unless called directly */
6606 			if (!bpf_pseudo_call(insn + i))
6607 				continue;
6608 			if (subprog[sidx].is_exception_cb) {
6609 				verbose(env, "insn %d cannot call exception cb directly", i);
6610 				return -EINVAL;
6611 			}
6612 		}
6613 		i = next_insn;
6614 		idx = sidx;
6615 		if (!priv_stack_supported)
6616 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6617 
6618 		if (subprog[idx].has_tail_call)
6619 			tail_call_reachable = true;
6620 
6621 		frame++;
6622 		if (frame >= MAX_CALL_FRAMES) {
6623 			verbose(env, "the call stack of %d frames is too deep !\n",
6624 				frame);
6625 			return -E2BIG;
6626 		}
6627 		goto process_func;
6628 	}
6629 	/* if tail call got detected across bpf2bpf calls then mark each of the
6630 	 * currently present subprog frames as tail call reachable subprogs;
6631 	 * this info will be utilized by JIT so that we will be preserving the
6632 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6633 	 */
6634 	if (tail_call_reachable)
6635 		for (j = 0; j < frame; j++) {
6636 			if (subprog[ret_prog[j]].is_exception_cb) {
6637 				verbose(env, "cannot tail call within exception cb\n");
6638 				return -EINVAL;
6639 			}
6640 			subprog[ret_prog[j]].tail_call_reachable = true;
6641 		}
6642 	if (subprog[0].tail_call_reachable)
6643 		env->prog->aux->tail_call_reachable = true;
6644 
6645 	/* end of for() loop means the last insn of the 'subprog'
6646 	 * was reached. Doesn't matter whether it was JA or EXIT
6647 	 */
6648 	if (frame == 0)
6649 		return 0;
6650 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6651 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6652 	frame--;
6653 	i = ret_insn[frame];
6654 	idx = ret_prog[frame];
6655 	goto continue_func;
6656 }
6657 
6658 static int check_max_stack_depth(struct bpf_verifier_env *env)
6659 {
6660 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6661 	struct bpf_subprog_info *si = env->subprog_info;
6662 	bool priv_stack_supported;
6663 	int ret;
6664 
6665 	for (int i = 0; i < env->subprog_cnt; i++) {
6666 		if (si[i].has_tail_call) {
6667 			priv_stack_mode = NO_PRIV_STACK;
6668 			break;
6669 		}
6670 	}
6671 
6672 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6673 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6674 
6675 	/* All async_cb subprogs use normal kernel stack. If a particular
6676 	 * subprog appears in both main prog and async_cb subtree, that
6677 	 * subprog will use normal kernel stack to avoid potential nesting.
6678 	 * The reverse subprog traversal ensures when main prog subtree is
6679 	 * checked, the subprogs appearing in async_cb subtrees are already
6680 	 * marked as using normal kernel stack, so stack size checking can
6681 	 * be done properly.
6682 	 */
6683 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6684 		if (!i || si[i].is_async_cb) {
6685 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6686 			ret = check_max_stack_depth_subprog(env, i, priv_stack_supported);
6687 			if (ret < 0)
6688 				return ret;
6689 		}
6690 	}
6691 
6692 	for (int i = 0; i < env->subprog_cnt; i++) {
6693 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6694 			env->prog->aux->jits_use_priv_stack = true;
6695 			break;
6696 		}
6697 	}
6698 
6699 	return 0;
6700 }
6701 
6702 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6703 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6704 				  const struct bpf_insn *insn, int idx)
6705 {
6706 	int start = idx + insn->imm + 1, subprog;
6707 
6708 	subprog = find_subprog(env, start);
6709 	if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start))
6710 		return -EFAULT;
6711 	return env->subprog_info[subprog].stack_depth;
6712 }
6713 #endif
6714 
6715 static int __check_buffer_access(struct bpf_verifier_env *env,
6716 				 const char *buf_info,
6717 				 const struct bpf_reg_state *reg,
6718 				 int regno, int off, int size)
6719 {
6720 	if (off < 0) {
6721 		verbose(env,
6722 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6723 			regno, buf_info, off, size);
6724 		return -EACCES;
6725 	}
6726 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6727 		char tn_buf[48];
6728 
6729 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6730 		verbose(env,
6731 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6732 			regno, off, tn_buf);
6733 		return -EACCES;
6734 	}
6735 
6736 	return 0;
6737 }
6738 
6739 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6740 				  const struct bpf_reg_state *reg,
6741 				  int regno, int off, int size)
6742 {
6743 	int err;
6744 
6745 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6746 	if (err)
6747 		return err;
6748 
6749 	if (off + size > env->prog->aux->max_tp_access)
6750 		env->prog->aux->max_tp_access = off + size;
6751 
6752 	return 0;
6753 }
6754 
6755 static int check_buffer_access(struct bpf_verifier_env *env,
6756 			       const struct bpf_reg_state *reg,
6757 			       int regno, int off, int size,
6758 			       bool zero_size_allowed,
6759 			       u32 *max_access)
6760 {
6761 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6762 	int err;
6763 
6764 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6765 	if (err)
6766 		return err;
6767 
6768 	if (off + size > *max_access)
6769 		*max_access = off + size;
6770 
6771 	return 0;
6772 }
6773 
6774 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6775 static void zext_32_to_64(struct bpf_reg_state *reg)
6776 {
6777 	reg->var_off = tnum_subreg(reg->var_off);
6778 	__reg_assign_32_into_64(reg);
6779 }
6780 
6781 /* truncate register to smaller size (in bytes)
6782  * must be called with size < BPF_REG_SIZE
6783  */
6784 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6785 {
6786 	u64 mask;
6787 
6788 	/* clear high bits in bit representation */
6789 	reg->var_off = tnum_cast(reg->var_off, size);
6790 
6791 	/* fix arithmetic bounds */
6792 	mask = ((u64)1 << (size * 8)) - 1;
6793 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6794 		reg->umin_value &= mask;
6795 		reg->umax_value &= mask;
6796 	} else {
6797 		reg->umin_value = 0;
6798 		reg->umax_value = mask;
6799 	}
6800 	reg->smin_value = reg->umin_value;
6801 	reg->smax_value = reg->umax_value;
6802 
6803 	/* If size is smaller than 32bit register the 32bit register
6804 	 * values are also truncated so we push 64-bit bounds into
6805 	 * 32-bit bounds. Above were truncated < 32-bits already.
6806 	 */
6807 	if (size < 4)
6808 		__mark_reg32_unbounded(reg);
6809 
6810 	reg_bounds_sync(reg);
6811 }
6812 
6813 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6814 {
6815 	if (size == 1) {
6816 		reg->smin_value = reg->s32_min_value = S8_MIN;
6817 		reg->smax_value = reg->s32_max_value = S8_MAX;
6818 	} else if (size == 2) {
6819 		reg->smin_value = reg->s32_min_value = S16_MIN;
6820 		reg->smax_value = reg->s32_max_value = S16_MAX;
6821 	} else {
6822 		/* size == 4 */
6823 		reg->smin_value = reg->s32_min_value = S32_MIN;
6824 		reg->smax_value = reg->s32_max_value = S32_MAX;
6825 	}
6826 	reg->umin_value = reg->u32_min_value = 0;
6827 	reg->umax_value = U64_MAX;
6828 	reg->u32_max_value = U32_MAX;
6829 	reg->var_off = tnum_unknown;
6830 }
6831 
6832 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6833 {
6834 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6835 	u64 top_smax_value, top_smin_value;
6836 	u64 num_bits = size * 8;
6837 
6838 	if (tnum_is_const(reg->var_off)) {
6839 		u64_cval = reg->var_off.value;
6840 		if (size == 1)
6841 			reg->var_off = tnum_const((s8)u64_cval);
6842 		else if (size == 2)
6843 			reg->var_off = tnum_const((s16)u64_cval);
6844 		else
6845 			/* size == 4 */
6846 			reg->var_off = tnum_const((s32)u64_cval);
6847 
6848 		u64_cval = reg->var_off.value;
6849 		reg->smax_value = reg->smin_value = u64_cval;
6850 		reg->umax_value = reg->umin_value = u64_cval;
6851 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6852 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6853 		return;
6854 	}
6855 
6856 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6857 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6858 
6859 	if (top_smax_value != top_smin_value)
6860 		goto out;
6861 
6862 	/* find the s64_min and s64_min after sign extension */
6863 	if (size == 1) {
6864 		init_s64_max = (s8)reg->smax_value;
6865 		init_s64_min = (s8)reg->smin_value;
6866 	} else if (size == 2) {
6867 		init_s64_max = (s16)reg->smax_value;
6868 		init_s64_min = (s16)reg->smin_value;
6869 	} else {
6870 		init_s64_max = (s32)reg->smax_value;
6871 		init_s64_min = (s32)reg->smin_value;
6872 	}
6873 
6874 	s64_max = max(init_s64_max, init_s64_min);
6875 	s64_min = min(init_s64_max, init_s64_min);
6876 
6877 	/* both of s64_max/s64_min positive or negative */
6878 	if ((s64_max >= 0) == (s64_min >= 0)) {
6879 		reg->s32_min_value = reg->smin_value = s64_min;
6880 		reg->s32_max_value = reg->smax_value = s64_max;
6881 		reg->u32_min_value = reg->umin_value = s64_min;
6882 		reg->u32_max_value = reg->umax_value = s64_max;
6883 		reg->var_off = tnum_range(s64_min, s64_max);
6884 		return;
6885 	}
6886 
6887 out:
6888 	set_sext64_default_val(reg, size);
6889 }
6890 
6891 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6892 {
6893 	if (size == 1) {
6894 		reg->s32_min_value = S8_MIN;
6895 		reg->s32_max_value = S8_MAX;
6896 	} else {
6897 		/* size == 2 */
6898 		reg->s32_min_value = S16_MIN;
6899 		reg->s32_max_value = S16_MAX;
6900 	}
6901 	reg->u32_min_value = 0;
6902 	reg->u32_max_value = U32_MAX;
6903 	reg->var_off = tnum_subreg(tnum_unknown);
6904 }
6905 
6906 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6907 {
6908 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6909 	u32 top_smax_value, top_smin_value;
6910 	u32 num_bits = size * 8;
6911 
6912 	if (tnum_is_const(reg->var_off)) {
6913 		u32_val = reg->var_off.value;
6914 		if (size == 1)
6915 			reg->var_off = tnum_const((s8)u32_val);
6916 		else
6917 			reg->var_off = tnum_const((s16)u32_val);
6918 
6919 		u32_val = reg->var_off.value;
6920 		reg->s32_min_value = reg->s32_max_value = u32_val;
6921 		reg->u32_min_value = reg->u32_max_value = u32_val;
6922 		return;
6923 	}
6924 
6925 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6926 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6927 
6928 	if (top_smax_value != top_smin_value)
6929 		goto out;
6930 
6931 	/* find the s32_min and s32_min after sign extension */
6932 	if (size == 1) {
6933 		init_s32_max = (s8)reg->s32_max_value;
6934 		init_s32_min = (s8)reg->s32_min_value;
6935 	} else {
6936 		/* size == 2 */
6937 		init_s32_max = (s16)reg->s32_max_value;
6938 		init_s32_min = (s16)reg->s32_min_value;
6939 	}
6940 	s32_max = max(init_s32_max, init_s32_min);
6941 	s32_min = min(init_s32_max, init_s32_min);
6942 
6943 	if ((s32_min >= 0) == (s32_max >= 0)) {
6944 		reg->s32_min_value = s32_min;
6945 		reg->s32_max_value = s32_max;
6946 		reg->u32_min_value = (u32)s32_min;
6947 		reg->u32_max_value = (u32)s32_max;
6948 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6949 		return;
6950 	}
6951 
6952 out:
6953 	set_sext32_default_val(reg, size);
6954 }
6955 
6956 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6957 {
6958 	/* A map is considered read-only if the following condition are true:
6959 	 *
6960 	 * 1) BPF program side cannot change any of the map content. The
6961 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6962 	 *    and was set at map creation time.
6963 	 * 2) The map value(s) have been initialized from user space by a
6964 	 *    loader and then "frozen", such that no new map update/delete
6965 	 *    operations from syscall side are possible for the rest of
6966 	 *    the map's lifetime from that point onwards.
6967 	 * 3) Any parallel/pending map update/delete operations from syscall
6968 	 *    side have been completed. Only after that point, it's safe to
6969 	 *    assume that map value(s) are immutable.
6970 	 */
6971 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6972 	       READ_ONCE(map->frozen) &&
6973 	       !bpf_map_write_active(map);
6974 }
6975 
6976 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6977 			       bool is_ldsx)
6978 {
6979 	void *ptr;
6980 	u64 addr;
6981 	int err;
6982 
6983 	err = map->ops->map_direct_value_addr(map, &addr, off);
6984 	if (err)
6985 		return err;
6986 	ptr = (void *)(long)addr + off;
6987 
6988 	switch (size) {
6989 	case sizeof(u8):
6990 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6991 		break;
6992 	case sizeof(u16):
6993 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6994 		break;
6995 	case sizeof(u32):
6996 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6997 		break;
6998 	case sizeof(u64):
6999 		*val = *(u64 *)ptr;
7000 		break;
7001 	default:
7002 		return -EINVAL;
7003 	}
7004 	return 0;
7005 }
7006 
7007 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
7008 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
7009 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
7010 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
7011 
7012 /*
7013  * Allow list few fields as RCU trusted or full trusted.
7014  * This logic doesn't allow mix tagging and will be removed once GCC supports
7015  * btf_type_tag.
7016  */
7017 
7018 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
7019 BTF_TYPE_SAFE_RCU(struct task_struct) {
7020 	const cpumask_t *cpus_ptr;
7021 	struct css_set __rcu *cgroups;
7022 	struct task_struct __rcu *real_parent;
7023 	struct task_struct *group_leader;
7024 };
7025 
7026 BTF_TYPE_SAFE_RCU(struct cgroup) {
7027 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
7028 	struct kernfs_node *kn;
7029 };
7030 
7031 BTF_TYPE_SAFE_RCU(struct css_set) {
7032 	struct cgroup *dfl_cgrp;
7033 };
7034 
7035 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
7036 	struct cgroup *cgroup;
7037 };
7038 
7039 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
7040 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
7041 	struct file __rcu *exe_file;
7042 };
7043 
7044 /* skb->sk, req->sk are not RCU protected, but we mark them as such
7045  * because bpf prog accessible sockets are SOCK_RCU_FREE.
7046  */
7047 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
7048 	struct sock *sk;
7049 };
7050 
7051 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
7052 	struct sock *sk;
7053 };
7054 
7055 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
7056 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
7057 	struct seq_file *seq;
7058 };
7059 
7060 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
7061 	struct bpf_iter_meta *meta;
7062 	struct task_struct *task;
7063 };
7064 
7065 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
7066 	struct file *file;
7067 };
7068 
7069 BTF_TYPE_SAFE_TRUSTED(struct file) {
7070 	struct inode *f_inode;
7071 };
7072 
7073 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
7074 	struct inode *d_inode;
7075 };
7076 
7077 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
7078 	struct sock *sk;
7079 };
7080 
7081 static bool type_is_rcu(struct bpf_verifier_env *env,
7082 			struct bpf_reg_state *reg,
7083 			const char *field_name, u32 btf_id)
7084 {
7085 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
7086 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
7087 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
7088 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
7089 
7090 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
7091 }
7092 
7093 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
7094 				struct bpf_reg_state *reg,
7095 				const char *field_name, u32 btf_id)
7096 {
7097 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
7098 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
7099 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
7100 
7101 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
7102 }
7103 
7104 static bool type_is_trusted(struct bpf_verifier_env *env,
7105 			    struct bpf_reg_state *reg,
7106 			    const char *field_name, u32 btf_id)
7107 {
7108 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
7109 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
7110 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
7111 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
7112 
7113 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
7114 }
7115 
7116 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
7117 				    struct bpf_reg_state *reg,
7118 				    const char *field_name, u32 btf_id)
7119 {
7120 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
7121 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
7122 
7123 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
7124 					  "__safe_trusted_or_null");
7125 }
7126 
7127 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
7128 				   struct bpf_reg_state *regs,
7129 				   int regno, int off, int size,
7130 				   enum bpf_access_type atype,
7131 				   int value_regno)
7132 {
7133 	struct bpf_reg_state *reg = regs + regno;
7134 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
7135 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
7136 	const char *field_name = NULL;
7137 	enum bpf_type_flag flag = 0;
7138 	u32 btf_id = 0;
7139 	int ret;
7140 
7141 	if (!env->allow_ptr_leaks) {
7142 		verbose(env,
7143 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7144 			tname);
7145 		return -EPERM;
7146 	}
7147 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
7148 		verbose(env,
7149 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
7150 			tname);
7151 		return -EINVAL;
7152 	}
7153 	if (off < 0) {
7154 		verbose(env,
7155 			"R%d is ptr_%s invalid negative access: off=%d\n",
7156 			regno, tname, off);
7157 		return -EACCES;
7158 	}
7159 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
7160 		char tn_buf[48];
7161 
7162 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7163 		verbose(env,
7164 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
7165 			regno, tname, off, tn_buf);
7166 		return -EACCES;
7167 	}
7168 
7169 	if (reg->type & MEM_USER) {
7170 		verbose(env,
7171 			"R%d is ptr_%s access user memory: off=%d\n",
7172 			regno, tname, off);
7173 		return -EACCES;
7174 	}
7175 
7176 	if (reg->type & MEM_PERCPU) {
7177 		verbose(env,
7178 			"R%d is ptr_%s access percpu memory: off=%d\n",
7179 			regno, tname, off);
7180 		return -EACCES;
7181 	}
7182 
7183 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
7184 		if (!btf_is_kernel(reg->btf)) {
7185 			verifier_bug(env, "reg->btf must be kernel btf");
7186 			return -EFAULT;
7187 		}
7188 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
7189 	} else {
7190 		/* Writes are permitted with default btf_struct_access for
7191 		 * program allocated objects (which always have ref_obj_id > 0),
7192 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
7193 		 */
7194 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
7195 			verbose(env, "only read is supported\n");
7196 			return -EACCES;
7197 		}
7198 
7199 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
7200 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
7201 			verifier_bug(env, "ref_obj_id for allocated object must be non-zero");
7202 			return -EFAULT;
7203 		}
7204 
7205 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
7206 	}
7207 
7208 	if (ret < 0)
7209 		return ret;
7210 
7211 	if (ret != PTR_TO_BTF_ID) {
7212 		/* just mark; */
7213 
7214 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
7215 		/* If this is an untrusted pointer, all pointers formed by walking it
7216 		 * also inherit the untrusted flag.
7217 		 */
7218 		flag = PTR_UNTRUSTED;
7219 
7220 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
7221 		/* By default any pointer obtained from walking a trusted pointer is no
7222 		 * longer trusted, unless the field being accessed has explicitly been
7223 		 * marked as inheriting its parent's state of trust (either full or RCU).
7224 		 * For example:
7225 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
7226 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
7227 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
7228 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
7229 		 *
7230 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
7231 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
7232 		 */
7233 		if (type_is_trusted(env, reg, field_name, btf_id)) {
7234 			flag |= PTR_TRUSTED;
7235 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
7236 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
7237 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
7238 			if (type_is_rcu(env, reg, field_name, btf_id)) {
7239 				/* ignore __rcu tag and mark it MEM_RCU */
7240 				flag |= MEM_RCU;
7241 			} else if (flag & MEM_RCU ||
7242 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
7243 				/* __rcu tagged pointers can be NULL */
7244 				flag |= MEM_RCU | PTR_MAYBE_NULL;
7245 
7246 				/* We always trust them */
7247 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
7248 				    flag & PTR_UNTRUSTED)
7249 					flag &= ~PTR_UNTRUSTED;
7250 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
7251 				/* keep as-is */
7252 			} else {
7253 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
7254 				clear_trusted_flags(&flag);
7255 			}
7256 		} else {
7257 			/*
7258 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
7259 			 * aggressively mark as untrusted otherwise such
7260 			 * pointers will be plain PTR_TO_BTF_ID without flags
7261 			 * and will be allowed to be passed into helpers for
7262 			 * compat reasons.
7263 			 */
7264 			flag = PTR_UNTRUSTED;
7265 		}
7266 	} else {
7267 		/* Old compat. Deprecated */
7268 		clear_trusted_flags(&flag);
7269 	}
7270 
7271 	if (atype == BPF_READ && value_regno >= 0) {
7272 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
7273 		if (ret < 0)
7274 			return ret;
7275 	}
7276 
7277 	return 0;
7278 }
7279 
7280 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
7281 				   struct bpf_reg_state *regs,
7282 				   int regno, int off, int size,
7283 				   enum bpf_access_type atype,
7284 				   int value_regno)
7285 {
7286 	struct bpf_reg_state *reg = regs + regno;
7287 	struct bpf_map *map = reg->map_ptr;
7288 	struct bpf_reg_state map_reg;
7289 	enum bpf_type_flag flag = 0;
7290 	const struct btf_type *t;
7291 	const char *tname;
7292 	u32 btf_id;
7293 	int ret;
7294 
7295 	if (!btf_vmlinux) {
7296 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
7297 		return -ENOTSUPP;
7298 	}
7299 
7300 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
7301 		verbose(env, "map_ptr access not supported for map type %d\n",
7302 			map->map_type);
7303 		return -ENOTSUPP;
7304 	}
7305 
7306 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
7307 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
7308 
7309 	if (!env->allow_ptr_leaks) {
7310 		verbose(env,
7311 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7312 			tname);
7313 		return -EPERM;
7314 	}
7315 
7316 	if (off < 0) {
7317 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
7318 			regno, tname, off);
7319 		return -EACCES;
7320 	}
7321 
7322 	if (atype != BPF_READ) {
7323 		verbose(env, "only read from %s is supported\n", tname);
7324 		return -EACCES;
7325 	}
7326 
7327 	/* Simulate access to a PTR_TO_BTF_ID */
7328 	memset(&map_reg, 0, sizeof(map_reg));
7329 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
7330 			      btf_vmlinux, *map->ops->map_btf_id, 0);
7331 	if (ret < 0)
7332 		return ret;
7333 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
7334 	if (ret < 0)
7335 		return ret;
7336 
7337 	if (value_regno >= 0) {
7338 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
7339 		if (ret < 0)
7340 			return ret;
7341 	}
7342 
7343 	return 0;
7344 }
7345 
7346 /* Check that the stack access at the given offset is within bounds. The
7347  * maximum valid offset is -1.
7348  *
7349  * The minimum valid offset is -MAX_BPF_STACK for writes, and
7350  * -state->allocated_stack for reads.
7351  */
7352 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
7353                                           s64 off,
7354                                           struct bpf_func_state *state,
7355                                           enum bpf_access_type t)
7356 {
7357 	int min_valid_off;
7358 
7359 	if (t == BPF_WRITE || env->allow_uninit_stack)
7360 		min_valid_off = -MAX_BPF_STACK;
7361 	else
7362 		min_valid_off = -state->allocated_stack;
7363 
7364 	if (off < min_valid_off || off > -1)
7365 		return -EACCES;
7366 	return 0;
7367 }
7368 
7369 /* Check that the stack access at 'regno + off' falls within the maximum stack
7370  * bounds.
7371  *
7372  * 'off' includes `regno->offset`, but not its dynamic part (if any).
7373  */
7374 static int check_stack_access_within_bounds(
7375 		struct bpf_verifier_env *env,
7376 		int regno, int off, int access_size,
7377 		enum bpf_access_type type)
7378 {
7379 	struct bpf_reg_state *regs = cur_regs(env);
7380 	struct bpf_reg_state *reg = regs + regno;
7381 	struct bpf_func_state *state = func(env, reg);
7382 	s64 min_off, max_off;
7383 	int err;
7384 	char *err_extra;
7385 
7386 	if (type == BPF_READ)
7387 		err_extra = " read from";
7388 	else
7389 		err_extra = " write to";
7390 
7391 	if (tnum_is_const(reg->var_off)) {
7392 		min_off = (s64)reg->var_off.value + off;
7393 		max_off = min_off + access_size;
7394 	} else {
7395 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
7396 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
7397 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
7398 				err_extra, regno);
7399 			return -EACCES;
7400 		}
7401 		min_off = reg->smin_value + off;
7402 		max_off = reg->smax_value + off + access_size;
7403 	}
7404 
7405 	err = check_stack_slot_within_bounds(env, min_off, state, type);
7406 	if (!err && max_off > 0)
7407 		err = -EINVAL; /* out of stack access into non-negative offsets */
7408 	if (!err && access_size < 0)
7409 		/* access_size should not be negative (or overflow an int); others checks
7410 		 * along the way should have prevented such an access.
7411 		 */
7412 		err = -EFAULT; /* invalid negative access size; integer overflow? */
7413 
7414 	if (err) {
7415 		if (tnum_is_const(reg->var_off)) {
7416 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
7417 				err_extra, regno, off, access_size);
7418 		} else {
7419 			char tn_buf[48];
7420 
7421 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7422 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
7423 				err_extra, regno, tn_buf, off, access_size);
7424 		}
7425 		return err;
7426 	}
7427 
7428 	/* Note that there is no stack access with offset zero, so the needed stack
7429 	 * size is -min_off, not -min_off+1.
7430 	 */
7431 	return grow_stack_state(env, state, -min_off /* size */);
7432 }
7433 
7434 static bool get_func_retval_range(struct bpf_prog *prog,
7435 				  struct bpf_retval_range *range)
7436 {
7437 	if (prog->type == BPF_PROG_TYPE_LSM &&
7438 		prog->expected_attach_type == BPF_LSM_MAC &&
7439 		!bpf_lsm_get_retval_range(prog, range)) {
7440 		return true;
7441 	}
7442 	return false;
7443 }
7444 
7445 /* check whether memory at (regno + off) is accessible for t = (read | write)
7446  * if t==write, value_regno is a register which value is stored into memory
7447  * if t==read, value_regno is a register which will receive the value from memory
7448  * if t==write && value_regno==-1, some unknown value is stored into memory
7449  * if t==read && value_regno==-1, don't care what we read from memory
7450  */
7451 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
7452 			    int off, int bpf_size, enum bpf_access_type t,
7453 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7454 {
7455 	struct bpf_reg_state *regs = cur_regs(env);
7456 	struct bpf_reg_state *reg = regs + regno;
7457 	int size, err = 0;
7458 
7459 	size = bpf_size_to_bytes(bpf_size);
7460 	if (size < 0)
7461 		return size;
7462 
7463 	/* alignment checks will add in reg->off themselves */
7464 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7465 	if (err)
7466 		return err;
7467 
7468 	/* for access checks, reg->off is just part of off */
7469 	off += reg->off;
7470 
7471 	if (reg->type == PTR_TO_MAP_KEY) {
7472 		if (t == BPF_WRITE) {
7473 			verbose(env, "write to change key R%d not allowed\n", regno);
7474 			return -EACCES;
7475 		}
7476 
7477 		err = check_mem_region_access(env, regno, off, size,
7478 					      reg->map_ptr->key_size, false);
7479 		if (err)
7480 			return err;
7481 		if (value_regno >= 0)
7482 			mark_reg_unknown(env, regs, value_regno);
7483 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7484 		struct btf_field *kptr_field = NULL;
7485 
7486 		if (t == BPF_WRITE && value_regno >= 0 &&
7487 		    is_pointer_value(env, value_regno)) {
7488 			verbose(env, "R%d leaks addr into map\n", value_regno);
7489 			return -EACCES;
7490 		}
7491 		err = check_map_access_type(env, regno, off, size, t);
7492 		if (err)
7493 			return err;
7494 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
7495 		if (err)
7496 			return err;
7497 		if (tnum_is_const(reg->var_off))
7498 			kptr_field = btf_record_find(reg->map_ptr->record,
7499 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7500 		if (kptr_field) {
7501 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
7502 		} else if (t == BPF_READ && value_regno >= 0) {
7503 			struct bpf_map *map = reg->map_ptr;
7504 
7505 			/* if map is read-only, track its contents as scalars */
7506 			if (tnum_is_const(reg->var_off) &&
7507 			    bpf_map_is_rdonly(map) &&
7508 			    map->ops->map_direct_value_addr) {
7509 				int map_off = off + reg->var_off.value;
7510 				u64 val = 0;
7511 
7512 				err = bpf_map_direct_read(map, map_off, size,
7513 							  &val, is_ldsx);
7514 				if (err)
7515 					return err;
7516 
7517 				regs[value_regno].type = SCALAR_VALUE;
7518 				__mark_reg_known(&regs[value_regno], val);
7519 			} else {
7520 				mark_reg_unknown(env, regs, value_regno);
7521 			}
7522 		}
7523 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7524 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7525 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
7526 
7527 		if (type_may_be_null(reg->type)) {
7528 			verbose(env, "R%d invalid mem access '%s'\n", regno,
7529 				reg_type_str(env, reg->type));
7530 			return -EACCES;
7531 		}
7532 
7533 		if (t == BPF_WRITE && rdonly_mem) {
7534 			verbose(env, "R%d cannot write into %s\n",
7535 				regno, reg_type_str(env, reg->type));
7536 			return -EACCES;
7537 		}
7538 
7539 		if (t == BPF_WRITE && value_regno >= 0 &&
7540 		    is_pointer_value(env, value_regno)) {
7541 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7542 			return -EACCES;
7543 		}
7544 
7545 		/*
7546 		 * Accesses to untrusted PTR_TO_MEM are done through probe
7547 		 * instructions, hence no need to check bounds in that case.
7548 		 */
7549 		if (!rdonly_untrusted)
7550 			err = check_mem_region_access(env, regno, off, size,
7551 						      reg->mem_size, false);
7552 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7553 			mark_reg_unknown(env, regs, value_regno);
7554 	} else if (reg->type == PTR_TO_CTX) {
7555 		struct bpf_retval_range range;
7556 		struct bpf_insn_access_aux info = {
7557 			.reg_type = SCALAR_VALUE,
7558 			.is_ldsx = is_ldsx,
7559 			.log = &env->log,
7560 		};
7561 
7562 		if (t == BPF_WRITE && value_regno >= 0 &&
7563 		    is_pointer_value(env, value_regno)) {
7564 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7565 			return -EACCES;
7566 		}
7567 
7568 		err = check_ptr_off_reg(env, reg, regno);
7569 		if (err < 0)
7570 			return err;
7571 
7572 		err = check_ctx_access(env, insn_idx, off, size, t, &info);
7573 		if (err)
7574 			verbose_linfo(env, insn_idx, "; ");
7575 		if (!err && t == BPF_READ && value_regno >= 0) {
7576 			/* ctx access returns either a scalar, or a
7577 			 * PTR_TO_PACKET[_META,_END]. In the latter
7578 			 * case, we know the offset is zero.
7579 			 */
7580 			if (info.reg_type == SCALAR_VALUE) {
7581 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
7582 					err = __mark_reg_s32_range(env, regs, value_regno,
7583 								   range.minval, range.maxval);
7584 					if (err)
7585 						return err;
7586 				} else {
7587 					mark_reg_unknown(env, regs, value_regno);
7588 				}
7589 			} else {
7590 				mark_reg_known_zero(env, regs,
7591 						    value_regno);
7592 				if (type_may_be_null(info.reg_type))
7593 					regs[value_regno].id = ++env->id_gen;
7594 				/* A load of ctx field could have different
7595 				 * actual load size with the one encoded in the
7596 				 * insn. When the dst is PTR, it is for sure not
7597 				 * a sub-register.
7598 				 */
7599 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7600 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
7601 					regs[value_regno].btf = info.btf;
7602 					regs[value_regno].btf_id = info.btf_id;
7603 					regs[value_regno].ref_obj_id = info.ref_obj_id;
7604 				}
7605 			}
7606 			regs[value_regno].type = info.reg_type;
7607 		}
7608 
7609 	} else if (reg->type == PTR_TO_STACK) {
7610 		/* Basic bounds checks. */
7611 		err = check_stack_access_within_bounds(env, regno, off, size, t);
7612 		if (err)
7613 			return err;
7614 
7615 		if (t == BPF_READ)
7616 			err = check_stack_read(env, regno, off, size,
7617 					       value_regno);
7618 		else
7619 			err = check_stack_write(env, regno, off, size,
7620 						value_regno, insn_idx);
7621 	} else if (reg_is_pkt_pointer(reg)) {
7622 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7623 			verbose(env, "cannot write into packet\n");
7624 			return -EACCES;
7625 		}
7626 		if (t == BPF_WRITE && value_regno >= 0 &&
7627 		    is_pointer_value(env, value_regno)) {
7628 			verbose(env, "R%d leaks addr into packet\n",
7629 				value_regno);
7630 			return -EACCES;
7631 		}
7632 		err = check_packet_access(env, regno, off, size, false);
7633 		if (!err && t == BPF_READ && value_regno >= 0)
7634 			mark_reg_unknown(env, regs, value_regno);
7635 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7636 		if (t == BPF_WRITE && value_regno >= 0 &&
7637 		    is_pointer_value(env, value_regno)) {
7638 			verbose(env, "R%d leaks addr into flow keys\n",
7639 				value_regno);
7640 			return -EACCES;
7641 		}
7642 
7643 		err = check_flow_keys_access(env, off, size);
7644 		if (!err && t == BPF_READ && value_regno >= 0)
7645 			mark_reg_unknown(env, regs, value_regno);
7646 	} else if (type_is_sk_pointer(reg->type)) {
7647 		if (t == BPF_WRITE) {
7648 			verbose(env, "R%d cannot write into %s\n",
7649 				regno, reg_type_str(env, reg->type));
7650 			return -EACCES;
7651 		}
7652 		err = check_sock_access(env, insn_idx, regno, off, size, t);
7653 		if (!err && value_regno >= 0)
7654 			mark_reg_unknown(env, regs, value_regno);
7655 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7656 		err = check_tp_buffer_access(env, reg, regno, off, size);
7657 		if (!err && t == BPF_READ && value_regno >= 0)
7658 			mark_reg_unknown(env, regs, value_regno);
7659 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7660 		   !type_may_be_null(reg->type)) {
7661 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7662 					      value_regno);
7663 	} else if (reg->type == CONST_PTR_TO_MAP) {
7664 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7665 					      value_regno);
7666 	} else if (base_type(reg->type) == PTR_TO_BUF) {
7667 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7668 		u32 *max_access;
7669 
7670 		if (rdonly_mem) {
7671 			if (t == BPF_WRITE) {
7672 				verbose(env, "R%d cannot write into %s\n",
7673 					regno, reg_type_str(env, reg->type));
7674 				return -EACCES;
7675 			}
7676 			max_access = &env->prog->aux->max_rdonly_access;
7677 		} else {
7678 			max_access = &env->prog->aux->max_rdwr_access;
7679 		}
7680 
7681 		err = check_buffer_access(env, reg, regno, off, size, false,
7682 					  max_access);
7683 
7684 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7685 			mark_reg_unknown(env, regs, value_regno);
7686 	} else if (reg->type == PTR_TO_ARENA) {
7687 		if (t == BPF_READ && value_regno >= 0)
7688 			mark_reg_unknown(env, regs, value_regno);
7689 	} else {
7690 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7691 			reg_type_str(env, reg->type));
7692 		return -EACCES;
7693 	}
7694 
7695 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7696 	    regs[value_regno].type == SCALAR_VALUE) {
7697 		if (!is_ldsx)
7698 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7699 			coerce_reg_to_size(&regs[value_regno], size);
7700 		else
7701 			coerce_reg_to_size_sx(&regs[value_regno], size);
7702 	}
7703 	return err;
7704 }
7705 
7706 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7707 			     bool allow_trust_mismatch);
7708 
7709 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
7710 			  bool strict_alignment_once, bool is_ldsx,
7711 			  bool allow_trust_mismatch, const char *ctx)
7712 {
7713 	struct bpf_reg_state *regs = cur_regs(env);
7714 	enum bpf_reg_type src_reg_type;
7715 	int err;
7716 
7717 	/* check src operand */
7718 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7719 	if (err)
7720 		return err;
7721 
7722 	/* check dst operand */
7723 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7724 	if (err)
7725 		return err;
7726 
7727 	src_reg_type = regs[insn->src_reg].type;
7728 
7729 	/* Check if (src_reg + off) is readable. The state of dst_reg will be
7730 	 * updated by this call.
7731 	 */
7732 	err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off,
7733 			       BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
7734 			       strict_alignment_once, is_ldsx);
7735 	err = err ?: save_aux_ptr_type(env, src_reg_type,
7736 				       allow_trust_mismatch);
7737 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
7738 
7739 	return err;
7740 }
7741 
7742 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
7743 			   bool strict_alignment_once)
7744 {
7745 	struct bpf_reg_state *regs = cur_regs(env);
7746 	enum bpf_reg_type dst_reg_type;
7747 	int err;
7748 
7749 	/* check src1 operand */
7750 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7751 	if (err)
7752 		return err;
7753 
7754 	/* check src2 operand */
7755 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7756 	if (err)
7757 		return err;
7758 
7759 	dst_reg_type = regs[insn->dst_reg].type;
7760 
7761 	/* Check if (dst_reg + off) is writeable. */
7762 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7763 			       BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
7764 			       strict_alignment_once, false);
7765 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
7766 
7767 	return err;
7768 }
7769 
7770 static int check_atomic_rmw(struct bpf_verifier_env *env,
7771 			    struct bpf_insn *insn)
7772 {
7773 	int load_reg;
7774 	int err;
7775 
7776 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7777 		verbose(env, "invalid atomic operand size\n");
7778 		return -EINVAL;
7779 	}
7780 
7781 	/* check src1 operand */
7782 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7783 	if (err)
7784 		return err;
7785 
7786 	/* check src2 operand */
7787 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7788 	if (err)
7789 		return err;
7790 
7791 	if (insn->imm == BPF_CMPXCHG) {
7792 		/* Check comparison of R0 with memory location */
7793 		const u32 aux_reg = BPF_REG_0;
7794 
7795 		err = check_reg_arg(env, aux_reg, SRC_OP);
7796 		if (err)
7797 			return err;
7798 
7799 		if (is_pointer_value(env, aux_reg)) {
7800 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7801 			return -EACCES;
7802 		}
7803 	}
7804 
7805 	if (is_pointer_value(env, insn->src_reg)) {
7806 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7807 		return -EACCES;
7808 	}
7809 
7810 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7811 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7812 			insn->dst_reg,
7813 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7814 		return -EACCES;
7815 	}
7816 
7817 	if (insn->imm & BPF_FETCH) {
7818 		if (insn->imm == BPF_CMPXCHG)
7819 			load_reg = BPF_REG_0;
7820 		else
7821 			load_reg = insn->src_reg;
7822 
7823 		/* check and record load of old value */
7824 		err = check_reg_arg(env, load_reg, DST_OP);
7825 		if (err)
7826 			return err;
7827 	} else {
7828 		/* This instruction accesses a memory location but doesn't
7829 		 * actually load it into a register.
7830 		 */
7831 		load_reg = -1;
7832 	}
7833 
7834 	/* Check whether we can read the memory, with second call for fetch
7835 	 * case to simulate the register fill.
7836 	 */
7837 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7838 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7839 	if (!err && load_reg >= 0)
7840 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
7841 				       insn->off, BPF_SIZE(insn->code),
7842 				       BPF_READ, load_reg, true, false);
7843 	if (err)
7844 		return err;
7845 
7846 	if (is_arena_reg(env, insn->dst_reg)) {
7847 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7848 		if (err)
7849 			return err;
7850 	}
7851 	/* Check whether we can write into the same memory. */
7852 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7853 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7854 	if (err)
7855 		return err;
7856 	return 0;
7857 }
7858 
7859 static int check_atomic_load(struct bpf_verifier_env *env,
7860 			     struct bpf_insn *insn)
7861 {
7862 	int err;
7863 
7864 	err = check_load_mem(env, insn, true, false, false, "atomic_load");
7865 	if (err)
7866 		return err;
7867 
7868 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
7869 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
7870 			insn->src_reg,
7871 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
7872 		return -EACCES;
7873 	}
7874 
7875 	return 0;
7876 }
7877 
7878 static int check_atomic_store(struct bpf_verifier_env *env,
7879 			      struct bpf_insn *insn)
7880 {
7881 	int err;
7882 
7883 	err = check_store_reg(env, insn, true);
7884 	if (err)
7885 		return err;
7886 
7887 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7888 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7889 			insn->dst_reg,
7890 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7891 		return -EACCES;
7892 	}
7893 
7894 	return 0;
7895 }
7896 
7897 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
7898 {
7899 	switch (insn->imm) {
7900 	case BPF_ADD:
7901 	case BPF_ADD | BPF_FETCH:
7902 	case BPF_AND:
7903 	case BPF_AND | BPF_FETCH:
7904 	case BPF_OR:
7905 	case BPF_OR | BPF_FETCH:
7906 	case BPF_XOR:
7907 	case BPF_XOR | BPF_FETCH:
7908 	case BPF_XCHG:
7909 	case BPF_CMPXCHG:
7910 		return check_atomic_rmw(env, insn);
7911 	case BPF_LOAD_ACQ:
7912 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7913 			verbose(env,
7914 				"64-bit load-acquires are only supported on 64-bit arches\n");
7915 			return -EOPNOTSUPP;
7916 		}
7917 		return check_atomic_load(env, insn);
7918 	case BPF_STORE_REL:
7919 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7920 			verbose(env,
7921 				"64-bit store-releases are only supported on 64-bit arches\n");
7922 			return -EOPNOTSUPP;
7923 		}
7924 		return check_atomic_store(env, insn);
7925 	default:
7926 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
7927 			insn->imm);
7928 		return -EINVAL;
7929 	}
7930 }
7931 
7932 /* When register 'regno' is used to read the stack (either directly or through
7933  * a helper function) make sure that it's within stack boundary and, depending
7934  * on the access type and privileges, that all elements of the stack are
7935  * initialized.
7936  *
7937  * 'off' includes 'regno->off', but not its dynamic part (if any).
7938  *
7939  * All registers that have been spilled on the stack in the slots within the
7940  * read offsets are marked as read.
7941  */
7942 static int check_stack_range_initialized(
7943 		struct bpf_verifier_env *env, int regno, int off,
7944 		int access_size, bool zero_size_allowed,
7945 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
7946 {
7947 	struct bpf_reg_state *reg = reg_state(env, regno);
7948 	struct bpf_func_state *state = func(env, reg);
7949 	int err, min_off, max_off, i, j, slot, spi;
7950 	/* Some accesses can write anything into the stack, others are
7951 	 * read-only.
7952 	 */
7953 	bool clobber = false;
7954 
7955 	if (access_size == 0 && !zero_size_allowed) {
7956 		verbose(env, "invalid zero-sized read\n");
7957 		return -EACCES;
7958 	}
7959 
7960 	if (type == BPF_WRITE)
7961 		clobber = true;
7962 
7963 	err = check_stack_access_within_bounds(env, regno, off, access_size, type);
7964 	if (err)
7965 		return err;
7966 
7967 
7968 	if (tnum_is_const(reg->var_off)) {
7969 		min_off = max_off = reg->var_off.value + off;
7970 	} else {
7971 		/* Variable offset is prohibited for unprivileged mode for
7972 		 * simplicity since it requires corresponding support in
7973 		 * Spectre masking for stack ALU.
7974 		 * See also retrieve_ptr_limit().
7975 		 */
7976 		if (!env->bypass_spec_v1) {
7977 			char tn_buf[48];
7978 
7979 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7980 			verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
7981 				regno, tn_buf);
7982 			return -EACCES;
7983 		}
7984 		/* Only initialized buffer on stack is allowed to be accessed
7985 		 * with variable offset. With uninitialized buffer it's hard to
7986 		 * guarantee that whole memory is marked as initialized on
7987 		 * helper return since specific bounds are unknown what may
7988 		 * cause uninitialized stack leaking.
7989 		 */
7990 		if (meta && meta->raw_mode)
7991 			meta = NULL;
7992 
7993 		min_off = reg->smin_value + off;
7994 		max_off = reg->smax_value + off;
7995 	}
7996 
7997 	if (meta && meta->raw_mode) {
7998 		/* Ensure we won't be overwriting dynptrs when simulating byte
7999 		 * by byte access in check_helper_call using meta.access_size.
8000 		 * This would be a problem if we have a helper in the future
8001 		 * which takes:
8002 		 *
8003 		 *	helper(uninit_mem, len, dynptr)
8004 		 *
8005 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
8006 		 * may end up writing to dynptr itself when touching memory from
8007 		 * arg 1. This can be relaxed on a case by case basis for known
8008 		 * safe cases, but reject due to the possibilitiy of aliasing by
8009 		 * default.
8010 		 */
8011 		for (i = min_off; i < max_off + access_size; i++) {
8012 			int stack_off = -i - 1;
8013 
8014 			spi = __get_spi(i);
8015 			/* raw_mode may write past allocated_stack */
8016 			if (state->allocated_stack <= stack_off)
8017 				continue;
8018 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
8019 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
8020 				return -EACCES;
8021 			}
8022 		}
8023 		meta->access_size = access_size;
8024 		meta->regno = regno;
8025 		return 0;
8026 	}
8027 
8028 	for (i = min_off; i < max_off + access_size; i++) {
8029 		u8 *stype;
8030 
8031 		slot = -i - 1;
8032 		spi = slot / BPF_REG_SIZE;
8033 		if (state->allocated_stack <= slot) {
8034 			verbose(env, "allocated_stack too small\n");
8035 			return -EFAULT;
8036 		}
8037 
8038 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
8039 		if (*stype == STACK_MISC)
8040 			goto mark;
8041 		if ((*stype == STACK_ZERO) ||
8042 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
8043 			if (clobber) {
8044 				/* helper can write anything into the stack */
8045 				*stype = STACK_MISC;
8046 			}
8047 			goto mark;
8048 		}
8049 
8050 		if (is_spilled_reg(&state->stack[spi]) &&
8051 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
8052 		     env->allow_ptr_leaks)) {
8053 			if (clobber) {
8054 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
8055 				for (j = 0; j < BPF_REG_SIZE; j++)
8056 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
8057 			}
8058 			goto mark;
8059 		}
8060 
8061 		if (tnum_is_const(reg->var_off)) {
8062 			verbose(env, "invalid read from stack R%d off %d+%d size %d\n",
8063 				regno, min_off, i - min_off, access_size);
8064 		} else {
8065 			char tn_buf[48];
8066 
8067 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8068 			verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n",
8069 				regno, tn_buf, i - min_off, access_size);
8070 		}
8071 		return -EACCES;
8072 mark:
8073 		/* reading any byte out of 8-byte 'spill_slot' will cause
8074 		 * the whole slot to be marked as 'read'
8075 		 */
8076 		err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi));
8077 		if (err)
8078 			return err;
8079 		/* We do not call bpf_mark_stack_write(), as we can not
8080 		 * be sure that whether stack slot is written to or not. Hence,
8081 		 * we must still conservatively propagate reads upwards even if
8082 		 * helper may write to the entire memory range.
8083 		 */
8084 	}
8085 	return 0;
8086 }
8087 
8088 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
8089 				   int access_size, enum bpf_access_type access_type,
8090 				   bool zero_size_allowed,
8091 				   struct bpf_call_arg_meta *meta)
8092 {
8093 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8094 	u32 *max_access;
8095 
8096 	switch (base_type(reg->type)) {
8097 	case PTR_TO_PACKET:
8098 	case PTR_TO_PACKET_META:
8099 		return check_packet_access(env, regno, reg->off, access_size,
8100 					   zero_size_allowed);
8101 	case PTR_TO_MAP_KEY:
8102 		if (access_type == BPF_WRITE) {
8103 			verbose(env, "R%d cannot write into %s\n", regno,
8104 				reg_type_str(env, reg->type));
8105 			return -EACCES;
8106 		}
8107 		return check_mem_region_access(env, regno, reg->off, access_size,
8108 					       reg->map_ptr->key_size, false);
8109 	case PTR_TO_MAP_VALUE:
8110 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
8111 			return -EACCES;
8112 		return check_map_access(env, regno, reg->off, access_size,
8113 					zero_size_allowed, ACCESS_HELPER);
8114 	case PTR_TO_MEM:
8115 		if (type_is_rdonly_mem(reg->type)) {
8116 			if (access_type == BPF_WRITE) {
8117 				verbose(env, "R%d cannot write into %s\n", regno,
8118 					reg_type_str(env, reg->type));
8119 				return -EACCES;
8120 			}
8121 		}
8122 		return check_mem_region_access(env, regno, reg->off,
8123 					       access_size, reg->mem_size,
8124 					       zero_size_allowed);
8125 	case PTR_TO_BUF:
8126 		if (type_is_rdonly_mem(reg->type)) {
8127 			if (access_type == BPF_WRITE) {
8128 				verbose(env, "R%d cannot write into %s\n", regno,
8129 					reg_type_str(env, reg->type));
8130 				return -EACCES;
8131 			}
8132 
8133 			max_access = &env->prog->aux->max_rdonly_access;
8134 		} else {
8135 			max_access = &env->prog->aux->max_rdwr_access;
8136 		}
8137 		return check_buffer_access(env, reg, regno, reg->off,
8138 					   access_size, zero_size_allowed,
8139 					   max_access);
8140 	case PTR_TO_STACK:
8141 		return check_stack_range_initialized(
8142 				env,
8143 				regno, reg->off, access_size,
8144 				zero_size_allowed, access_type, meta);
8145 	case PTR_TO_BTF_ID:
8146 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
8147 					       access_size, BPF_READ, -1);
8148 	case PTR_TO_CTX:
8149 		/* in case the function doesn't know how to access the context,
8150 		 * (because we are in a program of type SYSCALL for example), we
8151 		 * can not statically check its size.
8152 		 * Dynamically check it now.
8153 		 */
8154 		if (!env->ops->convert_ctx_access) {
8155 			int offset = access_size - 1;
8156 
8157 			/* Allow zero-byte read from PTR_TO_CTX */
8158 			if (access_size == 0)
8159 				return zero_size_allowed ? 0 : -EACCES;
8160 
8161 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
8162 						access_type, -1, false, false);
8163 		}
8164 
8165 		fallthrough;
8166 	default: /* scalar_value or invalid ptr */
8167 		/* Allow zero-byte read from NULL, regardless of pointer type */
8168 		if (zero_size_allowed && access_size == 0 &&
8169 		    register_is_null(reg))
8170 			return 0;
8171 
8172 		verbose(env, "R%d type=%s ", regno,
8173 			reg_type_str(env, reg->type));
8174 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
8175 		return -EACCES;
8176 	}
8177 }
8178 
8179 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
8180  * size.
8181  *
8182  * @regno is the register containing the access size. regno-1 is the register
8183  * containing the pointer.
8184  */
8185 static int check_mem_size_reg(struct bpf_verifier_env *env,
8186 			      struct bpf_reg_state *reg, u32 regno,
8187 			      enum bpf_access_type access_type,
8188 			      bool zero_size_allowed,
8189 			      struct bpf_call_arg_meta *meta)
8190 {
8191 	int err;
8192 
8193 	/* This is used to refine r0 return value bounds for helpers
8194 	 * that enforce this value as an upper bound on return values.
8195 	 * See do_refine_retval_range() for helpers that can refine
8196 	 * the return value. C type of helper is u32 so we pull register
8197 	 * bound from umax_value however, if negative verifier errors
8198 	 * out. Only upper bounds can be learned because retval is an
8199 	 * int type and negative retvals are allowed.
8200 	 */
8201 	meta->msize_max_value = reg->umax_value;
8202 
8203 	/* The register is SCALAR_VALUE; the access check happens using
8204 	 * its boundaries. For unprivileged variable accesses, disable
8205 	 * raw mode so that the program is required to initialize all
8206 	 * the memory that the helper could just partially fill up.
8207 	 */
8208 	if (!tnum_is_const(reg->var_off))
8209 		meta = NULL;
8210 
8211 	if (reg->smin_value < 0) {
8212 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
8213 			regno);
8214 		return -EACCES;
8215 	}
8216 
8217 	if (reg->umin_value == 0 && !zero_size_allowed) {
8218 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
8219 			regno, reg->umin_value, reg->umax_value);
8220 		return -EACCES;
8221 	}
8222 
8223 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
8224 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
8225 			regno);
8226 		return -EACCES;
8227 	}
8228 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
8229 				      access_type, zero_size_allowed, meta);
8230 	if (!err)
8231 		err = mark_chain_precision(env, regno);
8232 	return err;
8233 }
8234 
8235 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8236 			 u32 regno, u32 mem_size)
8237 {
8238 	bool may_be_null = type_may_be_null(reg->type);
8239 	struct bpf_reg_state saved_reg;
8240 	int err;
8241 
8242 	if (register_is_null(reg))
8243 		return 0;
8244 
8245 	/* Assuming that the register contains a value check if the memory
8246 	 * access is safe. Temporarily save and restore the register's state as
8247 	 * the conversion shouldn't be visible to a caller.
8248 	 */
8249 	if (may_be_null) {
8250 		saved_reg = *reg;
8251 		mark_ptr_not_null_reg(reg);
8252 	}
8253 
8254 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
8255 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
8256 
8257 	if (may_be_null)
8258 		*reg = saved_reg;
8259 
8260 	return err;
8261 }
8262 
8263 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8264 				    u32 regno)
8265 {
8266 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
8267 	bool may_be_null = type_may_be_null(mem_reg->type);
8268 	struct bpf_reg_state saved_reg;
8269 	struct bpf_call_arg_meta meta;
8270 	int err;
8271 
8272 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
8273 
8274 	memset(&meta, 0, sizeof(meta));
8275 
8276 	if (may_be_null) {
8277 		saved_reg = *mem_reg;
8278 		mark_ptr_not_null_reg(mem_reg);
8279 	}
8280 
8281 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
8282 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
8283 
8284 	if (may_be_null)
8285 		*mem_reg = saved_reg;
8286 
8287 	return err;
8288 }
8289 
8290 enum {
8291 	PROCESS_SPIN_LOCK = (1 << 0),
8292 	PROCESS_RES_LOCK  = (1 << 1),
8293 	PROCESS_LOCK_IRQ  = (1 << 2),
8294 };
8295 
8296 /* Implementation details:
8297  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
8298  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
8299  * Two bpf_map_lookups (even with the same key) will have different reg->id.
8300  * Two separate bpf_obj_new will also have different reg->id.
8301  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
8302  * clears reg->id after value_or_null->value transition, since the verifier only
8303  * cares about the range of access to valid map value pointer and doesn't care
8304  * about actual address of the map element.
8305  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
8306  * reg->id > 0 after value_or_null->value transition. By doing so
8307  * two bpf_map_lookups will be considered two different pointers that
8308  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
8309  * returned from bpf_obj_new.
8310  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8311  * dead-locks.
8312  * Since only one bpf_spin_lock is allowed the checks are simpler than
8313  * reg_is_refcounted() logic. The verifier needs to remember only
8314  * one spin_lock instead of array of acquired_refs.
8315  * env->cur_state->active_locks remembers which map value element or allocated
8316  * object got locked and clears it after bpf_spin_unlock.
8317  */
8318 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags)
8319 {
8320 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
8321 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
8322 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8323 	struct bpf_verifier_state *cur = env->cur_state;
8324 	bool is_const = tnum_is_const(reg->var_off);
8325 	bool is_irq = flags & PROCESS_LOCK_IRQ;
8326 	u64 val = reg->var_off.value;
8327 	struct bpf_map *map = NULL;
8328 	struct btf *btf = NULL;
8329 	struct btf_record *rec;
8330 	u32 spin_lock_off;
8331 	int err;
8332 
8333 	if (!is_const) {
8334 		verbose(env,
8335 			"R%d doesn't have constant offset. %s_lock has to be at the constant offset\n",
8336 			regno, lock_str);
8337 		return -EINVAL;
8338 	}
8339 	if (reg->type == PTR_TO_MAP_VALUE) {
8340 		map = reg->map_ptr;
8341 		if (!map->btf) {
8342 			verbose(env,
8343 				"map '%s' has to have BTF in order to use %s_lock\n",
8344 				map->name, lock_str);
8345 			return -EINVAL;
8346 		}
8347 	} else {
8348 		btf = reg->btf;
8349 	}
8350 
8351 	rec = reg_btf_record(reg);
8352 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
8353 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
8354 			map ? map->name : "kptr", lock_str);
8355 		return -EINVAL;
8356 	}
8357 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
8358 	if (spin_lock_off != val + reg->off) {
8359 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
8360 			val + reg->off, lock_str, spin_lock_off);
8361 		return -EINVAL;
8362 	}
8363 	if (is_lock) {
8364 		void *ptr;
8365 		int type;
8366 
8367 		if (map)
8368 			ptr = map;
8369 		else
8370 			ptr = btf;
8371 
8372 		if (!is_res_lock && cur->active_locks) {
8373 			if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) {
8374 				verbose(env,
8375 					"Locking two bpf_spin_locks are not allowed\n");
8376 				return -EINVAL;
8377 			}
8378 		} else if (is_res_lock && cur->active_locks) {
8379 			if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) {
8380 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
8381 				return -EINVAL;
8382 			}
8383 		}
8384 
8385 		if (is_res_lock && is_irq)
8386 			type = REF_TYPE_RES_LOCK_IRQ;
8387 		else if (is_res_lock)
8388 			type = REF_TYPE_RES_LOCK;
8389 		else
8390 			type = REF_TYPE_LOCK;
8391 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
8392 		if (err < 0) {
8393 			verbose(env, "Failed to acquire lock state\n");
8394 			return err;
8395 		}
8396 	} else {
8397 		void *ptr;
8398 		int type;
8399 
8400 		if (map)
8401 			ptr = map;
8402 		else
8403 			ptr = btf;
8404 
8405 		if (!cur->active_locks) {
8406 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
8407 			return -EINVAL;
8408 		}
8409 
8410 		if (is_res_lock && is_irq)
8411 			type = REF_TYPE_RES_LOCK_IRQ;
8412 		else if (is_res_lock)
8413 			type = REF_TYPE_RES_LOCK;
8414 		else
8415 			type = REF_TYPE_LOCK;
8416 		if (!find_lock_state(cur, type, reg->id, ptr)) {
8417 			verbose(env, "%s_unlock of different lock\n", lock_str);
8418 			return -EINVAL;
8419 		}
8420 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
8421 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
8422 			return -EINVAL;
8423 		}
8424 		if (release_lock_state(cur, type, reg->id, ptr)) {
8425 			verbose(env, "%s_unlock of different lock\n", lock_str);
8426 			return -EINVAL;
8427 		}
8428 
8429 		invalidate_non_owning_refs(env);
8430 	}
8431 	return 0;
8432 }
8433 
8434 /* Check if @regno is a pointer to a specific field in a map value */
8435 static int check_map_field_pointer(struct bpf_verifier_env *env, u32 regno,
8436 				   enum btf_field_type field_type)
8437 {
8438 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8439 	bool is_const = tnum_is_const(reg->var_off);
8440 	struct bpf_map *map = reg->map_ptr;
8441 	u64 val = reg->var_off.value;
8442 	const char *struct_name = btf_field_type_name(field_type);
8443 	int field_off = -1;
8444 
8445 	if (!is_const) {
8446 		verbose(env,
8447 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
8448 			regno, struct_name);
8449 		return -EINVAL;
8450 	}
8451 	if (!map->btf) {
8452 		verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name,
8453 			struct_name);
8454 		return -EINVAL;
8455 	}
8456 	if (!btf_record_has_field(map->record, field_type)) {
8457 		verbose(env, "map '%s' has no valid %s\n", map->name, struct_name);
8458 		return -EINVAL;
8459 	}
8460 	switch (field_type) {
8461 	case BPF_TIMER:
8462 		field_off = map->record->timer_off;
8463 		break;
8464 	case BPF_TASK_WORK:
8465 		field_off = map->record->task_work_off;
8466 		break;
8467 	default:
8468 		verifier_bug(env, "unsupported BTF field type: %s\n", struct_name);
8469 		return -EINVAL;
8470 	}
8471 	if (field_off != val + reg->off) {
8472 		verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n",
8473 			val + reg->off, struct_name, field_off);
8474 		return -EINVAL;
8475 	}
8476 	return 0;
8477 }
8478 
8479 static int process_timer_func(struct bpf_verifier_env *env, int regno,
8480 			      struct bpf_call_arg_meta *meta)
8481 {
8482 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8483 	struct bpf_map *map = reg->map_ptr;
8484 	int err;
8485 
8486 	err = check_map_field_pointer(env, regno, BPF_TIMER);
8487 	if (err)
8488 		return err;
8489 
8490 	if (meta->map_ptr) {
8491 		verifier_bug(env, "Two map pointers in a timer helper");
8492 		return -EFAULT;
8493 	}
8494 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8495 		verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
8496 		return -EOPNOTSUPP;
8497 	}
8498 	meta->map_uid = reg->map_uid;
8499 	meta->map_ptr = map;
8500 	return 0;
8501 }
8502 
8503 static int process_wq_func(struct bpf_verifier_env *env, int regno,
8504 			   struct bpf_kfunc_call_arg_meta *meta)
8505 {
8506 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8507 	struct bpf_map *map = reg->map_ptr;
8508 	u64 val = reg->var_off.value;
8509 
8510 	if (map->record->wq_off != val + reg->off) {
8511 		verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
8512 			val + reg->off, map->record->wq_off);
8513 		return -EINVAL;
8514 	}
8515 	meta->map.uid = reg->map_uid;
8516 	meta->map.ptr = map;
8517 	return 0;
8518 }
8519 
8520 static int process_task_work_func(struct bpf_verifier_env *env, int regno,
8521 				  struct bpf_kfunc_call_arg_meta *meta)
8522 {
8523 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8524 	struct bpf_map *map = reg->map_ptr;
8525 	int err;
8526 
8527 	err = check_map_field_pointer(env, regno, BPF_TASK_WORK);
8528 	if (err)
8529 		return err;
8530 
8531 	if (meta->map.ptr) {
8532 		verifier_bug(env, "Two map pointers in a bpf_task_work helper");
8533 		return -EFAULT;
8534 	}
8535 	meta->map.uid = reg->map_uid;
8536 	meta->map.ptr = map;
8537 	return 0;
8538 }
8539 
8540 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8541 			     struct bpf_call_arg_meta *meta)
8542 {
8543 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8544 	struct btf_field *kptr_field;
8545 	struct bpf_map *map_ptr;
8546 	struct btf_record *rec;
8547 	u32 kptr_off;
8548 
8549 	if (type_is_ptr_alloc_obj(reg->type)) {
8550 		rec = reg_btf_record(reg);
8551 	} else { /* PTR_TO_MAP_VALUE */
8552 		map_ptr = reg->map_ptr;
8553 		if (!map_ptr->btf) {
8554 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8555 				map_ptr->name);
8556 			return -EINVAL;
8557 		}
8558 		rec = map_ptr->record;
8559 		meta->map_ptr = map_ptr;
8560 	}
8561 
8562 	if (!tnum_is_const(reg->var_off)) {
8563 		verbose(env,
8564 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8565 			regno);
8566 		return -EINVAL;
8567 	}
8568 
8569 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8570 		verbose(env, "R%d has no valid kptr\n", regno);
8571 		return -EINVAL;
8572 	}
8573 
8574 	kptr_off = reg->off + reg->var_off.value;
8575 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8576 	if (!kptr_field) {
8577 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8578 		return -EACCES;
8579 	}
8580 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8581 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8582 		return -EACCES;
8583 	}
8584 	meta->kptr_field = kptr_field;
8585 	return 0;
8586 }
8587 
8588 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8589  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8590  *
8591  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8592  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8593  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8594  *
8595  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
8596  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
8597  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
8598  * mutate the view of the dynptr and also possibly destroy it. In the latter
8599  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
8600  * memory that dynptr points to.
8601  *
8602  * The verifier will keep track both levels of mutation (bpf_dynptr's in
8603  * reg->type and the memory's in reg->dynptr.type), but there is no support for
8604  * readonly dynptr view yet, hence only the first case is tracked and checked.
8605  *
8606  * This is consistent with how C applies the const modifier to a struct object,
8607  * where the pointer itself inside bpf_dynptr becomes const but not what it
8608  * points to.
8609  *
8610  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
8611  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
8612  */
8613 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
8614 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
8615 {
8616 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8617 	int err;
8618 
8619 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
8620 		verbose(env,
8621 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
8622 			regno - 1);
8623 		return -EINVAL;
8624 	}
8625 
8626 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
8627 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
8628 	 */
8629 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
8630 		verifier_bug(env, "misconfigured dynptr helper type flags");
8631 		return -EFAULT;
8632 	}
8633 
8634 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8635 	 *		 constructing a mutable bpf_dynptr object.
8636 	 *
8637 	 *		 Currently, this is only possible with PTR_TO_STACK
8638 	 *		 pointing to a region of at least 16 bytes which doesn't
8639 	 *		 contain an existing bpf_dynptr.
8640 	 *
8641 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
8642 	 *		 mutated or destroyed. However, the memory it points to
8643 	 *		 may be mutated.
8644 	 *
8645 	 *  None       - Points to a initialized dynptr that can be mutated and
8646 	 *		 destroyed, including mutation of the memory it points
8647 	 *		 to.
8648 	 */
8649 	if (arg_type & MEM_UNINIT) {
8650 		int i;
8651 
8652 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8653 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8654 			return -EINVAL;
8655 		}
8656 
8657 		/* we write BPF_DW bits (8 bytes) at a time */
8658 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8659 			err = check_mem_access(env, insn_idx, regno,
8660 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8661 			if (err)
8662 				return err;
8663 		}
8664 
8665 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
8666 	} else /* MEM_RDONLY and None case from above */ {
8667 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8668 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
8669 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
8670 			return -EINVAL;
8671 		}
8672 
8673 		if (!is_dynptr_reg_valid_init(env, reg)) {
8674 			verbose(env,
8675 				"Expected an initialized dynptr as arg #%d\n",
8676 				regno - 1);
8677 			return -EINVAL;
8678 		}
8679 
8680 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
8681 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
8682 			verbose(env,
8683 				"Expected a dynptr of type %s as arg #%d\n",
8684 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
8685 			return -EINVAL;
8686 		}
8687 
8688 		err = mark_dynptr_read(env, reg);
8689 	}
8690 	return err;
8691 }
8692 
8693 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
8694 {
8695 	struct bpf_func_state *state = func(env, reg);
8696 
8697 	return state->stack[spi].spilled_ptr.ref_obj_id;
8698 }
8699 
8700 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8701 {
8702 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8703 }
8704 
8705 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8706 {
8707 	return meta->kfunc_flags & KF_ITER_NEW;
8708 }
8709 
8710 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8711 {
8712 	return meta->kfunc_flags & KF_ITER_NEXT;
8713 }
8714 
8715 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8716 {
8717 	return meta->kfunc_flags & KF_ITER_DESTROY;
8718 }
8719 
8720 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
8721 			      const struct btf_param *arg)
8722 {
8723 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8724 	 * kfunc is iter state pointer
8725 	 */
8726 	if (is_iter_kfunc(meta))
8727 		return arg_idx == 0;
8728 
8729 	/* iter passed as an argument to a generic kfunc */
8730 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8731 }
8732 
8733 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
8734 			    struct bpf_kfunc_call_arg_meta *meta)
8735 {
8736 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8737 	const struct btf_type *t;
8738 	int spi, err, i, nr_slots, btf_id;
8739 
8740 	if (reg->type != PTR_TO_STACK) {
8741 		verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
8742 		return -EINVAL;
8743 	}
8744 
8745 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8746 	 * ensures struct convention, so we wouldn't need to do any BTF
8747 	 * validation here. But given iter state can be passed as a parameter
8748 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8749 	 * conservative here.
8750 	 */
8751 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8752 	if (btf_id < 0) {
8753 		verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
8754 		return -EINVAL;
8755 	}
8756 	t = btf_type_by_id(meta->btf, btf_id);
8757 	nr_slots = t->size / BPF_REG_SIZE;
8758 
8759 	if (is_iter_new_kfunc(meta)) {
8760 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8761 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8762 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8763 				iter_type_str(meta->btf, btf_id), regno - 1);
8764 			return -EINVAL;
8765 		}
8766 
8767 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8768 			err = check_mem_access(env, insn_idx, regno,
8769 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8770 			if (err)
8771 				return err;
8772 		}
8773 
8774 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8775 		if (err)
8776 			return err;
8777 	} else {
8778 		/* iter_next() or iter_destroy(), as well as any kfunc
8779 		 * accepting iter argument, expect initialized iter state
8780 		 */
8781 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8782 		switch (err) {
8783 		case 0:
8784 			break;
8785 		case -EINVAL:
8786 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
8787 				iter_type_str(meta->btf, btf_id), regno - 1);
8788 			return err;
8789 		case -EPROTO:
8790 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8791 			return err;
8792 		default:
8793 			return err;
8794 		}
8795 
8796 		spi = iter_get_spi(env, reg, nr_slots);
8797 		if (spi < 0)
8798 			return spi;
8799 
8800 		err = mark_iter_read(env, reg, spi, nr_slots);
8801 		if (err)
8802 			return err;
8803 
8804 		/* remember meta->iter info for process_iter_next_call() */
8805 		meta->iter.spi = spi;
8806 		meta->iter.frameno = reg->frameno;
8807 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8808 
8809 		if (is_iter_destroy_kfunc(meta)) {
8810 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8811 			if (err)
8812 				return err;
8813 		}
8814 	}
8815 
8816 	return 0;
8817 }
8818 
8819 /* Look for a previous loop entry at insn_idx: nearest parent state
8820  * stopped at insn_idx with callsites matching those in cur->frame.
8821  */
8822 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8823 						  struct bpf_verifier_state *cur,
8824 						  int insn_idx)
8825 {
8826 	struct bpf_verifier_state_list *sl;
8827 	struct bpf_verifier_state *st;
8828 	struct list_head *pos, *head;
8829 
8830 	/* Explored states are pushed in stack order, most recent states come first */
8831 	head = explored_state(env, insn_idx);
8832 	list_for_each(pos, head) {
8833 		sl = container_of(pos, struct bpf_verifier_state_list, node);
8834 		/* If st->branches != 0 state is a part of current DFS verification path,
8835 		 * hence cur & st for a loop.
8836 		 */
8837 		st = &sl->state;
8838 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8839 		    st->dfs_depth < cur->dfs_depth)
8840 			return st;
8841 	}
8842 
8843 	return NULL;
8844 }
8845 
8846 static void reset_idmap_scratch(struct bpf_verifier_env *env);
8847 static bool regs_exact(const struct bpf_reg_state *rold,
8848 		       const struct bpf_reg_state *rcur,
8849 		       struct bpf_idmap *idmap);
8850 
8851 static void maybe_widen_reg(struct bpf_verifier_env *env,
8852 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8853 			    struct bpf_idmap *idmap)
8854 {
8855 	if (rold->type != SCALAR_VALUE)
8856 		return;
8857 	if (rold->type != rcur->type)
8858 		return;
8859 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
8860 		return;
8861 	__mark_reg_unknown(env, rcur);
8862 }
8863 
8864 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8865 				   struct bpf_verifier_state *old,
8866 				   struct bpf_verifier_state *cur)
8867 {
8868 	struct bpf_func_state *fold, *fcur;
8869 	int i, fr;
8870 
8871 	reset_idmap_scratch(env);
8872 	for (fr = old->curframe; fr >= 0; fr--) {
8873 		fold = old->frame[fr];
8874 		fcur = cur->frame[fr];
8875 
8876 		for (i = 0; i < MAX_BPF_REG; i++)
8877 			maybe_widen_reg(env,
8878 					&fold->regs[i],
8879 					&fcur->regs[i],
8880 					&env->idmap_scratch);
8881 
8882 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
8883 			if (!is_spilled_reg(&fold->stack[i]) ||
8884 			    !is_spilled_reg(&fcur->stack[i]))
8885 				continue;
8886 
8887 			maybe_widen_reg(env,
8888 					&fold->stack[i].spilled_ptr,
8889 					&fcur->stack[i].spilled_ptr,
8890 					&env->idmap_scratch);
8891 		}
8892 	}
8893 	return 0;
8894 }
8895 
8896 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8897 						 struct bpf_kfunc_call_arg_meta *meta)
8898 {
8899 	int iter_frameno = meta->iter.frameno;
8900 	int iter_spi = meta->iter.spi;
8901 
8902 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8903 }
8904 
8905 /* process_iter_next_call() is called when verifier gets to iterator's next
8906  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8907  * to it as just "iter_next()" in comments below.
8908  *
8909  * BPF verifier relies on a crucial contract for any iter_next()
8910  * implementation: it should *eventually* return NULL, and once that happens
8911  * it should keep returning NULL. That is, once iterator exhausts elements to
8912  * iterate, it should never reset or spuriously return new elements.
8913  *
8914  * With the assumption of such contract, process_iter_next_call() simulates
8915  * a fork in the verifier state to validate loop logic correctness and safety
8916  * without having to simulate infinite amount of iterations.
8917  *
8918  * In current state, we first assume that iter_next() returned NULL and
8919  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8920  * conditions we should not form an infinite loop and should eventually reach
8921  * exit.
8922  *
8923  * Besides that, we also fork current state and enqueue it for later
8924  * verification. In a forked state we keep iterator state as ACTIVE
8925  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8926  * also bump iteration depth to prevent erroneous infinite loop detection
8927  * later on (see iter_active_depths_differ() comment for details). In this
8928  * state we assume that we'll eventually loop back to another iter_next()
8929  * calls (it could be in exactly same location or in some other instruction,
8930  * it doesn't matter, we don't make any unnecessary assumptions about this,
8931  * everything revolves around iterator state in a stack slot, not which
8932  * instruction is calling iter_next()). When that happens, we either will come
8933  * to iter_next() with equivalent state and can conclude that next iteration
8934  * will proceed in exactly the same way as we just verified, so it's safe to
8935  * assume that loop converges. If not, we'll go on another iteration
8936  * simulation with a different input state, until all possible starting states
8937  * are validated or we reach maximum number of instructions limit.
8938  *
8939  * This way, we will either exhaustively discover all possible input states
8940  * that iterator loop can start with and eventually will converge, or we'll
8941  * effectively regress into bounded loop simulation logic and either reach
8942  * maximum number of instructions if loop is not provably convergent, or there
8943  * is some statically known limit on number of iterations (e.g., if there is
8944  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8945  *
8946  * Iteration convergence logic in is_state_visited() relies on exact
8947  * states comparison, which ignores read and precision marks.
8948  * This is necessary because read and precision marks are not finalized
8949  * while in the loop. Exact comparison might preclude convergence for
8950  * simple programs like below:
8951  *
8952  *     i = 0;
8953  *     while(iter_next(&it))
8954  *       i++;
8955  *
8956  * At each iteration step i++ would produce a new distinct state and
8957  * eventually instruction processing limit would be reached.
8958  *
8959  * To avoid such behavior speculatively forget (widen) range for
8960  * imprecise scalar registers, if those registers were not precise at the
8961  * end of the previous iteration and do not match exactly.
8962  *
8963  * This is a conservative heuristic that allows to verify wide range of programs,
8964  * however it precludes verification of programs that conjure an
8965  * imprecise value on the first loop iteration and use it as precise on a second.
8966  * For example, the following safe program would fail to verify:
8967  *
8968  *     struct bpf_num_iter it;
8969  *     int arr[10];
8970  *     int i = 0, a = 0;
8971  *     bpf_iter_num_new(&it, 0, 10);
8972  *     while (bpf_iter_num_next(&it)) {
8973  *       if (a == 0) {
8974  *         a = 1;
8975  *         i = 7; // Because i changed verifier would forget
8976  *                // it's range on second loop entry.
8977  *       } else {
8978  *         arr[i] = 42; // This would fail to verify.
8979  *       }
8980  *     }
8981  *     bpf_iter_num_destroy(&it);
8982  */
8983 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8984 				  struct bpf_kfunc_call_arg_meta *meta)
8985 {
8986 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8987 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8988 	struct bpf_reg_state *cur_iter, *queued_iter;
8989 
8990 	BTF_TYPE_EMIT(struct bpf_iter);
8991 
8992 	cur_iter = get_iter_from_state(cur_st, meta);
8993 
8994 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8995 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8996 		verifier_bug(env, "unexpected iterator state %d (%s)",
8997 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8998 		return -EFAULT;
8999 	}
9000 
9001 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
9002 		/* Because iter_next() call is a checkpoint is_state_visitied()
9003 		 * should guarantee parent state with same call sites and insn_idx.
9004 		 */
9005 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
9006 		    !same_callsites(cur_st->parent, cur_st)) {
9007 			verifier_bug(env, "bad parent state for iter next call");
9008 			return -EFAULT;
9009 		}
9010 		/* Note cur_st->parent in the call below, it is necessary to skip
9011 		 * checkpoint created for cur_st by is_state_visited()
9012 		 * right at this instruction.
9013 		 */
9014 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
9015 		/* branch out active iter state */
9016 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
9017 		if (!queued_st)
9018 			return -ENOMEM;
9019 
9020 		queued_iter = get_iter_from_state(queued_st, meta);
9021 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
9022 		queued_iter->iter.depth++;
9023 		if (prev_st)
9024 			widen_imprecise_scalars(env, prev_st, queued_st);
9025 
9026 		queued_fr = queued_st->frame[queued_st->curframe];
9027 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
9028 	}
9029 
9030 	/* switch to DRAINED state, but keep the depth unchanged */
9031 	/* mark current iter state as drained and assume returned NULL */
9032 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
9033 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
9034 
9035 	return 0;
9036 }
9037 
9038 static bool arg_type_is_mem_size(enum bpf_arg_type type)
9039 {
9040 	return type == ARG_CONST_SIZE ||
9041 	       type == ARG_CONST_SIZE_OR_ZERO;
9042 }
9043 
9044 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
9045 {
9046 	return base_type(type) == ARG_PTR_TO_MEM &&
9047 	       type & MEM_UNINIT;
9048 }
9049 
9050 static bool arg_type_is_release(enum bpf_arg_type type)
9051 {
9052 	return type & OBJ_RELEASE;
9053 }
9054 
9055 static bool arg_type_is_dynptr(enum bpf_arg_type type)
9056 {
9057 	return base_type(type) == ARG_PTR_TO_DYNPTR;
9058 }
9059 
9060 static int resolve_map_arg_type(struct bpf_verifier_env *env,
9061 				 const struct bpf_call_arg_meta *meta,
9062 				 enum bpf_arg_type *arg_type)
9063 {
9064 	if (!meta->map_ptr) {
9065 		/* kernel subsystem misconfigured verifier */
9066 		verifier_bug(env, "invalid map_ptr to access map->type");
9067 		return -EFAULT;
9068 	}
9069 
9070 	switch (meta->map_ptr->map_type) {
9071 	case BPF_MAP_TYPE_SOCKMAP:
9072 	case BPF_MAP_TYPE_SOCKHASH:
9073 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
9074 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
9075 		} else {
9076 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
9077 			return -EINVAL;
9078 		}
9079 		break;
9080 	case BPF_MAP_TYPE_BLOOM_FILTER:
9081 		if (meta->func_id == BPF_FUNC_map_peek_elem)
9082 			*arg_type = ARG_PTR_TO_MAP_VALUE;
9083 		break;
9084 	default:
9085 		break;
9086 	}
9087 	return 0;
9088 }
9089 
9090 struct bpf_reg_types {
9091 	const enum bpf_reg_type types[10];
9092 	u32 *btf_id;
9093 };
9094 
9095 static const struct bpf_reg_types sock_types = {
9096 	.types = {
9097 		PTR_TO_SOCK_COMMON,
9098 		PTR_TO_SOCKET,
9099 		PTR_TO_TCP_SOCK,
9100 		PTR_TO_XDP_SOCK,
9101 	},
9102 };
9103 
9104 #ifdef CONFIG_NET
9105 static const struct bpf_reg_types btf_id_sock_common_types = {
9106 	.types = {
9107 		PTR_TO_SOCK_COMMON,
9108 		PTR_TO_SOCKET,
9109 		PTR_TO_TCP_SOCK,
9110 		PTR_TO_XDP_SOCK,
9111 		PTR_TO_BTF_ID,
9112 		PTR_TO_BTF_ID | PTR_TRUSTED,
9113 	},
9114 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9115 };
9116 #endif
9117 
9118 static const struct bpf_reg_types mem_types = {
9119 	.types = {
9120 		PTR_TO_STACK,
9121 		PTR_TO_PACKET,
9122 		PTR_TO_PACKET_META,
9123 		PTR_TO_MAP_KEY,
9124 		PTR_TO_MAP_VALUE,
9125 		PTR_TO_MEM,
9126 		PTR_TO_MEM | MEM_RINGBUF,
9127 		PTR_TO_BUF,
9128 		PTR_TO_BTF_ID | PTR_TRUSTED,
9129 	},
9130 };
9131 
9132 static const struct bpf_reg_types spin_lock_types = {
9133 	.types = {
9134 		PTR_TO_MAP_VALUE,
9135 		PTR_TO_BTF_ID | MEM_ALLOC,
9136 	}
9137 };
9138 
9139 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
9140 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
9141 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
9142 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
9143 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
9144 static const struct bpf_reg_types btf_ptr_types = {
9145 	.types = {
9146 		PTR_TO_BTF_ID,
9147 		PTR_TO_BTF_ID | PTR_TRUSTED,
9148 		PTR_TO_BTF_ID | MEM_RCU,
9149 	},
9150 };
9151 static const struct bpf_reg_types percpu_btf_ptr_types = {
9152 	.types = {
9153 		PTR_TO_BTF_ID | MEM_PERCPU,
9154 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
9155 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
9156 	}
9157 };
9158 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
9159 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
9160 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
9161 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
9162 static const struct bpf_reg_types kptr_xchg_dest_types = {
9163 	.types = {
9164 		PTR_TO_MAP_VALUE,
9165 		PTR_TO_BTF_ID | MEM_ALLOC
9166 	}
9167 };
9168 static const struct bpf_reg_types dynptr_types = {
9169 	.types = {
9170 		PTR_TO_STACK,
9171 		CONST_PTR_TO_DYNPTR,
9172 	}
9173 };
9174 
9175 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
9176 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
9177 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
9178 	[ARG_CONST_SIZE]		= &scalar_types,
9179 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
9180 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
9181 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
9182 	[ARG_PTR_TO_CTX]		= &context_types,
9183 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
9184 #ifdef CONFIG_NET
9185 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
9186 #endif
9187 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
9188 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
9189 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
9190 	[ARG_PTR_TO_MEM]		= &mem_types,
9191 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
9192 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
9193 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
9194 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
9195 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
9196 	[ARG_PTR_TO_TIMER]		= &timer_types,
9197 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
9198 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
9199 };
9200 
9201 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
9202 			  enum bpf_arg_type arg_type,
9203 			  const u32 *arg_btf_id,
9204 			  struct bpf_call_arg_meta *meta)
9205 {
9206 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9207 	enum bpf_reg_type expected, type = reg->type;
9208 	const struct bpf_reg_types *compatible;
9209 	int i, j;
9210 
9211 	compatible = compatible_reg_types[base_type(arg_type)];
9212 	if (!compatible) {
9213 		verifier_bug(env, "unsupported arg type %d", arg_type);
9214 		return -EFAULT;
9215 	}
9216 
9217 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
9218 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
9219 	 *
9220 	 * Same for MAYBE_NULL:
9221 	 *
9222 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
9223 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
9224 	 *
9225 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
9226 	 *
9227 	 * Therefore we fold these flags depending on the arg_type before comparison.
9228 	 */
9229 	if (arg_type & MEM_RDONLY)
9230 		type &= ~MEM_RDONLY;
9231 	if (arg_type & PTR_MAYBE_NULL)
9232 		type &= ~PTR_MAYBE_NULL;
9233 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
9234 		type &= ~DYNPTR_TYPE_FLAG_MASK;
9235 
9236 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
9237 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
9238 		type &= ~MEM_ALLOC;
9239 		type &= ~MEM_PERCPU;
9240 	}
9241 
9242 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
9243 		expected = compatible->types[i];
9244 		if (expected == NOT_INIT)
9245 			break;
9246 
9247 		if (type == expected)
9248 			goto found;
9249 	}
9250 
9251 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
9252 	for (j = 0; j + 1 < i; j++)
9253 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
9254 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
9255 	return -EACCES;
9256 
9257 found:
9258 	if (base_type(reg->type) != PTR_TO_BTF_ID)
9259 		return 0;
9260 
9261 	if (compatible == &mem_types) {
9262 		if (!(arg_type & MEM_RDONLY)) {
9263 			verbose(env,
9264 				"%s() may write into memory pointed by R%d type=%s\n",
9265 				func_id_name(meta->func_id),
9266 				regno, reg_type_str(env, reg->type));
9267 			return -EACCES;
9268 		}
9269 		return 0;
9270 	}
9271 
9272 	switch ((int)reg->type) {
9273 	case PTR_TO_BTF_ID:
9274 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9275 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
9276 	case PTR_TO_BTF_ID | MEM_RCU:
9277 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
9278 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
9279 	{
9280 		/* For bpf_sk_release, it needs to match against first member
9281 		 * 'struct sock_common', hence make an exception for it. This
9282 		 * allows bpf_sk_release to work for multiple socket types.
9283 		 */
9284 		bool strict_type_match = arg_type_is_release(arg_type) &&
9285 					 meta->func_id != BPF_FUNC_sk_release;
9286 
9287 		if (type_may_be_null(reg->type) &&
9288 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
9289 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
9290 			return -EACCES;
9291 		}
9292 
9293 		if (!arg_btf_id) {
9294 			if (!compatible->btf_id) {
9295 				verifier_bug(env, "missing arg compatible BTF ID");
9296 				return -EFAULT;
9297 			}
9298 			arg_btf_id = compatible->btf_id;
9299 		}
9300 
9301 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
9302 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9303 				return -EACCES;
9304 		} else {
9305 			if (arg_btf_id == BPF_PTR_POISON) {
9306 				verbose(env, "verifier internal error:");
9307 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
9308 					regno);
9309 				return -EACCES;
9310 			}
9311 
9312 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
9313 						  btf_vmlinux, *arg_btf_id,
9314 						  strict_type_match)) {
9315 				verbose(env, "R%d is of type %s but %s is expected\n",
9316 					regno, btf_type_name(reg->btf, reg->btf_id),
9317 					btf_type_name(btf_vmlinux, *arg_btf_id));
9318 				return -EACCES;
9319 			}
9320 		}
9321 		break;
9322 	}
9323 	case PTR_TO_BTF_ID | MEM_ALLOC:
9324 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
9325 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
9326 		    meta->func_id != BPF_FUNC_kptr_xchg) {
9327 			verifier_bug(env, "unimplemented handling of MEM_ALLOC");
9328 			return -EFAULT;
9329 		}
9330 		/* Check if local kptr in src arg matches kptr in dst arg */
9331 		if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
9332 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9333 				return -EACCES;
9334 		}
9335 		break;
9336 	case PTR_TO_BTF_ID | MEM_PERCPU:
9337 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
9338 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
9339 		/* Handled by helper specific checks */
9340 		break;
9341 	default:
9342 		verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match");
9343 		return -EFAULT;
9344 	}
9345 	return 0;
9346 }
9347 
9348 static struct btf_field *
9349 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
9350 {
9351 	struct btf_field *field;
9352 	struct btf_record *rec;
9353 
9354 	rec = reg_btf_record(reg);
9355 	if (!rec)
9356 		return NULL;
9357 
9358 	field = btf_record_find(rec, off, fields);
9359 	if (!field)
9360 		return NULL;
9361 
9362 	return field;
9363 }
9364 
9365 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
9366 				  const struct bpf_reg_state *reg, int regno,
9367 				  enum bpf_arg_type arg_type)
9368 {
9369 	u32 type = reg->type;
9370 
9371 	/* When referenced register is passed to release function, its fixed
9372 	 * offset must be 0.
9373 	 *
9374 	 * We will check arg_type_is_release reg has ref_obj_id when storing
9375 	 * meta->release_regno.
9376 	 */
9377 	if (arg_type_is_release(arg_type)) {
9378 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
9379 		 * may not directly point to the object being released, but to
9380 		 * dynptr pointing to such object, which might be at some offset
9381 		 * on the stack. In that case, we simply to fallback to the
9382 		 * default handling.
9383 		 */
9384 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
9385 			return 0;
9386 
9387 		/* Doing check_ptr_off_reg check for the offset will catch this
9388 		 * because fixed_off_ok is false, but checking here allows us
9389 		 * to give the user a better error message.
9390 		 */
9391 		if (reg->off) {
9392 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
9393 				regno);
9394 			return -EINVAL;
9395 		}
9396 		return __check_ptr_off_reg(env, reg, regno, false);
9397 	}
9398 
9399 	switch (type) {
9400 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9401 	case PTR_TO_STACK:
9402 	case PTR_TO_PACKET:
9403 	case PTR_TO_PACKET_META:
9404 	case PTR_TO_MAP_KEY:
9405 	case PTR_TO_MAP_VALUE:
9406 	case PTR_TO_MEM:
9407 	case PTR_TO_MEM | MEM_RDONLY:
9408 	case PTR_TO_MEM | MEM_RINGBUF:
9409 	case PTR_TO_BUF:
9410 	case PTR_TO_BUF | MEM_RDONLY:
9411 	case PTR_TO_ARENA:
9412 	case SCALAR_VALUE:
9413 		return 0;
9414 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9415 	 * fixed offset.
9416 	 */
9417 	case PTR_TO_BTF_ID:
9418 	case PTR_TO_BTF_ID | MEM_ALLOC:
9419 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9420 	case PTR_TO_BTF_ID | MEM_RCU:
9421 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9422 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9423 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9424 		 * its fixed offset must be 0. In the other cases, fixed offset
9425 		 * can be non-zero. This was already checked above. So pass
9426 		 * fixed_off_ok as true to allow fixed offset for all other
9427 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
9428 		 * still need to do checks instead of returning.
9429 		 */
9430 		return __check_ptr_off_reg(env, reg, regno, true);
9431 	default:
9432 		return __check_ptr_off_reg(env, reg, regno, false);
9433 	}
9434 }
9435 
9436 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
9437 						const struct bpf_func_proto *fn,
9438 						struct bpf_reg_state *regs)
9439 {
9440 	struct bpf_reg_state *state = NULL;
9441 	int i;
9442 
9443 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
9444 		if (arg_type_is_dynptr(fn->arg_type[i])) {
9445 			if (state) {
9446 				verbose(env, "verifier internal error: multiple dynptr args\n");
9447 				return NULL;
9448 			}
9449 			state = &regs[BPF_REG_1 + i];
9450 		}
9451 
9452 	if (!state)
9453 		verbose(env, "verifier internal error: no dynptr arg found\n");
9454 
9455 	return state;
9456 }
9457 
9458 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9459 {
9460 	struct bpf_func_state *state = func(env, reg);
9461 	int spi;
9462 
9463 	if (reg->type == CONST_PTR_TO_DYNPTR)
9464 		return reg->id;
9465 	spi = dynptr_get_spi(env, reg);
9466 	if (spi < 0)
9467 		return spi;
9468 	return state->stack[spi].spilled_ptr.id;
9469 }
9470 
9471 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9472 {
9473 	struct bpf_func_state *state = func(env, reg);
9474 	int spi;
9475 
9476 	if (reg->type == CONST_PTR_TO_DYNPTR)
9477 		return reg->ref_obj_id;
9478 	spi = dynptr_get_spi(env, reg);
9479 	if (spi < 0)
9480 		return spi;
9481 	return state->stack[spi].spilled_ptr.ref_obj_id;
9482 }
9483 
9484 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
9485 					    struct bpf_reg_state *reg)
9486 {
9487 	struct bpf_func_state *state = func(env, reg);
9488 	int spi;
9489 
9490 	if (reg->type == CONST_PTR_TO_DYNPTR)
9491 		return reg->dynptr.type;
9492 
9493 	spi = __get_spi(reg->off);
9494 	if (spi < 0) {
9495 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
9496 		return BPF_DYNPTR_TYPE_INVALID;
9497 	}
9498 
9499 	return state->stack[spi].spilled_ptr.dynptr.type;
9500 }
9501 
9502 static int check_reg_const_str(struct bpf_verifier_env *env,
9503 			       struct bpf_reg_state *reg, u32 regno)
9504 {
9505 	struct bpf_map *map = reg->map_ptr;
9506 	int err;
9507 	int map_off;
9508 	u64 map_addr;
9509 	char *str_ptr;
9510 
9511 	if (reg->type != PTR_TO_MAP_VALUE)
9512 		return -EINVAL;
9513 
9514 	if (!bpf_map_is_rdonly(map)) {
9515 		verbose(env, "R%d does not point to a readonly map'\n", regno);
9516 		return -EACCES;
9517 	}
9518 
9519 	if (!tnum_is_const(reg->var_off)) {
9520 		verbose(env, "R%d is not a constant address'\n", regno);
9521 		return -EACCES;
9522 	}
9523 
9524 	if (!map->ops->map_direct_value_addr) {
9525 		verbose(env, "no direct value access support for this map type\n");
9526 		return -EACCES;
9527 	}
9528 
9529 	err = check_map_access(env, regno, reg->off,
9530 			       map->value_size - reg->off, false,
9531 			       ACCESS_HELPER);
9532 	if (err)
9533 		return err;
9534 
9535 	map_off = reg->off + reg->var_off.value;
9536 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9537 	if (err) {
9538 		verbose(env, "direct value access on string failed\n");
9539 		return err;
9540 	}
9541 
9542 	str_ptr = (char *)(long)(map_addr);
9543 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9544 		verbose(env, "string is not zero-terminated\n");
9545 		return -EINVAL;
9546 	}
9547 	return 0;
9548 }
9549 
9550 /* Returns constant key value in `value` if possible, else negative error */
9551 static int get_constant_map_key(struct bpf_verifier_env *env,
9552 				struct bpf_reg_state *key,
9553 				u32 key_size,
9554 				s64 *value)
9555 {
9556 	struct bpf_func_state *state = func(env, key);
9557 	struct bpf_reg_state *reg;
9558 	int slot, spi, off;
9559 	int spill_size = 0;
9560 	int zero_size = 0;
9561 	int stack_off;
9562 	int i, err;
9563 	u8 *stype;
9564 
9565 	if (!env->bpf_capable)
9566 		return -EOPNOTSUPP;
9567 	if (key->type != PTR_TO_STACK)
9568 		return -EOPNOTSUPP;
9569 	if (!tnum_is_const(key->var_off))
9570 		return -EOPNOTSUPP;
9571 
9572 	stack_off = key->off + key->var_off.value;
9573 	slot = -stack_off - 1;
9574 	spi = slot / BPF_REG_SIZE;
9575 	off = slot % BPF_REG_SIZE;
9576 	stype = state->stack[spi].slot_type;
9577 
9578 	/* First handle precisely tracked STACK_ZERO */
9579 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9580 		zero_size++;
9581 	if (zero_size >= key_size) {
9582 		*value = 0;
9583 		return 0;
9584 	}
9585 
9586 	/* Check that stack contains a scalar spill of expected size */
9587 	if (!is_spilled_scalar_reg(&state->stack[spi]))
9588 		return -EOPNOTSUPP;
9589 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9590 		spill_size++;
9591 	if (spill_size != key_size)
9592 		return -EOPNOTSUPP;
9593 
9594 	reg = &state->stack[spi].spilled_ptr;
9595 	if (!tnum_is_const(reg->var_off))
9596 		/* Stack value not statically known */
9597 		return -EOPNOTSUPP;
9598 
9599 	/* We are relying on a constant value. So mark as precise
9600 	 * to prevent pruning on it.
9601 	 */
9602 	bt_set_frame_slot(&env->bt, key->frameno, spi);
9603 	err = mark_chain_precision_batch(env, env->cur_state);
9604 	if (err < 0)
9605 		return err;
9606 
9607 	*value = reg->var_off.value;
9608 	return 0;
9609 }
9610 
9611 static bool can_elide_value_nullness(enum bpf_map_type type);
9612 
9613 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9614 			  struct bpf_call_arg_meta *meta,
9615 			  const struct bpf_func_proto *fn,
9616 			  int insn_idx)
9617 {
9618 	u32 regno = BPF_REG_1 + arg;
9619 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9620 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9621 	enum bpf_reg_type type = reg->type;
9622 	u32 *arg_btf_id = NULL;
9623 	u32 key_size;
9624 	int err = 0;
9625 
9626 	if (arg_type == ARG_DONTCARE)
9627 		return 0;
9628 
9629 	err = check_reg_arg(env, regno, SRC_OP);
9630 	if (err)
9631 		return err;
9632 
9633 	if (arg_type == ARG_ANYTHING) {
9634 		if (is_pointer_value(env, regno)) {
9635 			verbose(env, "R%d leaks addr into helper function\n",
9636 				regno);
9637 			return -EACCES;
9638 		}
9639 		return 0;
9640 	}
9641 
9642 	if (type_is_pkt_pointer(type) &&
9643 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9644 		verbose(env, "helper access to the packet is not allowed\n");
9645 		return -EACCES;
9646 	}
9647 
9648 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9649 		err = resolve_map_arg_type(env, meta, &arg_type);
9650 		if (err)
9651 			return err;
9652 	}
9653 
9654 	if (register_is_null(reg) && type_may_be_null(arg_type))
9655 		/* A NULL register has a SCALAR_VALUE type, so skip
9656 		 * type checking.
9657 		 */
9658 		goto skip_type_check;
9659 
9660 	/* arg_btf_id and arg_size are in a union. */
9661 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9662 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9663 		arg_btf_id = fn->arg_btf_id[arg];
9664 
9665 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9666 	if (err)
9667 		return err;
9668 
9669 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
9670 	if (err)
9671 		return err;
9672 
9673 skip_type_check:
9674 	if (arg_type_is_release(arg_type)) {
9675 		if (arg_type_is_dynptr(arg_type)) {
9676 			struct bpf_func_state *state = func(env, reg);
9677 			int spi;
9678 
9679 			/* Only dynptr created on stack can be released, thus
9680 			 * the get_spi and stack state checks for spilled_ptr
9681 			 * should only be done before process_dynptr_func for
9682 			 * PTR_TO_STACK.
9683 			 */
9684 			if (reg->type == PTR_TO_STACK) {
9685 				spi = dynptr_get_spi(env, reg);
9686 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9687 					verbose(env, "arg %d is an unacquired reference\n", regno);
9688 					return -EINVAL;
9689 				}
9690 			} else {
9691 				verbose(env, "cannot release unowned const bpf_dynptr\n");
9692 				return -EINVAL;
9693 			}
9694 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
9695 			verbose(env, "R%d must be referenced when passed to release function\n",
9696 				regno);
9697 			return -EINVAL;
9698 		}
9699 		if (meta->release_regno) {
9700 			verifier_bug(env, "more than one release argument");
9701 			return -EFAULT;
9702 		}
9703 		meta->release_regno = regno;
9704 	}
9705 
9706 	if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9707 		if (meta->ref_obj_id) {
9708 			verbose(env, "more than one arg with ref_obj_id R%d %u %u",
9709 				regno, reg->ref_obj_id,
9710 				meta->ref_obj_id);
9711 			return -EACCES;
9712 		}
9713 		meta->ref_obj_id = reg->ref_obj_id;
9714 	}
9715 
9716 	switch (base_type(arg_type)) {
9717 	case ARG_CONST_MAP_PTR:
9718 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9719 		if (meta->map_ptr) {
9720 			/* Use map_uid (which is unique id of inner map) to reject:
9721 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9722 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9723 			 * if (inner_map1 && inner_map2) {
9724 			 *     timer = bpf_map_lookup_elem(inner_map1);
9725 			 *     if (timer)
9726 			 *         // mismatch would have been allowed
9727 			 *         bpf_timer_init(timer, inner_map2);
9728 			 * }
9729 			 *
9730 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
9731 			 */
9732 			if (meta->map_ptr != reg->map_ptr ||
9733 			    meta->map_uid != reg->map_uid) {
9734 				verbose(env,
9735 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9736 					meta->map_uid, reg->map_uid);
9737 				return -EINVAL;
9738 			}
9739 		}
9740 		meta->map_ptr = reg->map_ptr;
9741 		meta->map_uid = reg->map_uid;
9742 		break;
9743 	case ARG_PTR_TO_MAP_KEY:
9744 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9745 		 * check that [key, key + map->key_size) are within
9746 		 * stack limits and initialized
9747 		 */
9748 		if (!meta->map_ptr) {
9749 			/* in function declaration map_ptr must come before
9750 			 * map_key, so that it's verified and known before
9751 			 * we have to check map_key here. Otherwise it means
9752 			 * that kernel subsystem misconfigured verifier
9753 			 */
9754 			verifier_bug(env, "invalid map_ptr to access map->key");
9755 			return -EFAULT;
9756 		}
9757 		key_size = meta->map_ptr->key_size;
9758 		err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL);
9759 		if (err)
9760 			return err;
9761 		if (can_elide_value_nullness(meta->map_ptr->map_type)) {
9762 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9763 			if (err < 0) {
9764 				meta->const_map_key = -1;
9765 				if (err == -EOPNOTSUPP)
9766 					err = 0;
9767 				else
9768 					return err;
9769 			}
9770 		}
9771 		break;
9772 	case ARG_PTR_TO_MAP_VALUE:
9773 		if (type_may_be_null(arg_type) && register_is_null(reg))
9774 			return 0;
9775 
9776 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9777 		 * check [value, value + map->value_size) validity
9778 		 */
9779 		if (!meta->map_ptr) {
9780 			/* kernel subsystem misconfigured verifier */
9781 			verifier_bug(env, "invalid map_ptr to access map->value");
9782 			return -EFAULT;
9783 		}
9784 		meta->raw_mode = arg_type & MEM_UNINIT;
9785 		err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
9786 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9787 					      false, meta);
9788 		break;
9789 	case ARG_PTR_TO_PERCPU_BTF_ID:
9790 		if (!reg->btf_id) {
9791 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9792 			return -EACCES;
9793 		}
9794 		meta->ret_btf = reg->btf;
9795 		meta->ret_btf_id = reg->btf_id;
9796 		break;
9797 	case ARG_PTR_TO_SPIN_LOCK:
9798 		if (in_rbtree_lock_required_cb(env)) {
9799 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9800 			return -EACCES;
9801 		}
9802 		if (meta->func_id == BPF_FUNC_spin_lock) {
9803 			err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK);
9804 			if (err)
9805 				return err;
9806 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
9807 			err = process_spin_lock(env, regno, 0);
9808 			if (err)
9809 				return err;
9810 		} else {
9811 			verifier_bug(env, "spin lock arg on unexpected helper");
9812 			return -EFAULT;
9813 		}
9814 		break;
9815 	case ARG_PTR_TO_TIMER:
9816 		err = process_timer_func(env, regno, meta);
9817 		if (err)
9818 			return err;
9819 		break;
9820 	case ARG_PTR_TO_FUNC:
9821 		meta->subprogno = reg->subprogno;
9822 		break;
9823 	case ARG_PTR_TO_MEM:
9824 		/* The access to this pointer is only checked when we hit the
9825 		 * next is_mem_size argument below.
9826 		 */
9827 		meta->raw_mode = arg_type & MEM_UNINIT;
9828 		if (arg_type & MEM_FIXED_SIZE) {
9829 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
9830 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9831 						      false, meta);
9832 			if (err)
9833 				return err;
9834 			if (arg_type & MEM_ALIGNED)
9835 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9836 		}
9837 		break;
9838 	case ARG_CONST_SIZE:
9839 		err = check_mem_size_reg(env, reg, regno,
9840 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9841 					 BPF_WRITE : BPF_READ,
9842 					 false, meta);
9843 		break;
9844 	case ARG_CONST_SIZE_OR_ZERO:
9845 		err = check_mem_size_reg(env, reg, regno,
9846 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9847 					 BPF_WRITE : BPF_READ,
9848 					 true, meta);
9849 		break;
9850 	case ARG_PTR_TO_DYNPTR:
9851 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9852 		if (err)
9853 			return err;
9854 		break;
9855 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9856 		if (!tnum_is_const(reg->var_off)) {
9857 			verbose(env, "R%d is not a known constant'\n",
9858 				regno);
9859 			return -EACCES;
9860 		}
9861 		meta->mem_size = reg->var_off.value;
9862 		err = mark_chain_precision(env, regno);
9863 		if (err)
9864 			return err;
9865 		break;
9866 	case ARG_PTR_TO_CONST_STR:
9867 	{
9868 		err = check_reg_const_str(env, reg, regno);
9869 		if (err)
9870 			return err;
9871 		break;
9872 	}
9873 	case ARG_KPTR_XCHG_DEST:
9874 		err = process_kptr_func(env, regno, meta);
9875 		if (err)
9876 			return err;
9877 		break;
9878 	}
9879 
9880 	return err;
9881 }
9882 
9883 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9884 {
9885 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
9886 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9887 
9888 	if (func_id != BPF_FUNC_map_update_elem &&
9889 	    func_id != BPF_FUNC_map_delete_elem)
9890 		return false;
9891 
9892 	/* It's not possible to get access to a locked struct sock in these
9893 	 * contexts, so updating is safe.
9894 	 */
9895 	switch (type) {
9896 	case BPF_PROG_TYPE_TRACING:
9897 		if (eatype == BPF_TRACE_ITER)
9898 			return true;
9899 		break;
9900 	case BPF_PROG_TYPE_SOCK_OPS:
9901 		/* map_update allowed only via dedicated helpers with event type checks */
9902 		if (func_id == BPF_FUNC_map_delete_elem)
9903 			return true;
9904 		break;
9905 	case BPF_PROG_TYPE_SOCKET_FILTER:
9906 	case BPF_PROG_TYPE_SCHED_CLS:
9907 	case BPF_PROG_TYPE_SCHED_ACT:
9908 	case BPF_PROG_TYPE_XDP:
9909 	case BPF_PROG_TYPE_SK_REUSEPORT:
9910 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
9911 	case BPF_PROG_TYPE_SK_LOOKUP:
9912 		return true;
9913 	default:
9914 		break;
9915 	}
9916 
9917 	verbose(env, "cannot update sockmap in this context\n");
9918 	return false;
9919 }
9920 
9921 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
9922 {
9923 	return env->prog->jit_requested &&
9924 	       bpf_jit_supports_subprog_tailcalls();
9925 }
9926 
9927 static int check_map_func_compatibility(struct bpf_verifier_env *env,
9928 					struct bpf_map *map, int func_id)
9929 {
9930 	if (!map)
9931 		return 0;
9932 
9933 	/* We need a two way check, first is from map perspective ... */
9934 	switch (map->map_type) {
9935 	case BPF_MAP_TYPE_PROG_ARRAY:
9936 		if (func_id != BPF_FUNC_tail_call)
9937 			goto error;
9938 		break;
9939 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
9940 		if (func_id != BPF_FUNC_perf_event_read &&
9941 		    func_id != BPF_FUNC_perf_event_output &&
9942 		    func_id != BPF_FUNC_skb_output &&
9943 		    func_id != BPF_FUNC_perf_event_read_value &&
9944 		    func_id != BPF_FUNC_xdp_output)
9945 			goto error;
9946 		break;
9947 	case BPF_MAP_TYPE_RINGBUF:
9948 		if (func_id != BPF_FUNC_ringbuf_output &&
9949 		    func_id != BPF_FUNC_ringbuf_reserve &&
9950 		    func_id != BPF_FUNC_ringbuf_query &&
9951 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
9952 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
9953 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
9954 			goto error;
9955 		break;
9956 	case BPF_MAP_TYPE_USER_RINGBUF:
9957 		if (func_id != BPF_FUNC_user_ringbuf_drain)
9958 			goto error;
9959 		break;
9960 	case BPF_MAP_TYPE_STACK_TRACE:
9961 		if (func_id != BPF_FUNC_get_stackid)
9962 			goto error;
9963 		break;
9964 	case BPF_MAP_TYPE_CGROUP_ARRAY:
9965 		if (func_id != BPF_FUNC_skb_under_cgroup &&
9966 		    func_id != BPF_FUNC_current_task_under_cgroup)
9967 			goto error;
9968 		break;
9969 	case BPF_MAP_TYPE_CGROUP_STORAGE:
9970 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
9971 		if (func_id != BPF_FUNC_get_local_storage)
9972 			goto error;
9973 		break;
9974 	case BPF_MAP_TYPE_DEVMAP:
9975 	case BPF_MAP_TYPE_DEVMAP_HASH:
9976 		if (func_id != BPF_FUNC_redirect_map &&
9977 		    func_id != BPF_FUNC_map_lookup_elem)
9978 			goto error;
9979 		break;
9980 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
9981 	 * appear.
9982 	 */
9983 	case BPF_MAP_TYPE_CPUMAP:
9984 		if (func_id != BPF_FUNC_redirect_map)
9985 			goto error;
9986 		break;
9987 	case BPF_MAP_TYPE_XSKMAP:
9988 		if (func_id != BPF_FUNC_redirect_map &&
9989 		    func_id != BPF_FUNC_map_lookup_elem)
9990 			goto error;
9991 		break;
9992 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
9993 	case BPF_MAP_TYPE_HASH_OF_MAPS:
9994 		if (func_id != BPF_FUNC_map_lookup_elem)
9995 			goto error;
9996 		break;
9997 	case BPF_MAP_TYPE_SOCKMAP:
9998 		if (func_id != BPF_FUNC_sk_redirect_map &&
9999 		    func_id != BPF_FUNC_sock_map_update &&
10000 		    func_id != BPF_FUNC_msg_redirect_map &&
10001 		    func_id != BPF_FUNC_sk_select_reuseport &&
10002 		    func_id != BPF_FUNC_map_lookup_elem &&
10003 		    !may_update_sockmap(env, func_id))
10004 			goto error;
10005 		break;
10006 	case BPF_MAP_TYPE_SOCKHASH:
10007 		if (func_id != BPF_FUNC_sk_redirect_hash &&
10008 		    func_id != BPF_FUNC_sock_hash_update &&
10009 		    func_id != BPF_FUNC_msg_redirect_hash &&
10010 		    func_id != BPF_FUNC_sk_select_reuseport &&
10011 		    func_id != BPF_FUNC_map_lookup_elem &&
10012 		    !may_update_sockmap(env, func_id))
10013 			goto error;
10014 		break;
10015 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
10016 		if (func_id != BPF_FUNC_sk_select_reuseport)
10017 			goto error;
10018 		break;
10019 	case BPF_MAP_TYPE_QUEUE:
10020 	case BPF_MAP_TYPE_STACK:
10021 		if (func_id != BPF_FUNC_map_peek_elem &&
10022 		    func_id != BPF_FUNC_map_pop_elem &&
10023 		    func_id != BPF_FUNC_map_push_elem)
10024 			goto error;
10025 		break;
10026 	case BPF_MAP_TYPE_SK_STORAGE:
10027 		if (func_id != BPF_FUNC_sk_storage_get &&
10028 		    func_id != BPF_FUNC_sk_storage_delete &&
10029 		    func_id != BPF_FUNC_kptr_xchg)
10030 			goto error;
10031 		break;
10032 	case BPF_MAP_TYPE_INODE_STORAGE:
10033 		if (func_id != BPF_FUNC_inode_storage_get &&
10034 		    func_id != BPF_FUNC_inode_storage_delete &&
10035 		    func_id != BPF_FUNC_kptr_xchg)
10036 			goto error;
10037 		break;
10038 	case BPF_MAP_TYPE_TASK_STORAGE:
10039 		if (func_id != BPF_FUNC_task_storage_get &&
10040 		    func_id != BPF_FUNC_task_storage_delete &&
10041 		    func_id != BPF_FUNC_kptr_xchg)
10042 			goto error;
10043 		break;
10044 	case BPF_MAP_TYPE_CGRP_STORAGE:
10045 		if (func_id != BPF_FUNC_cgrp_storage_get &&
10046 		    func_id != BPF_FUNC_cgrp_storage_delete &&
10047 		    func_id != BPF_FUNC_kptr_xchg)
10048 			goto error;
10049 		break;
10050 	case BPF_MAP_TYPE_BLOOM_FILTER:
10051 		if (func_id != BPF_FUNC_map_peek_elem &&
10052 		    func_id != BPF_FUNC_map_push_elem)
10053 			goto error;
10054 		break;
10055 	default:
10056 		break;
10057 	}
10058 
10059 	/* ... and second from the function itself. */
10060 	switch (func_id) {
10061 	case BPF_FUNC_tail_call:
10062 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
10063 			goto error;
10064 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
10065 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
10066 			return -EINVAL;
10067 		}
10068 		break;
10069 	case BPF_FUNC_perf_event_read:
10070 	case BPF_FUNC_perf_event_output:
10071 	case BPF_FUNC_perf_event_read_value:
10072 	case BPF_FUNC_skb_output:
10073 	case BPF_FUNC_xdp_output:
10074 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10075 			goto error;
10076 		break;
10077 	case BPF_FUNC_ringbuf_output:
10078 	case BPF_FUNC_ringbuf_reserve:
10079 	case BPF_FUNC_ringbuf_query:
10080 	case BPF_FUNC_ringbuf_reserve_dynptr:
10081 	case BPF_FUNC_ringbuf_submit_dynptr:
10082 	case BPF_FUNC_ringbuf_discard_dynptr:
10083 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
10084 			goto error;
10085 		break;
10086 	case BPF_FUNC_user_ringbuf_drain:
10087 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
10088 			goto error;
10089 		break;
10090 	case BPF_FUNC_get_stackid:
10091 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
10092 			goto error;
10093 		break;
10094 	case BPF_FUNC_current_task_under_cgroup:
10095 	case BPF_FUNC_skb_under_cgroup:
10096 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
10097 			goto error;
10098 		break;
10099 	case BPF_FUNC_redirect_map:
10100 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
10101 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
10102 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
10103 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
10104 			goto error;
10105 		break;
10106 	case BPF_FUNC_sk_redirect_map:
10107 	case BPF_FUNC_msg_redirect_map:
10108 	case BPF_FUNC_sock_map_update:
10109 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10110 			goto error;
10111 		break;
10112 	case BPF_FUNC_sk_redirect_hash:
10113 	case BPF_FUNC_msg_redirect_hash:
10114 	case BPF_FUNC_sock_hash_update:
10115 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10116 			goto error;
10117 		break;
10118 	case BPF_FUNC_get_local_storage:
10119 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10120 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10121 			goto error;
10122 		break;
10123 	case BPF_FUNC_sk_select_reuseport:
10124 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10125 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10126 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
10127 			goto error;
10128 		break;
10129 	case BPF_FUNC_map_pop_elem:
10130 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10131 		    map->map_type != BPF_MAP_TYPE_STACK)
10132 			goto error;
10133 		break;
10134 	case BPF_FUNC_map_peek_elem:
10135 	case BPF_FUNC_map_push_elem:
10136 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10137 		    map->map_type != BPF_MAP_TYPE_STACK &&
10138 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10139 			goto error;
10140 		break;
10141 	case BPF_FUNC_map_lookup_percpu_elem:
10142 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10143 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10144 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10145 			goto error;
10146 		break;
10147 	case BPF_FUNC_sk_storage_get:
10148 	case BPF_FUNC_sk_storage_delete:
10149 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10150 			goto error;
10151 		break;
10152 	case BPF_FUNC_inode_storage_get:
10153 	case BPF_FUNC_inode_storage_delete:
10154 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10155 			goto error;
10156 		break;
10157 	case BPF_FUNC_task_storage_get:
10158 	case BPF_FUNC_task_storage_delete:
10159 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10160 			goto error;
10161 		break;
10162 	case BPF_FUNC_cgrp_storage_get:
10163 	case BPF_FUNC_cgrp_storage_delete:
10164 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10165 			goto error;
10166 		break;
10167 	default:
10168 		break;
10169 	}
10170 
10171 	return 0;
10172 error:
10173 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
10174 		map->map_type, func_id_name(func_id), func_id);
10175 	return -EINVAL;
10176 }
10177 
10178 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
10179 {
10180 	int count = 0;
10181 
10182 	if (arg_type_is_raw_mem(fn->arg1_type))
10183 		count++;
10184 	if (arg_type_is_raw_mem(fn->arg2_type))
10185 		count++;
10186 	if (arg_type_is_raw_mem(fn->arg3_type))
10187 		count++;
10188 	if (arg_type_is_raw_mem(fn->arg4_type))
10189 		count++;
10190 	if (arg_type_is_raw_mem(fn->arg5_type))
10191 		count++;
10192 
10193 	/* We only support one arg being in raw mode at the moment,
10194 	 * which is sufficient for the helper functions we have
10195 	 * right now.
10196 	 */
10197 	return count <= 1;
10198 }
10199 
10200 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10201 {
10202 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10203 	bool has_size = fn->arg_size[arg] != 0;
10204 	bool is_next_size = false;
10205 
10206 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10207 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10208 
10209 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10210 		return is_next_size;
10211 
10212 	return has_size == is_next_size || is_next_size == is_fixed;
10213 }
10214 
10215 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10216 {
10217 	/* bpf_xxx(..., buf, len) call will access 'len'
10218 	 * bytes from memory 'buf'. Both arg types need
10219 	 * to be paired, so make sure there's no buggy
10220 	 * helper function specification.
10221 	 */
10222 	if (arg_type_is_mem_size(fn->arg1_type) ||
10223 	    check_args_pair_invalid(fn, 0) ||
10224 	    check_args_pair_invalid(fn, 1) ||
10225 	    check_args_pair_invalid(fn, 2) ||
10226 	    check_args_pair_invalid(fn, 3) ||
10227 	    check_args_pair_invalid(fn, 4))
10228 		return false;
10229 
10230 	return true;
10231 }
10232 
10233 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10234 {
10235 	int i;
10236 
10237 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10238 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10239 			return !!fn->arg_btf_id[i];
10240 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10241 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
10242 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10243 		    /* arg_btf_id and arg_size are in a union. */
10244 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10245 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10246 			return false;
10247 	}
10248 
10249 	return true;
10250 }
10251 
10252 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
10253 {
10254 	return check_raw_mode_ok(fn) &&
10255 	       check_arg_pair_ok(fn) &&
10256 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
10257 }
10258 
10259 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
10260  * are now invalid, so turn them into unknown SCALAR_VALUE.
10261  *
10262  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
10263  * since these slices point to packet data.
10264  */
10265 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
10266 {
10267 	struct bpf_func_state *state;
10268 	struct bpf_reg_state *reg;
10269 
10270 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10271 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
10272 			mark_reg_invalid(env, reg);
10273 	}));
10274 }
10275 
10276 enum {
10277 	AT_PKT_END = -1,
10278 	BEYOND_PKT_END = -2,
10279 };
10280 
10281 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
10282 {
10283 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10284 	struct bpf_reg_state *reg = &state->regs[regn];
10285 
10286 	if (reg->type != PTR_TO_PACKET)
10287 		/* PTR_TO_PACKET_META is not supported yet */
10288 		return;
10289 
10290 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
10291 	 * How far beyond pkt_end it goes is unknown.
10292 	 * if (!range_open) it's the case of pkt >= pkt_end
10293 	 * if (range_open) it's the case of pkt > pkt_end
10294 	 * hence this pointer is at least 1 byte bigger than pkt_end
10295 	 */
10296 	if (range_open)
10297 		reg->range = BEYOND_PKT_END;
10298 	else
10299 		reg->range = AT_PKT_END;
10300 }
10301 
10302 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id)
10303 {
10304 	int i;
10305 
10306 	for (i = 0; i < state->acquired_refs; i++) {
10307 		if (state->refs[i].type != REF_TYPE_PTR)
10308 			continue;
10309 		if (state->refs[i].id == ref_obj_id) {
10310 			release_reference_state(state, i);
10311 			return 0;
10312 		}
10313 	}
10314 	return -EINVAL;
10315 }
10316 
10317 /* The pointer with the specified id has released its reference to kernel
10318  * resources. Identify all copies of the same pointer and clear the reference.
10319  *
10320  * This is the release function corresponding to acquire_reference(). Idempotent.
10321  */
10322 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id)
10323 {
10324 	struct bpf_verifier_state *vstate = env->cur_state;
10325 	struct bpf_func_state *state;
10326 	struct bpf_reg_state *reg;
10327 	int err;
10328 
10329 	err = release_reference_nomark(vstate, ref_obj_id);
10330 	if (err)
10331 		return err;
10332 
10333 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10334 		if (reg->ref_obj_id == ref_obj_id)
10335 			mark_reg_invalid(env, reg);
10336 	}));
10337 
10338 	return 0;
10339 }
10340 
10341 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
10342 {
10343 	struct bpf_func_state *unused;
10344 	struct bpf_reg_state *reg;
10345 
10346 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10347 		if (type_is_non_owning_ref(reg->type))
10348 			mark_reg_invalid(env, reg);
10349 	}));
10350 }
10351 
10352 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
10353 				    struct bpf_reg_state *regs)
10354 {
10355 	int i;
10356 
10357 	/* after the call registers r0 - r5 were scratched */
10358 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10359 		mark_reg_not_init(env, regs, caller_saved[i]);
10360 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
10361 	}
10362 }
10363 
10364 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
10365 				   struct bpf_func_state *caller,
10366 				   struct bpf_func_state *callee,
10367 				   int insn_idx);
10368 
10369 static bool is_task_work_add_kfunc(u32 func_id);
10370 
10371 static int set_callee_state(struct bpf_verifier_env *env,
10372 			    struct bpf_func_state *caller,
10373 			    struct bpf_func_state *callee, int insn_idx);
10374 
10375 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
10376 			    set_callee_state_fn set_callee_state_cb,
10377 			    struct bpf_verifier_state *state)
10378 {
10379 	struct bpf_func_state *caller, *callee;
10380 	int err;
10381 
10382 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
10383 		verbose(env, "the call stack of %d frames is too deep\n",
10384 			state->curframe + 2);
10385 		return -E2BIG;
10386 	}
10387 
10388 	if (state->frame[state->curframe + 1]) {
10389 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
10390 		return -EFAULT;
10391 	}
10392 
10393 	caller = state->frame[state->curframe];
10394 	callee = kzalloc(sizeof(*callee), GFP_KERNEL_ACCOUNT);
10395 	if (!callee)
10396 		return -ENOMEM;
10397 	state->frame[state->curframe + 1] = callee;
10398 
10399 	/* callee cannot access r0, r6 - r9 for reading and has to write
10400 	 * into its own stack before reading from it.
10401 	 * callee can read/write into caller's stack
10402 	 */
10403 	init_func_state(env, callee,
10404 			/* remember the callsite, it will be used by bpf_exit */
10405 			callsite,
10406 			state->curframe + 1 /* frameno within this callchain */,
10407 			subprog /* subprog number within this prog */);
10408 	err = set_callee_state_cb(env, caller, callee, callsite);
10409 	if (err)
10410 		goto err_out;
10411 
10412 	/* only increment it after check_reg_arg() finished */
10413 	state->curframe++;
10414 
10415 	return 0;
10416 
10417 err_out:
10418 	free_func_state(callee);
10419 	state->frame[state->curframe + 1] = NULL;
10420 	return err;
10421 }
10422 
10423 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
10424 				    const struct btf *btf,
10425 				    struct bpf_reg_state *regs)
10426 {
10427 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
10428 	struct bpf_verifier_log *log = &env->log;
10429 	u32 i;
10430 	int ret;
10431 
10432 	ret = btf_prepare_func_args(env, subprog);
10433 	if (ret)
10434 		return ret;
10435 
10436 	/* check that BTF function arguments match actual types that the
10437 	 * verifier sees.
10438 	 */
10439 	for (i = 0; i < sub->arg_cnt; i++) {
10440 		u32 regno = i + 1;
10441 		struct bpf_reg_state *reg = &regs[regno];
10442 		struct bpf_subprog_arg_info *arg = &sub->args[i];
10443 
10444 		if (arg->arg_type == ARG_ANYTHING) {
10445 			if (reg->type != SCALAR_VALUE) {
10446 				bpf_log(log, "R%d is not a scalar\n", regno);
10447 				return -EINVAL;
10448 			}
10449 		} else if (arg->arg_type & PTR_UNTRUSTED) {
10450 			/*
10451 			 * Anything is allowed for untrusted arguments, as these are
10452 			 * read-only and probe read instructions would protect against
10453 			 * invalid memory access.
10454 			 */
10455 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
10456 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10457 			if (ret < 0)
10458 				return ret;
10459 			/* If function expects ctx type in BTF check that caller
10460 			 * is passing PTR_TO_CTX.
10461 			 */
10462 			if (reg->type != PTR_TO_CTX) {
10463 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
10464 				return -EINVAL;
10465 			}
10466 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
10467 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10468 			if (ret < 0)
10469 				return ret;
10470 			if (check_mem_reg(env, reg, regno, arg->mem_size))
10471 				return -EINVAL;
10472 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
10473 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
10474 				return -EINVAL;
10475 			}
10476 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
10477 			/*
10478 			 * Can pass any value and the kernel won't crash, but
10479 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
10480 			 * else is a bug in the bpf program. Point it out to
10481 			 * the user at the verification time instead of
10482 			 * run-time debug nightmare.
10483 			 */
10484 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
10485 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
10486 				return -EINVAL;
10487 			}
10488 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
10489 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
10490 			if (ret)
10491 				return ret;
10492 
10493 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
10494 			if (ret)
10495 				return ret;
10496 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
10497 			struct bpf_call_arg_meta meta;
10498 			int err;
10499 
10500 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
10501 				continue;
10502 
10503 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
10504 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
10505 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
10506 			if (err)
10507 				return err;
10508 		} else {
10509 			verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type);
10510 			return -EFAULT;
10511 		}
10512 	}
10513 
10514 	return 0;
10515 }
10516 
10517 /* Compare BTF of a function call with given bpf_reg_state.
10518  * Returns:
10519  * EFAULT - there is a verifier bug. Abort verification.
10520  * EINVAL - there is a type mismatch or BTF is not available.
10521  * 0 - BTF matches with what bpf_reg_state expects.
10522  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
10523  */
10524 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
10525 				  struct bpf_reg_state *regs)
10526 {
10527 	struct bpf_prog *prog = env->prog;
10528 	struct btf *btf = prog->aux->btf;
10529 	u32 btf_id;
10530 	int err;
10531 
10532 	if (!prog->aux->func_info)
10533 		return -EINVAL;
10534 
10535 	btf_id = prog->aux->func_info[subprog].type_id;
10536 	if (!btf_id)
10537 		return -EFAULT;
10538 
10539 	if (prog->aux->func_info_aux[subprog].unreliable)
10540 		return -EINVAL;
10541 
10542 	err = btf_check_func_arg_match(env, subprog, btf, regs);
10543 	/* Compiler optimizations can remove arguments from static functions
10544 	 * or mismatched type can be passed into a global function.
10545 	 * In such cases mark the function as unreliable from BTF point of view.
10546 	 */
10547 	if (err)
10548 		prog->aux->func_info_aux[subprog].unreliable = true;
10549 	return err;
10550 }
10551 
10552 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10553 			      int insn_idx, int subprog,
10554 			      set_callee_state_fn set_callee_state_cb)
10555 {
10556 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
10557 	struct bpf_func_state *caller, *callee;
10558 	int err;
10559 
10560 	caller = state->frame[state->curframe];
10561 	err = btf_check_subprog_call(env, subprog, caller->regs);
10562 	if (err == -EFAULT)
10563 		return err;
10564 
10565 	/* set_callee_state is used for direct subprog calls, but we are
10566 	 * interested in validating only BPF helpers that can call subprogs as
10567 	 * callbacks
10568 	 */
10569 	env->subprog_info[subprog].is_cb = true;
10570 	if (bpf_pseudo_kfunc_call(insn) &&
10571 	    !is_callback_calling_kfunc(insn->imm)) {
10572 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
10573 			     func_id_name(insn->imm), insn->imm);
10574 		return -EFAULT;
10575 	} else if (!bpf_pseudo_kfunc_call(insn) &&
10576 		   !is_callback_calling_function(insn->imm)) { /* helper */
10577 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
10578 			     func_id_name(insn->imm), insn->imm);
10579 		return -EFAULT;
10580 	}
10581 
10582 	if (is_async_callback_calling_insn(insn)) {
10583 		struct bpf_verifier_state *async_cb;
10584 
10585 		/* there is no real recursion here. timer and workqueue callbacks are async */
10586 		env->subprog_info[subprog].is_async_cb = true;
10587 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
10588 					 insn_idx, subprog,
10589 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm) ||
10590 					 is_task_work_add_kfunc(insn->imm));
10591 		if (!async_cb)
10592 			return -EFAULT;
10593 		callee = async_cb->frame[0];
10594 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
10595 
10596 		/* Convert bpf_timer_set_callback() args into timer callback args */
10597 		err = set_callee_state_cb(env, caller, callee, insn_idx);
10598 		if (err)
10599 			return err;
10600 
10601 		return 0;
10602 	}
10603 
10604 	/* for callback functions enqueue entry to callback and
10605 	 * proceed with next instruction within current frame.
10606 	 */
10607 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
10608 	if (!callback_state)
10609 		return -ENOMEM;
10610 
10611 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
10612 			       callback_state);
10613 	if (err)
10614 		return err;
10615 
10616 	callback_state->callback_unroll_depth++;
10617 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
10618 	caller->callback_depth = 0;
10619 	return 0;
10620 }
10621 
10622 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10623 			   int *insn_idx)
10624 {
10625 	struct bpf_verifier_state *state = env->cur_state;
10626 	struct bpf_func_state *caller;
10627 	int err, subprog, target_insn;
10628 
10629 	target_insn = *insn_idx + insn->imm + 1;
10630 	subprog = find_subprog(env, target_insn);
10631 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
10632 			    target_insn))
10633 		return -EFAULT;
10634 
10635 	caller = state->frame[state->curframe];
10636 	err = btf_check_subprog_call(env, subprog, caller->regs);
10637 	if (err == -EFAULT)
10638 		return err;
10639 	if (subprog_is_global(env, subprog)) {
10640 		const char *sub_name = subprog_name(env, subprog);
10641 
10642 		if (env->cur_state->active_locks) {
10643 			verbose(env, "global function calls are not allowed while holding a lock,\n"
10644 				     "use static function instead\n");
10645 			return -EINVAL;
10646 		}
10647 
10648 		if (env->subprog_info[subprog].might_sleep &&
10649 		    (env->cur_state->active_rcu_lock || env->cur_state->active_preempt_locks ||
10650 		     env->cur_state->active_irq_id || !in_sleepable(env))) {
10651 			verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n"
10652 				     "i.e., in a RCU/IRQ/preempt-disabled section, or in\n"
10653 				     "a non-sleepable BPF program context\n");
10654 			return -EINVAL;
10655 		}
10656 
10657 		if (err) {
10658 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10659 				subprog, sub_name);
10660 			return err;
10661 		}
10662 
10663 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10664 			subprog, sub_name);
10665 		if (env->subprog_info[subprog].changes_pkt_data)
10666 			clear_all_pkt_pointers(env);
10667 		/* mark global subprog for verifying after main prog */
10668 		subprog_aux(env, subprog)->called = true;
10669 		clear_caller_saved_regs(env, caller->regs);
10670 
10671 		/* All global functions return a 64-bit SCALAR_VALUE */
10672 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
10673 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10674 
10675 		/* continue with next insn after call */
10676 		return 0;
10677 	}
10678 
10679 	/* for regular function entry setup new frame and continue
10680 	 * from that frame.
10681 	 */
10682 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10683 	if (err)
10684 		return err;
10685 
10686 	clear_caller_saved_regs(env, caller->regs);
10687 
10688 	/* and go analyze first insn of the callee */
10689 	*insn_idx = env->subprog_info[subprog].start - 1;
10690 
10691 	bpf_reset_live_stack_callchain(env);
10692 
10693 	if (env->log.level & BPF_LOG_LEVEL) {
10694 		verbose(env, "caller:\n");
10695 		print_verifier_state(env, state, caller->frameno, true);
10696 		verbose(env, "callee:\n");
10697 		print_verifier_state(env, state, state->curframe, true);
10698 	}
10699 
10700 	return 0;
10701 }
10702 
10703 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10704 				   struct bpf_func_state *caller,
10705 				   struct bpf_func_state *callee)
10706 {
10707 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10708 	 *      void *callback_ctx, u64 flags);
10709 	 * callback_fn(struct bpf_map *map, void *key, void *value,
10710 	 *      void *callback_ctx);
10711 	 */
10712 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10713 
10714 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10715 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10716 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10717 
10718 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10719 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10720 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10721 
10722 	/* pointer to stack or null */
10723 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10724 
10725 	/* unused */
10726 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10727 	return 0;
10728 }
10729 
10730 static int set_callee_state(struct bpf_verifier_env *env,
10731 			    struct bpf_func_state *caller,
10732 			    struct bpf_func_state *callee, int insn_idx)
10733 {
10734 	int i;
10735 
10736 	/* copy r1 - r5 args that callee can access.  The copy includes parent
10737 	 * pointers, which connects us up to the liveness chain
10738 	 */
10739 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10740 		callee->regs[i] = caller->regs[i];
10741 	return 0;
10742 }
10743 
10744 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10745 				       struct bpf_func_state *caller,
10746 				       struct bpf_func_state *callee,
10747 				       int insn_idx)
10748 {
10749 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10750 	struct bpf_map *map;
10751 	int err;
10752 
10753 	/* valid map_ptr and poison value does not matter */
10754 	map = insn_aux->map_ptr_state.map_ptr;
10755 	if (!map->ops->map_set_for_each_callback_args ||
10756 	    !map->ops->map_for_each_callback) {
10757 		verbose(env, "callback function not allowed for map\n");
10758 		return -ENOTSUPP;
10759 	}
10760 
10761 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10762 	if (err)
10763 		return err;
10764 
10765 	callee->in_callback_fn = true;
10766 	callee->callback_ret_range = retval_range(0, 1);
10767 	return 0;
10768 }
10769 
10770 static int set_loop_callback_state(struct bpf_verifier_env *env,
10771 				   struct bpf_func_state *caller,
10772 				   struct bpf_func_state *callee,
10773 				   int insn_idx)
10774 {
10775 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10776 	 *	    u64 flags);
10777 	 * callback_fn(u64 index, void *callback_ctx);
10778 	 */
10779 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10780 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10781 
10782 	/* unused */
10783 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10784 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10785 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10786 
10787 	callee->in_callback_fn = true;
10788 	callee->callback_ret_range = retval_range(0, 1);
10789 	return 0;
10790 }
10791 
10792 static int set_timer_callback_state(struct bpf_verifier_env *env,
10793 				    struct bpf_func_state *caller,
10794 				    struct bpf_func_state *callee,
10795 				    int insn_idx)
10796 {
10797 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10798 
10799 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10800 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10801 	 */
10802 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10803 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10804 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10805 
10806 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10807 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10808 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10809 
10810 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10811 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10812 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10813 
10814 	/* unused */
10815 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10816 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10817 	callee->in_async_callback_fn = true;
10818 	callee->callback_ret_range = retval_range(0, 0);
10819 	return 0;
10820 }
10821 
10822 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
10823 				       struct bpf_func_state *caller,
10824 				       struct bpf_func_state *callee,
10825 				       int insn_idx)
10826 {
10827 	/* bpf_find_vma(struct task_struct *task, u64 addr,
10828 	 *               void *callback_fn, void *callback_ctx, u64 flags)
10829 	 * (callback_fn)(struct task_struct *task,
10830 	 *               struct vm_area_struct *vma, void *callback_ctx);
10831 	 */
10832 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10833 
10834 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
10835 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10836 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
10837 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
10838 
10839 	/* pointer to stack or null */
10840 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
10841 
10842 	/* unused */
10843 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10844 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10845 	callee->in_callback_fn = true;
10846 	callee->callback_ret_range = retval_range(0, 1);
10847 	return 0;
10848 }
10849 
10850 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10851 					   struct bpf_func_state *caller,
10852 					   struct bpf_func_state *callee,
10853 					   int insn_idx)
10854 {
10855 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10856 	 *			  callback_ctx, u64 flags);
10857 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10858 	 */
10859 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10860 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10861 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10862 
10863 	/* unused */
10864 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10865 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10866 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10867 
10868 	callee->in_callback_fn = true;
10869 	callee->callback_ret_range = retval_range(0, 1);
10870 	return 0;
10871 }
10872 
10873 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10874 					 struct bpf_func_state *caller,
10875 					 struct bpf_func_state *callee,
10876 					 int insn_idx)
10877 {
10878 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10879 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10880 	 *
10881 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10882 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10883 	 * by this point, so look at 'root'
10884 	 */
10885 	struct btf_field *field;
10886 
10887 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10888 				      BPF_RB_ROOT);
10889 	if (!field || !field->graph_root.value_btf_id)
10890 		return -EFAULT;
10891 
10892 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10893 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10894 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10895 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10896 
10897 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10898 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10899 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10900 	callee->in_callback_fn = true;
10901 	callee->callback_ret_range = retval_range(0, 1);
10902 	return 0;
10903 }
10904 
10905 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
10906 						 struct bpf_func_state *caller,
10907 						 struct bpf_func_state *callee,
10908 						 int insn_idx)
10909 {
10910 	struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
10911 
10912 	/*
10913 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10914 	 */
10915 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10916 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10917 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10918 
10919 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10920 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10921 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10922 
10923 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10924 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10925 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10926 
10927 	/* unused */
10928 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10929 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10930 	callee->in_async_callback_fn = true;
10931 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
10932 	return 0;
10933 }
10934 
10935 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
10936 
10937 /* Are we currently verifying the callback for a rbtree helper that must
10938  * be called with lock held? If so, no need to complain about unreleased
10939  * lock
10940  */
10941 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
10942 {
10943 	struct bpf_verifier_state *state = env->cur_state;
10944 	struct bpf_insn *insn = env->prog->insnsi;
10945 	struct bpf_func_state *callee;
10946 	int kfunc_btf_id;
10947 
10948 	if (!state->curframe)
10949 		return false;
10950 
10951 	callee = state->frame[state->curframe];
10952 
10953 	if (!callee->in_callback_fn)
10954 		return false;
10955 
10956 	kfunc_btf_id = insn[callee->callsite].imm;
10957 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
10958 }
10959 
10960 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
10961 				bool return_32bit)
10962 {
10963 	if (return_32bit)
10964 		return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
10965 	else
10966 		return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
10967 }
10968 
10969 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
10970 {
10971 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
10972 	struct bpf_func_state *caller, *callee;
10973 	struct bpf_reg_state *r0;
10974 	bool in_callback_fn;
10975 	int err;
10976 
10977 	callee = state->frame[state->curframe];
10978 	r0 = &callee->regs[BPF_REG_0];
10979 	if (r0->type == PTR_TO_STACK) {
10980 		/* technically it's ok to return caller's stack pointer
10981 		 * (or caller's caller's pointer) back to the caller,
10982 		 * since these pointers are valid. Only current stack
10983 		 * pointer will be invalid as soon as function exits,
10984 		 * but let's be conservative
10985 		 */
10986 		verbose(env, "cannot return stack pointer to the caller\n");
10987 		return -EINVAL;
10988 	}
10989 
10990 	caller = state->frame[state->curframe - 1];
10991 	if (callee->in_callback_fn) {
10992 		if (r0->type != SCALAR_VALUE) {
10993 			verbose(env, "R0 not a scalar value\n");
10994 			return -EACCES;
10995 		}
10996 
10997 		/* we are going to rely on register's precise value */
10998 		err = mark_chain_precision(env, BPF_REG_0);
10999 		if (err)
11000 			return err;
11001 
11002 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
11003 		if (!retval_range_within(callee->callback_ret_range, r0, false)) {
11004 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
11005 					       "At callback return", "R0");
11006 			return -EINVAL;
11007 		}
11008 		if (!bpf_calls_callback(env, callee->callsite)) {
11009 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
11010 				     *insn_idx, callee->callsite);
11011 			return -EFAULT;
11012 		}
11013 	} else {
11014 		/* return to the caller whatever r0 had in the callee */
11015 		caller->regs[BPF_REG_0] = *r0;
11016 	}
11017 
11018 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
11019 	 * there function call logic would reschedule callback visit. If iteration
11020 	 * converges is_state_visited() would prune that visit eventually.
11021 	 */
11022 	in_callback_fn = callee->in_callback_fn;
11023 	if (in_callback_fn)
11024 		*insn_idx = callee->callsite;
11025 	else
11026 		*insn_idx = callee->callsite + 1;
11027 
11028 	if (env->log.level & BPF_LOG_LEVEL) {
11029 		verbose(env, "returning from callee:\n");
11030 		print_verifier_state(env, state, callee->frameno, true);
11031 		verbose(env, "to caller at %d:\n", *insn_idx);
11032 		print_verifier_state(env, state, caller->frameno, true);
11033 	}
11034 	/* clear everything in the callee. In case of exceptional exits using
11035 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
11036 	free_func_state(callee);
11037 	state->frame[state->curframe--] = NULL;
11038 
11039 	/* for callbacks widen imprecise scalars to make programs like below verify:
11040 	 *
11041 	 *   struct ctx { int i; }
11042 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
11043 	 *   ...
11044 	 *   struct ctx = { .i = 0; }
11045 	 *   bpf_loop(100, cb, &ctx, 0);
11046 	 *
11047 	 * This is similar to what is done in process_iter_next_call() for open
11048 	 * coded iterators.
11049 	 */
11050 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
11051 	if (prev_st) {
11052 		err = widen_imprecise_scalars(env, prev_st, state);
11053 		if (err)
11054 			return err;
11055 	}
11056 	return 0;
11057 }
11058 
11059 static int do_refine_retval_range(struct bpf_verifier_env *env,
11060 				  struct bpf_reg_state *regs, int ret_type,
11061 				  int func_id,
11062 				  struct bpf_call_arg_meta *meta)
11063 {
11064 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
11065 
11066 	if (ret_type != RET_INTEGER)
11067 		return 0;
11068 
11069 	switch (func_id) {
11070 	case BPF_FUNC_get_stack:
11071 	case BPF_FUNC_get_task_stack:
11072 	case BPF_FUNC_probe_read_str:
11073 	case BPF_FUNC_probe_read_kernel_str:
11074 	case BPF_FUNC_probe_read_user_str:
11075 		ret_reg->smax_value = meta->msize_max_value;
11076 		ret_reg->s32_max_value = meta->msize_max_value;
11077 		ret_reg->smin_value = -MAX_ERRNO;
11078 		ret_reg->s32_min_value = -MAX_ERRNO;
11079 		reg_bounds_sync(ret_reg);
11080 		break;
11081 	case BPF_FUNC_get_smp_processor_id:
11082 		ret_reg->umax_value = nr_cpu_ids - 1;
11083 		ret_reg->u32_max_value = nr_cpu_ids - 1;
11084 		ret_reg->smax_value = nr_cpu_ids - 1;
11085 		ret_reg->s32_max_value = nr_cpu_ids - 1;
11086 		ret_reg->umin_value = 0;
11087 		ret_reg->u32_min_value = 0;
11088 		ret_reg->smin_value = 0;
11089 		ret_reg->s32_min_value = 0;
11090 		reg_bounds_sync(ret_reg);
11091 		break;
11092 	}
11093 
11094 	return reg_bounds_sanity_check(env, ret_reg, "retval");
11095 }
11096 
11097 static int
11098 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11099 		int func_id, int insn_idx)
11100 {
11101 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11102 	struct bpf_map *map = meta->map_ptr;
11103 
11104 	if (func_id != BPF_FUNC_tail_call &&
11105 	    func_id != BPF_FUNC_map_lookup_elem &&
11106 	    func_id != BPF_FUNC_map_update_elem &&
11107 	    func_id != BPF_FUNC_map_delete_elem &&
11108 	    func_id != BPF_FUNC_map_push_elem &&
11109 	    func_id != BPF_FUNC_map_pop_elem &&
11110 	    func_id != BPF_FUNC_map_peek_elem &&
11111 	    func_id != BPF_FUNC_for_each_map_elem &&
11112 	    func_id != BPF_FUNC_redirect_map &&
11113 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
11114 		return 0;
11115 
11116 	if (map == NULL) {
11117 		verifier_bug(env, "expected map for helper call");
11118 		return -EFAULT;
11119 	}
11120 
11121 	/* In case of read-only, some additional restrictions
11122 	 * need to be applied in order to prevent altering the
11123 	 * state of the map from program side.
11124 	 */
11125 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
11126 	    (func_id == BPF_FUNC_map_delete_elem ||
11127 	     func_id == BPF_FUNC_map_update_elem ||
11128 	     func_id == BPF_FUNC_map_push_elem ||
11129 	     func_id == BPF_FUNC_map_pop_elem)) {
11130 		verbose(env, "write into map forbidden\n");
11131 		return -EACCES;
11132 	}
11133 
11134 	if (!aux->map_ptr_state.map_ptr)
11135 		bpf_map_ptr_store(aux, meta->map_ptr,
11136 				  !meta->map_ptr->bypass_spec_v1, false);
11137 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
11138 		bpf_map_ptr_store(aux, meta->map_ptr,
11139 				  !meta->map_ptr->bypass_spec_v1, true);
11140 	return 0;
11141 }
11142 
11143 static int
11144 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11145 		int func_id, int insn_idx)
11146 {
11147 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11148 	struct bpf_reg_state *regs = cur_regs(env), *reg;
11149 	struct bpf_map *map = meta->map_ptr;
11150 	u64 val, max;
11151 	int err;
11152 
11153 	if (func_id != BPF_FUNC_tail_call)
11154 		return 0;
11155 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
11156 		verbose(env, "expected prog array map for tail call");
11157 		return -EINVAL;
11158 	}
11159 
11160 	reg = &regs[BPF_REG_3];
11161 	val = reg->var_off.value;
11162 	max = map->max_entries;
11163 
11164 	if (!(is_reg_const(reg, false) && val < max)) {
11165 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11166 		return 0;
11167 	}
11168 
11169 	err = mark_chain_precision(env, BPF_REG_3);
11170 	if (err)
11171 		return err;
11172 	if (bpf_map_key_unseen(aux))
11173 		bpf_map_key_store(aux, val);
11174 	else if (!bpf_map_key_poisoned(aux) &&
11175 		  bpf_map_key_immediate(aux) != val)
11176 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11177 	return 0;
11178 }
11179 
11180 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
11181 {
11182 	struct bpf_verifier_state *state = env->cur_state;
11183 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11184 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
11185 	bool refs_lingering = false;
11186 	int i;
11187 
11188 	if (!exception_exit && cur_func(env)->frameno)
11189 		return 0;
11190 
11191 	for (i = 0; i < state->acquired_refs; i++) {
11192 		if (state->refs[i].type != REF_TYPE_PTR)
11193 			continue;
11194 		/* Allow struct_ops programs to return a referenced kptr back to
11195 		 * kernel. Type checks are performed later in check_return_code.
11196 		 */
11197 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
11198 		    reg->ref_obj_id == state->refs[i].id)
11199 			continue;
11200 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
11201 			state->refs[i].id, state->refs[i].insn_idx);
11202 		refs_lingering = true;
11203 	}
11204 	return refs_lingering ? -EINVAL : 0;
11205 }
11206 
11207 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
11208 {
11209 	int err;
11210 
11211 	if (check_lock && env->cur_state->active_locks) {
11212 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
11213 		return -EINVAL;
11214 	}
11215 
11216 	err = check_reference_leak(env, exception_exit);
11217 	if (err) {
11218 		verbose(env, "%s would lead to reference leak\n", prefix);
11219 		return err;
11220 	}
11221 
11222 	if (check_lock && env->cur_state->active_irq_id) {
11223 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
11224 		return -EINVAL;
11225 	}
11226 
11227 	if (check_lock && env->cur_state->active_rcu_lock) {
11228 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
11229 		return -EINVAL;
11230 	}
11231 
11232 	if (check_lock && env->cur_state->active_preempt_locks) {
11233 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
11234 		return -EINVAL;
11235 	}
11236 
11237 	return 0;
11238 }
11239 
11240 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
11241 				   struct bpf_reg_state *regs)
11242 {
11243 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
11244 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
11245 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
11246 	struct bpf_bprintf_data data = {};
11247 	int err, fmt_map_off, num_args;
11248 	u64 fmt_addr;
11249 	char *fmt;
11250 
11251 	/* data must be an array of u64 */
11252 	if (data_len_reg->var_off.value % 8)
11253 		return -EINVAL;
11254 	num_args = data_len_reg->var_off.value / 8;
11255 
11256 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
11257 	 * and map_direct_value_addr is set.
11258 	 */
11259 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
11260 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
11261 						  fmt_map_off);
11262 	if (err) {
11263 		verbose(env, "failed to retrieve map value address\n");
11264 		return -EFAULT;
11265 	}
11266 	fmt = (char *)(long)fmt_addr + fmt_map_off;
11267 
11268 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
11269 	 * can focus on validating the format specifiers.
11270 	 */
11271 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
11272 	if (err < 0)
11273 		verbose(env, "Invalid format string\n");
11274 
11275 	return err;
11276 }
11277 
11278 static int check_get_func_ip(struct bpf_verifier_env *env)
11279 {
11280 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11281 	int func_id = BPF_FUNC_get_func_ip;
11282 
11283 	if (type == BPF_PROG_TYPE_TRACING) {
11284 		if (!bpf_prog_has_trampoline(env->prog)) {
11285 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
11286 				func_id_name(func_id), func_id);
11287 			return -ENOTSUPP;
11288 		}
11289 		return 0;
11290 	} else if (type == BPF_PROG_TYPE_KPROBE) {
11291 		return 0;
11292 	}
11293 
11294 	verbose(env, "func %s#%d not supported for program type %d\n",
11295 		func_id_name(func_id), func_id, type);
11296 	return -ENOTSUPP;
11297 }
11298 
11299 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
11300 {
11301 	return &env->insn_aux_data[env->insn_idx];
11302 }
11303 
11304 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
11305 {
11306 	struct bpf_reg_state *regs = cur_regs(env);
11307 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
11308 	bool reg_is_null = register_is_null(reg);
11309 
11310 	if (reg_is_null)
11311 		mark_chain_precision(env, BPF_REG_4);
11312 
11313 	return reg_is_null;
11314 }
11315 
11316 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
11317 {
11318 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
11319 
11320 	if (!state->initialized) {
11321 		state->initialized = 1;
11322 		state->fit_for_inline = loop_flag_is_zero(env);
11323 		state->callback_subprogno = subprogno;
11324 		return;
11325 	}
11326 
11327 	if (!state->fit_for_inline)
11328 		return;
11329 
11330 	state->fit_for_inline = (loop_flag_is_zero(env) &&
11331 				 state->callback_subprogno == subprogno);
11332 }
11333 
11334 /* Returns whether or not the given map type can potentially elide
11335  * lookup return value nullness check. This is possible if the key
11336  * is statically known.
11337  */
11338 static bool can_elide_value_nullness(enum bpf_map_type type)
11339 {
11340 	switch (type) {
11341 	case BPF_MAP_TYPE_ARRAY:
11342 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11343 		return true;
11344 	default:
11345 		return false;
11346 	}
11347 }
11348 
11349 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
11350 			    const struct bpf_func_proto **ptr)
11351 {
11352 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
11353 		return -ERANGE;
11354 
11355 	if (!env->ops->get_func_proto)
11356 		return -EINVAL;
11357 
11358 	*ptr = env->ops->get_func_proto(func_id, env->prog);
11359 	return *ptr && (*ptr)->func ? 0 : -EINVAL;
11360 }
11361 
11362 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11363 			     int *insn_idx_p)
11364 {
11365 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11366 	bool returns_cpu_specific_alloc_ptr = false;
11367 	const struct bpf_func_proto *fn = NULL;
11368 	enum bpf_return_type ret_type;
11369 	enum bpf_type_flag ret_flag;
11370 	struct bpf_reg_state *regs;
11371 	struct bpf_call_arg_meta meta;
11372 	int insn_idx = *insn_idx_p;
11373 	bool changes_data;
11374 	int i, err, func_id;
11375 
11376 	/* find function prototype */
11377 	func_id = insn->imm;
11378 	err = get_helper_proto(env, insn->imm, &fn);
11379 	if (err == -ERANGE) {
11380 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
11381 		return -EINVAL;
11382 	}
11383 
11384 	if (err) {
11385 		verbose(env, "program of this type cannot use helper %s#%d\n",
11386 			func_id_name(func_id), func_id);
11387 		return err;
11388 	}
11389 
11390 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
11391 	if (!env->prog->gpl_compatible && fn->gpl_only) {
11392 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
11393 		return -EINVAL;
11394 	}
11395 
11396 	if (fn->allowed && !fn->allowed(env->prog)) {
11397 		verbose(env, "helper call is not allowed in probe\n");
11398 		return -EINVAL;
11399 	}
11400 
11401 	if (!in_sleepable(env) && fn->might_sleep) {
11402 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
11403 		return -EINVAL;
11404 	}
11405 
11406 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
11407 	changes_data = bpf_helper_changes_pkt_data(func_id);
11408 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
11409 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
11410 		return -EFAULT;
11411 	}
11412 
11413 	memset(&meta, 0, sizeof(meta));
11414 	meta.pkt_access = fn->pkt_access;
11415 
11416 	err = check_func_proto(fn, func_id);
11417 	if (err) {
11418 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
11419 		return err;
11420 	}
11421 
11422 	if (env->cur_state->active_rcu_lock) {
11423 		if (fn->might_sleep) {
11424 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
11425 				func_id_name(func_id), func_id);
11426 			return -EINVAL;
11427 		}
11428 
11429 		if (in_sleepable(env) && is_storage_get_function(func_id))
11430 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11431 	}
11432 
11433 	if (env->cur_state->active_preempt_locks) {
11434 		if (fn->might_sleep) {
11435 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
11436 				func_id_name(func_id), func_id);
11437 			return -EINVAL;
11438 		}
11439 
11440 		if (in_sleepable(env) && is_storage_get_function(func_id))
11441 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11442 	}
11443 
11444 	if (env->cur_state->active_irq_id) {
11445 		if (fn->might_sleep) {
11446 			verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n",
11447 				func_id_name(func_id), func_id);
11448 			return -EINVAL;
11449 		}
11450 
11451 		if (in_sleepable(env) && is_storage_get_function(func_id))
11452 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11453 	}
11454 
11455 	meta.func_id = func_id;
11456 	/* check args */
11457 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
11458 		err = check_func_arg(env, i, &meta, fn, insn_idx);
11459 		if (err)
11460 			return err;
11461 	}
11462 
11463 	err = record_func_map(env, &meta, func_id, insn_idx);
11464 	if (err)
11465 		return err;
11466 
11467 	err = record_func_key(env, &meta, func_id, insn_idx);
11468 	if (err)
11469 		return err;
11470 
11471 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
11472 	 * is inferred from register state.
11473 	 */
11474 	for (i = 0; i < meta.access_size; i++) {
11475 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
11476 				       BPF_WRITE, -1, false, false);
11477 		if (err)
11478 			return err;
11479 	}
11480 
11481 	regs = cur_regs(env);
11482 
11483 	if (meta.release_regno) {
11484 		err = -EINVAL;
11485 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
11486 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
11487 		 * is safe to do directly.
11488 		 */
11489 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
11490 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
11491 				verifier_bug(env, "CONST_PTR_TO_DYNPTR cannot be released");
11492 				return -EFAULT;
11493 			}
11494 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
11495 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
11496 			u32 ref_obj_id = meta.ref_obj_id;
11497 			bool in_rcu = in_rcu_cs(env);
11498 			struct bpf_func_state *state;
11499 			struct bpf_reg_state *reg;
11500 
11501 			err = release_reference_nomark(env->cur_state, ref_obj_id);
11502 			if (!err) {
11503 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11504 					if (reg->ref_obj_id == ref_obj_id) {
11505 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11506 							reg->ref_obj_id = 0;
11507 							reg->type &= ~MEM_ALLOC;
11508 							reg->type |= MEM_RCU;
11509 						} else {
11510 							mark_reg_invalid(env, reg);
11511 						}
11512 					}
11513 				}));
11514 			}
11515 		} else if (meta.ref_obj_id) {
11516 			err = release_reference(env, meta.ref_obj_id);
11517 		} else if (register_is_null(&regs[meta.release_regno])) {
11518 			/* meta.ref_obj_id can only be 0 if register that is meant to be
11519 			 * released is NULL, which must be > R0.
11520 			 */
11521 			err = 0;
11522 		}
11523 		if (err) {
11524 			verbose(env, "func %s#%d reference has not been acquired before\n",
11525 				func_id_name(func_id), func_id);
11526 			return err;
11527 		}
11528 	}
11529 
11530 	switch (func_id) {
11531 	case BPF_FUNC_tail_call:
11532 		err = check_resource_leak(env, false, true, "tail_call");
11533 		if (err)
11534 			return err;
11535 		break;
11536 	case BPF_FUNC_get_local_storage:
11537 		/* check that flags argument in get_local_storage(map, flags) is 0,
11538 		 * this is required because get_local_storage() can't return an error.
11539 		 */
11540 		if (!register_is_null(&regs[BPF_REG_2])) {
11541 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
11542 			return -EINVAL;
11543 		}
11544 		break;
11545 	case BPF_FUNC_for_each_map_elem:
11546 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11547 					 set_map_elem_callback_state);
11548 		break;
11549 	case BPF_FUNC_timer_set_callback:
11550 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11551 					 set_timer_callback_state);
11552 		break;
11553 	case BPF_FUNC_find_vma:
11554 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11555 					 set_find_vma_callback_state);
11556 		break;
11557 	case BPF_FUNC_snprintf:
11558 		err = check_bpf_snprintf_call(env, regs);
11559 		break;
11560 	case BPF_FUNC_loop:
11561 		update_loop_inline_state(env, meta.subprogno);
11562 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
11563 		 * is finished, thus mark it precise.
11564 		 */
11565 		err = mark_chain_precision(env, BPF_REG_1);
11566 		if (err)
11567 			return err;
11568 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
11569 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11570 						 set_loop_callback_state);
11571 		} else {
11572 			cur_func(env)->callback_depth = 0;
11573 			if (env->log.level & BPF_LOG_LEVEL2)
11574 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
11575 					env->cur_state->curframe);
11576 		}
11577 		break;
11578 	case BPF_FUNC_dynptr_from_mem:
11579 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
11580 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
11581 				reg_type_str(env, regs[BPF_REG_1].type));
11582 			return -EACCES;
11583 		}
11584 		break;
11585 	case BPF_FUNC_set_retval:
11586 		if (prog_type == BPF_PROG_TYPE_LSM &&
11587 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11588 			if (!env->prog->aux->attach_func_proto->type) {
11589 				/* Make sure programs that attach to void
11590 				 * hooks don't try to modify return value.
11591 				 */
11592 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11593 				return -EINVAL;
11594 			}
11595 		}
11596 		break;
11597 	case BPF_FUNC_dynptr_data:
11598 	{
11599 		struct bpf_reg_state *reg;
11600 		int id, ref_obj_id;
11601 
11602 		reg = get_dynptr_arg_reg(env, fn, regs);
11603 		if (!reg)
11604 			return -EFAULT;
11605 
11606 
11607 		if (meta.dynptr_id) {
11608 			verifier_bug(env, "meta.dynptr_id already set");
11609 			return -EFAULT;
11610 		}
11611 		if (meta.ref_obj_id) {
11612 			verifier_bug(env, "meta.ref_obj_id already set");
11613 			return -EFAULT;
11614 		}
11615 
11616 		id = dynptr_id(env, reg);
11617 		if (id < 0) {
11618 			verifier_bug(env, "failed to obtain dynptr id");
11619 			return id;
11620 		}
11621 
11622 		ref_obj_id = dynptr_ref_obj_id(env, reg);
11623 		if (ref_obj_id < 0) {
11624 			verifier_bug(env, "failed to obtain dynptr ref_obj_id");
11625 			return ref_obj_id;
11626 		}
11627 
11628 		meta.dynptr_id = id;
11629 		meta.ref_obj_id = ref_obj_id;
11630 
11631 		break;
11632 	}
11633 	case BPF_FUNC_dynptr_write:
11634 	{
11635 		enum bpf_dynptr_type dynptr_type;
11636 		struct bpf_reg_state *reg;
11637 
11638 		reg = get_dynptr_arg_reg(env, fn, regs);
11639 		if (!reg)
11640 			return -EFAULT;
11641 
11642 		dynptr_type = dynptr_get_type(env, reg);
11643 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11644 			return -EFAULT;
11645 
11646 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
11647 		    dynptr_type == BPF_DYNPTR_TYPE_SKB_META)
11648 			/* this will trigger clear_all_pkt_pointers(), which will
11649 			 * invalidate all dynptr slices associated with the skb
11650 			 */
11651 			changes_data = true;
11652 
11653 		break;
11654 	}
11655 	case BPF_FUNC_per_cpu_ptr:
11656 	case BPF_FUNC_this_cpu_ptr:
11657 	{
11658 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
11659 		const struct btf_type *type;
11660 
11661 		if (reg->type & MEM_RCU) {
11662 			type = btf_type_by_id(reg->btf, reg->btf_id);
11663 			if (!type || !btf_type_is_struct(type)) {
11664 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
11665 				return -EFAULT;
11666 			}
11667 			returns_cpu_specific_alloc_ptr = true;
11668 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11669 		}
11670 		break;
11671 	}
11672 	case BPF_FUNC_user_ringbuf_drain:
11673 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11674 					 set_user_ringbuf_callback_state);
11675 		break;
11676 	}
11677 
11678 	if (err)
11679 		return err;
11680 
11681 	/* reset caller saved regs */
11682 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11683 		mark_reg_not_init(env, regs, caller_saved[i]);
11684 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11685 	}
11686 
11687 	/* helper call returns 64-bit value. */
11688 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
11689 
11690 	/* update return register (already marked as written above) */
11691 	ret_type = fn->ret_type;
11692 	ret_flag = type_flag(ret_type);
11693 
11694 	switch (base_type(ret_type)) {
11695 	case RET_INTEGER:
11696 		/* sets type to SCALAR_VALUE */
11697 		mark_reg_unknown(env, regs, BPF_REG_0);
11698 		break;
11699 	case RET_VOID:
11700 		regs[BPF_REG_0].type = NOT_INIT;
11701 		break;
11702 	case RET_PTR_TO_MAP_VALUE:
11703 		/* There is no offset yet applied, variable or fixed */
11704 		mark_reg_known_zero(env, regs, BPF_REG_0);
11705 		/* remember map_ptr, so that check_map_access()
11706 		 * can check 'value_size' boundary of memory access
11707 		 * to map element returned from bpf_map_lookup_elem()
11708 		 */
11709 		if (meta.map_ptr == NULL) {
11710 			verifier_bug(env, "unexpected null map_ptr");
11711 			return -EFAULT;
11712 		}
11713 
11714 		if (func_id == BPF_FUNC_map_lookup_elem &&
11715 		    can_elide_value_nullness(meta.map_ptr->map_type) &&
11716 		    meta.const_map_key >= 0 &&
11717 		    meta.const_map_key < meta.map_ptr->max_entries)
11718 			ret_flag &= ~PTR_MAYBE_NULL;
11719 
11720 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
11721 		regs[BPF_REG_0].map_uid = meta.map_uid;
11722 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11723 		if (!type_may_be_null(ret_flag) &&
11724 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
11725 			regs[BPF_REG_0].id = ++env->id_gen;
11726 		}
11727 		break;
11728 	case RET_PTR_TO_SOCKET:
11729 		mark_reg_known_zero(env, regs, BPF_REG_0);
11730 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11731 		break;
11732 	case RET_PTR_TO_SOCK_COMMON:
11733 		mark_reg_known_zero(env, regs, BPF_REG_0);
11734 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11735 		break;
11736 	case RET_PTR_TO_TCP_SOCK:
11737 		mark_reg_known_zero(env, regs, BPF_REG_0);
11738 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11739 		break;
11740 	case RET_PTR_TO_MEM:
11741 		mark_reg_known_zero(env, regs, BPF_REG_0);
11742 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11743 		regs[BPF_REG_0].mem_size = meta.mem_size;
11744 		break;
11745 	case RET_PTR_TO_MEM_OR_BTF_ID:
11746 	{
11747 		const struct btf_type *t;
11748 
11749 		mark_reg_known_zero(env, regs, BPF_REG_0);
11750 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11751 		if (!btf_type_is_struct(t)) {
11752 			u32 tsize;
11753 			const struct btf_type *ret;
11754 			const char *tname;
11755 
11756 			/* resolve the type size of ksym. */
11757 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11758 			if (IS_ERR(ret)) {
11759 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11760 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
11761 					tname, PTR_ERR(ret));
11762 				return -EINVAL;
11763 			}
11764 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11765 			regs[BPF_REG_0].mem_size = tsize;
11766 		} else {
11767 			if (returns_cpu_specific_alloc_ptr) {
11768 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11769 			} else {
11770 				/* MEM_RDONLY may be carried from ret_flag, but it
11771 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11772 				 * it will confuse the check of PTR_TO_BTF_ID in
11773 				 * check_mem_access().
11774 				 */
11775 				ret_flag &= ~MEM_RDONLY;
11776 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11777 			}
11778 
11779 			regs[BPF_REG_0].btf = meta.ret_btf;
11780 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11781 		}
11782 		break;
11783 	}
11784 	case RET_PTR_TO_BTF_ID:
11785 	{
11786 		struct btf *ret_btf;
11787 		int ret_btf_id;
11788 
11789 		mark_reg_known_zero(env, regs, BPF_REG_0);
11790 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11791 		if (func_id == BPF_FUNC_kptr_xchg) {
11792 			ret_btf = meta.kptr_field->kptr.btf;
11793 			ret_btf_id = meta.kptr_field->kptr.btf_id;
11794 			if (!btf_is_kernel(ret_btf)) {
11795 				regs[BPF_REG_0].type |= MEM_ALLOC;
11796 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11797 					regs[BPF_REG_0].type |= MEM_PERCPU;
11798 			}
11799 		} else {
11800 			if (fn->ret_btf_id == BPF_PTR_POISON) {
11801 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
11802 					     func_id_name(func_id));
11803 				return -EFAULT;
11804 			}
11805 			ret_btf = btf_vmlinux;
11806 			ret_btf_id = *fn->ret_btf_id;
11807 		}
11808 		if (ret_btf_id == 0) {
11809 			verbose(env, "invalid return type %u of func %s#%d\n",
11810 				base_type(ret_type), func_id_name(func_id),
11811 				func_id);
11812 			return -EINVAL;
11813 		}
11814 		regs[BPF_REG_0].btf = ret_btf;
11815 		regs[BPF_REG_0].btf_id = ret_btf_id;
11816 		break;
11817 	}
11818 	default:
11819 		verbose(env, "unknown return type %u of func %s#%d\n",
11820 			base_type(ret_type), func_id_name(func_id), func_id);
11821 		return -EINVAL;
11822 	}
11823 
11824 	if (type_may_be_null(regs[BPF_REG_0].type))
11825 		regs[BPF_REG_0].id = ++env->id_gen;
11826 
11827 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
11828 		verifier_bug(env, "func %s#%d sets ref_obj_id more than once",
11829 			     func_id_name(func_id), func_id);
11830 		return -EFAULT;
11831 	}
11832 
11833 	if (is_dynptr_ref_function(func_id))
11834 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
11835 
11836 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
11837 		/* For release_reference() */
11838 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11839 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
11840 		int id = acquire_reference(env, insn_idx);
11841 
11842 		if (id < 0)
11843 			return id;
11844 		/* For mark_ptr_or_null_reg() */
11845 		regs[BPF_REG_0].id = id;
11846 		/* For release_reference() */
11847 		regs[BPF_REG_0].ref_obj_id = id;
11848 	}
11849 
11850 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
11851 	if (err)
11852 		return err;
11853 
11854 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
11855 	if (err)
11856 		return err;
11857 
11858 	if ((func_id == BPF_FUNC_get_stack ||
11859 	     func_id == BPF_FUNC_get_task_stack) &&
11860 	    !env->prog->has_callchain_buf) {
11861 		const char *err_str;
11862 
11863 #ifdef CONFIG_PERF_EVENTS
11864 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
11865 		err_str = "cannot get callchain buffer for func %s#%d\n";
11866 #else
11867 		err = -ENOTSUPP;
11868 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
11869 #endif
11870 		if (err) {
11871 			verbose(env, err_str, func_id_name(func_id), func_id);
11872 			return err;
11873 		}
11874 
11875 		env->prog->has_callchain_buf = true;
11876 	}
11877 
11878 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
11879 		env->prog->call_get_stack = true;
11880 
11881 	if (func_id == BPF_FUNC_get_func_ip) {
11882 		if (check_get_func_ip(env))
11883 			return -ENOTSUPP;
11884 		env->prog->call_get_func_ip = true;
11885 	}
11886 
11887 	if (changes_data)
11888 		clear_all_pkt_pointers(env);
11889 	return 0;
11890 }
11891 
11892 /* mark_btf_func_reg_size() is used when the reg size is determined by
11893  * the BTF func_proto's return value size and argument.
11894  */
11895 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
11896 				     u32 regno, size_t reg_size)
11897 {
11898 	struct bpf_reg_state *reg = &regs[regno];
11899 
11900 	if (regno == BPF_REG_0) {
11901 		/* Function return value */
11902 		reg->subreg_def = reg_size == sizeof(u64) ?
11903 			DEF_NOT_SUBREG : env->insn_idx + 1;
11904 	} else if (reg_size == sizeof(u64)) {
11905 		/* Function argument */
11906 		mark_insn_zext(env, reg);
11907 	}
11908 }
11909 
11910 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
11911 				   size_t reg_size)
11912 {
11913 	return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size);
11914 }
11915 
11916 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
11917 {
11918 	return meta->kfunc_flags & KF_ACQUIRE;
11919 }
11920 
11921 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
11922 {
11923 	return meta->kfunc_flags & KF_RELEASE;
11924 }
11925 
11926 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
11927 {
11928 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
11929 }
11930 
11931 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
11932 {
11933 	return meta->kfunc_flags & KF_SLEEPABLE;
11934 }
11935 
11936 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
11937 {
11938 	return meta->kfunc_flags & KF_DESTRUCTIVE;
11939 }
11940 
11941 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
11942 {
11943 	return meta->kfunc_flags & KF_RCU;
11944 }
11945 
11946 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
11947 {
11948 	return meta->kfunc_flags & KF_RCU_PROTECTED;
11949 }
11950 
11951 static bool is_kfunc_arg_mem_size(const struct btf *btf,
11952 				  const struct btf_param *arg,
11953 				  const struct bpf_reg_state *reg)
11954 {
11955 	const struct btf_type *t;
11956 
11957 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11958 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11959 		return false;
11960 
11961 	return btf_param_match_suffix(btf, arg, "__sz");
11962 }
11963 
11964 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
11965 					const struct btf_param *arg,
11966 					const struct bpf_reg_state *reg)
11967 {
11968 	const struct btf_type *t;
11969 
11970 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11971 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11972 		return false;
11973 
11974 	return btf_param_match_suffix(btf, arg, "__szk");
11975 }
11976 
11977 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
11978 {
11979 	return btf_param_match_suffix(btf, arg, "__opt");
11980 }
11981 
11982 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
11983 {
11984 	return btf_param_match_suffix(btf, arg, "__k");
11985 }
11986 
11987 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
11988 {
11989 	return btf_param_match_suffix(btf, arg, "__ign");
11990 }
11991 
11992 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
11993 {
11994 	return btf_param_match_suffix(btf, arg, "__map");
11995 }
11996 
11997 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
11998 {
11999 	return btf_param_match_suffix(btf, arg, "__alloc");
12000 }
12001 
12002 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
12003 {
12004 	return btf_param_match_suffix(btf, arg, "__uninit");
12005 }
12006 
12007 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
12008 {
12009 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
12010 }
12011 
12012 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
12013 {
12014 	return btf_param_match_suffix(btf, arg, "__nullable");
12015 }
12016 
12017 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
12018 {
12019 	return btf_param_match_suffix(btf, arg, "__str");
12020 }
12021 
12022 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
12023 {
12024 	return btf_param_match_suffix(btf, arg, "__irq_flag");
12025 }
12026 
12027 static bool is_kfunc_arg_prog(const struct btf *btf, const struct btf_param *arg)
12028 {
12029 	return btf_param_match_suffix(btf, arg, "__prog");
12030 }
12031 
12032 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
12033 					  const struct btf_param *arg,
12034 					  const char *name)
12035 {
12036 	int len, target_len = strlen(name);
12037 	const char *param_name;
12038 
12039 	param_name = btf_name_by_offset(btf, arg->name_off);
12040 	if (str_is_empty(param_name))
12041 		return false;
12042 	len = strlen(param_name);
12043 	if (len != target_len)
12044 		return false;
12045 	if (strcmp(param_name, name))
12046 		return false;
12047 
12048 	return true;
12049 }
12050 
12051 enum {
12052 	KF_ARG_DYNPTR_ID,
12053 	KF_ARG_LIST_HEAD_ID,
12054 	KF_ARG_LIST_NODE_ID,
12055 	KF_ARG_RB_ROOT_ID,
12056 	KF_ARG_RB_NODE_ID,
12057 	KF_ARG_WORKQUEUE_ID,
12058 	KF_ARG_RES_SPIN_LOCK_ID,
12059 	KF_ARG_TASK_WORK_ID,
12060 };
12061 
12062 BTF_ID_LIST(kf_arg_btf_ids)
12063 BTF_ID(struct, bpf_dynptr)
12064 BTF_ID(struct, bpf_list_head)
12065 BTF_ID(struct, bpf_list_node)
12066 BTF_ID(struct, bpf_rb_root)
12067 BTF_ID(struct, bpf_rb_node)
12068 BTF_ID(struct, bpf_wq)
12069 BTF_ID(struct, bpf_res_spin_lock)
12070 BTF_ID(struct, bpf_task_work)
12071 
12072 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
12073 				    const struct btf_param *arg, int type)
12074 {
12075 	const struct btf_type *t;
12076 	u32 res_id;
12077 
12078 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12079 	if (!t)
12080 		return false;
12081 	if (!btf_type_is_ptr(t))
12082 		return false;
12083 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
12084 	if (!t)
12085 		return false;
12086 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
12087 }
12088 
12089 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
12090 {
12091 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
12092 }
12093 
12094 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
12095 {
12096 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
12097 }
12098 
12099 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
12100 {
12101 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
12102 }
12103 
12104 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
12105 {
12106 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
12107 }
12108 
12109 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
12110 {
12111 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
12112 }
12113 
12114 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
12115 {
12116 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
12117 }
12118 
12119 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
12120 {
12121 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
12122 }
12123 
12124 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
12125 {
12126 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
12127 }
12128 
12129 static bool is_rbtree_node_type(const struct btf_type *t)
12130 {
12131 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
12132 }
12133 
12134 static bool is_list_node_type(const struct btf_type *t)
12135 {
12136 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
12137 }
12138 
12139 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
12140 				  const struct btf_param *arg)
12141 {
12142 	const struct btf_type *t;
12143 
12144 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
12145 	if (!t)
12146 		return false;
12147 
12148 	return true;
12149 }
12150 
12151 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
12152 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
12153 					const struct btf *btf,
12154 					const struct btf_type *t, int rec)
12155 {
12156 	const struct btf_type *member_type;
12157 	const struct btf_member *member;
12158 	u32 i;
12159 
12160 	if (!btf_type_is_struct(t))
12161 		return false;
12162 
12163 	for_each_member(i, t, member) {
12164 		const struct btf_array *array;
12165 
12166 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
12167 		if (btf_type_is_struct(member_type)) {
12168 			if (rec >= 3) {
12169 				verbose(env, "max struct nesting depth exceeded\n");
12170 				return false;
12171 			}
12172 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
12173 				return false;
12174 			continue;
12175 		}
12176 		if (btf_type_is_array(member_type)) {
12177 			array = btf_array(member_type);
12178 			if (!array->nelems)
12179 				return false;
12180 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
12181 			if (!btf_type_is_scalar(member_type))
12182 				return false;
12183 			continue;
12184 		}
12185 		if (!btf_type_is_scalar(member_type))
12186 			return false;
12187 	}
12188 	return true;
12189 }
12190 
12191 enum kfunc_ptr_arg_type {
12192 	KF_ARG_PTR_TO_CTX,
12193 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
12194 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
12195 	KF_ARG_PTR_TO_DYNPTR,
12196 	KF_ARG_PTR_TO_ITER,
12197 	KF_ARG_PTR_TO_LIST_HEAD,
12198 	KF_ARG_PTR_TO_LIST_NODE,
12199 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
12200 	KF_ARG_PTR_TO_MEM,
12201 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
12202 	KF_ARG_PTR_TO_CALLBACK,
12203 	KF_ARG_PTR_TO_RB_ROOT,
12204 	KF_ARG_PTR_TO_RB_NODE,
12205 	KF_ARG_PTR_TO_NULL,
12206 	KF_ARG_PTR_TO_CONST_STR,
12207 	KF_ARG_PTR_TO_MAP,
12208 	KF_ARG_PTR_TO_WORKQUEUE,
12209 	KF_ARG_PTR_TO_IRQ_FLAG,
12210 	KF_ARG_PTR_TO_RES_SPIN_LOCK,
12211 	KF_ARG_PTR_TO_TASK_WORK,
12212 };
12213 
12214 enum special_kfunc_type {
12215 	KF_bpf_obj_new_impl,
12216 	KF_bpf_obj_drop_impl,
12217 	KF_bpf_refcount_acquire_impl,
12218 	KF_bpf_list_push_front_impl,
12219 	KF_bpf_list_push_back_impl,
12220 	KF_bpf_list_pop_front,
12221 	KF_bpf_list_pop_back,
12222 	KF_bpf_list_front,
12223 	KF_bpf_list_back,
12224 	KF_bpf_cast_to_kern_ctx,
12225 	KF_bpf_rdonly_cast,
12226 	KF_bpf_rcu_read_lock,
12227 	KF_bpf_rcu_read_unlock,
12228 	KF_bpf_rbtree_remove,
12229 	KF_bpf_rbtree_add_impl,
12230 	KF_bpf_rbtree_first,
12231 	KF_bpf_rbtree_root,
12232 	KF_bpf_rbtree_left,
12233 	KF_bpf_rbtree_right,
12234 	KF_bpf_dynptr_from_skb,
12235 	KF_bpf_dynptr_from_xdp,
12236 	KF_bpf_dynptr_from_skb_meta,
12237 	KF_bpf_xdp_pull_data,
12238 	KF_bpf_dynptr_slice,
12239 	KF_bpf_dynptr_slice_rdwr,
12240 	KF_bpf_dynptr_clone,
12241 	KF_bpf_percpu_obj_new_impl,
12242 	KF_bpf_percpu_obj_drop_impl,
12243 	KF_bpf_throw,
12244 	KF_bpf_wq_set_callback_impl,
12245 	KF_bpf_preempt_disable,
12246 	KF_bpf_preempt_enable,
12247 	KF_bpf_iter_css_task_new,
12248 	KF_bpf_session_cookie,
12249 	KF_bpf_get_kmem_cache,
12250 	KF_bpf_local_irq_save,
12251 	KF_bpf_local_irq_restore,
12252 	KF_bpf_iter_num_new,
12253 	KF_bpf_iter_num_next,
12254 	KF_bpf_iter_num_destroy,
12255 	KF_bpf_set_dentry_xattr,
12256 	KF_bpf_remove_dentry_xattr,
12257 	KF_bpf_res_spin_lock,
12258 	KF_bpf_res_spin_unlock,
12259 	KF_bpf_res_spin_lock_irqsave,
12260 	KF_bpf_res_spin_unlock_irqrestore,
12261 	KF___bpf_trap,
12262 	KF_bpf_task_work_schedule_signal,
12263 	KF_bpf_task_work_schedule_resume,
12264 };
12265 
12266 BTF_ID_LIST(special_kfunc_list)
12267 BTF_ID(func, bpf_obj_new_impl)
12268 BTF_ID(func, bpf_obj_drop_impl)
12269 BTF_ID(func, bpf_refcount_acquire_impl)
12270 BTF_ID(func, bpf_list_push_front_impl)
12271 BTF_ID(func, bpf_list_push_back_impl)
12272 BTF_ID(func, bpf_list_pop_front)
12273 BTF_ID(func, bpf_list_pop_back)
12274 BTF_ID(func, bpf_list_front)
12275 BTF_ID(func, bpf_list_back)
12276 BTF_ID(func, bpf_cast_to_kern_ctx)
12277 BTF_ID(func, bpf_rdonly_cast)
12278 BTF_ID(func, bpf_rcu_read_lock)
12279 BTF_ID(func, bpf_rcu_read_unlock)
12280 BTF_ID(func, bpf_rbtree_remove)
12281 BTF_ID(func, bpf_rbtree_add_impl)
12282 BTF_ID(func, bpf_rbtree_first)
12283 BTF_ID(func, bpf_rbtree_root)
12284 BTF_ID(func, bpf_rbtree_left)
12285 BTF_ID(func, bpf_rbtree_right)
12286 #ifdef CONFIG_NET
12287 BTF_ID(func, bpf_dynptr_from_skb)
12288 BTF_ID(func, bpf_dynptr_from_xdp)
12289 BTF_ID(func, bpf_dynptr_from_skb_meta)
12290 BTF_ID(func, bpf_xdp_pull_data)
12291 #else
12292 BTF_ID_UNUSED
12293 BTF_ID_UNUSED
12294 BTF_ID_UNUSED
12295 BTF_ID_UNUSED
12296 #endif
12297 BTF_ID(func, bpf_dynptr_slice)
12298 BTF_ID(func, bpf_dynptr_slice_rdwr)
12299 BTF_ID(func, bpf_dynptr_clone)
12300 BTF_ID(func, bpf_percpu_obj_new_impl)
12301 BTF_ID(func, bpf_percpu_obj_drop_impl)
12302 BTF_ID(func, bpf_throw)
12303 BTF_ID(func, bpf_wq_set_callback_impl)
12304 BTF_ID(func, bpf_preempt_disable)
12305 BTF_ID(func, bpf_preempt_enable)
12306 #ifdef CONFIG_CGROUPS
12307 BTF_ID(func, bpf_iter_css_task_new)
12308 #else
12309 BTF_ID_UNUSED
12310 #endif
12311 #ifdef CONFIG_BPF_EVENTS
12312 BTF_ID(func, bpf_session_cookie)
12313 #else
12314 BTF_ID_UNUSED
12315 #endif
12316 BTF_ID(func, bpf_get_kmem_cache)
12317 BTF_ID(func, bpf_local_irq_save)
12318 BTF_ID(func, bpf_local_irq_restore)
12319 BTF_ID(func, bpf_iter_num_new)
12320 BTF_ID(func, bpf_iter_num_next)
12321 BTF_ID(func, bpf_iter_num_destroy)
12322 #ifdef CONFIG_BPF_LSM
12323 BTF_ID(func, bpf_set_dentry_xattr)
12324 BTF_ID(func, bpf_remove_dentry_xattr)
12325 #else
12326 BTF_ID_UNUSED
12327 BTF_ID_UNUSED
12328 #endif
12329 BTF_ID(func, bpf_res_spin_lock)
12330 BTF_ID(func, bpf_res_spin_unlock)
12331 BTF_ID(func, bpf_res_spin_lock_irqsave)
12332 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
12333 BTF_ID(func, __bpf_trap)
12334 BTF_ID(func, bpf_task_work_schedule_signal)
12335 BTF_ID(func, bpf_task_work_schedule_resume)
12336 
12337 static bool is_task_work_add_kfunc(u32 func_id)
12338 {
12339 	return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] ||
12340 	       func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume];
12341 }
12342 
12343 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
12344 {
12345 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
12346 	    meta->arg_owning_ref) {
12347 		return false;
12348 	}
12349 
12350 	return meta->kfunc_flags & KF_RET_NULL;
12351 }
12352 
12353 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
12354 {
12355 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
12356 }
12357 
12358 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
12359 {
12360 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
12361 }
12362 
12363 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
12364 {
12365 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
12366 }
12367 
12368 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
12369 {
12370 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
12371 }
12372 
12373 static bool is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta)
12374 {
12375 	return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data];
12376 }
12377 
12378 static enum kfunc_ptr_arg_type
12379 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
12380 		       struct bpf_kfunc_call_arg_meta *meta,
12381 		       const struct btf_type *t, const struct btf_type *ref_t,
12382 		       const char *ref_tname, const struct btf_param *args,
12383 		       int argno, int nargs)
12384 {
12385 	u32 regno = argno + 1;
12386 	struct bpf_reg_state *regs = cur_regs(env);
12387 	struct bpf_reg_state *reg = &regs[regno];
12388 	bool arg_mem_size = false;
12389 
12390 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
12391 		return KF_ARG_PTR_TO_CTX;
12392 
12393 	/* In this function, we verify the kfunc's BTF as per the argument type,
12394 	 * leaving the rest of the verification with respect to the register
12395 	 * type to our caller. When a set of conditions hold in the BTF type of
12396 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
12397 	 */
12398 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
12399 		return KF_ARG_PTR_TO_CTX;
12400 
12401 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
12402 		return KF_ARG_PTR_TO_NULL;
12403 
12404 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
12405 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
12406 
12407 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
12408 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
12409 
12410 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
12411 		return KF_ARG_PTR_TO_DYNPTR;
12412 
12413 	if (is_kfunc_arg_iter(meta, argno, &args[argno]))
12414 		return KF_ARG_PTR_TO_ITER;
12415 
12416 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
12417 		return KF_ARG_PTR_TO_LIST_HEAD;
12418 
12419 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
12420 		return KF_ARG_PTR_TO_LIST_NODE;
12421 
12422 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
12423 		return KF_ARG_PTR_TO_RB_ROOT;
12424 
12425 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
12426 		return KF_ARG_PTR_TO_RB_NODE;
12427 
12428 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
12429 		return KF_ARG_PTR_TO_CONST_STR;
12430 
12431 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
12432 		return KF_ARG_PTR_TO_MAP;
12433 
12434 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
12435 		return KF_ARG_PTR_TO_WORKQUEUE;
12436 
12437 	if (is_kfunc_arg_task_work(meta->btf, &args[argno]))
12438 		return KF_ARG_PTR_TO_TASK_WORK;
12439 
12440 	if (is_kfunc_arg_irq_flag(meta->btf, &args[argno]))
12441 		return KF_ARG_PTR_TO_IRQ_FLAG;
12442 
12443 	if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno]))
12444 		return KF_ARG_PTR_TO_RES_SPIN_LOCK;
12445 
12446 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
12447 		if (!btf_type_is_struct(ref_t)) {
12448 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
12449 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
12450 			return -EINVAL;
12451 		}
12452 		return KF_ARG_PTR_TO_BTF_ID;
12453 	}
12454 
12455 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
12456 		return KF_ARG_PTR_TO_CALLBACK;
12457 
12458 	if (argno + 1 < nargs &&
12459 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
12460 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
12461 		arg_mem_size = true;
12462 
12463 	/* This is the catch all argument type of register types supported by
12464 	 * check_helper_mem_access. However, we only allow when argument type is
12465 	 * pointer to scalar, or struct composed (recursively) of scalars. When
12466 	 * arg_mem_size is true, the pointer can be void *.
12467 	 */
12468 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
12469 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
12470 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
12471 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
12472 		return -EINVAL;
12473 	}
12474 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
12475 }
12476 
12477 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
12478 					struct bpf_reg_state *reg,
12479 					const struct btf_type *ref_t,
12480 					const char *ref_tname, u32 ref_id,
12481 					struct bpf_kfunc_call_arg_meta *meta,
12482 					int argno)
12483 {
12484 	const struct btf_type *reg_ref_t;
12485 	bool strict_type_match = false;
12486 	const struct btf *reg_btf;
12487 	const char *reg_ref_tname;
12488 	bool taking_projection;
12489 	bool struct_same;
12490 	u32 reg_ref_id;
12491 
12492 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
12493 		reg_btf = reg->btf;
12494 		reg_ref_id = reg->btf_id;
12495 	} else {
12496 		reg_btf = btf_vmlinux;
12497 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
12498 	}
12499 
12500 	/* Enforce strict type matching for calls to kfuncs that are acquiring
12501 	 * or releasing a reference, or are no-cast aliases. We do _not_
12502 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
12503 	 * as we want to enable BPF programs to pass types that are bitwise
12504 	 * equivalent without forcing them to explicitly cast with something
12505 	 * like bpf_cast_to_kern_ctx().
12506 	 *
12507 	 * For example, say we had a type like the following:
12508 	 *
12509 	 * struct bpf_cpumask {
12510 	 *	cpumask_t cpumask;
12511 	 *	refcount_t usage;
12512 	 * };
12513 	 *
12514 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
12515 	 * to a struct cpumask, so it would be safe to pass a struct
12516 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
12517 	 *
12518 	 * The philosophy here is similar to how we allow scalars of different
12519 	 * types to be passed to kfuncs as long as the size is the same. The
12520 	 * only difference here is that we're simply allowing
12521 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
12522 	 * resolve types.
12523 	 */
12524 	if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
12525 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
12526 		strict_type_match = true;
12527 
12528 	WARN_ON_ONCE(is_kfunc_release(meta) &&
12529 		     (reg->off || !tnum_is_const(reg->var_off) ||
12530 		      reg->var_off.value));
12531 
12532 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
12533 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
12534 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
12535 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
12536 	 * actually use it -- it must cast to the underlying type. So we allow
12537 	 * caller to pass in the underlying type.
12538 	 */
12539 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
12540 	if (!taking_projection && !struct_same) {
12541 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
12542 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
12543 			btf_type_str(reg_ref_t), reg_ref_tname);
12544 		return -EINVAL;
12545 	}
12546 	return 0;
12547 }
12548 
12549 static int process_irq_flag(struct bpf_verifier_env *env, int regno,
12550 			     struct bpf_kfunc_call_arg_meta *meta)
12551 {
12552 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
12553 	int err, kfunc_class = IRQ_NATIVE_KFUNC;
12554 	bool irq_save;
12555 
12556 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
12557 	    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
12558 		irq_save = true;
12559 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12560 			kfunc_class = IRQ_LOCK_KFUNC;
12561 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
12562 		   meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
12563 		irq_save = false;
12564 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12565 			kfunc_class = IRQ_LOCK_KFUNC;
12566 	} else {
12567 		verifier_bug(env, "unknown irq flags kfunc");
12568 		return -EFAULT;
12569 	}
12570 
12571 	if (irq_save) {
12572 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
12573 			verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1);
12574 			return -EINVAL;
12575 		}
12576 
12577 		err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false);
12578 		if (err)
12579 			return err;
12580 
12581 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
12582 		if (err)
12583 			return err;
12584 	} else {
12585 		err = is_irq_flag_reg_valid_init(env, reg);
12586 		if (err) {
12587 			verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1);
12588 			return err;
12589 		}
12590 
12591 		err = mark_irq_flag_read(env, reg);
12592 		if (err)
12593 			return err;
12594 
12595 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
12596 		if (err)
12597 			return err;
12598 	}
12599 	return 0;
12600 }
12601 
12602 
12603 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12604 {
12605 	struct btf_record *rec = reg_btf_record(reg);
12606 
12607 	if (!env->cur_state->active_locks) {
12608 		verifier_bug(env, "%s w/o active lock", __func__);
12609 		return -EFAULT;
12610 	}
12611 
12612 	if (type_flag(reg->type) & NON_OWN_REF) {
12613 		verifier_bug(env, "NON_OWN_REF already set");
12614 		return -EFAULT;
12615 	}
12616 
12617 	reg->type |= NON_OWN_REF;
12618 	if (rec->refcount_off >= 0)
12619 		reg->type |= MEM_RCU;
12620 
12621 	return 0;
12622 }
12623 
12624 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
12625 {
12626 	struct bpf_verifier_state *state = env->cur_state;
12627 	struct bpf_func_state *unused;
12628 	struct bpf_reg_state *reg;
12629 	int i;
12630 
12631 	if (!ref_obj_id) {
12632 		verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion");
12633 		return -EFAULT;
12634 	}
12635 
12636 	for (i = 0; i < state->acquired_refs; i++) {
12637 		if (state->refs[i].id != ref_obj_id)
12638 			continue;
12639 
12640 		/* Clear ref_obj_id here so release_reference doesn't clobber
12641 		 * the whole reg
12642 		 */
12643 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12644 			if (reg->ref_obj_id == ref_obj_id) {
12645 				reg->ref_obj_id = 0;
12646 				ref_set_non_owning(env, reg);
12647 			}
12648 		}));
12649 		return 0;
12650 	}
12651 
12652 	verifier_bug(env, "ref state missing for ref_obj_id");
12653 	return -EFAULT;
12654 }
12655 
12656 /* Implementation details:
12657  *
12658  * Each register points to some region of memory, which we define as an
12659  * allocation. Each allocation may embed a bpf_spin_lock which protects any
12660  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12661  * allocation. The lock and the data it protects are colocated in the same
12662  * memory region.
12663  *
12664  * Hence, everytime a register holds a pointer value pointing to such
12665  * allocation, the verifier preserves a unique reg->id for it.
12666  *
12667  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12668  * bpf_spin_lock is called.
12669  *
12670  * To enable this, lock state in the verifier captures two values:
12671  *	active_lock.ptr = Register's type specific pointer
12672  *	active_lock.id  = A unique ID for each register pointer value
12673  *
12674  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12675  * supported register types.
12676  *
12677  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12678  * allocated objects is the reg->btf pointer.
12679  *
12680  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12681  * can establish the provenance of the map value statically for each distinct
12682  * lookup into such maps. They always contain a single map value hence unique
12683  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12684  *
12685  * So, in case of global variables, they use array maps with max_entries = 1,
12686  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12687  * into the same map value as max_entries is 1, as described above).
12688  *
12689  * In case of inner map lookups, the inner map pointer has same map_ptr as the
12690  * outer map pointer (in verifier context), but each lookup into an inner map
12691  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12692  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12693  * will get different reg->id assigned to each lookup, hence different
12694  * active_lock.id.
12695  *
12696  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12697  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12698  * returned from bpf_obj_new. Each allocation receives a new reg->id.
12699  */
12700 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12701 {
12702 	struct bpf_reference_state *s;
12703 	void *ptr;
12704 	u32 id;
12705 
12706 	switch ((int)reg->type) {
12707 	case PTR_TO_MAP_VALUE:
12708 		ptr = reg->map_ptr;
12709 		break;
12710 	case PTR_TO_BTF_ID | MEM_ALLOC:
12711 		ptr = reg->btf;
12712 		break;
12713 	default:
12714 		verifier_bug(env, "unknown reg type for lock check");
12715 		return -EFAULT;
12716 	}
12717 	id = reg->id;
12718 
12719 	if (!env->cur_state->active_locks)
12720 		return -EINVAL;
12721 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
12722 	if (!s) {
12723 		verbose(env, "held lock and object are not in the same allocation\n");
12724 		return -EINVAL;
12725 	}
12726 	return 0;
12727 }
12728 
12729 static bool is_bpf_list_api_kfunc(u32 btf_id)
12730 {
12731 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12732 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12733 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12734 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
12735 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
12736 	       btf_id == special_kfunc_list[KF_bpf_list_back];
12737 }
12738 
12739 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
12740 {
12741 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12742 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12743 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
12744 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
12745 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12746 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
12747 }
12748 
12749 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
12750 {
12751 	return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
12752 	       btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
12753 	       btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
12754 }
12755 
12756 static bool is_bpf_graph_api_kfunc(u32 btf_id)
12757 {
12758 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
12759 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
12760 }
12761 
12762 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
12763 {
12764 	return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
12765 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
12766 	       btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
12767 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
12768 }
12769 
12770 static bool kfunc_spin_allowed(u32 btf_id)
12771 {
12772 	return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) ||
12773 	       is_bpf_res_spin_lock_kfunc(btf_id);
12774 }
12775 
12776 static bool is_sync_callback_calling_kfunc(u32 btf_id)
12777 {
12778 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
12779 }
12780 
12781 static bool is_async_callback_calling_kfunc(u32 btf_id)
12782 {
12783 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl] ||
12784 	       is_task_work_add_kfunc(btf_id);
12785 }
12786 
12787 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
12788 {
12789 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
12790 	       insn->imm == special_kfunc_list[KF_bpf_throw];
12791 }
12792 
12793 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
12794 {
12795 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12796 }
12797 
12798 static bool is_callback_calling_kfunc(u32 btf_id)
12799 {
12800 	return is_sync_callback_calling_kfunc(btf_id) ||
12801 	       is_async_callback_calling_kfunc(btf_id);
12802 }
12803 
12804 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
12805 {
12806 	return is_bpf_rbtree_api_kfunc(btf_id);
12807 }
12808 
12809 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
12810 					  enum btf_field_type head_field_type,
12811 					  u32 kfunc_btf_id)
12812 {
12813 	bool ret;
12814 
12815 	switch (head_field_type) {
12816 	case BPF_LIST_HEAD:
12817 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
12818 		break;
12819 	case BPF_RB_ROOT:
12820 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
12821 		break;
12822 	default:
12823 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
12824 			btf_field_type_name(head_field_type));
12825 		return false;
12826 	}
12827 
12828 	if (!ret)
12829 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
12830 			btf_field_type_name(head_field_type));
12831 	return ret;
12832 }
12833 
12834 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
12835 					  enum btf_field_type node_field_type,
12836 					  u32 kfunc_btf_id)
12837 {
12838 	bool ret;
12839 
12840 	switch (node_field_type) {
12841 	case BPF_LIST_NODE:
12842 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12843 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
12844 		break;
12845 	case BPF_RB_NODE:
12846 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12847 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12848 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12849 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
12850 		break;
12851 	default:
12852 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
12853 			btf_field_type_name(node_field_type));
12854 		return false;
12855 	}
12856 
12857 	if (!ret)
12858 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
12859 			btf_field_type_name(node_field_type));
12860 	return ret;
12861 }
12862 
12863 static int
12864 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
12865 				   struct bpf_reg_state *reg, u32 regno,
12866 				   struct bpf_kfunc_call_arg_meta *meta,
12867 				   enum btf_field_type head_field_type,
12868 				   struct btf_field **head_field)
12869 {
12870 	const char *head_type_name;
12871 	struct btf_field *field;
12872 	struct btf_record *rec;
12873 	u32 head_off;
12874 
12875 	if (meta->btf != btf_vmlinux) {
12876 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
12877 		return -EFAULT;
12878 	}
12879 
12880 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
12881 		return -EFAULT;
12882 
12883 	head_type_name = btf_field_type_name(head_field_type);
12884 	if (!tnum_is_const(reg->var_off)) {
12885 		verbose(env,
12886 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12887 			regno, head_type_name);
12888 		return -EINVAL;
12889 	}
12890 
12891 	rec = reg_btf_record(reg);
12892 	head_off = reg->off + reg->var_off.value;
12893 	field = btf_record_find(rec, head_off, head_field_type);
12894 	if (!field) {
12895 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
12896 		return -EINVAL;
12897 	}
12898 
12899 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
12900 	if (check_reg_allocation_locked(env, reg)) {
12901 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
12902 			rec->spin_lock_off, head_type_name);
12903 		return -EINVAL;
12904 	}
12905 
12906 	if (*head_field) {
12907 		verifier_bug(env, "repeating %s arg", head_type_name);
12908 		return -EFAULT;
12909 	}
12910 	*head_field = field;
12911 	return 0;
12912 }
12913 
12914 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
12915 					   struct bpf_reg_state *reg, u32 regno,
12916 					   struct bpf_kfunc_call_arg_meta *meta)
12917 {
12918 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
12919 							  &meta->arg_list_head.field);
12920 }
12921 
12922 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
12923 					     struct bpf_reg_state *reg, u32 regno,
12924 					     struct bpf_kfunc_call_arg_meta *meta)
12925 {
12926 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
12927 							  &meta->arg_rbtree_root.field);
12928 }
12929 
12930 static int
12931 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
12932 				   struct bpf_reg_state *reg, u32 regno,
12933 				   struct bpf_kfunc_call_arg_meta *meta,
12934 				   enum btf_field_type head_field_type,
12935 				   enum btf_field_type node_field_type,
12936 				   struct btf_field **node_field)
12937 {
12938 	const char *node_type_name;
12939 	const struct btf_type *et, *t;
12940 	struct btf_field *field;
12941 	u32 node_off;
12942 
12943 	if (meta->btf != btf_vmlinux) {
12944 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
12945 		return -EFAULT;
12946 	}
12947 
12948 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
12949 		return -EFAULT;
12950 
12951 	node_type_name = btf_field_type_name(node_field_type);
12952 	if (!tnum_is_const(reg->var_off)) {
12953 		verbose(env,
12954 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12955 			regno, node_type_name);
12956 		return -EINVAL;
12957 	}
12958 
12959 	node_off = reg->off + reg->var_off.value;
12960 	field = reg_find_field_offset(reg, node_off, node_field_type);
12961 	if (!field) {
12962 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
12963 		return -EINVAL;
12964 	}
12965 
12966 	field = *node_field;
12967 
12968 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
12969 	t = btf_type_by_id(reg->btf, reg->btf_id);
12970 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
12971 				  field->graph_root.value_btf_id, true)) {
12972 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
12973 			"in struct %s, but arg is at offset=%d in struct %s\n",
12974 			btf_field_type_name(head_field_type),
12975 			btf_field_type_name(node_field_type),
12976 			field->graph_root.node_offset,
12977 			btf_name_by_offset(field->graph_root.btf, et->name_off),
12978 			node_off, btf_name_by_offset(reg->btf, t->name_off));
12979 		return -EINVAL;
12980 	}
12981 	meta->arg_btf = reg->btf;
12982 	meta->arg_btf_id = reg->btf_id;
12983 
12984 	if (node_off != field->graph_root.node_offset) {
12985 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
12986 			node_off, btf_field_type_name(node_field_type),
12987 			field->graph_root.node_offset,
12988 			btf_name_by_offset(field->graph_root.btf, et->name_off));
12989 		return -EINVAL;
12990 	}
12991 
12992 	return 0;
12993 }
12994 
12995 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
12996 					   struct bpf_reg_state *reg, u32 regno,
12997 					   struct bpf_kfunc_call_arg_meta *meta)
12998 {
12999 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13000 						  BPF_LIST_HEAD, BPF_LIST_NODE,
13001 						  &meta->arg_list_head.field);
13002 }
13003 
13004 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
13005 					     struct bpf_reg_state *reg, u32 regno,
13006 					     struct bpf_kfunc_call_arg_meta *meta)
13007 {
13008 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13009 						  BPF_RB_ROOT, BPF_RB_NODE,
13010 						  &meta->arg_rbtree_root.field);
13011 }
13012 
13013 /*
13014  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
13015  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
13016  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
13017  * them can only be attached to some specific hook points.
13018  */
13019 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
13020 {
13021 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13022 
13023 	switch (prog_type) {
13024 	case BPF_PROG_TYPE_LSM:
13025 		return true;
13026 	case BPF_PROG_TYPE_TRACING:
13027 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
13028 			return true;
13029 		fallthrough;
13030 	default:
13031 		return in_sleepable(env);
13032 	}
13033 }
13034 
13035 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13036 			    int insn_idx)
13037 {
13038 	const char *func_name = meta->func_name, *ref_tname;
13039 	const struct btf *btf = meta->btf;
13040 	const struct btf_param *args;
13041 	struct btf_record *rec;
13042 	u32 i, nargs;
13043 	int ret;
13044 
13045 	args = (const struct btf_param *)(meta->func_proto + 1);
13046 	nargs = btf_type_vlen(meta->func_proto);
13047 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
13048 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
13049 			MAX_BPF_FUNC_REG_ARGS);
13050 		return -EINVAL;
13051 	}
13052 
13053 	/* Check that BTF function arguments match actual types that the
13054 	 * verifier sees.
13055 	 */
13056 	for (i = 0; i < nargs; i++) {
13057 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
13058 		const struct btf_type *t, *ref_t, *resolve_ret;
13059 		enum bpf_arg_type arg_type = ARG_DONTCARE;
13060 		u32 regno = i + 1, ref_id, type_size;
13061 		bool is_ret_buf_sz = false;
13062 		int kf_arg_type;
13063 
13064 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
13065 
13066 		if (is_kfunc_arg_ignore(btf, &args[i]))
13067 			continue;
13068 
13069 		if (is_kfunc_arg_prog(btf, &args[i])) {
13070 			/* Used to reject repeated use of __prog. */
13071 			if (meta->arg_prog) {
13072 				verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc");
13073 				return -EFAULT;
13074 			}
13075 			meta->arg_prog = true;
13076 			cur_aux(env)->arg_prog = regno;
13077 			continue;
13078 		}
13079 
13080 		if (btf_type_is_scalar(t)) {
13081 			if (reg->type != SCALAR_VALUE) {
13082 				verbose(env, "R%d is not a scalar\n", regno);
13083 				return -EINVAL;
13084 			}
13085 
13086 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
13087 				if (meta->arg_constant.found) {
13088 					verifier_bug(env, "only one constant argument permitted");
13089 					return -EFAULT;
13090 				}
13091 				if (!tnum_is_const(reg->var_off)) {
13092 					verbose(env, "R%d must be a known constant\n", regno);
13093 					return -EINVAL;
13094 				}
13095 				ret = mark_chain_precision(env, regno);
13096 				if (ret < 0)
13097 					return ret;
13098 				meta->arg_constant.found = true;
13099 				meta->arg_constant.value = reg->var_off.value;
13100 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
13101 				meta->r0_rdonly = true;
13102 				is_ret_buf_sz = true;
13103 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
13104 				is_ret_buf_sz = true;
13105 			}
13106 
13107 			if (is_ret_buf_sz) {
13108 				if (meta->r0_size) {
13109 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
13110 					return -EINVAL;
13111 				}
13112 
13113 				if (!tnum_is_const(reg->var_off)) {
13114 					verbose(env, "R%d is not a const\n", regno);
13115 					return -EINVAL;
13116 				}
13117 
13118 				meta->r0_size = reg->var_off.value;
13119 				ret = mark_chain_precision(env, regno);
13120 				if (ret)
13121 					return ret;
13122 			}
13123 			continue;
13124 		}
13125 
13126 		if (!btf_type_is_ptr(t)) {
13127 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
13128 			return -EINVAL;
13129 		}
13130 
13131 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
13132 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
13133 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
13134 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
13135 			return -EACCES;
13136 		}
13137 
13138 		if (reg->ref_obj_id) {
13139 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
13140 				verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u",
13141 					     regno, reg->ref_obj_id,
13142 					     meta->ref_obj_id);
13143 				return -EFAULT;
13144 			}
13145 			meta->ref_obj_id = reg->ref_obj_id;
13146 			if (is_kfunc_release(meta))
13147 				meta->release_regno = regno;
13148 		}
13149 
13150 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
13151 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13152 
13153 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
13154 		if (kf_arg_type < 0)
13155 			return kf_arg_type;
13156 
13157 		switch (kf_arg_type) {
13158 		case KF_ARG_PTR_TO_NULL:
13159 			continue;
13160 		case KF_ARG_PTR_TO_MAP:
13161 			if (!reg->map_ptr) {
13162 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
13163 				return -EINVAL;
13164 			}
13165 			if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 ||
13166 					      reg->map_ptr->record->task_work_off >= 0)) {
13167 				/* Use map_uid (which is unique id of inner map) to reject:
13168 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
13169 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
13170 				 * if (inner_map1 && inner_map2) {
13171 				 *     wq = bpf_map_lookup_elem(inner_map1);
13172 				 *     if (wq)
13173 				 *         // mismatch would have been allowed
13174 				 *         bpf_wq_init(wq, inner_map2);
13175 				 * }
13176 				 *
13177 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
13178 				 */
13179 				if (meta->map.ptr != reg->map_ptr ||
13180 				    meta->map.uid != reg->map_uid) {
13181 					if (reg->map_ptr->record->task_work_off >= 0) {
13182 						verbose(env,
13183 							"bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n",
13184 							meta->map.uid, reg->map_uid);
13185 						return -EINVAL;
13186 					}
13187 					verbose(env,
13188 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
13189 						meta->map.uid, reg->map_uid);
13190 					return -EINVAL;
13191 				}
13192 			}
13193 			meta->map.ptr = reg->map_ptr;
13194 			meta->map.uid = reg->map_uid;
13195 			fallthrough;
13196 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13197 		case KF_ARG_PTR_TO_BTF_ID:
13198 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
13199 				break;
13200 
13201 			if (!is_trusted_reg(reg)) {
13202 				if (!is_kfunc_rcu(meta)) {
13203 					verbose(env, "R%d must be referenced or trusted\n", regno);
13204 					return -EINVAL;
13205 				}
13206 				if (!is_rcu_reg(reg)) {
13207 					verbose(env, "R%d must be a rcu pointer\n", regno);
13208 					return -EINVAL;
13209 				}
13210 			}
13211 			fallthrough;
13212 		case KF_ARG_PTR_TO_CTX:
13213 		case KF_ARG_PTR_TO_DYNPTR:
13214 		case KF_ARG_PTR_TO_ITER:
13215 		case KF_ARG_PTR_TO_LIST_HEAD:
13216 		case KF_ARG_PTR_TO_LIST_NODE:
13217 		case KF_ARG_PTR_TO_RB_ROOT:
13218 		case KF_ARG_PTR_TO_RB_NODE:
13219 		case KF_ARG_PTR_TO_MEM:
13220 		case KF_ARG_PTR_TO_MEM_SIZE:
13221 		case KF_ARG_PTR_TO_CALLBACK:
13222 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13223 		case KF_ARG_PTR_TO_CONST_STR:
13224 		case KF_ARG_PTR_TO_WORKQUEUE:
13225 		case KF_ARG_PTR_TO_TASK_WORK:
13226 		case KF_ARG_PTR_TO_IRQ_FLAG:
13227 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13228 			break;
13229 		default:
13230 			verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type);
13231 			return -EFAULT;
13232 		}
13233 
13234 		if (is_kfunc_release(meta) && reg->ref_obj_id)
13235 			arg_type |= OBJ_RELEASE;
13236 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
13237 		if (ret < 0)
13238 			return ret;
13239 
13240 		switch (kf_arg_type) {
13241 		case KF_ARG_PTR_TO_CTX:
13242 			if (reg->type != PTR_TO_CTX) {
13243 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
13244 					i, reg_type_str(env, reg->type));
13245 				return -EINVAL;
13246 			}
13247 
13248 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13249 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
13250 				if (ret < 0)
13251 					return -EINVAL;
13252 				meta->ret_btf_id  = ret;
13253 			}
13254 			break;
13255 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13256 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
13257 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
13258 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
13259 					return -EINVAL;
13260 				}
13261 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
13262 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13263 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
13264 					return -EINVAL;
13265 				}
13266 			} else {
13267 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13268 				return -EINVAL;
13269 			}
13270 			if (!reg->ref_obj_id) {
13271 				verbose(env, "allocated object must be referenced\n");
13272 				return -EINVAL;
13273 			}
13274 			if (meta->btf == btf_vmlinux) {
13275 				meta->arg_btf = reg->btf;
13276 				meta->arg_btf_id = reg->btf_id;
13277 			}
13278 			break;
13279 		case KF_ARG_PTR_TO_DYNPTR:
13280 		{
13281 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
13282 			int clone_ref_obj_id = 0;
13283 
13284 			if (reg->type == CONST_PTR_TO_DYNPTR)
13285 				dynptr_arg_type |= MEM_RDONLY;
13286 
13287 			if (is_kfunc_arg_uninit(btf, &args[i]))
13288 				dynptr_arg_type |= MEM_UNINIT;
13289 
13290 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
13291 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
13292 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
13293 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
13294 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
13295 				dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
13296 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
13297 				   (dynptr_arg_type & MEM_UNINIT)) {
13298 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
13299 
13300 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
13301 					verifier_bug(env, "no dynptr type for parent of clone");
13302 					return -EFAULT;
13303 				}
13304 
13305 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
13306 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
13307 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
13308 					verifier_bug(env, "missing ref obj id for parent of clone");
13309 					return -EFAULT;
13310 				}
13311 			}
13312 
13313 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
13314 			if (ret < 0)
13315 				return ret;
13316 
13317 			if (!(dynptr_arg_type & MEM_UNINIT)) {
13318 				int id = dynptr_id(env, reg);
13319 
13320 				if (id < 0) {
13321 					verifier_bug(env, "failed to obtain dynptr id");
13322 					return id;
13323 				}
13324 				meta->initialized_dynptr.id = id;
13325 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
13326 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
13327 			}
13328 
13329 			break;
13330 		}
13331 		case KF_ARG_PTR_TO_ITER:
13332 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
13333 				if (!check_css_task_iter_allowlist(env)) {
13334 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
13335 					return -EINVAL;
13336 				}
13337 			}
13338 			ret = process_iter_arg(env, regno, insn_idx, meta);
13339 			if (ret < 0)
13340 				return ret;
13341 			break;
13342 		case KF_ARG_PTR_TO_LIST_HEAD:
13343 			if (reg->type != PTR_TO_MAP_VALUE &&
13344 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13345 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13346 				return -EINVAL;
13347 			}
13348 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13349 				verbose(env, "allocated object must be referenced\n");
13350 				return -EINVAL;
13351 			}
13352 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
13353 			if (ret < 0)
13354 				return ret;
13355 			break;
13356 		case KF_ARG_PTR_TO_RB_ROOT:
13357 			if (reg->type != PTR_TO_MAP_VALUE &&
13358 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13359 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13360 				return -EINVAL;
13361 			}
13362 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13363 				verbose(env, "allocated object must be referenced\n");
13364 				return -EINVAL;
13365 			}
13366 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
13367 			if (ret < 0)
13368 				return ret;
13369 			break;
13370 		case KF_ARG_PTR_TO_LIST_NODE:
13371 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13372 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13373 				return -EINVAL;
13374 			}
13375 			if (!reg->ref_obj_id) {
13376 				verbose(env, "allocated object must be referenced\n");
13377 				return -EINVAL;
13378 			}
13379 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
13380 			if (ret < 0)
13381 				return ret;
13382 			break;
13383 		case KF_ARG_PTR_TO_RB_NODE:
13384 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13385 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13386 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
13387 					return -EINVAL;
13388 				}
13389 				if (!reg->ref_obj_id) {
13390 					verbose(env, "allocated object must be referenced\n");
13391 					return -EINVAL;
13392 				}
13393 			} else {
13394 				if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) {
13395 					verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
13396 					return -EINVAL;
13397 				}
13398 				if (in_rbtree_lock_required_cb(env)) {
13399 					verbose(env, "%s not allowed in rbtree cb\n", func_name);
13400 					return -EINVAL;
13401 				}
13402 			}
13403 
13404 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
13405 			if (ret < 0)
13406 				return ret;
13407 			break;
13408 		case KF_ARG_PTR_TO_MAP:
13409 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
13410 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
13411 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
13412 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13413 			fallthrough;
13414 		case KF_ARG_PTR_TO_BTF_ID:
13415 			/* Only base_type is checked, further checks are done here */
13416 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
13417 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
13418 			    !reg2btf_ids[base_type(reg->type)]) {
13419 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
13420 				verbose(env, "expected %s or socket\n",
13421 					reg_type_str(env, base_type(reg->type) |
13422 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
13423 				return -EINVAL;
13424 			}
13425 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
13426 			if (ret < 0)
13427 				return ret;
13428 			break;
13429 		case KF_ARG_PTR_TO_MEM:
13430 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
13431 			if (IS_ERR(resolve_ret)) {
13432 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
13433 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
13434 				return -EINVAL;
13435 			}
13436 			ret = check_mem_reg(env, reg, regno, type_size);
13437 			if (ret < 0)
13438 				return ret;
13439 			break;
13440 		case KF_ARG_PTR_TO_MEM_SIZE:
13441 		{
13442 			struct bpf_reg_state *buff_reg = &regs[regno];
13443 			const struct btf_param *buff_arg = &args[i];
13444 			struct bpf_reg_state *size_reg = &regs[regno + 1];
13445 			const struct btf_param *size_arg = &args[i + 1];
13446 
13447 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
13448 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
13449 				if (ret < 0) {
13450 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
13451 					return ret;
13452 				}
13453 			}
13454 
13455 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
13456 				if (meta->arg_constant.found) {
13457 					verifier_bug(env, "only one constant argument permitted");
13458 					return -EFAULT;
13459 				}
13460 				if (!tnum_is_const(size_reg->var_off)) {
13461 					verbose(env, "R%d must be a known constant\n", regno + 1);
13462 					return -EINVAL;
13463 				}
13464 				meta->arg_constant.found = true;
13465 				meta->arg_constant.value = size_reg->var_off.value;
13466 			}
13467 
13468 			/* Skip next '__sz' or '__szk' argument */
13469 			i++;
13470 			break;
13471 		}
13472 		case KF_ARG_PTR_TO_CALLBACK:
13473 			if (reg->type != PTR_TO_FUNC) {
13474 				verbose(env, "arg%d expected pointer to func\n", i);
13475 				return -EINVAL;
13476 			}
13477 			meta->subprogno = reg->subprogno;
13478 			break;
13479 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13480 			if (!type_is_ptr_alloc_obj(reg->type)) {
13481 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
13482 				return -EINVAL;
13483 			}
13484 			if (!type_is_non_owning_ref(reg->type))
13485 				meta->arg_owning_ref = true;
13486 
13487 			rec = reg_btf_record(reg);
13488 			if (!rec) {
13489 				verifier_bug(env, "Couldn't find btf_record");
13490 				return -EFAULT;
13491 			}
13492 
13493 			if (rec->refcount_off < 0) {
13494 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
13495 				return -EINVAL;
13496 			}
13497 
13498 			meta->arg_btf = reg->btf;
13499 			meta->arg_btf_id = reg->btf_id;
13500 			break;
13501 		case KF_ARG_PTR_TO_CONST_STR:
13502 			if (reg->type != PTR_TO_MAP_VALUE) {
13503 				verbose(env, "arg#%d doesn't point to a const string\n", i);
13504 				return -EINVAL;
13505 			}
13506 			ret = check_reg_const_str(env, reg, regno);
13507 			if (ret)
13508 				return ret;
13509 			break;
13510 		case KF_ARG_PTR_TO_WORKQUEUE:
13511 			if (reg->type != PTR_TO_MAP_VALUE) {
13512 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13513 				return -EINVAL;
13514 			}
13515 			ret = process_wq_func(env, regno, meta);
13516 			if (ret < 0)
13517 				return ret;
13518 			break;
13519 		case KF_ARG_PTR_TO_TASK_WORK:
13520 			if (reg->type != PTR_TO_MAP_VALUE) {
13521 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13522 				return -EINVAL;
13523 			}
13524 			ret = process_task_work_func(env, regno, meta);
13525 			if (ret < 0)
13526 				return ret;
13527 			break;
13528 		case KF_ARG_PTR_TO_IRQ_FLAG:
13529 			if (reg->type != PTR_TO_STACK) {
13530 				verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i);
13531 				return -EINVAL;
13532 			}
13533 			ret = process_irq_flag(env, regno, meta);
13534 			if (ret < 0)
13535 				return ret;
13536 			break;
13537 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13538 		{
13539 			int flags = PROCESS_RES_LOCK;
13540 
13541 			if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13542 				verbose(env, "arg#%d doesn't point to map value or allocated object\n", i);
13543 				return -EINVAL;
13544 			}
13545 
13546 			if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
13547 				return -EFAULT;
13548 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13549 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
13550 				flags |= PROCESS_SPIN_LOCK;
13551 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
13552 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
13553 				flags |= PROCESS_LOCK_IRQ;
13554 			ret = process_spin_lock(env, regno, flags);
13555 			if (ret < 0)
13556 				return ret;
13557 			break;
13558 		}
13559 		}
13560 	}
13561 
13562 	if (is_kfunc_release(meta) && !meta->release_regno) {
13563 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
13564 			func_name);
13565 		return -EINVAL;
13566 	}
13567 
13568 	return 0;
13569 }
13570 
13571 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
13572 			    struct bpf_insn *insn,
13573 			    struct bpf_kfunc_call_arg_meta *meta,
13574 			    const char **kfunc_name)
13575 {
13576 	const struct btf_type *func, *func_proto;
13577 	u32 func_id, *kfunc_flags;
13578 	const char *func_name;
13579 	struct btf *desc_btf;
13580 
13581 	if (kfunc_name)
13582 		*kfunc_name = NULL;
13583 
13584 	if (!insn->imm)
13585 		return -EINVAL;
13586 
13587 	desc_btf = find_kfunc_desc_btf(env, insn->off);
13588 	if (IS_ERR(desc_btf))
13589 		return PTR_ERR(desc_btf);
13590 
13591 	func_id = insn->imm;
13592 	func = btf_type_by_id(desc_btf, func_id);
13593 	func_name = btf_name_by_offset(desc_btf, func->name_off);
13594 	if (kfunc_name)
13595 		*kfunc_name = func_name;
13596 	func_proto = btf_type_by_id(desc_btf, func->type);
13597 
13598 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
13599 	if (!kfunc_flags) {
13600 		return -EACCES;
13601 	}
13602 
13603 	memset(meta, 0, sizeof(*meta));
13604 	meta->btf = desc_btf;
13605 	meta->func_id = func_id;
13606 	meta->kfunc_flags = *kfunc_flags;
13607 	meta->func_proto = func_proto;
13608 	meta->func_name = func_name;
13609 
13610 	return 0;
13611 }
13612 
13613 /* check special kfuncs and return:
13614  *  1  - not fall-through to 'else' branch, continue verification
13615  *  0  - fall-through to 'else' branch
13616  * < 0 - not fall-through to 'else' branch, return error
13617  */
13618 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13619 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
13620 			       const struct btf_type *ptr_type, struct btf *desc_btf)
13621 {
13622 	const struct btf_type *ret_t;
13623 	int err = 0;
13624 
13625 	if (meta->btf != btf_vmlinux)
13626 		return 0;
13627 
13628 	if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
13629 	    meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13630 		struct btf_struct_meta *struct_meta;
13631 		struct btf *ret_btf;
13632 		u32 ret_btf_id;
13633 
13634 		if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
13635 			return -ENOMEM;
13636 
13637 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
13638 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13639 			return -EINVAL;
13640 		}
13641 
13642 		ret_btf = env->prog->aux->btf;
13643 		ret_btf_id = meta->arg_constant.value;
13644 
13645 		/* This may be NULL due to user not supplying a BTF */
13646 		if (!ret_btf) {
13647 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13648 			return -EINVAL;
13649 		}
13650 
13651 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13652 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
13653 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13654 			return -EINVAL;
13655 		}
13656 
13657 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13658 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13659 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13660 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13661 				return -EINVAL;
13662 			}
13663 
13664 			if (!bpf_global_percpu_ma_set) {
13665 				mutex_lock(&bpf_percpu_ma_lock);
13666 				if (!bpf_global_percpu_ma_set) {
13667 					/* Charge memory allocated with bpf_global_percpu_ma to
13668 					 * root memcg. The obj_cgroup for root memcg is NULL.
13669 					 */
13670 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13671 					if (!err)
13672 						bpf_global_percpu_ma_set = true;
13673 				}
13674 				mutex_unlock(&bpf_percpu_ma_lock);
13675 				if (err)
13676 					return err;
13677 			}
13678 
13679 			mutex_lock(&bpf_percpu_ma_lock);
13680 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13681 			mutex_unlock(&bpf_percpu_ma_lock);
13682 			if (err)
13683 				return err;
13684 		}
13685 
13686 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13687 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13688 			if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13689 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13690 				return -EINVAL;
13691 			}
13692 
13693 			if (struct_meta) {
13694 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13695 				return -EINVAL;
13696 			}
13697 		}
13698 
13699 		mark_reg_known_zero(env, regs, BPF_REG_0);
13700 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13701 		regs[BPF_REG_0].btf = ret_btf;
13702 		regs[BPF_REG_0].btf_id = ret_btf_id;
13703 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
13704 			regs[BPF_REG_0].type |= MEM_PERCPU;
13705 
13706 		insn_aux->obj_new_size = ret_t->size;
13707 		insn_aux->kptr_struct_meta = struct_meta;
13708 	} else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
13709 		mark_reg_known_zero(env, regs, BPF_REG_0);
13710 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13711 		regs[BPF_REG_0].btf = meta->arg_btf;
13712 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
13713 
13714 		insn_aux->kptr_struct_meta =
13715 			btf_find_struct_meta(meta->arg_btf,
13716 					     meta->arg_btf_id);
13717 	} else if (is_list_node_type(ptr_type)) {
13718 		struct btf_field *field = meta->arg_list_head.field;
13719 
13720 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13721 	} else if (is_rbtree_node_type(ptr_type)) {
13722 		struct btf_field *field = meta->arg_rbtree_root.field;
13723 
13724 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13725 	} else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13726 		mark_reg_known_zero(env, regs, BPF_REG_0);
13727 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13728 		regs[BPF_REG_0].btf = desc_btf;
13729 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
13730 	} else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
13731 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
13732 		if (!ret_t) {
13733 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
13734 				meta->arg_constant.value);
13735 			return -EINVAL;
13736 		} else if (btf_type_is_struct(ret_t)) {
13737 			mark_reg_known_zero(env, regs, BPF_REG_0);
13738 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13739 			regs[BPF_REG_0].btf = desc_btf;
13740 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
13741 		} else if (btf_type_is_void(ret_t)) {
13742 			mark_reg_known_zero(env, regs, BPF_REG_0);
13743 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
13744 			regs[BPF_REG_0].mem_size = 0;
13745 		} else {
13746 			verbose(env,
13747 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
13748 			return -EINVAL;
13749 		}
13750 	} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13751 		   meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13752 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type);
13753 
13754 		mark_reg_known_zero(env, regs, BPF_REG_0);
13755 
13756 		if (!meta->arg_constant.found) {
13757 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
13758 			return -EFAULT;
13759 		}
13760 
13761 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
13762 
13763 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
13764 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
13765 
13766 		if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
13767 			regs[BPF_REG_0].type |= MEM_RDONLY;
13768 		} else {
13769 			/* this will set env->seen_direct_write to true */
13770 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
13771 				verbose(env, "the prog does not allow writes to packet data\n");
13772 				return -EINVAL;
13773 			}
13774 		}
13775 
13776 		if (!meta->initialized_dynptr.id) {
13777 			verifier_bug(env, "no dynptr id");
13778 			return -EFAULT;
13779 		}
13780 		regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id;
13781 
13782 		/* we don't need to set BPF_REG_0's ref obj id
13783 		 * because packet slices are not refcounted (see
13784 		 * dynptr_type_refcounted)
13785 		 */
13786 	} else {
13787 		return 0;
13788 	}
13789 
13790 	return 1;
13791 }
13792 
13793 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
13794 
13795 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
13796 			    int *insn_idx_p)
13797 {
13798 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
13799 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
13800 	struct bpf_reg_state *regs = cur_regs(env);
13801 	const char *func_name, *ptr_type_name;
13802 	const struct btf_type *t, *ptr_type;
13803 	struct bpf_kfunc_call_arg_meta meta;
13804 	struct bpf_insn_aux_data *insn_aux;
13805 	int err, insn_idx = *insn_idx_p;
13806 	const struct btf_param *args;
13807 	struct btf *desc_btf;
13808 
13809 	/* skip for now, but return error when we find this in fixup_kfunc_call */
13810 	if (!insn->imm)
13811 		return 0;
13812 
13813 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
13814 	if (err == -EACCES && func_name)
13815 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
13816 	if (err)
13817 		return err;
13818 	desc_btf = meta.btf;
13819 	insn_aux = &env->insn_aux_data[insn_idx];
13820 
13821 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
13822 
13823 	if (!insn->off &&
13824 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
13825 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
13826 		struct bpf_verifier_state *branch;
13827 		struct bpf_reg_state *regs;
13828 
13829 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13830 		if (!branch) {
13831 			verbose(env, "failed to push state for failed lock acquisition\n");
13832 			return -ENOMEM;
13833 		}
13834 
13835 		regs = branch->frame[branch->curframe]->regs;
13836 
13837 		/* Clear r0-r5 registers in forked state */
13838 		for (i = 0; i < CALLER_SAVED_REGS; i++)
13839 			mark_reg_not_init(env, regs, caller_saved[i]);
13840 
13841 		mark_reg_unknown(env, regs, BPF_REG_0);
13842 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
13843 		if (err) {
13844 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
13845 			return err;
13846 		}
13847 		__mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32));
13848 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
13849 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
13850 		return -EFAULT;
13851 	}
13852 
13853 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
13854 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
13855 		return -EACCES;
13856 	}
13857 
13858 	sleepable = is_kfunc_sleepable(&meta);
13859 	if (sleepable && !in_sleepable(env)) {
13860 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
13861 		return -EACCES;
13862 	}
13863 
13864 	/* Check the arguments */
13865 	err = check_kfunc_args(env, &meta, insn_idx);
13866 	if (err < 0)
13867 		return err;
13868 
13869 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13870 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13871 					 set_rbtree_add_callback_state);
13872 		if (err) {
13873 			verbose(env, "kfunc %s#%d failed callback verification\n",
13874 				func_name, meta.func_id);
13875 			return err;
13876 		}
13877 	}
13878 
13879 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
13880 		meta.r0_size = sizeof(u64);
13881 		meta.r0_rdonly = false;
13882 	}
13883 
13884 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
13885 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13886 					 set_timer_callback_state);
13887 		if (err) {
13888 			verbose(env, "kfunc %s#%d failed callback verification\n",
13889 				func_name, meta.func_id);
13890 			return err;
13891 		}
13892 	}
13893 
13894 	if (is_task_work_add_kfunc(meta.func_id)) {
13895 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13896 					 set_task_work_schedule_callback_state);
13897 		if (err) {
13898 			verbose(env, "kfunc %s#%d failed callback verification\n",
13899 				func_name, meta.func_id);
13900 			return err;
13901 		}
13902 	}
13903 
13904 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
13905 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
13906 
13907 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
13908 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
13909 
13910 	if (env->cur_state->active_rcu_lock) {
13911 		struct bpf_func_state *state;
13912 		struct bpf_reg_state *reg;
13913 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
13914 
13915 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
13916 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
13917 			return -EACCES;
13918 		}
13919 
13920 		if (rcu_lock) {
13921 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
13922 			return -EINVAL;
13923 		} else if (rcu_unlock) {
13924 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
13925 				if (reg->type & MEM_RCU) {
13926 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
13927 					reg->type |= PTR_UNTRUSTED;
13928 				}
13929 			}));
13930 			env->cur_state->active_rcu_lock = false;
13931 		} else if (sleepable) {
13932 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
13933 			return -EACCES;
13934 		}
13935 	} else if (rcu_lock) {
13936 		env->cur_state->active_rcu_lock = true;
13937 	} else if (rcu_unlock) {
13938 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
13939 		return -EINVAL;
13940 	}
13941 
13942 	if (env->cur_state->active_preempt_locks) {
13943 		if (preempt_disable) {
13944 			env->cur_state->active_preempt_locks++;
13945 		} else if (preempt_enable) {
13946 			env->cur_state->active_preempt_locks--;
13947 		} else if (sleepable) {
13948 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
13949 			return -EACCES;
13950 		}
13951 	} else if (preempt_disable) {
13952 		env->cur_state->active_preempt_locks++;
13953 	} else if (preempt_enable) {
13954 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
13955 		return -EINVAL;
13956 	}
13957 
13958 	if (env->cur_state->active_irq_id && sleepable) {
13959 		verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name);
13960 		return -EACCES;
13961 	}
13962 
13963 	if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
13964 		verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
13965 		return -EACCES;
13966 	}
13967 
13968 	/* In case of release function, we get register number of refcounted
13969 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
13970 	 */
13971 	if (meta.release_regno) {
13972 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
13973 		if (err) {
13974 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13975 				func_name, meta.func_id);
13976 			return err;
13977 		}
13978 	}
13979 
13980 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
13981 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
13982 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13983 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
13984 		insn_aux->insert_off = regs[BPF_REG_2].off;
13985 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
13986 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
13987 		if (err) {
13988 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
13989 				func_name, meta.func_id);
13990 			return err;
13991 		}
13992 
13993 		err = release_reference(env, release_ref_obj_id);
13994 		if (err) {
13995 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13996 				func_name, meta.func_id);
13997 			return err;
13998 		}
13999 	}
14000 
14001 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
14002 		if (!bpf_jit_supports_exceptions()) {
14003 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
14004 				func_name, meta.func_id);
14005 			return -ENOTSUPP;
14006 		}
14007 		env->seen_exception = true;
14008 
14009 		/* In the case of the default callback, the cookie value passed
14010 		 * to bpf_throw becomes the return value of the program.
14011 		 */
14012 		if (!env->exception_callback_subprog) {
14013 			err = check_return_code(env, BPF_REG_1, "R1");
14014 			if (err < 0)
14015 				return err;
14016 		}
14017 	}
14018 
14019 	for (i = 0; i < CALLER_SAVED_REGS; i++)
14020 		mark_reg_not_init(env, regs, caller_saved[i]);
14021 
14022 	/* Check return type */
14023 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
14024 
14025 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
14026 		/* Only exception is bpf_obj_new_impl */
14027 		if (meta.btf != btf_vmlinux ||
14028 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
14029 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
14030 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
14031 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
14032 			return -EINVAL;
14033 		}
14034 	}
14035 
14036 	if (btf_type_is_scalar(t)) {
14037 		mark_reg_unknown(env, regs, BPF_REG_0);
14038 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
14039 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14040 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
14041 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
14042 	} else if (btf_type_is_ptr(t)) {
14043 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
14044 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
14045 		if (err) {
14046 			if (err < 0)
14047 				return err;
14048 		} else if (btf_type_is_void(ptr_type)) {
14049 			/* kfunc returning 'void *' is equivalent to returning scalar */
14050 			mark_reg_unknown(env, regs, BPF_REG_0);
14051 		} else if (!__btf_type_is_struct(ptr_type)) {
14052 			if (!meta.r0_size) {
14053 				__u32 sz;
14054 
14055 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
14056 					meta.r0_size = sz;
14057 					meta.r0_rdonly = true;
14058 				}
14059 			}
14060 			if (!meta.r0_size) {
14061 				ptr_type_name = btf_name_by_offset(desc_btf,
14062 								   ptr_type->name_off);
14063 				verbose(env,
14064 					"kernel function %s returns pointer type %s %s is not supported\n",
14065 					func_name,
14066 					btf_type_str(ptr_type),
14067 					ptr_type_name);
14068 				return -EINVAL;
14069 			}
14070 
14071 			mark_reg_known_zero(env, regs, BPF_REG_0);
14072 			regs[BPF_REG_0].type = PTR_TO_MEM;
14073 			regs[BPF_REG_0].mem_size = meta.r0_size;
14074 
14075 			if (meta.r0_rdonly)
14076 				regs[BPF_REG_0].type |= MEM_RDONLY;
14077 
14078 			/* Ensures we don't access the memory after a release_reference() */
14079 			if (meta.ref_obj_id)
14080 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
14081 
14082 			if (is_kfunc_rcu_protected(&meta))
14083 				regs[BPF_REG_0].type |= MEM_RCU;
14084 		} else {
14085 			mark_reg_known_zero(env, regs, BPF_REG_0);
14086 			regs[BPF_REG_0].btf = desc_btf;
14087 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
14088 			regs[BPF_REG_0].btf_id = ptr_type_id;
14089 
14090 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
14091 				regs[BPF_REG_0].type |= PTR_UNTRUSTED;
14092 			else if (is_kfunc_rcu_protected(&meta))
14093 				regs[BPF_REG_0].type |= MEM_RCU;
14094 
14095 			if (is_iter_next_kfunc(&meta)) {
14096 				struct bpf_reg_state *cur_iter;
14097 
14098 				cur_iter = get_iter_from_state(env->cur_state, &meta);
14099 
14100 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
14101 					regs[BPF_REG_0].type |= MEM_RCU;
14102 				else
14103 					regs[BPF_REG_0].type |= PTR_TRUSTED;
14104 			}
14105 		}
14106 
14107 		if (is_kfunc_ret_null(&meta)) {
14108 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
14109 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
14110 			regs[BPF_REG_0].id = ++env->id_gen;
14111 		}
14112 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
14113 		if (is_kfunc_acquire(&meta)) {
14114 			int id = acquire_reference(env, insn_idx);
14115 
14116 			if (id < 0)
14117 				return id;
14118 			if (is_kfunc_ret_null(&meta))
14119 				regs[BPF_REG_0].id = id;
14120 			regs[BPF_REG_0].ref_obj_id = id;
14121 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
14122 			ref_set_non_owning(env, &regs[BPF_REG_0]);
14123 		}
14124 
14125 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
14126 			regs[BPF_REG_0].id = ++env->id_gen;
14127 	} else if (btf_type_is_void(t)) {
14128 		if (meta.btf == btf_vmlinux) {
14129 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
14130 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
14131 				insn_aux->kptr_struct_meta =
14132 					btf_find_struct_meta(meta.arg_btf,
14133 							     meta.arg_btf_id);
14134 			}
14135 		}
14136 	}
14137 
14138 	if (is_kfunc_pkt_changing(&meta))
14139 		clear_all_pkt_pointers(env);
14140 
14141 	nargs = btf_type_vlen(meta.func_proto);
14142 	args = (const struct btf_param *)(meta.func_proto + 1);
14143 	for (i = 0; i < nargs; i++) {
14144 		u32 regno = i + 1;
14145 
14146 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
14147 		if (btf_type_is_ptr(t))
14148 			mark_btf_func_reg_size(env, regno, sizeof(void *));
14149 		else
14150 			/* scalar. ensured by btf_check_kfunc_arg_match() */
14151 			mark_btf_func_reg_size(env, regno, t->size);
14152 	}
14153 
14154 	if (is_iter_next_kfunc(&meta)) {
14155 		err = process_iter_next_call(env, insn_idx, &meta);
14156 		if (err)
14157 			return err;
14158 	}
14159 
14160 	return 0;
14161 }
14162 
14163 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
14164 				  const struct bpf_reg_state *reg,
14165 				  enum bpf_reg_type type)
14166 {
14167 	bool known = tnum_is_const(reg->var_off);
14168 	s64 val = reg->var_off.value;
14169 	s64 smin = reg->smin_value;
14170 
14171 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
14172 		verbose(env, "math between %s pointer and %lld is not allowed\n",
14173 			reg_type_str(env, type), val);
14174 		return false;
14175 	}
14176 
14177 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
14178 		verbose(env, "%s pointer offset %d is not allowed\n",
14179 			reg_type_str(env, type), reg->off);
14180 		return false;
14181 	}
14182 
14183 	if (smin == S64_MIN) {
14184 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
14185 			reg_type_str(env, type));
14186 		return false;
14187 	}
14188 
14189 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
14190 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
14191 			smin, reg_type_str(env, type));
14192 		return false;
14193 	}
14194 
14195 	return true;
14196 }
14197 
14198 enum {
14199 	REASON_BOUNDS	= -1,
14200 	REASON_TYPE	= -2,
14201 	REASON_PATHS	= -3,
14202 	REASON_LIMIT	= -4,
14203 	REASON_STACK	= -5,
14204 };
14205 
14206 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
14207 			      u32 *alu_limit, bool mask_to_left)
14208 {
14209 	u32 max = 0, ptr_limit = 0;
14210 
14211 	switch (ptr_reg->type) {
14212 	case PTR_TO_STACK:
14213 		/* Offset 0 is out-of-bounds, but acceptable start for the
14214 		 * left direction, see BPF_REG_FP. Also, unknown scalar
14215 		 * offset where we would need to deal with min/max bounds is
14216 		 * currently prohibited for unprivileged.
14217 		 */
14218 		max = MAX_BPF_STACK + mask_to_left;
14219 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
14220 		break;
14221 	case PTR_TO_MAP_VALUE:
14222 		max = ptr_reg->map_ptr->value_size;
14223 		ptr_limit = (mask_to_left ?
14224 			     ptr_reg->smin_value :
14225 			     ptr_reg->umax_value) + ptr_reg->off;
14226 		break;
14227 	default:
14228 		return REASON_TYPE;
14229 	}
14230 
14231 	if (ptr_limit >= max)
14232 		return REASON_LIMIT;
14233 	*alu_limit = ptr_limit;
14234 	return 0;
14235 }
14236 
14237 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
14238 				    const struct bpf_insn *insn)
14239 {
14240 	return env->bypass_spec_v1 ||
14241 		BPF_SRC(insn->code) == BPF_K ||
14242 		cur_aux(env)->nospec;
14243 }
14244 
14245 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
14246 				       u32 alu_state, u32 alu_limit)
14247 {
14248 	/* If we arrived here from different branches with different
14249 	 * state or limits to sanitize, then this won't work.
14250 	 */
14251 	if (aux->alu_state &&
14252 	    (aux->alu_state != alu_state ||
14253 	     aux->alu_limit != alu_limit))
14254 		return REASON_PATHS;
14255 
14256 	/* Corresponding fixup done in do_misc_fixups(). */
14257 	aux->alu_state = alu_state;
14258 	aux->alu_limit = alu_limit;
14259 	return 0;
14260 }
14261 
14262 static int sanitize_val_alu(struct bpf_verifier_env *env,
14263 			    struct bpf_insn *insn)
14264 {
14265 	struct bpf_insn_aux_data *aux = cur_aux(env);
14266 
14267 	if (can_skip_alu_sanitation(env, insn))
14268 		return 0;
14269 
14270 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
14271 }
14272 
14273 static bool sanitize_needed(u8 opcode)
14274 {
14275 	return opcode == BPF_ADD || opcode == BPF_SUB;
14276 }
14277 
14278 struct bpf_sanitize_info {
14279 	struct bpf_insn_aux_data aux;
14280 	bool mask_to_left;
14281 };
14282 
14283 static struct bpf_verifier_state *
14284 sanitize_speculative_path(struct bpf_verifier_env *env,
14285 			  const struct bpf_insn *insn,
14286 			  u32 next_idx, u32 curr_idx)
14287 {
14288 	struct bpf_verifier_state *branch;
14289 	struct bpf_reg_state *regs;
14290 
14291 	branch = push_stack(env, next_idx, curr_idx, true);
14292 	if (branch && insn) {
14293 		regs = branch->frame[branch->curframe]->regs;
14294 		if (BPF_SRC(insn->code) == BPF_K) {
14295 			mark_reg_unknown(env, regs, insn->dst_reg);
14296 		} else if (BPF_SRC(insn->code) == BPF_X) {
14297 			mark_reg_unknown(env, regs, insn->dst_reg);
14298 			mark_reg_unknown(env, regs, insn->src_reg);
14299 		}
14300 	}
14301 	return branch;
14302 }
14303 
14304 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
14305 			    struct bpf_insn *insn,
14306 			    const struct bpf_reg_state *ptr_reg,
14307 			    const struct bpf_reg_state *off_reg,
14308 			    struct bpf_reg_state *dst_reg,
14309 			    struct bpf_sanitize_info *info,
14310 			    const bool commit_window)
14311 {
14312 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
14313 	struct bpf_verifier_state *vstate = env->cur_state;
14314 	bool off_is_imm = tnum_is_const(off_reg->var_off);
14315 	bool off_is_neg = off_reg->smin_value < 0;
14316 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
14317 	u8 opcode = BPF_OP(insn->code);
14318 	u32 alu_state, alu_limit;
14319 	struct bpf_reg_state tmp;
14320 	bool ret;
14321 	int err;
14322 
14323 	if (can_skip_alu_sanitation(env, insn))
14324 		return 0;
14325 
14326 	/* We already marked aux for masking from non-speculative
14327 	 * paths, thus we got here in the first place. We only care
14328 	 * to explore bad access from here.
14329 	 */
14330 	if (vstate->speculative)
14331 		goto do_sim;
14332 
14333 	if (!commit_window) {
14334 		if (!tnum_is_const(off_reg->var_off) &&
14335 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
14336 			return REASON_BOUNDS;
14337 
14338 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
14339 				     (opcode == BPF_SUB && !off_is_neg);
14340 	}
14341 
14342 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
14343 	if (err < 0)
14344 		return err;
14345 
14346 	if (commit_window) {
14347 		/* In commit phase we narrow the masking window based on
14348 		 * the observed pointer move after the simulated operation.
14349 		 */
14350 		alu_state = info->aux.alu_state;
14351 		alu_limit = abs(info->aux.alu_limit - alu_limit);
14352 	} else {
14353 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
14354 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
14355 		alu_state |= ptr_is_dst_reg ?
14356 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
14357 
14358 		/* Limit pruning on unknown scalars to enable deep search for
14359 		 * potential masking differences from other program paths.
14360 		 */
14361 		if (!off_is_imm)
14362 			env->explore_alu_limits = true;
14363 	}
14364 
14365 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
14366 	if (err < 0)
14367 		return err;
14368 do_sim:
14369 	/* If we're in commit phase, we're done here given we already
14370 	 * pushed the truncated dst_reg into the speculative verification
14371 	 * stack.
14372 	 *
14373 	 * Also, when register is a known constant, we rewrite register-based
14374 	 * operation to immediate-based, and thus do not need masking (and as
14375 	 * a consequence, do not need to simulate the zero-truncation either).
14376 	 */
14377 	if (commit_window || off_is_imm)
14378 		return 0;
14379 
14380 	/* Simulate and find potential out-of-bounds access under
14381 	 * speculative execution from truncation as a result of
14382 	 * masking when off was not within expected range. If off
14383 	 * sits in dst, then we temporarily need to move ptr there
14384 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
14385 	 * for cases where we use K-based arithmetic in one direction
14386 	 * and truncated reg-based in the other in order to explore
14387 	 * bad access.
14388 	 */
14389 	if (!ptr_is_dst_reg) {
14390 		tmp = *dst_reg;
14391 		copy_register_state(dst_reg, ptr_reg);
14392 	}
14393 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
14394 					env->insn_idx);
14395 	if (!ptr_is_dst_reg && ret)
14396 		*dst_reg = tmp;
14397 	return !ret ? REASON_STACK : 0;
14398 }
14399 
14400 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
14401 {
14402 	struct bpf_verifier_state *vstate = env->cur_state;
14403 
14404 	/* If we simulate paths under speculation, we don't update the
14405 	 * insn as 'seen' such that when we verify unreachable paths in
14406 	 * the non-speculative domain, sanitize_dead_code() can still
14407 	 * rewrite/sanitize them.
14408 	 */
14409 	if (!vstate->speculative)
14410 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
14411 }
14412 
14413 static int sanitize_err(struct bpf_verifier_env *env,
14414 			const struct bpf_insn *insn, int reason,
14415 			const struct bpf_reg_state *off_reg,
14416 			const struct bpf_reg_state *dst_reg)
14417 {
14418 	static const char *err = "pointer arithmetic with it prohibited for !root";
14419 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
14420 	u32 dst = insn->dst_reg, src = insn->src_reg;
14421 
14422 	switch (reason) {
14423 	case REASON_BOUNDS:
14424 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
14425 			off_reg == dst_reg ? dst : src, err);
14426 		break;
14427 	case REASON_TYPE:
14428 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
14429 			off_reg == dst_reg ? src : dst, err);
14430 		break;
14431 	case REASON_PATHS:
14432 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
14433 			dst, op, err);
14434 		break;
14435 	case REASON_LIMIT:
14436 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
14437 			dst, op, err);
14438 		break;
14439 	case REASON_STACK:
14440 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
14441 			dst, err);
14442 		return -ENOMEM;
14443 	default:
14444 		verifier_bug(env, "unknown reason (%d)", reason);
14445 		break;
14446 	}
14447 
14448 	return -EACCES;
14449 }
14450 
14451 /* check that stack access falls within stack limits and that 'reg' doesn't
14452  * have a variable offset.
14453  *
14454  * Variable offset is prohibited for unprivileged mode for simplicity since it
14455  * requires corresponding support in Spectre masking for stack ALU.  See also
14456  * retrieve_ptr_limit().
14457  *
14458  *
14459  * 'off' includes 'reg->off'.
14460  */
14461 static int check_stack_access_for_ptr_arithmetic(
14462 				struct bpf_verifier_env *env,
14463 				int regno,
14464 				const struct bpf_reg_state *reg,
14465 				int off)
14466 {
14467 	if (!tnum_is_const(reg->var_off)) {
14468 		char tn_buf[48];
14469 
14470 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
14471 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
14472 			regno, tn_buf, off);
14473 		return -EACCES;
14474 	}
14475 
14476 	if (off >= 0 || off < -MAX_BPF_STACK) {
14477 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
14478 			"prohibited for !root; off=%d\n", regno, off);
14479 		return -EACCES;
14480 	}
14481 
14482 	return 0;
14483 }
14484 
14485 static int sanitize_check_bounds(struct bpf_verifier_env *env,
14486 				 const struct bpf_insn *insn,
14487 				 const struct bpf_reg_state *dst_reg)
14488 {
14489 	u32 dst = insn->dst_reg;
14490 
14491 	/* For unprivileged we require that resulting offset must be in bounds
14492 	 * in order to be able to sanitize access later on.
14493 	 */
14494 	if (env->bypass_spec_v1)
14495 		return 0;
14496 
14497 	switch (dst_reg->type) {
14498 	case PTR_TO_STACK:
14499 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
14500 					dst_reg->off + dst_reg->var_off.value))
14501 			return -EACCES;
14502 		break;
14503 	case PTR_TO_MAP_VALUE:
14504 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
14505 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
14506 				"prohibited for !root\n", dst);
14507 			return -EACCES;
14508 		}
14509 		break;
14510 	default:
14511 		return -EOPNOTSUPP;
14512 	}
14513 
14514 	return 0;
14515 }
14516 
14517 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
14518  * Caller should also handle BPF_MOV case separately.
14519  * If we return -EACCES, caller may want to try again treating pointer as a
14520  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
14521  */
14522 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
14523 				   struct bpf_insn *insn,
14524 				   const struct bpf_reg_state *ptr_reg,
14525 				   const struct bpf_reg_state *off_reg)
14526 {
14527 	struct bpf_verifier_state *vstate = env->cur_state;
14528 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14529 	struct bpf_reg_state *regs = state->regs, *dst_reg;
14530 	bool known = tnum_is_const(off_reg->var_off);
14531 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
14532 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
14533 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
14534 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
14535 	struct bpf_sanitize_info info = {};
14536 	u8 opcode = BPF_OP(insn->code);
14537 	u32 dst = insn->dst_reg;
14538 	int ret, bounds_ret;
14539 
14540 	dst_reg = &regs[dst];
14541 
14542 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
14543 	    smin_val > smax_val || umin_val > umax_val) {
14544 		/* Taint dst register if offset had invalid bounds derived from
14545 		 * e.g. dead branches.
14546 		 */
14547 		__mark_reg_unknown(env, dst_reg);
14548 		return 0;
14549 	}
14550 
14551 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
14552 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
14553 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14554 			__mark_reg_unknown(env, dst_reg);
14555 			return 0;
14556 		}
14557 
14558 		verbose(env,
14559 			"R%d 32-bit pointer arithmetic prohibited\n",
14560 			dst);
14561 		return -EACCES;
14562 	}
14563 
14564 	if (ptr_reg->type & PTR_MAYBE_NULL) {
14565 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
14566 			dst, reg_type_str(env, ptr_reg->type));
14567 		return -EACCES;
14568 	}
14569 
14570 	/*
14571 	 * Accesses to untrusted PTR_TO_MEM are done through probe
14572 	 * instructions, hence no need to track offsets.
14573 	 */
14574 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
14575 		return 0;
14576 
14577 	switch (base_type(ptr_reg->type)) {
14578 	case PTR_TO_CTX:
14579 	case PTR_TO_MAP_VALUE:
14580 	case PTR_TO_MAP_KEY:
14581 	case PTR_TO_STACK:
14582 	case PTR_TO_PACKET_META:
14583 	case PTR_TO_PACKET:
14584 	case PTR_TO_TP_BUFFER:
14585 	case PTR_TO_BTF_ID:
14586 	case PTR_TO_MEM:
14587 	case PTR_TO_BUF:
14588 	case PTR_TO_FUNC:
14589 	case CONST_PTR_TO_DYNPTR:
14590 		break;
14591 	case PTR_TO_FLOW_KEYS:
14592 		if (known)
14593 			break;
14594 		fallthrough;
14595 	case CONST_PTR_TO_MAP:
14596 		/* smin_val represents the known value */
14597 		if (known && smin_val == 0 && opcode == BPF_ADD)
14598 			break;
14599 		fallthrough;
14600 	default:
14601 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
14602 			dst, reg_type_str(env, ptr_reg->type));
14603 		return -EACCES;
14604 	}
14605 
14606 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
14607 	 * The id may be overwritten later if we create a new variable offset.
14608 	 */
14609 	dst_reg->type = ptr_reg->type;
14610 	dst_reg->id = ptr_reg->id;
14611 
14612 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
14613 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
14614 		return -EINVAL;
14615 
14616 	/* pointer types do not carry 32-bit bounds at the moment. */
14617 	__mark_reg32_unbounded(dst_reg);
14618 
14619 	if (sanitize_needed(opcode)) {
14620 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
14621 				       &info, false);
14622 		if (ret < 0)
14623 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14624 	}
14625 
14626 	switch (opcode) {
14627 	case BPF_ADD:
14628 		/* We can take a fixed offset as long as it doesn't overflow
14629 		 * the s32 'off' field
14630 		 */
14631 		if (known && (ptr_reg->off + smin_val ==
14632 			      (s64)(s32)(ptr_reg->off + smin_val))) {
14633 			/* pointer += K.  Accumulate it into fixed offset */
14634 			dst_reg->smin_value = smin_ptr;
14635 			dst_reg->smax_value = smax_ptr;
14636 			dst_reg->umin_value = umin_ptr;
14637 			dst_reg->umax_value = umax_ptr;
14638 			dst_reg->var_off = ptr_reg->var_off;
14639 			dst_reg->off = ptr_reg->off + smin_val;
14640 			dst_reg->raw = ptr_reg->raw;
14641 			break;
14642 		}
14643 		/* A new variable offset is created.  Note that off_reg->off
14644 		 * == 0, since it's a scalar.
14645 		 * dst_reg gets the pointer type and since some positive
14646 		 * integer value was added to the pointer, give it a new 'id'
14647 		 * if it's a PTR_TO_PACKET.
14648 		 * this creates a new 'base' pointer, off_reg (variable) gets
14649 		 * added into the variable offset, and we copy the fixed offset
14650 		 * from ptr_reg.
14651 		 */
14652 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
14653 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
14654 			dst_reg->smin_value = S64_MIN;
14655 			dst_reg->smax_value = S64_MAX;
14656 		}
14657 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
14658 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
14659 			dst_reg->umin_value = 0;
14660 			dst_reg->umax_value = U64_MAX;
14661 		}
14662 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
14663 		dst_reg->off = ptr_reg->off;
14664 		dst_reg->raw = ptr_reg->raw;
14665 		if (reg_is_pkt_pointer(ptr_reg)) {
14666 			dst_reg->id = ++env->id_gen;
14667 			/* something was added to pkt_ptr, set range to zero */
14668 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14669 		}
14670 		break;
14671 	case BPF_SUB:
14672 		if (dst_reg == off_reg) {
14673 			/* scalar -= pointer.  Creates an unknown scalar */
14674 			verbose(env, "R%d tried to subtract pointer from scalar\n",
14675 				dst);
14676 			return -EACCES;
14677 		}
14678 		/* We don't allow subtraction from FP, because (according to
14679 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
14680 		 * be able to deal with it.
14681 		 */
14682 		if (ptr_reg->type == PTR_TO_STACK) {
14683 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
14684 				dst);
14685 			return -EACCES;
14686 		}
14687 		if (known && (ptr_reg->off - smin_val ==
14688 			      (s64)(s32)(ptr_reg->off - smin_val))) {
14689 			/* pointer -= K.  Subtract it from fixed offset */
14690 			dst_reg->smin_value = smin_ptr;
14691 			dst_reg->smax_value = smax_ptr;
14692 			dst_reg->umin_value = umin_ptr;
14693 			dst_reg->umax_value = umax_ptr;
14694 			dst_reg->var_off = ptr_reg->var_off;
14695 			dst_reg->id = ptr_reg->id;
14696 			dst_reg->off = ptr_reg->off - smin_val;
14697 			dst_reg->raw = ptr_reg->raw;
14698 			break;
14699 		}
14700 		/* A new variable offset is created.  If the subtrahend is known
14701 		 * nonnegative, then any reg->range we had before is still good.
14702 		 */
14703 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
14704 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
14705 			/* Overflow possible, we know nothing */
14706 			dst_reg->smin_value = S64_MIN;
14707 			dst_reg->smax_value = S64_MAX;
14708 		}
14709 		if (umin_ptr < umax_val) {
14710 			/* Overflow possible, we know nothing */
14711 			dst_reg->umin_value = 0;
14712 			dst_reg->umax_value = U64_MAX;
14713 		} else {
14714 			/* Cannot overflow (as long as bounds are consistent) */
14715 			dst_reg->umin_value = umin_ptr - umax_val;
14716 			dst_reg->umax_value = umax_ptr - umin_val;
14717 		}
14718 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
14719 		dst_reg->off = ptr_reg->off;
14720 		dst_reg->raw = ptr_reg->raw;
14721 		if (reg_is_pkt_pointer(ptr_reg)) {
14722 			dst_reg->id = ++env->id_gen;
14723 			/* something was added to pkt_ptr, set range to zero */
14724 			if (smin_val < 0)
14725 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14726 		}
14727 		break;
14728 	case BPF_AND:
14729 	case BPF_OR:
14730 	case BPF_XOR:
14731 		/* bitwise ops on pointers are troublesome, prohibit. */
14732 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
14733 			dst, bpf_alu_string[opcode >> 4]);
14734 		return -EACCES;
14735 	default:
14736 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
14737 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
14738 			dst, bpf_alu_string[opcode >> 4]);
14739 		return -EACCES;
14740 	}
14741 
14742 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
14743 		return -EINVAL;
14744 	reg_bounds_sync(dst_reg);
14745 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
14746 	if (bounds_ret == -EACCES)
14747 		return bounds_ret;
14748 	if (sanitize_needed(opcode)) {
14749 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
14750 				       &info, true);
14751 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
14752 				    && !env->cur_state->speculative
14753 				    && bounds_ret
14754 				    && !ret,
14755 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
14756 			return -EFAULT;
14757 		}
14758 		if (ret < 0)
14759 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14760 	}
14761 
14762 	return 0;
14763 }
14764 
14765 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
14766 				 struct bpf_reg_state *src_reg)
14767 {
14768 	s32 *dst_smin = &dst_reg->s32_min_value;
14769 	s32 *dst_smax = &dst_reg->s32_max_value;
14770 	u32 *dst_umin = &dst_reg->u32_min_value;
14771 	u32 *dst_umax = &dst_reg->u32_max_value;
14772 	u32 umin_val = src_reg->u32_min_value;
14773 	u32 umax_val = src_reg->u32_max_value;
14774 	bool min_overflow, max_overflow;
14775 
14776 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
14777 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
14778 		*dst_smin = S32_MIN;
14779 		*dst_smax = S32_MAX;
14780 	}
14781 
14782 	/* If either all additions overflow or no additions overflow, then
14783 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14784 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
14785 	 * the output bounds to unbounded.
14786 	 */
14787 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14788 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14789 
14790 	if (!min_overflow && max_overflow) {
14791 		*dst_umin = 0;
14792 		*dst_umax = U32_MAX;
14793 	}
14794 }
14795 
14796 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
14797 			       struct bpf_reg_state *src_reg)
14798 {
14799 	s64 *dst_smin = &dst_reg->smin_value;
14800 	s64 *dst_smax = &dst_reg->smax_value;
14801 	u64 *dst_umin = &dst_reg->umin_value;
14802 	u64 *dst_umax = &dst_reg->umax_value;
14803 	u64 umin_val = src_reg->umin_value;
14804 	u64 umax_val = src_reg->umax_value;
14805 	bool min_overflow, max_overflow;
14806 
14807 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
14808 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
14809 		*dst_smin = S64_MIN;
14810 		*dst_smax = S64_MAX;
14811 	}
14812 
14813 	/* If either all additions overflow or no additions overflow, then
14814 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14815 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
14816 	 * the output bounds to unbounded.
14817 	 */
14818 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14819 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14820 
14821 	if (!min_overflow && max_overflow) {
14822 		*dst_umin = 0;
14823 		*dst_umax = U64_MAX;
14824 	}
14825 }
14826 
14827 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
14828 				 struct bpf_reg_state *src_reg)
14829 {
14830 	s32 *dst_smin = &dst_reg->s32_min_value;
14831 	s32 *dst_smax = &dst_reg->s32_max_value;
14832 	u32 *dst_umin = &dst_reg->u32_min_value;
14833 	u32 *dst_umax = &dst_reg->u32_max_value;
14834 	u32 umin_val = src_reg->u32_min_value;
14835 	u32 umax_val = src_reg->u32_max_value;
14836 	bool min_underflow, max_underflow;
14837 
14838 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
14839 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
14840 		/* Overflow possible, we know nothing */
14841 		*dst_smin = S32_MIN;
14842 		*dst_smax = S32_MAX;
14843 	}
14844 
14845 	/* If either all subtractions underflow or no subtractions
14846 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
14847 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
14848 	 * underflow), set the output bounds to unbounded.
14849 	 */
14850 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
14851 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
14852 
14853 	if (min_underflow && !max_underflow) {
14854 		*dst_umin = 0;
14855 		*dst_umax = U32_MAX;
14856 	}
14857 }
14858 
14859 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
14860 			       struct bpf_reg_state *src_reg)
14861 {
14862 	s64 *dst_smin = &dst_reg->smin_value;
14863 	s64 *dst_smax = &dst_reg->smax_value;
14864 	u64 *dst_umin = &dst_reg->umin_value;
14865 	u64 *dst_umax = &dst_reg->umax_value;
14866 	u64 umin_val = src_reg->umin_value;
14867 	u64 umax_val = src_reg->umax_value;
14868 	bool min_underflow, max_underflow;
14869 
14870 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
14871 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
14872 		/* Overflow possible, we know nothing */
14873 		*dst_smin = S64_MIN;
14874 		*dst_smax = S64_MAX;
14875 	}
14876 
14877 	/* If either all subtractions underflow or no subtractions
14878 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
14879 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
14880 	 * underflow), set the output bounds to unbounded.
14881 	 */
14882 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
14883 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
14884 
14885 	if (min_underflow && !max_underflow) {
14886 		*dst_umin = 0;
14887 		*dst_umax = U64_MAX;
14888 	}
14889 }
14890 
14891 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
14892 				 struct bpf_reg_state *src_reg)
14893 {
14894 	s32 *dst_smin = &dst_reg->s32_min_value;
14895 	s32 *dst_smax = &dst_reg->s32_max_value;
14896 	u32 *dst_umin = &dst_reg->u32_min_value;
14897 	u32 *dst_umax = &dst_reg->u32_max_value;
14898 	s32 tmp_prod[4];
14899 
14900 	if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) ||
14901 	    check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) {
14902 		/* Overflow possible, we know nothing */
14903 		*dst_umin = 0;
14904 		*dst_umax = U32_MAX;
14905 	}
14906 	if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) ||
14907 	    check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) ||
14908 	    check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) ||
14909 	    check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) {
14910 		/* Overflow possible, we know nothing */
14911 		*dst_smin = S32_MIN;
14912 		*dst_smax = S32_MAX;
14913 	} else {
14914 		*dst_smin = min_array(tmp_prod, 4);
14915 		*dst_smax = max_array(tmp_prod, 4);
14916 	}
14917 }
14918 
14919 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
14920 			       struct bpf_reg_state *src_reg)
14921 {
14922 	s64 *dst_smin = &dst_reg->smin_value;
14923 	s64 *dst_smax = &dst_reg->smax_value;
14924 	u64 *dst_umin = &dst_reg->umin_value;
14925 	u64 *dst_umax = &dst_reg->umax_value;
14926 	s64 tmp_prod[4];
14927 
14928 	if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) ||
14929 	    check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) {
14930 		/* Overflow possible, we know nothing */
14931 		*dst_umin = 0;
14932 		*dst_umax = U64_MAX;
14933 	}
14934 	if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) ||
14935 	    check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) ||
14936 	    check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) ||
14937 	    check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) {
14938 		/* Overflow possible, we know nothing */
14939 		*dst_smin = S64_MIN;
14940 		*dst_smax = S64_MAX;
14941 	} else {
14942 		*dst_smin = min_array(tmp_prod, 4);
14943 		*dst_smax = max_array(tmp_prod, 4);
14944 	}
14945 }
14946 
14947 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
14948 				 struct bpf_reg_state *src_reg)
14949 {
14950 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14951 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14952 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14953 	u32 umax_val = src_reg->u32_max_value;
14954 
14955 	if (src_known && dst_known) {
14956 		__mark_reg32_known(dst_reg, var32_off.value);
14957 		return;
14958 	}
14959 
14960 	/* We get our minimum from the var_off, since that's inherently
14961 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14962 	 */
14963 	dst_reg->u32_min_value = var32_off.value;
14964 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
14965 
14966 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14967 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14968 	 */
14969 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14970 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14971 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14972 	} else {
14973 		dst_reg->s32_min_value = S32_MIN;
14974 		dst_reg->s32_max_value = S32_MAX;
14975 	}
14976 }
14977 
14978 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
14979 			       struct bpf_reg_state *src_reg)
14980 {
14981 	bool src_known = tnum_is_const(src_reg->var_off);
14982 	bool dst_known = tnum_is_const(dst_reg->var_off);
14983 	u64 umax_val = src_reg->umax_value;
14984 
14985 	if (src_known && dst_known) {
14986 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14987 		return;
14988 	}
14989 
14990 	/* We get our minimum from the var_off, since that's inherently
14991 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14992 	 */
14993 	dst_reg->umin_value = dst_reg->var_off.value;
14994 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
14995 
14996 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14997 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14998 	 */
14999 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15000 		dst_reg->smin_value = dst_reg->umin_value;
15001 		dst_reg->smax_value = dst_reg->umax_value;
15002 	} else {
15003 		dst_reg->smin_value = S64_MIN;
15004 		dst_reg->smax_value = S64_MAX;
15005 	}
15006 	/* We may learn something more from the var_off */
15007 	__update_reg_bounds(dst_reg);
15008 }
15009 
15010 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
15011 				struct bpf_reg_state *src_reg)
15012 {
15013 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15014 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15015 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15016 	u32 umin_val = src_reg->u32_min_value;
15017 
15018 	if (src_known && dst_known) {
15019 		__mark_reg32_known(dst_reg, var32_off.value);
15020 		return;
15021 	}
15022 
15023 	/* We get our maximum from the var_off, and our minimum is the
15024 	 * maximum of the operands' minima
15025 	 */
15026 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
15027 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15028 
15029 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15030 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15031 	 */
15032 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15033 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15034 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15035 	} else {
15036 		dst_reg->s32_min_value = S32_MIN;
15037 		dst_reg->s32_max_value = S32_MAX;
15038 	}
15039 }
15040 
15041 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
15042 			      struct bpf_reg_state *src_reg)
15043 {
15044 	bool src_known = tnum_is_const(src_reg->var_off);
15045 	bool dst_known = tnum_is_const(dst_reg->var_off);
15046 	u64 umin_val = src_reg->umin_value;
15047 
15048 	if (src_known && dst_known) {
15049 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15050 		return;
15051 	}
15052 
15053 	/* We get our maximum from the var_off, and our minimum is the
15054 	 * maximum of the operands' minima
15055 	 */
15056 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
15057 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15058 
15059 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15060 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15061 	 */
15062 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15063 		dst_reg->smin_value = dst_reg->umin_value;
15064 		dst_reg->smax_value = dst_reg->umax_value;
15065 	} else {
15066 		dst_reg->smin_value = S64_MIN;
15067 		dst_reg->smax_value = S64_MAX;
15068 	}
15069 	/* We may learn something more from the var_off */
15070 	__update_reg_bounds(dst_reg);
15071 }
15072 
15073 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
15074 				 struct bpf_reg_state *src_reg)
15075 {
15076 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15077 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15078 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15079 
15080 	if (src_known && dst_known) {
15081 		__mark_reg32_known(dst_reg, var32_off.value);
15082 		return;
15083 	}
15084 
15085 	/* We get both minimum and maximum from the var32_off. */
15086 	dst_reg->u32_min_value = var32_off.value;
15087 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15088 
15089 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15090 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15091 	 */
15092 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15093 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15094 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15095 	} else {
15096 		dst_reg->s32_min_value = S32_MIN;
15097 		dst_reg->s32_max_value = S32_MAX;
15098 	}
15099 }
15100 
15101 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
15102 			       struct bpf_reg_state *src_reg)
15103 {
15104 	bool src_known = tnum_is_const(src_reg->var_off);
15105 	bool dst_known = tnum_is_const(dst_reg->var_off);
15106 
15107 	if (src_known && dst_known) {
15108 		/* dst_reg->var_off.value has been updated earlier */
15109 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15110 		return;
15111 	}
15112 
15113 	/* We get both minimum and maximum from the var_off. */
15114 	dst_reg->umin_value = dst_reg->var_off.value;
15115 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15116 
15117 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15118 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15119 	 */
15120 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15121 		dst_reg->smin_value = dst_reg->umin_value;
15122 		dst_reg->smax_value = dst_reg->umax_value;
15123 	} else {
15124 		dst_reg->smin_value = S64_MIN;
15125 		dst_reg->smax_value = S64_MAX;
15126 	}
15127 
15128 	__update_reg_bounds(dst_reg);
15129 }
15130 
15131 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15132 				   u64 umin_val, u64 umax_val)
15133 {
15134 	/* We lose all sign bit information (except what we can pick
15135 	 * up from var_off)
15136 	 */
15137 	dst_reg->s32_min_value = S32_MIN;
15138 	dst_reg->s32_max_value = S32_MAX;
15139 	/* If we might shift our top bit out, then we know nothing */
15140 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
15141 		dst_reg->u32_min_value = 0;
15142 		dst_reg->u32_max_value = U32_MAX;
15143 	} else {
15144 		dst_reg->u32_min_value <<= umin_val;
15145 		dst_reg->u32_max_value <<= umax_val;
15146 	}
15147 }
15148 
15149 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15150 				 struct bpf_reg_state *src_reg)
15151 {
15152 	u32 umax_val = src_reg->u32_max_value;
15153 	u32 umin_val = src_reg->u32_min_value;
15154 	/* u32 alu operation will zext upper bits */
15155 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15156 
15157 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15158 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
15159 	/* Not required but being careful mark reg64 bounds as unknown so
15160 	 * that we are forced to pick them up from tnum and zext later and
15161 	 * if some path skips this step we are still safe.
15162 	 */
15163 	__mark_reg64_unbounded(dst_reg);
15164 	__update_reg32_bounds(dst_reg);
15165 }
15166 
15167 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
15168 				   u64 umin_val, u64 umax_val)
15169 {
15170 	/* Special case <<32 because it is a common compiler pattern to sign
15171 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
15172 	 * positive we know this shift will also be positive so we can track
15173 	 * bounds correctly. Otherwise we lose all sign bit information except
15174 	 * what we can pick up from var_off. Perhaps we can generalize this
15175 	 * later to shifts of any length.
15176 	 */
15177 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
15178 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
15179 	else
15180 		dst_reg->smax_value = S64_MAX;
15181 
15182 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
15183 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
15184 	else
15185 		dst_reg->smin_value = S64_MIN;
15186 
15187 	/* If we might shift our top bit out, then we know nothing */
15188 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
15189 		dst_reg->umin_value = 0;
15190 		dst_reg->umax_value = U64_MAX;
15191 	} else {
15192 		dst_reg->umin_value <<= umin_val;
15193 		dst_reg->umax_value <<= umax_val;
15194 	}
15195 }
15196 
15197 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
15198 			       struct bpf_reg_state *src_reg)
15199 {
15200 	u64 umax_val = src_reg->umax_value;
15201 	u64 umin_val = src_reg->umin_value;
15202 
15203 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
15204 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
15205 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15206 
15207 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
15208 	/* We may learn something more from the var_off */
15209 	__update_reg_bounds(dst_reg);
15210 }
15211 
15212 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
15213 				 struct bpf_reg_state *src_reg)
15214 {
15215 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15216 	u32 umax_val = src_reg->u32_max_value;
15217 	u32 umin_val = src_reg->u32_min_value;
15218 
15219 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15220 	 * be negative, then either:
15221 	 * 1) src_reg might be zero, so the sign bit of the result is
15222 	 *    unknown, so we lose our signed bounds
15223 	 * 2) it's known negative, thus the unsigned bounds capture the
15224 	 *    signed bounds
15225 	 * 3) the signed bounds cross zero, so they tell us nothing
15226 	 *    about the result
15227 	 * If the value in dst_reg is known nonnegative, then again the
15228 	 * unsigned bounds capture the signed bounds.
15229 	 * Thus, in all cases it suffices to blow away our signed bounds
15230 	 * and rely on inferring new ones from the unsigned bounds and
15231 	 * var_off of the result.
15232 	 */
15233 	dst_reg->s32_min_value = S32_MIN;
15234 	dst_reg->s32_max_value = S32_MAX;
15235 
15236 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
15237 	dst_reg->u32_min_value >>= umax_val;
15238 	dst_reg->u32_max_value >>= umin_val;
15239 
15240 	__mark_reg64_unbounded(dst_reg);
15241 	__update_reg32_bounds(dst_reg);
15242 }
15243 
15244 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
15245 			       struct bpf_reg_state *src_reg)
15246 {
15247 	u64 umax_val = src_reg->umax_value;
15248 	u64 umin_val = src_reg->umin_value;
15249 
15250 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15251 	 * be negative, then either:
15252 	 * 1) src_reg might be zero, so the sign bit of the result is
15253 	 *    unknown, so we lose our signed bounds
15254 	 * 2) it's known negative, thus the unsigned bounds capture the
15255 	 *    signed bounds
15256 	 * 3) the signed bounds cross zero, so they tell us nothing
15257 	 *    about the result
15258 	 * If the value in dst_reg is known nonnegative, then again the
15259 	 * unsigned bounds capture the signed bounds.
15260 	 * Thus, in all cases it suffices to blow away our signed bounds
15261 	 * and rely on inferring new ones from the unsigned bounds and
15262 	 * var_off of the result.
15263 	 */
15264 	dst_reg->smin_value = S64_MIN;
15265 	dst_reg->smax_value = S64_MAX;
15266 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
15267 	dst_reg->umin_value >>= umax_val;
15268 	dst_reg->umax_value >>= umin_val;
15269 
15270 	/* Its not easy to operate on alu32 bounds here because it depends
15271 	 * on bits being shifted in. Take easy way out and mark unbounded
15272 	 * so we can recalculate later from tnum.
15273 	 */
15274 	__mark_reg32_unbounded(dst_reg);
15275 	__update_reg_bounds(dst_reg);
15276 }
15277 
15278 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
15279 				  struct bpf_reg_state *src_reg)
15280 {
15281 	u64 umin_val = src_reg->u32_min_value;
15282 
15283 	/* Upon reaching here, src_known is true and
15284 	 * umax_val is equal to umin_val.
15285 	 */
15286 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
15287 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
15288 
15289 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
15290 
15291 	/* blow away the dst_reg umin_value/umax_value and rely on
15292 	 * dst_reg var_off to refine the result.
15293 	 */
15294 	dst_reg->u32_min_value = 0;
15295 	dst_reg->u32_max_value = U32_MAX;
15296 
15297 	__mark_reg64_unbounded(dst_reg);
15298 	__update_reg32_bounds(dst_reg);
15299 }
15300 
15301 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
15302 				struct bpf_reg_state *src_reg)
15303 {
15304 	u64 umin_val = src_reg->umin_value;
15305 
15306 	/* Upon reaching here, src_known is true and umax_val is equal
15307 	 * to umin_val.
15308 	 */
15309 	dst_reg->smin_value >>= umin_val;
15310 	dst_reg->smax_value >>= umin_val;
15311 
15312 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
15313 
15314 	/* blow away the dst_reg umin_value/umax_value and rely on
15315 	 * dst_reg var_off to refine the result.
15316 	 */
15317 	dst_reg->umin_value = 0;
15318 	dst_reg->umax_value = U64_MAX;
15319 
15320 	/* Its not easy to operate on alu32 bounds here because it depends
15321 	 * on bits being shifted in from upper 32-bits. Take easy way out
15322 	 * and mark unbounded so we can recalculate later from tnum.
15323 	 */
15324 	__mark_reg32_unbounded(dst_reg);
15325 	__update_reg_bounds(dst_reg);
15326 }
15327 
15328 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
15329 					     const struct bpf_reg_state *src_reg)
15330 {
15331 	bool src_is_const = false;
15332 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
15333 
15334 	if (insn_bitness == 32) {
15335 		if (tnum_subreg_is_const(src_reg->var_off)
15336 		    && src_reg->s32_min_value == src_reg->s32_max_value
15337 		    && src_reg->u32_min_value == src_reg->u32_max_value)
15338 			src_is_const = true;
15339 	} else {
15340 		if (tnum_is_const(src_reg->var_off)
15341 		    && src_reg->smin_value == src_reg->smax_value
15342 		    && src_reg->umin_value == src_reg->umax_value)
15343 			src_is_const = true;
15344 	}
15345 
15346 	switch (BPF_OP(insn->code)) {
15347 	case BPF_ADD:
15348 	case BPF_SUB:
15349 	case BPF_NEG:
15350 	case BPF_AND:
15351 	case BPF_XOR:
15352 	case BPF_OR:
15353 	case BPF_MUL:
15354 		return true;
15355 
15356 	/* Shift operators range is only computable if shift dimension operand
15357 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
15358 	 * includes shifts by a negative number.
15359 	 */
15360 	case BPF_LSH:
15361 	case BPF_RSH:
15362 	case BPF_ARSH:
15363 		return (src_is_const && src_reg->umax_value < insn_bitness);
15364 	default:
15365 		return false;
15366 	}
15367 }
15368 
15369 /* WARNING: This function does calculations on 64-bit values, but the actual
15370  * execution may occur on 32-bit values. Therefore, things like bitshifts
15371  * need extra checks in the 32-bit case.
15372  */
15373 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
15374 				      struct bpf_insn *insn,
15375 				      struct bpf_reg_state *dst_reg,
15376 				      struct bpf_reg_state src_reg)
15377 {
15378 	u8 opcode = BPF_OP(insn->code);
15379 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15380 	int ret;
15381 
15382 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
15383 		__mark_reg_unknown(env, dst_reg);
15384 		return 0;
15385 	}
15386 
15387 	if (sanitize_needed(opcode)) {
15388 		ret = sanitize_val_alu(env, insn);
15389 		if (ret < 0)
15390 			return sanitize_err(env, insn, ret, NULL, NULL);
15391 	}
15392 
15393 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
15394 	 * There are two classes of instructions: The first class we track both
15395 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
15396 	 * greatest amount of precision when alu operations are mixed with jmp32
15397 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
15398 	 * and BPF_OR. This is possible because these ops have fairly easy to
15399 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
15400 	 * See alu32 verifier tests for examples. The second class of
15401 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
15402 	 * with regards to tracking sign/unsigned bounds because the bits may
15403 	 * cross subreg boundaries in the alu64 case. When this happens we mark
15404 	 * the reg unbounded in the subreg bound space and use the resulting
15405 	 * tnum to calculate an approximation of the sign/unsigned bounds.
15406 	 */
15407 	switch (opcode) {
15408 	case BPF_ADD:
15409 		scalar32_min_max_add(dst_reg, &src_reg);
15410 		scalar_min_max_add(dst_reg, &src_reg);
15411 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
15412 		break;
15413 	case BPF_SUB:
15414 		scalar32_min_max_sub(dst_reg, &src_reg);
15415 		scalar_min_max_sub(dst_reg, &src_reg);
15416 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
15417 		break;
15418 	case BPF_NEG:
15419 		env->fake_reg[0] = *dst_reg;
15420 		__mark_reg_known(dst_reg, 0);
15421 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
15422 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
15423 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
15424 		break;
15425 	case BPF_MUL:
15426 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
15427 		scalar32_min_max_mul(dst_reg, &src_reg);
15428 		scalar_min_max_mul(dst_reg, &src_reg);
15429 		break;
15430 	case BPF_AND:
15431 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
15432 		scalar32_min_max_and(dst_reg, &src_reg);
15433 		scalar_min_max_and(dst_reg, &src_reg);
15434 		break;
15435 	case BPF_OR:
15436 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
15437 		scalar32_min_max_or(dst_reg, &src_reg);
15438 		scalar_min_max_or(dst_reg, &src_reg);
15439 		break;
15440 	case BPF_XOR:
15441 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
15442 		scalar32_min_max_xor(dst_reg, &src_reg);
15443 		scalar_min_max_xor(dst_reg, &src_reg);
15444 		break;
15445 	case BPF_LSH:
15446 		if (alu32)
15447 			scalar32_min_max_lsh(dst_reg, &src_reg);
15448 		else
15449 			scalar_min_max_lsh(dst_reg, &src_reg);
15450 		break;
15451 	case BPF_RSH:
15452 		if (alu32)
15453 			scalar32_min_max_rsh(dst_reg, &src_reg);
15454 		else
15455 			scalar_min_max_rsh(dst_reg, &src_reg);
15456 		break;
15457 	case BPF_ARSH:
15458 		if (alu32)
15459 			scalar32_min_max_arsh(dst_reg, &src_reg);
15460 		else
15461 			scalar_min_max_arsh(dst_reg, &src_reg);
15462 		break;
15463 	default:
15464 		break;
15465 	}
15466 
15467 	/* ALU32 ops are zero extended into 64bit register */
15468 	if (alu32)
15469 		zext_32_to_64(dst_reg);
15470 	reg_bounds_sync(dst_reg);
15471 	return 0;
15472 }
15473 
15474 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
15475  * and var_off.
15476  */
15477 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
15478 				   struct bpf_insn *insn)
15479 {
15480 	struct bpf_verifier_state *vstate = env->cur_state;
15481 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15482 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
15483 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
15484 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15485 	u8 opcode = BPF_OP(insn->code);
15486 	int err;
15487 
15488 	dst_reg = &regs[insn->dst_reg];
15489 	src_reg = NULL;
15490 
15491 	if (dst_reg->type == PTR_TO_ARENA) {
15492 		struct bpf_insn_aux_data *aux = cur_aux(env);
15493 
15494 		if (BPF_CLASS(insn->code) == BPF_ALU64)
15495 			/*
15496 			 * 32-bit operations zero upper bits automatically.
15497 			 * 64-bit operations need to be converted to 32.
15498 			 */
15499 			aux->needs_zext = true;
15500 
15501 		/* Any arithmetic operations are allowed on arena pointers */
15502 		return 0;
15503 	}
15504 
15505 	if (dst_reg->type != SCALAR_VALUE)
15506 		ptr_reg = dst_reg;
15507 
15508 	if (BPF_SRC(insn->code) == BPF_X) {
15509 		src_reg = &regs[insn->src_reg];
15510 		if (src_reg->type != SCALAR_VALUE) {
15511 			if (dst_reg->type != SCALAR_VALUE) {
15512 				/* Combining two pointers by any ALU op yields
15513 				 * an arbitrary scalar. Disallow all math except
15514 				 * pointer subtraction
15515 				 */
15516 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
15517 					mark_reg_unknown(env, regs, insn->dst_reg);
15518 					return 0;
15519 				}
15520 				verbose(env, "R%d pointer %s pointer prohibited\n",
15521 					insn->dst_reg,
15522 					bpf_alu_string[opcode >> 4]);
15523 				return -EACCES;
15524 			} else {
15525 				/* scalar += pointer
15526 				 * This is legal, but we have to reverse our
15527 				 * src/dest handling in computing the range
15528 				 */
15529 				err = mark_chain_precision(env, insn->dst_reg);
15530 				if (err)
15531 					return err;
15532 				return adjust_ptr_min_max_vals(env, insn,
15533 							       src_reg, dst_reg);
15534 			}
15535 		} else if (ptr_reg) {
15536 			/* pointer += scalar */
15537 			err = mark_chain_precision(env, insn->src_reg);
15538 			if (err)
15539 				return err;
15540 			return adjust_ptr_min_max_vals(env, insn,
15541 						       dst_reg, src_reg);
15542 		} else if (dst_reg->precise) {
15543 			/* if dst_reg is precise, src_reg should be precise as well */
15544 			err = mark_chain_precision(env, insn->src_reg);
15545 			if (err)
15546 				return err;
15547 		}
15548 	} else {
15549 		/* Pretend the src is a reg with a known value, since we only
15550 		 * need to be able to read from this state.
15551 		 */
15552 		off_reg.type = SCALAR_VALUE;
15553 		__mark_reg_known(&off_reg, insn->imm);
15554 		src_reg = &off_reg;
15555 		if (ptr_reg) /* pointer += K */
15556 			return adjust_ptr_min_max_vals(env, insn,
15557 						       ptr_reg, src_reg);
15558 	}
15559 
15560 	/* Got here implies adding two SCALAR_VALUEs */
15561 	if (WARN_ON_ONCE(ptr_reg)) {
15562 		print_verifier_state(env, vstate, vstate->curframe, true);
15563 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
15564 		return -EFAULT;
15565 	}
15566 	if (WARN_ON(!src_reg)) {
15567 		print_verifier_state(env, vstate, vstate->curframe, true);
15568 		verbose(env, "verifier internal error: no src_reg\n");
15569 		return -EFAULT;
15570 	}
15571 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
15572 	if (err)
15573 		return err;
15574 	/*
15575 	 * Compilers can generate the code
15576 	 * r1 = r2
15577 	 * r1 += 0x1
15578 	 * if r2 < 1000 goto ...
15579 	 * use r1 in memory access
15580 	 * So for 64-bit alu remember constant delta between r2 and r1 and
15581 	 * update r1 after 'if' condition.
15582 	 */
15583 	if (env->bpf_capable &&
15584 	    BPF_OP(insn->code) == BPF_ADD && !alu32 &&
15585 	    dst_reg->id && is_reg_const(src_reg, false)) {
15586 		u64 val = reg_const_value(src_reg, false);
15587 
15588 		if ((dst_reg->id & BPF_ADD_CONST) ||
15589 		    /* prevent overflow in sync_linked_regs() later */
15590 		    val > (u32)S32_MAX) {
15591 			/*
15592 			 * If the register already went through rX += val
15593 			 * we cannot accumulate another val into rx->off.
15594 			 */
15595 			dst_reg->off = 0;
15596 			dst_reg->id = 0;
15597 		} else {
15598 			dst_reg->id |= BPF_ADD_CONST;
15599 			dst_reg->off = val;
15600 		}
15601 	} else {
15602 		/*
15603 		 * Make sure ID is cleared otherwise dst_reg min/max could be
15604 		 * incorrectly propagated into other registers by sync_linked_regs()
15605 		 */
15606 		dst_reg->id = 0;
15607 	}
15608 	return 0;
15609 }
15610 
15611 /* check validity of 32-bit and 64-bit arithmetic operations */
15612 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
15613 {
15614 	struct bpf_reg_state *regs = cur_regs(env);
15615 	u8 opcode = BPF_OP(insn->code);
15616 	int err;
15617 
15618 	if (opcode == BPF_END || opcode == BPF_NEG) {
15619 		if (opcode == BPF_NEG) {
15620 			if (BPF_SRC(insn->code) != BPF_K ||
15621 			    insn->src_reg != BPF_REG_0 ||
15622 			    insn->off != 0 || insn->imm != 0) {
15623 				verbose(env, "BPF_NEG uses reserved fields\n");
15624 				return -EINVAL;
15625 			}
15626 		} else {
15627 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
15628 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
15629 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
15630 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
15631 				verbose(env, "BPF_END uses reserved fields\n");
15632 				return -EINVAL;
15633 			}
15634 		}
15635 
15636 		/* check src operand */
15637 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15638 		if (err)
15639 			return err;
15640 
15641 		if (is_pointer_value(env, insn->dst_reg)) {
15642 			verbose(env, "R%d pointer arithmetic prohibited\n",
15643 				insn->dst_reg);
15644 			return -EACCES;
15645 		}
15646 
15647 		/* check dest operand */
15648 		if (opcode == BPF_NEG) {
15649 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15650 			err = err ?: adjust_scalar_min_max_vals(env, insn,
15651 							 &regs[insn->dst_reg],
15652 							 regs[insn->dst_reg]);
15653 		} else {
15654 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
15655 		}
15656 		if (err)
15657 			return err;
15658 
15659 	} else if (opcode == BPF_MOV) {
15660 
15661 		if (BPF_SRC(insn->code) == BPF_X) {
15662 			if (BPF_CLASS(insn->code) == BPF_ALU) {
15663 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
15664 				    insn->imm) {
15665 					verbose(env, "BPF_MOV uses reserved fields\n");
15666 					return -EINVAL;
15667 				}
15668 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
15669 				if (insn->imm != 1 && insn->imm != 1u << 16) {
15670 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
15671 					return -EINVAL;
15672 				}
15673 				if (!env->prog->aux->arena) {
15674 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
15675 					return -EINVAL;
15676 				}
15677 			} else {
15678 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
15679 				     insn->off != 32) || insn->imm) {
15680 					verbose(env, "BPF_MOV uses reserved fields\n");
15681 					return -EINVAL;
15682 				}
15683 			}
15684 
15685 			/* check src operand */
15686 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15687 			if (err)
15688 				return err;
15689 		} else {
15690 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
15691 				verbose(env, "BPF_MOV uses reserved fields\n");
15692 				return -EINVAL;
15693 			}
15694 		}
15695 
15696 		/* check dest operand, mark as required later */
15697 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15698 		if (err)
15699 			return err;
15700 
15701 		if (BPF_SRC(insn->code) == BPF_X) {
15702 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
15703 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
15704 
15705 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15706 				if (insn->imm) {
15707 					/* off == BPF_ADDR_SPACE_CAST */
15708 					mark_reg_unknown(env, regs, insn->dst_reg);
15709 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
15710 						dst_reg->type = PTR_TO_ARENA;
15711 						/* PTR_TO_ARENA is 32-bit */
15712 						dst_reg->subreg_def = env->insn_idx + 1;
15713 					}
15714 				} else if (insn->off == 0) {
15715 					/* case: R1 = R2
15716 					 * copy register state to dest reg
15717 					 */
15718 					assign_scalar_id_before_mov(env, src_reg);
15719 					copy_register_state(dst_reg, src_reg);
15720 					dst_reg->subreg_def = DEF_NOT_SUBREG;
15721 				} else {
15722 					/* case: R1 = (s8, s16 s32)R2 */
15723 					if (is_pointer_value(env, insn->src_reg)) {
15724 						verbose(env,
15725 							"R%d sign-extension part of pointer\n",
15726 							insn->src_reg);
15727 						return -EACCES;
15728 					} else if (src_reg->type == SCALAR_VALUE) {
15729 						bool no_sext;
15730 
15731 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15732 						if (no_sext)
15733 							assign_scalar_id_before_mov(env, src_reg);
15734 						copy_register_state(dst_reg, src_reg);
15735 						if (!no_sext)
15736 							dst_reg->id = 0;
15737 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
15738 						dst_reg->subreg_def = DEF_NOT_SUBREG;
15739 					} else {
15740 						mark_reg_unknown(env, regs, insn->dst_reg);
15741 					}
15742 				}
15743 			} else {
15744 				/* R1 = (u32) R2 */
15745 				if (is_pointer_value(env, insn->src_reg)) {
15746 					verbose(env,
15747 						"R%d partial copy of pointer\n",
15748 						insn->src_reg);
15749 					return -EACCES;
15750 				} else if (src_reg->type == SCALAR_VALUE) {
15751 					if (insn->off == 0) {
15752 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
15753 
15754 						if (is_src_reg_u32)
15755 							assign_scalar_id_before_mov(env, src_reg);
15756 						copy_register_state(dst_reg, src_reg);
15757 						/* Make sure ID is cleared if src_reg is not in u32
15758 						 * range otherwise dst_reg min/max could be incorrectly
15759 						 * propagated into src_reg by sync_linked_regs()
15760 						 */
15761 						if (!is_src_reg_u32)
15762 							dst_reg->id = 0;
15763 						dst_reg->subreg_def = env->insn_idx + 1;
15764 					} else {
15765 						/* case: W1 = (s8, s16)W2 */
15766 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15767 
15768 						if (no_sext)
15769 							assign_scalar_id_before_mov(env, src_reg);
15770 						copy_register_state(dst_reg, src_reg);
15771 						if (!no_sext)
15772 							dst_reg->id = 0;
15773 						dst_reg->subreg_def = env->insn_idx + 1;
15774 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
15775 					}
15776 				} else {
15777 					mark_reg_unknown(env, regs,
15778 							 insn->dst_reg);
15779 				}
15780 				zext_32_to_64(dst_reg);
15781 				reg_bounds_sync(dst_reg);
15782 			}
15783 		} else {
15784 			/* case: R = imm
15785 			 * remember the value we stored into this reg
15786 			 */
15787 			/* clear any state __mark_reg_known doesn't set */
15788 			mark_reg_unknown(env, regs, insn->dst_reg);
15789 			regs[insn->dst_reg].type = SCALAR_VALUE;
15790 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15791 				__mark_reg_known(regs + insn->dst_reg,
15792 						 insn->imm);
15793 			} else {
15794 				__mark_reg_known(regs + insn->dst_reg,
15795 						 (u32)insn->imm);
15796 			}
15797 		}
15798 
15799 	} else if (opcode > BPF_END) {
15800 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
15801 		return -EINVAL;
15802 
15803 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
15804 
15805 		if (BPF_SRC(insn->code) == BPF_X) {
15806 			if (insn->imm != 0 || insn->off > 1 ||
15807 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15808 				verbose(env, "BPF_ALU uses reserved fields\n");
15809 				return -EINVAL;
15810 			}
15811 			/* check src1 operand */
15812 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15813 			if (err)
15814 				return err;
15815 		} else {
15816 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
15817 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15818 				verbose(env, "BPF_ALU uses reserved fields\n");
15819 				return -EINVAL;
15820 			}
15821 		}
15822 
15823 		/* check src2 operand */
15824 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15825 		if (err)
15826 			return err;
15827 
15828 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
15829 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
15830 			verbose(env, "div by zero\n");
15831 			return -EINVAL;
15832 		}
15833 
15834 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
15835 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
15836 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
15837 
15838 			if (insn->imm < 0 || insn->imm >= size) {
15839 				verbose(env, "invalid shift %d\n", insn->imm);
15840 				return -EINVAL;
15841 			}
15842 		}
15843 
15844 		/* check dest operand */
15845 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15846 		err = err ?: adjust_reg_min_max_vals(env, insn);
15847 		if (err)
15848 			return err;
15849 	}
15850 
15851 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
15852 }
15853 
15854 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
15855 				   struct bpf_reg_state *dst_reg,
15856 				   enum bpf_reg_type type,
15857 				   bool range_right_open)
15858 {
15859 	struct bpf_func_state *state;
15860 	struct bpf_reg_state *reg;
15861 	int new_range;
15862 
15863 	if (dst_reg->off < 0 ||
15864 	    (dst_reg->off == 0 && range_right_open))
15865 		/* This doesn't give us any range */
15866 		return;
15867 
15868 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
15869 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
15870 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
15871 		 * than pkt_end, but that's because it's also less than pkt.
15872 		 */
15873 		return;
15874 
15875 	new_range = dst_reg->off;
15876 	if (range_right_open)
15877 		new_range++;
15878 
15879 	/* Examples for register markings:
15880 	 *
15881 	 * pkt_data in dst register:
15882 	 *
15883 	 *   r2 = r3;
15884 	 *   r2 += 8;
15885 	 *   if (r2 > pkt_end) goto <handle exception>
15886 	 *   <access okay>
15887 	 *
15888 	 *   r2 = r3;
15889 	 *   r2 += 8;
15890 	 *   if (r2 < pkt_end) goto <access okay>
15891 	 *   <handle exception>
15892 	 *
15893 	 *   Where:
15894 	 *     r2 == dst_reg, pkt_end == src_reg
15895 	 *     r2=pkt(id=n,off=8,r=0)
15896 	 *     r3=pkt(id=n,off=0,r=0)
15897 	 *
15898 	 * pkt_data in src register:
15899 	 *
15900 	 *   r2 = r3;
15901 	 *   r2 += 8;
15902 	 *   if (pkt_end >= r2) goto <access okay>
15903 	 *   <handle exception>
15904 	 *
15905 	 *   r2 = r3;
15906 	 *   r2 += 8;
15907 	 *   if (pkt_end <= r2) goto <handle exception>
15908 	 *   <access okay>
15909 	 *
15910 	 *   Where:
15911 	 *     pkt_end == dst_reg, r2 == src_reg
15912 	 *     r2=pkt(id=n,off=8,r=0)
15913 	 *     r3=pkt(id=n,off=0,r=0)
15914 	 *
15915 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
15916 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
15917 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
15918 	 * the check.
15919 	 */
15920 
15921 	/* If our ids match, then we must have the same max_value.  And we
15922 	 * don't care about the other reg's fixed offset, since if it's too big
15923 	 * the range won't allow anything.
15924 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
15925 	 */
15926 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15927 		if (reg->type == type && reg->id == dst_reg->id)
15928 			/* keep the maximum range already checked */
15929 			reg->range = max(reg->range, new_range);
15930 	}));
15931 }
15932 
15933 /*
15934  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
15935  */
15936 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15937 				  u8 opcode, bool is_jmp32)
15938 {
15939 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
15940 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
15941 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
15942 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
15943 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
15944 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
15945 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
15946 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
15947 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
15948 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
15949 
15950 	switch (opcode) {
15951 	case BPF_JEQ:
15952 		/* constants, umin/umax and smin/smax checks would be
15953 		 * redundant in this case because they all should match
15954 		 */
15955 		if (tnum_is_const(t1) && tnum_is_const(t2))
15956 			return t1.value == t2.value;
15957 		if (!tnum_overlap(t1, t2))
15958 			return 0;
15959 		/* non-overlapping ranges */
15960 		if (umin1 > umax2 || umax1 < umin2)
15961 			return 0;
15962 		if (smin1 > smax2 || smax1 < smin2)
15963 			return 0;
15964 		if (!is_jmp32) {
15965 			/* if 64-bit ranges are inconclusive, see if we can
15966 			 * utilize 32-bit subrange knowledge to eliminate
15967 			 * branches that can't be taken a priori
15968 			 */
15969 			if (reg1->u32_min_value > reg2->u32_max_value ||
15970 			    reg1->u32_max_value < reg2->u32_min_value)
15971 				return 0;
15972 			if (reg1->s32_min_value > reg2->s32_max_value ||
15973 			    reg1->s32_max_value < reg2->s32_min_value)
15974 				return 0;
15975 		}
15976 		break;
15977 	case BPF_JNE:
15978 		/* constants, umin/umax and smin/smax checks would be
15979 		 * redundant in this case because they all should match
15980 		 */
15981 		if (tnum_is_const(t1) && tnum_is_const(t2))
15982 			return t1.value != t2.value;
15983 		if (!tnum_overlap(t1, t2))
15984 			return 1;
15985 		/* non-overlapping ranges */
15986 		if (umin1 > umax2 || umax1 < umin2)
15987 			return 1;
15988 		if (smin1 > smax2 || smax1 < smin2)
15989 			return 1;
15990 		if (!is_jmp32) {
15991 			/* if 64-bit ranges are inconclusive, see if we can
15992 			 * utilize 32-bit subrange knowledge to eliminate
15993 			 * branches that can't be taken a priori
15994 			 */
15995 			if (reg1->u32_min_value > reg2->u32_max_value ||
15996 			    reg1->u32_max_value < reg2->u32_min_value)
15997 				return 1;
15998 			if (reg1->s32_min_value > reg2->s32_max_value ||
15999 			    reg1->s32_max_value < reg2->s32_min_value)
16000 				return 1;
16001 		}
16002 		break;
16003 	case BPF_JSET:
16004 		if (!is_reg_const(reg2, is_jmp32)) {
16005 			swap(reg1, reg2);
16006 			swap(t1, t2);
16007 		}
16008 		if (!is_reg_const(reg2, is_jmp32))
16009 			return -1;
16010 		if ((~t1.mask & t1.value) & t2.value)
16011 			return 1;
16012 		if (!((t1.mask | t1.value) & t2.value))
16013 			return 0;
16014 		break;
16015 	case BPF_JGT:
16016 		if (umin1 > umax2)
16017 			return 1;
16018 		else if (umax1 <= umin2)
16019 			return 0;
16020 		break;
16021 	case BPF_JSGT:
16022 		if (smin1 > smax2)
16023 			return 1;
16024 		else if (smax1 <= smin2)
16025 			return 0;
16026 		break;
16027 	case BPF_JLT:
16028 		if (umax1 < umin2)
16029 			return 1;
16030 		else if (umin1 >= umax2)
16031 			return 0;
16032 		break;
16033 	case BPF_JSLT:
16034 		if (smax1 < smin2)
16035 			return 1;
16036 		else if (smin1 >= smax2)
16037 			return 0;
16038 		break;
16039 	case BPF_JGE:
16040 		if (umin1 >= umax2)
16041 			return 1;
16042 		else if (umax1 < umin2)
16043 			return 0;
16044 		break;
16045 	case BPF_JSGE:
16046 		if (smin1 >= smax2)
16047 			return 1;
16048 		else if (smax1 < smin2)
16049 			return 0;
16050 		break;
16051 	case BPF_JLE:
16052 		if (umax1 <= umin2)
16053 			return 1;
16054 		else if (umin1 > umax2)
16055 			return 0;
16056 		break;
16057 	case BPF_JSLE:
16058 		if (smax1 <= smin2)
16059 			return 1;
16060 		else if (smin1 > smax2)
16061 			return 0;
16062 		break;
16063 	}
16064 
16065 	return -1;
16066 }
16067 
16068 static int flip_opcode(u32 opcode)
16069 {
16070 	/* How can we transform "a <op> b" into "b <op> a"? */
16071 	static const u8 opcode_flip[16] = {
16072 		/* these stay the same */
16073 		[BPF_JEQ  >> 4] = BPF_JEQ,
16074 		[BPF_JNE  >> 4] = BPF_JNE,
16075 		[BPF_JSET >> 4] = BPF_JSET,
16076 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
16077 		[BPF_JGE  >> 4] = BPF_JLE,
16078 		[BPF_JGT  >> 4] = BPF_JLT,
16079 		[BPF_JLE  >> 4] = BPF_JGE,
16080 		[BPF_JLT  >> 4] = BPF_JGT,
16081 		[BPF_JSGE >> 4] = BPF_JSLE,
16082 		[BPF_JSGT >> 4] = BPF_JSLT,
16083 		[BPF_JSLE >> 4] = BPF_JSGE,
16084 		[BPF_JSLT >> 4] = BPF_JSGT
16085 	};
16086 	return opcode_flip[opcode >> 4];
16087 }
16088 
16089 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
16090 				   struct bpf_reg_state *src_reg,
16091 				   u8 opcode)
16092 {
16093 	struct bpf_reg_state *pkt;
16094 
16095 	if (src_reg->type == PTR_TO_PACKET_END) {
16096 		pkt = dst_reg;
16097 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
16098 		pkt = src_reg;
16099 		opcode = flip_opcode(opcode);
16100 	} else {
16101 		return -1;
16102 	}
16103 
16104 	if (pkt->range >= 0)
16105 		return -1;
16106 
16107 	switch (opcode) {
16108 	case BPF_JLE:
16109 		/* pkt <= pkt_end */
16110 		fallthrough;
16111 	case BPF_JGT:
16112 		/* pkt > pkt_end */
16113 		if (pkt->range == BEYOND_PKT_END)
16114 			/* pkt has at last one extra byte beyond pkt_end */
16115 			return opcode == BPF_JGT;
16116 		break;
16117 	case BPF_JLT:
16118 		/* pkt < pkt_end */
16119 		fallthrough;
16120 	case BPF_JGE:
16121 		/* pkt >= pkt_end */
16122 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
16123 			return opcode == BPF_JGE;
16124 		break;
16125 	}
16126 	return -1;
16127 }
16128 
16129 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
16130  * and return:
16131  *  1 - branch will be taken and "goto target" will be executed
16132  *  0 - branch will not be taken and fall-through to next insn
16133  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
16134  *      range [0,10]
16135  */
16136 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16137 			   u8 opcode, bool is_jmp32)
16138 {
16139 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
16140 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
16141 
16142 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
16143 		u64 val;
16144 
16145 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
16146 		if (!is_reg_const(reg2, is_jmp32)) {
16147 			opcode = flip_opcode(opcode);
16148 			swap(reg1, reg2);
16149 		}
16150 		/* and ensure that reg2 is a constant */
16151 		if (!is_reg_const(reg2, is_jmp32))
16152 			return -1;
16153 
16154 		if (!reg_not_null(reg1))
16155 			return -1;
16156 
16157 		/* If pointer is valid tests against zero will fail so we can
16158 		 * use this to direct branch taken.
16159 		 */
16160 		val = reg_const_value(reg2, is_jmp32);
16161 		if (val != 0)
16162 			return -1;
16163 
16164 		switch (opcode) {
16165 		case BPF_JEQ:
16166 			return 0;
16167 		case BPF_JNE:
16168 			return 1;
16169 		default:
16170 			return -1;
16171 		}
16172 	}
16173 
16174 	/* now deal with two scalars, but not necessarily constants */
16175 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
16176 }
16177 
16178 /* Opcode that corresponds to a *false* branch condition.
16179  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
16180  */
16181 static u8 rev_opcode(u8 opcode)
16182 {
16183 	switch (opcode) {
16184 	case BPF_JEQ:		return BPF_JNE;
16185 	case BPF_JNE:		return BPF_JEQ;
16186 	/* JSET doesn't have it's reverse opcode in BPF, so add
16187 	 * BPF_X flag to denote the reverse of that operation
16188 	 */
16189 	case BPF_JSET:		return BPF_JSET | BPF_X;
16190 	case BPF_JSET | BPF_X:	return BPF_JSET;
16191 	case BPF_JGE:		return BPF_JLT;
16192 	case BPF_JGT:		return BPF_JLE;
16193 	case BPF_JLE:		return BPF_JGT;
16194 	case BPF_JLT:		return BPF_JGE;
16195 	case BPF_JSGE:		return BPF_JSLT;
16196 	case BPF_JSGT:		return BPF_JSLE;
16197 	case BPF_JSLE:		return BPF_JSGT;
16198 	case BPF_JSLT:		return BPF_JSGE;
16199 	default:		return 0;
16200 	}
16201 }
16202 
16203 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
16204 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16205 				u8 opcode, bool is_jmp32)
16206 {
16207 	struct tnum t;
16208 	u64 val;
16209 
16210 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
16211 	switch (opcode) {
16212 	case BPF_JGE:
16213 	case BPF_JGT:
16214 	case BPF_JSGE:
16215 	case BPF_JSGT:
16216 		opcode = flip_opcode(opcode);
16217 		swap(reg1, reg2);
16218 		break;
16219 	default:
16220 		break;
16221 	}
16222 
16223 	switch (opcode) {
16224 	case BPF_JEQ:
16225 		if (is_jmp32) {
16226 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16227 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16228 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16229 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16230 			reg2->u32_min_value = reg1->u32_min_value;
16231 			reg2->u32_max_value = reg1->u32_max_value;
16232 			reg2->s32_min_value = reg1->s32_min_value;
16233 			reg2->s32_max_value = reg1->s32_max_value;
16234 
16235 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
16236 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16237 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
16238 		} else {
16239 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
16240 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16241 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
16242 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16243 			reg2->umin_value = reg1->umin_value;
16244 			reg2->umax_value = reg1->umax_value;
16245 			reg2->smin_value = reg1->smin_value;
16246 			reg2->smax_value = reg1->smax_value;
16247 
16248 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
16249 			reg2->var_off = reg1->var_off;
16250 		}
16251 		break;
16252 	case BPF_JNE:
16253 		if (!is_reg_const(reg2, is_jmp32))
16254 			swap(reg1, reg2);
16255 		if (!is_reg_const(reg2, is_jmp32))
16256 			break;
16257 
16258 		/* try to recompute the bound of reg1 if reg2 is a const and
16259 		 * is exactly the edge of reg1.
16260 		 */
16261 		val = reg_const_value(reg2, is_jmp32);
16262 		if (is_jmp32) {
16263 			/* u32_min_value is not equal to 0xffffffff at this point,
16264 			 * because otherwise u32_max_value is 0xffffffff as well,
16265 			 * in such a case both reg1 and reg2 would be constants,
16266 			 * jump would be predicted and reg_set_min_max() won't
16267 			 * be called.
16268 			 *
16269 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
16270 			 * below.
16271 			 */
16272 			if (reg1->u32_min_value == (u32)val)
16273 				reg1->u32_min_value++;
16274 			if (reg1->u32_max_value == (u32)val)
16275 				reg1->u32_max_value--;
16276 			if (reg1->s32_min_value == (s32)val)
16277 				reg1->s32_min_value++;
16278 			if (reg1->s32_max_value == (s32)val)
16279 				reg1->s32_max_value--;
16280 		} else {
16281 			if (reg1->umin_value == (u64)val)
16282 				reg1->umin_value++;
16283 			if (reg1->umax_value == (u64)val)
16284 				reg1->umax_value--;
16285 			if (reg1->smin_value == (s64)val)
16286 				reg1->smin_value++;
16287 			if (reg1->smax_value == (s64)val)
16288 				reg1->smax_value--;
16289 		}
16290 		break;
16291 	case BPF_JSET:
16292 		if (!is_reg_const(reg2, is_jmp32))
16293 			swap(reg1, reg2);
16294 		if (!is_reg_const(reg2, is_jmp32))
16295 			break;
16296 		val = reg_const_value(reg2, is_jmp32);
16297 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
16298 		 * requires single bit to learn something useful. E.g., if we
16299 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
16300 		 * are actually set? We can learn something definite only if
16301 		 * it's a single-bit value to begin with.
16302 		 *
16303 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
16304 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
16305 		 * bit 1 is set, which we can readily use in adjustments.
16306 		 */
16307 		if (!is_power_of_2(val))
16308 			break;
16309 		if (is_jmp32) {
16310 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
16311 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16312 		} else {
16313 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
16314 		}
16315 		break;
16316 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
16317 		if (!is_reg_const(reg2, is_jmp32))
16318 			swap(reg1, reg2);
16319 		if (!is_reg_const(reg2, is_jmp32))
16320 			break;
16321 		val = reg_const_value(reg2, is_jmp32);
16322 		/* Forget the ranges before narrowing tnums, to avoid invariant
16323 		 * violations if we're on a dead branch.
16324 		 */
16325 		__mark_reg_unbounded(reg1);
16326 		if (is_jmp32) {
16327 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
16328 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16329 		} else {
16330 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
16331 		}
16332 		break;
16333 	case BPF_JLE:
16334 		if (is_jmp32) {
16335 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16336 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16337 		} else {
16338 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16339 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
16340 		}
16341 		break;
16342 	case BPF_JLT:
16343 		if (is_jmp32) {
16344 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
16345 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
16346 		} else {
16347 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
16348 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
16349 		}
16350 		break;
16351 	case BPF_JSLE:
16352 		if (is_jmp32) {
16353 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16354 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16355 		} else {
16356 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16357 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
16358 		}
16359 		break;
16360 	case BPF_JSLT:
16361 		if (is_jmp32) {
16362 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
16363 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
16364 		} else {
16365 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
16366 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
16367 		}
16368 		break;
16369 	default:
16370 		return;
16371 	}
16372 }
16373 
16374 /* Adjusts the register min/max values in the case that the dst_reg and
16375  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
16376  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
16377  * Technically we can do similar adjustments for pointers to the same object,
16378  * but we don't support that right now.
16379  */
16380 static int reg_set_min_max(struct bpf_verifier_env *env,
16381 			   struct bpf_reg_state *true_reg1,
16382 			   struct bpf_reg_state *true_reg2,
16383 			   struct bpf_reg_state *false_reg1,
16384 			   struct bpf_reg_state *false_reg2,
16385 			   u8 opcode, bool is_jmp32)
16386 {
16387 	int err;
16388 
16389 	/* If either register is a pointer, we can't learn anything about its
16390 	 * variable offset from the compare (unless they were a pointer into
16391 	 * the same object, but we don't bother with that).
16392 	 */
16393 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
16394 		return 0;
16395 
16396 	/* fallthrough (FALSE) branch */
16397 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
16398 	reg_bounds_sync(false_reg1);
16399 	reg_bounds_sync(false_reg2);
16400 
16401 	/* jump (TRUE) branch */
16402 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
16403 	reg_bounds_sync(true_reg1);
16404 	reg_bounds_sync(true_reg2);
16405 
16406 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
16407 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
16408 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
16409 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
16410 	return err;
16411 }
16412 
16413 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
16414 				 struct bpf_reg_state *reg, u32 id,
16415 				 bool is_null)
16416 {
16417 	if (type_may_be_null(reg->type) && reg->id == id &&
16418 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
16419 		/* Old offset (both fixed and variable parts) should have been
16420 		 * known-zero, because we don't allow pointer arithmetic on
16421 		 * pointers that might be NULL. If we see this happening, don't
16422 		 * convert the register.
16423 		 *
16424 		 * But in some cases, some helpers that return local kptrs
16425 		 * advance offset for the returned pointer. In those cases, it
16426 		 * is fine to expect to see reg->off.
16427 		 */
16428 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
16429 			return;
16430 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
16431 		    WARN_ON_ONCE(reg->off))
16432 			return;
16433 
16434 		if (is_null) {
16435 			reg->type = SCALAR_VALUE;
16436 			/* We don't need id and ref_obj_id from this point
16437 			 * onwards anymore, thus we should better reset it,
16438 			 * so that state pruning has chances to take effect.
16439 			 */
16440 			reg->id = 0;
16441 			reg->ref_obj_id = 0;
16442 
16443 			return;
16444 		}
16445 
16446 		mark_ptr_not_null_reg(reg);
16447 
16448 		if (!reg_may_point_to_spin_lock(reg)) {
16449 			/* For not-NULL ptr, reg->ref_obj_id will be reset
16450 			 * in release_reference().
16451 			 *
16452 			 * reg->id is still used by spin_lock ptr. Other
16453 			 * than spin_lock ptr type, reg->id can be reset.
16454 			 */
16455 			reg->id = 0;
16456 		}
16457 	}
16458 }
16459 
16460 /* The logic is similar to find_good_pkt_pointers(), both could eventually
16461  * be folded together at some point.
16462  */
16463 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
16464 				  bool is_null)
16465 {
16466 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
16467 	struct bpf_reg_state *regs = state->regs, *reg;
16468 	u32 ref_obj_id = regs[regno].ref_obj_id;
16469 	u32 id = regs[regno].id;
16470 
16471 	if (ref_obj_id && ref_obj_id == id && is_null)
16472 		/* regs[regno] is in the " == NULL" branch.
16473 		 * No one could have freed the reference state before
16474 		 * doing the NULL check.
16475 		 */
16476 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
16477 
16478 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16479 		mark_ptr_or_null_reg(state, reg, id, is_null);
16480 	}));
16481 }
16482 
16483 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
16484 				   struct bpf_reg_state *dst_reg,
16485 				   struct bpf_reg_state *src_reg,
16486 				   struct bpf_verifier_state *this_branch,
16487 				   struct bpf_verifier_state *other_branch)
16488 {
16489 	if (BPF_SRC(insn->code) != BPF_X)
16490 		return false;
16491 
16492 	/* Pointers are always 64-bit. */
16493 	if (BPF_CLASS(insn->code) == BPF_JMP32)
16494 		return false;
16495 
16496 	switch (BPF_OP(insn->code)) {
16497 	case BPF_JGT:
16498 		if ((dst_reg->type == PTR_TO_PACKET &&
16499 		     src_reg->type == PTR_TO_PACKET_END) ||
16500 		    (dst_reg->type == PTR_TO_PACKET_META &&
16501 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16502 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
16503 			find_good_pkt_pointers(this_branch, dst_reg,
16504 					       dst_reg->type, false);
16505 			mark_pkt_end(other_branch, insn->dst_reg, true);
16506 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16507 			    src_reg->type == PTR_TO_PACKET) ||
16508 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16509 			    src_reg->type == PTR_TO_PACKET_META)) {
16510 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
16511 			find_good_pkt_pointers(other_branch, src_reg,
16512 					       src_reg->type, true);
16513 			mark_pkt_end(this_branch, insn->src_reg, false);
16514 		} else {
16515 			return false;
16516 		}
16517 		break;
16518 	case BPF_JLT:
16519 		if ((dst_reg->type == PTR_TO_PACKET &&
16520 		     src_reg->type == PTR_TO_PACKET_END) ||
16521 		    (dst_reg->type == PTR_TO_PACKET_META &&
16522 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16523 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
16524 			find_good_pkt_pointers(other_branch, dst_reg,
16525 					       dst_reg->type, true);
16526 			mark_pkt_end(this_branch, insn->dst_reg, false);
16527 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16528 			    src_reg->type == PTR_TO_PACKET) ||
16529 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16530 			    src_reg->type == PTR_TO_PACKET_META)) {
16531 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
16532 			find_good_pkt_pointers(this_branch, src_reg,
16533 					       src_reg->type, false);
16534 			mark_pkt_end(other_branch, insn->src_reg, true);
16535 		} else {
16536 			return false;
16537 		}
16538 		break;
16539 	case BPF_JGE:
16540 		if ((dst_reg->type == PTR_TO_PACKET &&
16541 		     src_reg->type == PTR_TO_PACKET_END) ||
16542 		    (dst_reg->type == PTR_TO_PACKET_META &&
16543 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16544 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
16545 			find_good_pkt_pointers(this_branch, dst_reg,
16546 					       dst_reg->type, true);
16547 			mark_pkt_end(other_branch, insn->dst_reg, false);
16548 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16549 			    src_reg->type == PTR_TO_PACKET) ||
16550 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16551 			    src_reg->type == PTR_TO_PACKET_META)) {
16552 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
16553 			find_good_pkt_pointers(other_branch, src_reg,
16554 					       src_reg->type, false);
16555 			mark_pkt_end(this_branch, insn->src_reg, true);
16556 		} else {
16557 			return false;
16558 		}
16559 		break;
16560 	case BPF_JLE:
16561 		if ((dst_reg->type == PTR_TO_PACKET &&
16562 		     src_reg->type == PTR_TO_PACKET_END) ||
16563 		    (dst_reg->type == PTR_TO_PACKET_META &&
16564 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16565 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
16566 			find_good_pkt_pointers(other_branch, dst_reg,
16567 					       dst_reg->type, false);
16568 			mark_pkt_end(this_branch, insn->dst_reg, true);
16569 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16570 			    src_reg->type == PTR_TO_PACKET) ||
16571 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16572 			    src_reg->type == PTR_TO_PACKET_META)) {
16573 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
16574 			find_good_pkt_pointers(this_branch, src_reg,
16575 					       src_reg->type, true);
16576 			mark_pkt_end(other_branch, insn->src_reg, false);
16577 		} else {
16578 			return false;
16579 		}
16580 		break;
16581 	default:
16582 		return false;
16583 	}
16584 
16585 	return true;
16586 }
16587 
16588 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
16589 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
16590 {
16591 	struct linked_reg *e;
16592 
16593 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
16594 		return;
16595 
16596 	e = linked_regs_push(reg_set);
16597 	if (e) {
16598 		e->frameno = frameno;
16599 		e->is_reg = is_reg;
16600 		e->regno = spi_or_reg;
16601 	} else {
16602 		reg->id = 0;
16603 	}
16604 }
16605 
16606 /* For all R being scalar registers or spilled scalar registers
16607  * in verifier state, save R in linked_regs if R->id == id.
16608  * If there are too many Rs sharing same id, reset id for leftover Rs.
16609  */
16610 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
16611 				struct linked_regs *linked_regs)
16612 {
16613 	struct bpf_func_state *func;
16614 	struct bpf_reg_state *reg;
16615 	int i, j;
16616 
16617 	id = id & ~BPF_ADD_CONST;
16618 	for (i = vstate->curframe; i >= 0; i--) {
16619 		func = vstate->frame[i];
16620 		for (j = 0; j < BPF_REG_FP; j++) {
16621 			reg = &func->regs[j];
16622 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
16623 		}
16624 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
16625 			if (!is_spilled_reg(&func->stack[j]))
16626 				continue;
16627 			reg = &func->stack[j].spilled_ptr;
16628 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
16629 		}
16630 	}
16631 }
16632 
16633 /* For all R in linked_regs, copy known_reg range into R
16634  * if R->id == known_reg->id.
16635  */
16636 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
16637 			     struct linked_regs *linked_regs)
16638 {
16639 	struct bpf_reg_state fake_reg;
16640 	struct bpf_reg_state *reg;
16641 	struct linked_reg *e;
16642 	int i;
16643 
16644 	for (i = 0; i < linked_regs->cnt; ++i) {
16645 		e = &linked_regs->entries[i];
16646 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
16647 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
16648 		if (reg->type != SCALAR_VALUE || reg == known_reg)
16649 			continue;
16650 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
16651 			continue;
16652 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
16653 		    reg->off == known_reg->off) {
16654 			s32 saved_subreg_def = reg->subreg_def;
16655 
16656 			copy_register_state(reg, known_reg);
16657 			reg->subreg_def = saved_subreg_def;
16658 		} else {
16659 			s32 saved_subreg_def = reg->subreg_def;
16660 			s32 saved_off = reg->off;
16661 
16662 			fake_reg.type = SCALAR_VALUE;
16663 			__mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
16664 
16665 			/* reg = known_reg; reg += delta */
16666 			copy_register_state(reg, known_reg);
16667 			/*
16668 			 * Must preserve off, id and add_const flag,
16669 			 * otherwise another sync_linked_regs() will be incorrect.
16670 			 */
16671 			reg->off = saved_off;
16672 			reg->subreg_def = saved_subreg_def;
16673 
16674 			scalar32_min_max_add(reg, &fake_reg);
16675 			scalar_min_max_add(reg, &fake_reg);
16676 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
16677 		}
16678 	}
16679 }
16680 
16681 static int check_cond_jmp_op(struct bpf_verifier_env *env,
16682 			     struct bpf_insn *insn, int *insn_idx)
16683 {
16684 	struct bpf_verifier_state *this_branch = env->cur_state;
16685 	struct bpf_verifier_state *other_branch;
16686 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
16687 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
16688 	struct bpf_reg_state *eq_branch_regs;
16689 	struct linked_regs linked_regs = {};
16690 	u8 opcode = BPF_OP(insn->code);
16691 	int insn_flags = 0;
16692 	bool is_jmp32;
16693 	int pred = -1;
16694 	int err;
16695 
16696 	/* Only conditional jumps are expected to reach here. */
16697 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
16698 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
16699 		return -EINVAL;
16700 	}
16701 
16702 	if (opcode == BPF_JCOND) {
16703 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
16704 		int idx = *insn_idx;
16705 
16706 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
16707 		    insn->src_reg != BPF_MAY_GOTO ||
16708 		    insn->dst_reg || insn->imm) {
16709 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
16710 			return -EINVAL;
16711 		}
16712 		prev_st = find_prev_entry(env, cur_st->parent, idx);
16713 
16714 		/* branch out 'fallthrough' insn as a new state to explore */
16715 		queued_st = push_stack(env, idx + 1, idx, false);
16716 		if (!queued_st)
16717 			return -ENOMEM;
16718 
16719 		queued_st->may_goto_depth++;
16720 		if (prev_st)
16721 			widen_imprecise_scalars(env, prev_st, queued_st);
16722 		*insn_idx += insn->off;
16723 		return 0;
16724 	}
16725 
16726 	/* check src2 operand */
16727 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16728 	if (err)
16729 		return err;
16730 
16731 	dst_reg = &regs[insn->dst_reg];
16732 	if (BPF_SRC(insn->code) == BPF_X) {
16733 		if (insn->imm != 0) {
16734 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16735 			return -EINVAL;
16736 		}
16737 
16738 		/* check src1 operand */
16739 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16740 		if (err)
16741 			return err;
16742 
16743 		src_reg = &regs[insn->src_reg];
16744 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
16745 		    is_pointer_value(env, insn->src_reg)) {
16746 			verbose(env, "R%d pointer comparison prohibited\n",
16747 				insn->src_reg);
16748 			return -EACCES;
16749 		}
16750 
16751 		if (src_reg->type == PTR_TO_STACK)
16752 			insn_flags |= INSN_F_SRC_REG_STACK;
16753 		if (dst_reg->type == PTR_TO_STACK)
16754 			insn_flags |= INSN_F_DST_REG_STACK;
16755 	} else {
16756 		if (insn->src_reg != BPF_REG_0) {
16757 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16758 			return -EINVAL;
16759 		}
16760 		src_reg = &env->fake_reg[0];
16761 		memset(src_reg, 0, sizeof(*src_reg));
16762 		src_reg->type = SCALAR_VALUE;
16763 		__mark_reg_known(src_reg, insn->imm);
16764 
16765 		if (dst_reg->type == PTR_TO_STACK)
16766 			insn_flags |= INSN_F_DST_REG_STACK;
16767 	}
16768 
16769 	if (insn_flags) {
16770 		err = push_jmp_history(env, this_branch, insn_flags, 0);
16771 		if (err)
16772 			return err;
16773 	}
16774 
16775 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
16776 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
16777 	if (pred >= 0) {
16778 		/* If we get here with a dst_reg pointer type it is because
16779 		 * above is_branch_taken() special cased the 0 comparison.
16780 		 */
16781 		if (!__is_pointer_value(false, dst_reg))
16782 			err = mark_chain_precision(env, insn->dst_reg);
16783 		if (BPF_SRC(insn->code) == BPF_X && !err &&
16784 		    !__is_pointer_value(false, src_reg))
16785 			err = mark_chain_precision(env, insn->src_reg);
16786 		if (err)
16787 			return err;
16788 	}
16789 
16790 	if (pred == 1) {
16791 		/* Only follow the goto, ignore fall-through. If needed, push
16792 		 * the fall-through branch for simulation under speculative
16793 		 * execution.
16794 		 */
16795 		if (!env->bypass_spec_v1 &&
16796 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
16797 					       *insn_idx))
16798 			return -EFAULT;
16799 		if (env->log.level & BPF_LOG_LEVEL)
16800 			print_insn_state(env, this_branch, this_branch->curframe);
16801 		*insn_idx += insn->off;
16802 		return 0;
16803 	} else if (pred == 0) {
16804 		/* Only follow the fall-through branch, since that's where the
16805 		 * program will go. If needed, push the goto branch for
16806 		 * simulation under speculative execution.
16807 		 */
16808 		if (!env->bypass_spec_v1 &&
16809 		    !sanitize_speculative_path(env, insn,
16810 					       *insn_idx + insn->off + 1,
16811 					       *insn_idx))
16812 			return -EFAULT;
16813 		if (env->log.level & BPF_LOG_LEVEL)
16814 			print_insn_state(env, this_branch, this_branch->curframe);
16815 		return 0;
16816 	}
16817 
16818 	/* Push scalar registers sharing same ID to jump history,
16819 	 * do this before creating 'other_branch', so that both
16820 	 * 'this_branch' and 'other_branch' share this history
16821 	 * if parent state is created.
16822 	 */
16823 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
16824 		collect_linked_regs(this_branch, src_reg->id, &linked_regs);
16825 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
16826 		collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
16827 	if (linked_regs.cnt > 1) {
16828 		err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
16829 		if (err)
16830 			return err;
16831 	}
16832 
16833 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
16834 				  false);
16835 	if (!other_branch)
16836 		return -EFAULT;
16837 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
16838 
16839 	if (BPF_SRC(insn->code) == BPF_X) {
16840 		err = reg_set_min_max(env,
16841 				      &other_branch_regs[insn->dst_reg],
16842 				      &other_branch_regs[insn->src_reg],
16843 				      dst_reg, src_reg, opcode, is_jmp32);
16844 	} else /* BPF_SRC(insn->code) == BPF_K */ {
16845 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
16846 		 * so that these are two different memory locations. The
16847 		 * src_reg is not used beyond here in context of K.
16848 		 */
16849 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
16850 		       sizeof(env->fake_reg[0]));
16851 		err = reg_set_min_max(env,
16852 				      &other_branch_regs[insn->dst_reg],
16853 				      &env->fake_reg[0],
16854 				      dst_reg, &env->fake_reg[1],
16855 				      opcode, is_jmp32);
16856 	}
16857 	if (err)
16858 		return err;
16859 
16860 	if (BPF_SRC(insn->code) == BPF_X &&
16861 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
16862 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
16863 		sync_linked_regs(this_branch, src_reg, &linked_regs);
16864 		sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
16865 	}
16866 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
16867 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
16868 		sync_linked_regs(this_branch, dst_reg, &linked_regs);
16869 		sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
16870 	}
16871 
16872 	/* if one pointer register is compared to another pointer
16873 	 * register check if PTR_MAYBE_NULL could be lifted.
16874 	 * E.g. register A - maybe null
16875 	 *      register B - not null
16876 	 * for JNE A, B, ... - A is not null in the false branch;
16877 	 * for JEQ A, B, ... - A is not null in the true branch.
16878 	 *
16879 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
16880 	 * not need to be null checked by the BPF program, i.e.,
16881 	 * could be null even without PTR_MAYBE_NULL marking, so
16882 	 * only propagate nullness when neither reg is that type.
16883 	 */
16884 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
16885 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
16886 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
16887 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
16888 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
16889 		eq_branch_regs = NULL;
16890 		switch (opcode) {
16891 		case BPF_JEQ:
16892 			eq_branch_regs = other_branch_regs;
16893 			break;
16894 		case BPF_JNE:
16895 			eq_branch_regs = regs;
16896 			break;
16897 		default:
16898 			/* do nothing */
16899 			break;
16900 		}
16901 		if (eq_branch_regs) {
16902 			if (type_may_be_null(src_reg->type))
16903 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
16904 			else
16905 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
16906 		}
16907 	}
16908 
16909 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
16910 	 * NOTE: these optimizations below are related with pointer comparison
16911 	 *       which will never be JMP32.
16912 	 */
16913 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
16914 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
16915 	    type_may_be_null(dst_reg->type)) {
16916 		/* Mark all identical registers in each branch as either
16917 		 * safe or unknown depending R == 0 or R != 0 conditional.
16918 		 */
16919 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
16920 				      opcode == BPF_JNE);
16921 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
16922 				      opcode == BPF_JEQ);
16923 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
16924 					   this_branch, other_branch) &&
16925 		   is_pointer_value(env, insn->dst_reg)) {
16926 		verbose(env, "R%d pointer comparison prohibited\n",
16927 			insn->dst_reg);
16928 		return -EACCES;
16929 	}
16930 	if (env->log.level & BPF_LOG_LEVEL)
16931 		print_insn_state(env, this_branch, this_branch->curframe);
16932 	return 0;
16933 }
16934 
16935 /* verify BPF_LD_IMM64 instruction */
16936 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
16937 {
16938 	struct bpf_insn_aux_data *aux = cur_aux(env);
16939 	struct bpf_reg_state *regs = cur_regs(env);
16940 	struct bpf_reg_state *dst_reg;
16941 	struct bpf_map *map;
16942 	int err;
16943 
16944 	if (BPF_SIZE(insn->code) != BPF_DW) {
16945 		verbose(env, "invalid BPF_LD_IMM insn\n");
16946 		return -EINVAL;
16947 	}
16948 	if (insn->off != 0) {
16949 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
16950 		return -EINVAL;
16951 	}
16952 
16953 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
16954 	if (err)
16955 		return err;
16956 
16957 	dst_reg = &regs[insn->dst_reg];
16958 	if (insn->src_reg == 0) {
16959 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
16960 
16961 		dst_reg->type = SCALAR_VALUE;
16962 		__mark_reg_known(&regs[insn->dst_reg], imm);
16963 		return 0;
16964 	}
16965 
16966 	/* All special src_reg cases are listed below. From this point onwards
16967 	 * we either succeed and assign a corresponding dst_reg->type after
16968 	 * zeroing the offset, or fail and reject the program.
16969 	 */
16970 	mark_reg_known_zero(env, regs, insn->dst_reg);
16971 
16972 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
16973 		dst_reg->type = aux->btf_var.reg_type;
16974 		switch (base_type(dst_reg->type)) {
16975 		case PTR_TO_MEM:
16976 			dst_reg->mem_size = aux->btf_var.mem_size;
16977 			break;
16978 		case PTR_TO_BTF_ID:
16979 			dst_reg->btf = aux->btf_var.btf;
16980 			dst_reg->btf_id = aux->btf_var.btf_id;
16981 			break;
16982 		default:
16983 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
16984 			return -EFAULT;
16985 		}
16986 		return 0;
16987 	}
16988 
16989 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
16990 		struct bpf_prog_aux *aux = env->prog->aux;
16991 		u32 subprogno = find_subprog(env,
16992 					     env->insn_idx + insn->imm + 1);
16993 
16994 		if (!aux->func_info) {
16995 			verbose(env, "missing btf func_info\n");
16996 			return -EINVAL;
16997 		}
16998 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
16999 			verbose(env, "callback function not static\n");
17000 			return -EINVAL;
17001 		}
17002 
17003 		dst_reg->type = PTR_TO_FUNC;
17004 		dst_reg->subprogno = subprogno;
17005 		return 0;
17006 	}
17007 
17008 	map = env->used_maps[aux->map_index];
17009 	dst_reg->map_ptr = map;
17010 
17011 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
17012 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
17013 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
17014 			__mark_reg_unknown(env, dst_reg);
17015 			return 0;
17016 		}
17017 		dst_reg->type = PTR_TO_MAP_VALUE;
17018 		dst_reg->off = aux->map_off;
17019 		WARN_ON_ONCE(map->max_entries != 1);
17020 		/* We want reg->id to be same (0) as map_value is not distinct */
17021 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
17022 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
17023 		dst_reg->type = CONST_PTR_TO_MAP;
17024 	} else {
17025 		verifier_bug(env, "unexpected src reg value for ldimm64");
17026 		return -EFAULT;
17027 	}
17028 
17029 	return 0;
17030 }
17031 
17032 static bool may_access_skb(enum bpf_prog_type type)
17033 {
17034 	switch (type) {
17035 	case BPF_PROG_TYPE_SOCKET_FILTER:
17036 	case BPF_PROG_TYPE_SCHED_CLS:
17037 	case BPF_PROG_TYPE_SCHED_ACT:
17038 		return true;
17039 	default:
17040 		return false;
17041 	}
17042 }
17043 
17044 /* verify safety of LD_ABS|LD_IND instructions:
17045  * - they can only appear in the programs where ctx == skb
17046  * - since they are wrappers of function calls, they scratch R1-R5 registers,
17047  *   preserve R6-R9, and store return value into R0
17048  *
17049  * Implicit input:
17050  *   ctx == skb == R6 == CTX
17051  *
17052  * Explicit input:
17053  *   SRC == any register
17054  *   IMM == 32-bit immediate
17055  *
17056  * Output:
17057  *   R0 - 8/16/32-bit skb data converted to cpu endianness
17058  */
17059 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
17060 {
17061 	struct bpf_reg_state *regs = cur_regs(env);
17062 	static const int ctx_reg = BPF_REG_6;
17063 	u8 mode = BPF_MODE(insn->code);
17064 	int i, err;
17065 
17066 	if (!may_access_skb(resolve_prog_type(env->prog))) {
17067 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
17068 		return -EINVAL;
17069 	}
17070 
17071 	if (!env->ops->gen_ld_abs) {
17072 		verifier_bug(env, "gen_ld_abs is null");
17073 		return -EFAULT;
17074 	}
17075 
17076 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
17077 	    BPF_SIZE(insn->code) == BPF_DW ||
17078 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
17079 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
17080 		return -EINVAL;
17081 	}
17082 
17083 	/* check whether implicit source operand (register R6) is readable */
17084 	err = check_reg_arg(env, ctx_reg, SRC_OP);
17085 	if (err)
17086 		return err;
17087 
17088 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
17089 	 * gen_ld_abs() may terminate the program at runtime, leading to
17090 	 * reference leak.
17091 	 */
17092 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
17093 	if (err)
17094 		return err;
17095 
17096 	if (regs[ctx_reg].type != PTR_TO_CTX) {
17097 		verbose(env,
17098 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
17099 		return -EINVAL;
17100 	}
17101 
17102 	if (mode == BPF_IND) {
17103 		/* check explicit source operand */
17104 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
17105 		if (err)
17106 			return err;
17107 	}
17108 
17109 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
17110 	if (err < 0)
17111 		return err;
17112 
17113 	/* reset caller saved regs to unreadable */
17114 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
17115 		mark_reg_not_init(env, regs, caller_saved[i]);
17116 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
17117 	}
17118 
17119 	/* mark destination R0 register as readable, since it contains
17120 	 * the value fetched from the packet.
17121 	 * Already marked as written above.
17122 	 */
17123 	mark_reg_unknown(env, regs, BPF_REG_0);
17124 	/* ld_abs load up to 32-bit skb data. */
17125 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
17126 	return 0;
17127 }
17128 
17129 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
17130 {
17131 	const char *exit_ctx = "At program exit";
17132 	struct tnum enforce_attach_type_range = tnum_unknown;
17133 	const struct bpf_prog *prog = env->prog;
17134 	struct bpf_reg_state *reg = reg_state(env, regno);
17135 	struct bpf_retval_range range = retval_range(0, 1);
17136 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17137 	int err;
17138 	struct bpf_func_state *frame = env->cur_state->frame[0];
17139 	const bool is_subprog = frame->subprogno;
17140 	bool return_32bit = false;
17141 	const struct btf_type *reg_type, *ret_type = NULL;
17142 
17143 	/* LSM and struct_ops func-ptr's return type could be "void" */
17144 	if (!is_subprog || frame->in_exception_callback_fn) {
17145 		switch (prog_type) {
17146 		case BPF_PROG_TYPE_LSM:
17147 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
17148 				/* See below, can be 0 or 0-1 depending on hook. */
17149 				break;
17150 			if (!prog->aux->attach_func_proto->type)
17151 				return 0;
17152 			break;
17153 		case BPF_PROG_TYPE_STRUCT_OPS:
17154 			if (!prog->aux->attach_func_proto->type)
17155 				return 0;
17156 
17157 			if (frame->in_exception_callback_fn)
17158 				break;
17159 
17160 			/* Allow a struct_ops program to return a referenced kptr if it
17161 			 * matches the operator's return type and is in its unmodified
17162 			 * form. A scalar zero (i.e., a null pointer) is also allowed.
17163 			 */
17164 			reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
17165 			ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
17166 							prog->aux->attach_func_proto->type,
17167 							NULL);
17168 			if (ret_type && ret_type == reg_type && reg->ref_obj_id)
17169 				return __check_ptr_off_reg(env, reg, regno, false);
17170 			break;
17171 		default:
17172 			break;
17173 		}
17174 	}
17175 
17176 	/* eBPF calling convention is such that R0 is used
17177 	 * to return the value from eBPF program.
17178 	 * Make sure that it's readable at this time
17179 	 * of bpf_exit, which means that program wrote
17180 	 * something into it earlier
17181 	 */
17182 	err = check_reg_arg(env, regno, SRC_OP);
17183 	if (err)
17184 		return err;
17185 
17186 	if (is_pointer_value(env, regno)) {
17187 		verbose(env, "R%d leaks addr as return value\n", regno);
17188 		return -EACCES;
17189 	}
17190 
17191 	if (frame->in_async_callback_fn) {
17192 		exit_ctx = "At async callback return";
17193 		range = frame->callback_ret_range;
17194 		goto enforce_retval;
17195 	}
17196 
17197 	if (is_subprog && !frame->in_exception_callback_fn) {
17198 		if (reg->type != SCALAR_VALUE) {
17199 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
17200 				regno, reg_type_str(env, reg->type));
17201 			return -EINVAL;
17202 		}
17203 		return 0;
17204 	}
17205 
17206 	switch (prog_type) {
17207 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
17208 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
17209 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
17210 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
17211 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
17212 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
17213 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
17214 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
17215 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
17216 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
17217 			range = retval_range(1, 1);
17218 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
17219 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
17220 			range = retval_range(0, 3);
17221 		break;
17222 	case BPF_PROG_TYPE_CGROUP_SKB:
17223 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
17224 			range = retval_range(0, 3);
17225 			enforce_attach_type_range = tnum_range(2, 3);
17226 		}
17227 		break;
17228 	case BPF_PROG_TYPE_CGROUP_SOCK:
17229 	case BPF_PROG_TYPE_SOCK_OPS:
17230 	case BPF_PROG_TYPE_CGROUP_DEVICE:
17231 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
17232 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
17233 		break;
17234 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17235 		if (!env->prog->aux->attach_btf_id)
17236 			return 0;
17237 		range = retval_range(0, 0);
17238 		break;
17239 	case BPF_PROG_TYPE_TRACING:
17240 		switch (env->prog->expected_attach_type) {
17241 		case BPF_TRACE_FENTRY:
17242 		case BPF_TRACE_FEXIT:
17243 			range = retval_range(0, 0);
17244 			break;
17245 		case BPF_TRACE_RAW_TP:
17246 		case BPF_MODIFY_RETURN:
17247 			return 0;
17248 		case BPF_TRACE_ITER:
17249 			break;
17250 		default:
17251 			return -ENOTSUPP;
17252 		}
17253 		break;
17254 	case BPF_PROG_TYPE_KPROBE:
17255 		switch (env->prog->expected_attach_type) {
17256 		case BPF_TRACE_KPROBE_SESSION:
17257 		case BPF_TRACE_UPROBE_SESSION:
17258 			range = retval_range(0, 1);
17259 			break;
17260 		default:
17261 			return 0;
17262 		}
17263 		break;
17264 	case BPF_PROG_TYPE_SK_LOOKUP:
17265 		range = retval_range(SK_DROP, SK_PASS);
17266 		break;
17267 
17268 	case BPF_PROG_TYPE_LSM:
17269 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
17270 			/* no range found, any return value is allowed */
17271 			if (!get_func_retval_range(env->prog, &range))
17272 				return 0;
17273 			/* no restricted range, any return value is allowed */
17274 			if (range.minval == S32_MIN && range.maxval == S32_MAX)
17275 				return 0;
17276 			return_32bit = true;
17277 		} else if (!env->prog->aux->attach_func_proto->type) {
17278 			/* Make sure programs that attach to void
17279 			 * hooks don't try to modify return value.
17280 			 */
17281 			range = retval_range(1, 1);
17282 		}
17283 		break;
17284 
17285 	case BPF_PROG_TYPE_NETFILTER:
17286 		range = retval_range(NF_DROP, NF_ACCEPT);
17287 		break;
17288 	case BPF_PROG_TYPE_STRUCT_OPS:
17289 		if (!ret_type)
17290 			return 0;
17291 		range = retval_range(0, 0);
17292 		break;
17293 	case BPF_PROG_TYPE_EXT:
17294 		/* freplace program can return anything as its return value
17295 		 * depends on the to-be-replaced kernel func or bpf program.
17296 		 */
17297 	default:
17298 		return 0;
17299 	}
17300 
17301 enforce_retval:
17302 	if (reg->type != SCALAR_VALUE) {
17303 		verbose(env, "%s the register R%d is not a known value (%s)\n",
17304 			exit_ctx, regno, reg_type_str(env, reg->type));
17305 		return -EINVAL;
17306 	}
17307 
17308 	err = mark_chain_precision(env, regno);
17309 	if (err)
17310 		return err;
17311 
17312 	if (!retval_range_within(range, reg, return_32bit)) {
17313 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
17314 		if (!is_subprog &&
17315 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
17316 		    prog_type == BPF_PROG_TYPE_LSM &&
17317 		    !prog->aux->attach_func_proto->type)
17318 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
17319 		return -EINVAL;
17320 	}
17321 
17322 	if (!tnum_is_unknown(enforce_attach_type_range) &&
17323 	    tnum_in(enforce_attach_type_range, reg->var_off))
17324 		env->prog->enforce_expected_attach_type = 1;
17325 	return 0;
17326 }
17327 
17328 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
17329 {
17330 	struct bpf_subprog_info *subprog;
17331 
17332 	subprog = bpf_find_containing_subprog(env, off);
17333 	subprog->changes_pkt_data = true;
17334 }
17335 
17336 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off)
17337 {
17338 	struct bpf_subprog_info *subprog;
17339 
17340 	subprog = bpf_find_containing_subprog(env, off);
17341 	subprog->might_sleep = true;
17342 }
17343 
17344 /* 't' is an index of a call-site.
17345  * 'w' is a callee entry point.
17346  * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
17347  * Rely on DFS traversal order and absence of recursive calls to guarantee that
17348  * callee's change_pkt_data marks would be correct at that moment.
17349  */
17350 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
17351 {
17352 	struct bpf_subprog_info *caller, *callee;
17353 
17354 	caller = bpf_find_containing_subprog(env, t);
17355 	callee = bpf_find_containing_subprog(env, w);
17356 	caller->changes_pkt_data |= callee->changes_pkt_data;
17357 	caller->might_sleep |= callee->might_sleep;
17358 }
17359 
17360 /* non-recursive DFS pseudo code
17361  * 1  procedure DFS-iterative(G,v):
17362  * 2      label v as discovered
17363  * 3      let S be a stack
17364  * 4      S.push(v)
17365  * 5      while S is not empty
17366  * 6            t <- S.peek()
17367  * 7            if t is what we're looking for:
17368  * 8                return t
17369  * 9            for all edges e in G.adjacentEdges(t) do
17370  * 10               if edge e is already labelled
17371  * 11                   continue with the next edge
17372  * 12               w <- G.adjacentVertex(t,e)
17373  * 13               if vertex w is not discovered and not explored
17374  * 14                   label e as tree-edge
17375  * 15                   label w as discovered
17376  * 16                   S.push(w)
17377  * 17                   continue at 5
17378  * 18               else if vertex w is discovered
17379  * 19                   label e as back-edge
17380  * 20               else
17381  * 21                   // vertex w is explored
17382  * 22                   label e as forward- or cross-edge
17383  * 23           label t as explored
17384  * 24           S.pop()
17385  *
17386  * convention:
17387  * 0x10 - discovered
17388  * 0x11 - discovered and fall-through edge labelled
17389  * 0x12 - discovered and fall-through and branch edges labelled
17390  * 0x20 - explored
17391  */
17392 
17393 enum {
17394 	DISCOVERED = 0x10,
17395 	EXPLORED = 0x20,
17396 	FALLTHROUGH = 1,
17397 	BRANCH = 2,
17398 };
17399 
17400 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
17401 {
17402 	env->insn_aux_data[idx].prune_point = true;
17403 }
17404 
17405 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
17406 {
17407 	return env->insn_aux_data[insn_idx].prune_point;
17408 }
17409 
17410 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
17411 {
17412 	env->insn_aux_data[idx].force_checkpoint = true;
17413 }
17414 
17415 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
17416 {
17417 	return env->insn_aux_data[insn_idx].force_checkpoint;
17418 }
17419 
17420 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
17421 {
17422 	env->insn_aux_data[idx].calls_callback = true;
17423 }
17424 
17425 bool bpf_calls_callback(struct bpf_verifier_env *env, int insn_idx)
17426 {
17427 	return env->insn_aux_data[insn_idx].calls_callback;
17428 }
17429 
17430 enum {
17431 	DONE_EXPLORING = 0,
17432 	KEEP_EXPLORING = 1,
17433 };
17434 
17435 /* t, w, e - match pseudo-code above:
17436  * t - index of current instruction
17437  * w - next instruction
17438  * e - edge
17439  */
17440 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
17441 {
17442 	int *insn_stack = env->cfg.insn_stack;
17443 	int *insn_state = env->cfg.insn_state;
17444 
17445 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
17446 		return DONE_EXPLORING;
17447 
17448 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
17449 		return DONE_EXPLORING;
17450 
17451 	if (w < 0 || w >= env->prog->len) {
17452 		verbose_linfo(env, t, "%d: ", t);
17453 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
17454 		return -EINVAL;
17455 	}
17456 
17457 	if (e == BRANCH) {
17458 		/* mark branch target for state pruning */
17459 		mark_prune_point(env, w);
17460 		mark_jmp_point(env, w);
17461 	}
17462 
17463 	if (insn_state[w] == 0) {
17464 		/* tree-edge */
17465 		insn_state[t] = DISCOVERED | e;
17466 		insn_state[w] = DISCOVERED;
17467 		if (env->cfg.cur_stack >= env->prog->len)
17468 			return -E2BIG;
17469 		insn_stack[env->cfg.cur_stack++] = w;
17470 		return KEEP_EXPLORING;
17471 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
17472 		if (env->bpf_capable)
17473 			return DONE_EXPLORING;
17474 		verbose_linfo(env, t, "%d: ", t);
17475 		verbose_linfo(env, w, "%d: ", w);
17476 		verbose(env, "back-edge from insn %d to %d\n", t, w);
17477 		return -EINVAL;
17478 	} else if (insn_state[w] == EXPLORED) {
17479 		/* forward- or cross-edge */
17480 		insn_state[t] = DISCOVERED | e;
17481 	} else {
17482 		verifier_bug(env, "insn state internal bug");
17483 		return -EFAULT;
17484 	}
17485 	return DONE_EXPLORING;
17486 }
17487 
17488 static int visit_func_call_insn(int t, struct bpf_insn *insns,
17489 				struct bpf_verifier_env *env,
17490 				bool visit_callee)
17491 {
17492 	int ret, insn_sz;
17493 	int w;
17494 
17495 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
17496 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
17497 	if (ret)
17498 		return ret;
17499 
17500 	mark_prune_point(env, t + insn_sz);
17501 	/* when we exit from subprog, we need to record non-linear history */
17502 	mark_jmp_point(env, t + insn_sz);
17503 
17504 	if (visit_callee) {
17505 		w = t + insns[t].imm + 1;
17506 		mark_prune_point(env, t);
17507 		merge_callee_effects(env, t, w);
17508 		ret = push_insn(t, w, BRANCH, env);
17509 	}
17510 	return ret;
17511 }
17512 
17513 /* Bitmask with 1s for all caller saved registers */
17514 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
17515 
17516 /* True if do_misc_fixups() replaces calls to helper number 'imm',
17517  * replacement patch is presumed to follow bpf_fastcall contract
17518  * (see mark_fastcall_pattern_for_call() below).
17519  */
17520 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
17521 {
17522 	switch (imm) {
17523 #ifdef CONFIG_X86_64
17524 	case BPF_FUNC_get_smp_processor_id:
17525 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
17526 #endif
17527 	default:
17528 		return false;
17529 	}
17530 }
17531 
17532 struct call_summary {
17533 	u8 num_params;
17534 	bool is_void;
17535 	bool fastcall;
17536 };
17537 
17538 /* If @call is a kfunc or helper call, fills @cs and returns true,
17539  * otherwise returns false.
17540  */
17541 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
17542 			     struct call_summary *cs)
17543 {
17544 	struct bpf_kfunc_call_arg_meta meta;
17545 	const struct bpf_func_proto *fn;
17546 	int i;
17547 
17548 	if (bpf_helper_call(call)) {
17549 
17550 		if (get_helper_proto(env, call->imm, &fn) < 0)
17551 			/* error would be reported later */
17552 			return false;
17553 		cs->fastcall = fn->allow_fastcall &&
17554 			       (verifier_inlines_helper_call(env, call->imm) ||
17555 				bpf_jit_inlines_helper_call(call->imm));
17556 		cs->is_void = fn->ret_type == RET_VOID;
17557 		cs->num_params = 0;
17558 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
17559 			if (fn->arg_type[i] == ARG_DONTCARE)
17560 				break;
17561 			cs->num_params++;
17562 		}
17563 		return true;
17564 	}
17565 
17566 	if (bpf_pseudo_kfunc_call(call)) {
17567 		int err;
17568 
17569 		err = fetch_kfunc_meta(env, call, &meta, NULL);
17570 		if (err < 0)
17571 			/* error would be reported later */
17572 			return false;
17573 		cs->num_params = btf_type_vlen(meta.func_proto);
17574 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
17575 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
17576 		return true;
17577 	}
17578 
17579 	return false;
17580 }
17581 
17582 /* LLVM define a bpf_fastcall function attribute.
17583  * This attribute means that function scratches only some of
17584  * the caller saved registers defined by ABI.
17585  * For BPF the set of such registers could be defined as follows:
17586  * - R0 is scratched only if function is non-void;
17587  * - R1-R5 are scratched only if corresponding parameter type is defined
17588  *   in the function prototype.
17589  *
17590  * The contract between kernel and clang allows to simultaneously use
17591  * such functions and maintain backwards compatibility with old
17592  * kernels that don't understand bpf_fastcall calls:
17593  *
17594  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
17595  *   registers are not scratched by the call;
17596  *
17597  * - as a post-processing step, clang visits each bpf_fastcall call and adds
17598  *   spill/fill for every live r0-r5;
17599  *
17600  * - stack offsets used for the spill/fill are allocated as lowest
17601  *   stack offsets in whole function and are not used for any other
17602  *   purposes;
17603  *
17604  * - when kernel loads a program, it looks for such patterns
17605  *   (bpf_fastcall function surrounded by spills/fills) and checks if
17606  *   spill/fill stack offsets are used exclusively in fastcall patterns;
17607  *
17608  * - if so, and if verifier or current JIT inlines the call to the
17609  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
17610  *   spill/fill pairs;
17611  *
17612  * - when old kernel loads a program, presence of spill/fill pairs
17613  *   keeps BPF program valid, albeit slightly less efficient.
17614  *
17615  * For example:
17616  *
17617  *   r1 = 1;
17618  *   r2 = 2;
17619  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17620  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
17621  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17622  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
17623  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
17624  *   r0 = r1;                            exit;
17625  *   r0 += r2;
17626  *   exit;
17627  *
17628  * The purpose of mark_fastcall_pattern_for_call is to:
17629  * - look for such patterns;
17630  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
17631  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
17632  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
17633  *   at which bpf_fastcall spill/fill stack slots start;
17634  * - update env->subprog_info[*]->keep_fastcall_stack.
17635  *
17636  * The .fastcall_pattern and .fastcall_stack_off are used by
17637  * check_fastcall_stack_contract() to check if every stack access to
17638  * fastcall spill/fill stack slot originates from spill/fill
17639  * instructions, members of fastcall patterns.
17640  *
17641  * If such condition holds true for a subprogram, fastcall patterns could
17642  * be rewritten by remove_fastcall_spills_fills().
17643  * Otherwise bpf_fastcall patterns are not changed in the subprogram
17644  * (code, presumably, generated by an older clang version).
17645  *
17646  * For example, it is *not* safe to remove spill/fill below:
17647  *
17648  *   r1 = 1;
17649  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17650  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17651  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
17652  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
17653  *   r0 += r1;                           exit;
17654  *   exit;
17655  */
17656 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
17657 					   struct bpf_subprog_info *subprog,
17658 					   int insn_idx, s16 lowest_off)
17659 {
17660 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
17661 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
17662 	u32 clobbered_regs_mask;
17663 	struct call_summary cs;
17664 	u32 expected_regs_mask;
17665 	s16 off;
17666 	int i;
17667 
17668 	if (!get_call_summary(env, call, &cs))
17669 		return;
17670 
17671 	/* A bitmask specifying which caller saved registers are clobbered
17672 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
17673 	 * bpf_fastcall contract:
17674 	 * - includes R0 if function is non-void;
17675 	 * - includes R1-R5 if corresponding parameter has is described
17676 	 *   in the function prototype.
17677 	 */
17678 	clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
17679 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
17680 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
17681 
17682 	/* match pairs of form:
17683 	 *
17684 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
17685 	 * ...
17686 	 * call %[to_be_inlined]
17687 	 * ...
17688 	 * rX = *(u64 *)(r10 - Y)
17689 	 */
17690 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
17691 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
17692 			break;
17693 		stx = &insns[insn_idx - i];
17694 		ldx = &insns[insn_idx + i];
17695 		/* must be a stack spill/fill pair */
17696 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17697 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
17698 		    stx->dst_reg != BPF_REG_10 ||
17699 		    ldx->src_reg != BPF_REG_10)
17700 			break;
17701 		/* must be a spill/fill for the same reg */
17702 		if (stx->src_reg != ldx->dst_reg)
17703 			break;
17704 		/* must be one of the previously unseen registers */
17705 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
17706 			break;
17707 		/* must be a spill/fill for the same expected offset,
17708 		 * no need to check offset alignment, BPF_DW stack access
17709 		 * is always 8-byte aligned.
17710 		 */
17711 		if (stx->off != off || ldx->off != off)
17712 			break;
17713 		expected_regs_mask &= ~BIT(stx->src_reg);
17714 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
17715 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
17716 	}
17717 	if (i == 1)
17718 		return;
17719 
17720 	/* Conditionally set 'fastcall_spills_num' to allow forward
17721 	 * compatibility when more helper functions are marked as
17722 	 * bpf_fastcall at compile time than current kernel supports, e.g:
17723 	 *
17724 	 *   1: *(u64 *)(r10 - 8) = r1
17725 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
17726 	 *   3: r1 = *(u64 *)(r10 - 8)
17727 	 *   4: *(u64 *)(r10 - 8) = r1
17728 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
17729 	 *   6: r1 = *(u64 *)(r10 - 8)
17730 	 *
17731 	 * There is no need to block bpf_fastcall rewrite for such program.
17732 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
17733 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
17734 	 * does not remove spill/fill pair {4,6}.
17735 	 */
17736 	if (cs.fastcall)
17737 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
17738 	else
17739 		subprog->keep_fastcall_stack = 1;
17740 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
17741 }
17742 
17743 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
17744 {
17745 	struct bpf_subprog_info *subprog = env->subprog_info;
17746 	struct bpf_insn *insn;
17747 	s16 lowest_off;
17748 	int s, i;
17749 
17750 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
17751 		/* find lowest stack spill offset used in this subprog */
17752 		lowest_off = 0;
17753 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17754 			insn = env->prog->insnsi + i;
17755 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17756 			    insn->dst_reg != BPF_REG_10)
17757 				continue;
17758 			lowest_off = min(lowest_off, insn->off);
17759 		}
17760 		/* use this offset to find fastcall patterns */
17761 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17762 			insn = env->prog->insnsi + i;
17763 			if (insn->code != (BPF_JMP | BPF_CALL))
17764 				continue;
17765 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
17766 		}
17767 	}
17768 	return 0;
17769 }
17770 
17771 /* Visits the instruction at index t and returns one of the following:
17772  *  < 0 - an error occurred
17773  *  DONE_EXPLORING - the instruction was fully explored
17774  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
17775  */
17776 static int visit_insn(int t, struct bpf_verifier_env *env)
17777 {
17778 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
17779 	int ret, off, insn_sz;
17780 
17781 	if (bpf_pseudo_func(insn))
17782 		return visit_func_call_insn(t, insns, env, true);
17783 
17784 	/* All non-branch instructions have a single fall-through edge. */
17785 	if (BPF_CLASS(insn->code) != BPF_JMP &&
17786 	    BPF_CLASS(insn->code) != BPF_JMP32) {
17787 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
17788 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
17789 	}
17790 
17791 	switch (BPF_OP(insn->code)) {
17792 	case BPF_EXIT:
17793 		return DONE_EXPLORING;
17794 
17795 	case BPF_CALL:
17796 		if (is_async_callback_calling_insn(insn))
17797 			/* Mark this call insn as a prune point to trigger
17798 			 * is_state_visited() check before call itself is
17799 			 * processed by __check_func_call(). Otherwise new
17800 			 * async state will be pushed for further exploration.
17801 			 */
17802 			mark_prune_point(env, t);
17803 		/* For functions that invoke callbacks it is not known how many times
17804 		 * callback would be called. Verifier models callback calling functions
17805 		 * by repeatedly visiting callback bodies and returning to origin call
17806 		 * instruction.
17807 		 * In order to stop such iteration verifier needs to identify when a
17808 		 * state identical some state from a previous iteration is reached.
17809 		 * Check below forces creation of checkpoint before callback calling
17810 		 * instruction to allow search for such identical states.
17811 		 */
17812 		if (is_sync_callback_calling_insn(insn)) {
17813 			mark_calls_callback(env, t);
17814 			mark_force_checkpoint(env, t);
17815 			mark_prune_point(env, t);
17816 			mark_jmp_point(env, t);
17817 		}
17818 		if (bpf_helper_call(insn)) {
17819 			const struct bpf_func_proto *fp;
17820 
17821 			ret = get_helper_proto(env, insn->imm, &fp);
17822 			/* If called in a non-sleepable context program will be
17823 			 * rejected anyway, so we should end up with precise
17824 			 * sleepable marks on subprogs, except for dead code
17825 			 * elimination.
17826 			 */
17827 			if (ret == 0 && fp->might_sleep)
17828 				mark_subprog_might_sleep(env, t);
17829 			if (bpf_helper_changes_pkt_data(insn->imm))
17830 				mark_subprog_changes_pkt_data(env, t);
17831 		} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17832 			struct bpf_kfunc_call_arg_meta meta;
17833 
17834 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
17835 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
17836 				mark_prune_point(env, t);
17837 				/* Checking and saving state checkpoints at iter_next() call
17838 				 * is crucial for fast convergence of open-coded iterator loop
17839 				 * logic, so we need to force it. If we don't do that,
17840 				 * is_state_visited() might skip saving a checkpoint, causing
17841 				 * unnecessarily long sequence of not checkpointed
17842 				 * instructions and jumps, leading to exhaustion of jump
17843 				 * history buffer, and potentially other undesired outcomes.
17844 				 * It is expected that with correct open-coded iterators
17845 				 * convergence will happen quickly, so we don't run a risk of
17846 				 * exhausting memory.
17847 				 */
17848 				mark_force_checkpoint(env, t);
17849 			}
17850 			/* Same as helpers, if called in a non-sleepable context
17851 			 * program will be rejected anyway, so we should end up
17852 			 * with precise sleepable marks on subprogs, except for
17853 			 * dead code elimination.
17854 			 */
17855 			if (ret == 0 && is_kfunc_sleepable(&meta))
17856 				mark_subprog_might_sleep(env, t);
17857 			if (ret == 0 && is_kfunc_pkt_changing(&meta))
17858 				mark_subprog_changes_pkt_data(env, t);
17859 		}
17860 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
17861 
17862 	case BPF_JA:
17863 		if (BPF_SRC(insn->code) != BPF_K)
17864 			return -EINVAL;
17865 
17866 		if (BPF_CLASS(insn->code) == BPF_JMP)
17867 			off = insn->off;
17868 		else
17869 			off = insn->imm;
17870 
17871 		/* unconditional jump with single edge */
17872 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
17873 		if (ret)
17874 			return ret;
17875 
17876 		mark_prune_point(env, t + off + 1);
17877 		mark_jmp_point(env, t + off + 1);
17878 
17879 		return ret;
17880 
17881 	default:
17882 		/* conditional jump with two edges */
17883 		mark_prune_point(env, t);
17884 		if (is_may_goto_insn(insn))
17885 			mark_force_checkpoint(env, t);
17886 
17887 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
17888 		if (ret)
17889 			return ret;
17890 
17891 		return push_insn(t, t + insn->off + 1, BRANCH, env);
17892 	}
17893 }
17894 
17895 /* non-recursive depth-first-search to detect loops in BPF program
17896  * loop == back-edge in directed graph
17897  */
17898 static int check_cfg(struct bpf_verifier_env *env)
17899 {
17900 	int insn_cnt = env->prog->len;
17901 	int *insn_stack, *insn_state;
17902 	int ex_insn_beg, i, ret = 0;
17903 
17904 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
17905 	if (!insn_state)
17906 		return -ENOMEM;
17907 
17908 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
17909 	if (!insn_stack) {
17910 		kvfree(insn_state);
17911 		return -ENOMEM;
17912 	}
17913 
17914 	ex_insn_beg = env->exception_callback_subprog
17915 		      ? env->subprog_info[env->exception_callback_subprog].start
17916 		      : 0;
17917 
17918 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
17919 	insn_stack[0] = 0; /* 0 is the first instruction */
17920 	env->cfg.cur_stack = 1;
17921 
17922 walk_cfg:
17923 	while (env->cfg.cur_stack > 0) {
17924 		int t = insn_stack[env->cfg.cur_stack - 1];
17925 
17926 		ret = visit_insn(t, env);
17927 		switch (ret) {
17928 		case DONE_EXPLORING:
17929 			insn_state[t] = EXPLORED;
17930 			env->cfg.cur_stack--;
17931 			break;
17932 		case KEEP_EXPLORING:
17933 			break;
17934 		default:
17935 			if (ret > 0) {
17936 				verifier_bug(env, "visit_insn internal bug");
17937 				ret = -EFAULT;
17938 			}
17939 			goto err_free;
17940 		}
17941 	}
17942 
17943 	if (env->cfg.cur_stack < 0) {
17944 		verifier_bug(env, "pop stack internal bug");
17945 		ret = -EFAULT;
17946 		goto err_free;
17947 	}
17948 
17949 	if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) {
17950 		insn_state[ex_insn_beg] = DISCOVERED;
17951 		insn_stack[0] = ex_insn_beg;
17952 		env->cfg.cur_stack = 1;
17953 		goto walk_cfg;
17954 	}
17955 
17956 	for (i = 0; i < insn_cnt; i++) {
17957 		struct bpf_insn *insn = &env->prog->insnsi[i];
17958 
17959 		if (insn_state[i] != EXPLORED) {
17960 			verbose(env, "unreachable insn %d\n", i);
17961 			ret = -EINVAL;
17962 			goto err_free;
17963 		}
17964 		if (bpf_is_ldimm64(insn)) {
17965 			if (insn_state[i + 1] != 0) {
17966 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
17967 				ret = -EINVAL;
17968 				goto err_free;
17969 			}
17970 			i++; /* skip second half of ldimm64 */
17971 		}
17972 	}
17973 	ret = 0; /* cfg looks good */
17974 	env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
17975 	env->prog->aux->might_sleep = env->subprog_info[0].might_sleep;
17976 
17977 err_free:
17978 	kvfree(insn_state);
17979 	kvfree(insn_stack);
17980 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
17981 	return ret;
17982 }
17983 
17984 /*
17985  * For each subprogram 'i' fill array env->cfg.insn_subprogram sub-range
17986  * [env->subprog_info[i].postorder_start, env->subprog_info[i+1].postorder_start)
17987  * with indices of 'i' instructions in postorder.
17988  */
17989 static int compute_postorder(struct bpf_verifier_env *env)
17990 {
17991 	u32 cur_postorder, i, top, stack_sz, s, succ_cnt, succ[2];
17992 	int *stack = NULL, *postorder = NULL, *state = NULL;
17993 
17994 	postorder = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
17995 	state = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
17996 	stack = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
17997 	if (!postorder || !state || !stack) {
17998 		kvfree(postorder);
17999 		kvfree(state);
18000 		kvfree(stack);
18001 		return -ENOMEM;
18002 	}
18003 	cur_postorder = 0;
18004 	for (i = 0; i < env->subprog_cnt; i++) {
18005 		env->subprog_info[i].postorder_start = cur_postorder;
18006 		stack[0] = env->subprog_info[i].start;
18007 		stack_sz = 1;
18008 		do {
18009 			top = stack[stack_sz - 1];
18010 			state[top] |= DISCOVERED;
18011 			if (state[top] & EXPLORED) {
18012 				postorder[cur_postorder++] = top;
18013 				stack_sz--;
18014 				continue;
18015 			}
18016 			succ_cnt = bpf_insn_successors(env->prog, top, succ);
18017 			for (s = 0; s < succ_cnt; ++s) {
18018 				if (!state[succ[s]]) {
18019 					stack[stack_sz++] = succ[s];
18020 					state[succ[s]] |= DISCOVERED;
18021 				}
18022 			}
18023 			state[top] |= EXPLORED;
18024 		} while (stack_sz);
18025 	}
18026 	env->subprog_info[i].postorder_start = cur_postorder;
18027 	env->cfg.insn_postorder = postorder;
18028 	env->cfg.cur_postorder = cur_postorder;
18029 	kvfree(stack);
18030 	kvfree(state);
18031 	return 0;
18032 }
18033 
18034 static int check_abnormal_return(struct bpf_verifier_env *env)
18035 {
18036 	int i;
18037 
18038 	for (i = 1; i < env->subprog_cnt; i++) {
18039 		if (env->subprog_info[i].has_ld_abs) {
18040 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
18041 			return -EINVAL;
18042 		}
18043 		if (env->subprog_info[i].has_tail_call) {
18044 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
18045 			return -EINVAL;
18046 		}
18047 	}
18048 	return 0;
18049 }
18050 
18051 /* The minimum supported BTF func info size */
18052 #define MIN_BPF_FUNCINFO_SIZE	8
18053 #define MAX_FUNCINFO_REC_SIZE	252
18054 
18055 static int check_btf_func_early(struct bpf_verifier_env *env,
18056 				const union bpf_attr *attr,
18057 				bpfptr_t uattr)
18058 {
18059 	u32 krec_size = sizeof(struct bpf_func_info);
18060 	const struct btf_type *type, *func_proto;
18061 	u32 i, nfuncs, urec_size, min_size;
18062 	struct bpf_func_info *krecord;
18063 	struct bpf_prog *prog;
18064 	const struct btf *btf;
18065 	u32 prev_offset = 0;
18066 	bpfptr_t urecord;
18067 	int ret = -ENOMEM;
18068 
18069 	nfuncs = attr->func_info_cnt;
18070 	if (!nfuncs) {
18071 		if (check_abnormal_return(env))
18072 			return -EINVAL;
18073 		return 0;
18074 	}
18075 
18076 	urec_size = attr->func_info_rec_size;
18077 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
18078 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
18079 	    urec_size % sizeof(u32)) {
18080 		verbose(env, "invalid func info rec size %u\n", urec_size);
18081 		return -EINVAL;
18082 	}
18083 
18084 	prog = env->prog;
18085 	btf = prog->aux->btf;
18086 
18087 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18088 	min_size = min_t(u32, krec_size, urec_size);
18089 
18090 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18091 	if (!krecord)
18092 		return -ENOMEM;
18093 
18094 	for (i = 0; i < nfuncs; i++) {
18095 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
18096 		if (ret) {
18097 			if (ret == -E2BIG) {
18098 				verbose(env, "nonzero tailing record in func info");
18099 				/* set the size kernel expects so loader can zero
18100 				 * out the rest of the record.
18101 				 */
18102 				if (copy_to_bpfptr_offset(uattr,
18103 							  offsetof(union bpf_attr, func_info_rec_size),
18104 							  &min_size, sizeof(min_size)))
18105 					ret = -EFAULT;
18106 			}
18107 			goto err_free;
18108 		}
18109 
18110 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
18111 			ret = -EFAULT;
18112 			goto err_free;
18113 		}
18114 
18115 		/* check insn_off */
18116 		ret = -EINVAL;
18117 		if (i == 0) {
18118 			if (krecord[i].insn_off) {
18119 				verbose(env,
18120 					"nonzero insn_off %u for the first func info record",
18121 					krecord[i].insn_off);
18122 				goto err_free;
18123 			}
18124 		} else if (krecord[i].insn_off <= prev_offset) {
18125 			verbose(env,
18126 				"same or smaller insn offset (%u) than previous func info record (%u)",
18127 				krecord[i].insn_off, prev_offset);
18128 			goto err_free;
18129 		}
18130 
18131 		/* check type_id */
18132 		type = btf_type_by_id(btf, krecord[i].type_id);
18133 		if (!type || !btf_type_is_func(type)) {
18134 			verbose(env, "invalid type id %d in func info",
18135 				krecord[i].type_id);
18136 			goto err_free;
18137 		}
18138 
18139 		func_proto = btf_type_by_id(btf, type->type);
18140 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
18141 			/* btf_func_check() already verified it during BTF load */
18142 			goto err_free;
18143 
18144 		prev_offset = krecord[i].insn_off;
18145 		bpfptr_add(&urecord, urec_size);
18146 	}
18147 
18148 	prog->aux->func_info = krecord;
18149 	prog->aux->func_info_cnt = nfuncs;
18150 	return 0;
18151 
18152 err_free:
18153 	kvfree(krecord);
18154 	return ret;
18155 }
18156 
18157 static int check_btf_func(struct bpf_verifier_env *env,
18158 			  const union bpf_attr *attr,
18159 			  bpfptr_t uattr)
18160 {
18161 	const struct btf_type *type, *func_proto, *ret_type;
18162 	u32 i, nfuncs, urec_size;
18163 	struct bpf_func_info *krecord;
18164 	struct bpf_func_info_aux *info_aux = NULL;
18165 	struct bpf_prog *prog;
18166 	const struct btf *btf;
18167 	bpfptr_t urecord;
18168 	bool scalar_return;
18169 	int ret = -ENOMEM;
18170 
18171 	nfuncs = attr->func_info_cnt;
18172 	if (!nfuncs) {
18173 		if (check_abnormal_return(env))
18174 			return -EINVAL;
18175 		return 0;
18176 	}
18177 	if (nfuncs != env->subprog_cnt) {
18178 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
18179 		return -EINVAL;
18180 	}
18181 
18182 	urec_size = attr->func_info_rec_size;
18183 
18184 	prog = env->prog;
18185 	btf = prog->aux->btf;
18186 
18187 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18188 
18189 	krecord = prog->aux->func_info;
18190 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18191 	if (!info_aux)
18192 		return -ENOMEM;
18193 
18194 	for (i = 0; i < nfuncs; i++) {
18195 		/* check insn_off */
18196 		ret = -EINVAL;
18197 
18198 		if (env->subprog_info[i].start != krecord[i].insn_off) {
18199 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
18200 			goto err_free;
18201 		}
18202 
18203 		/* Already checked type_id */
18204 		type = btf_type_by_id(btf, krecord[i].type_id);
18205 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
18206 		/* Already checked func_proto */
18207 		func_proto = btf_type_by_id(btf, type->type);
18208 
18209 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
18210 		scalar_return =
18211 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
18212 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
18213 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
18214 			goto err_free;
18215 		}
18216 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
18217 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
18218 			goto err_free;
18219 		}
18220 
18221 		bpfptr_add(&urecord, urec_size);
18222 	}
18223 
18224 	prog->aux->func_info_aux = info_aux;
18225 	return 0;
18226 
18227 err_free:
18228 	kfree(info_aux);
18229 	return ret;
18230 }
18231 
18232 static void adjust_btf_func(struct bpf_verifier_env *env)
18233 {
18234 	struct bpf_prog_aux *aux = env->prog->aux;
18235 	int i;
18236 
18237 	if (!aux->func_info)
18238 		return;
18239 
18240 	/* func_info is not available for hidden subprogs */
18241 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
18242 		aux->func_info[i].insn_off = env->subprog_info[i].start;
18243 }
18244 
18245 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
18246 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
18247 
18248 static int check_btf_line(struct bpf_verifier_env *env,
18249 			  const union bpf_attr *attr,
18250 			  bpfptr_t uattr)
18251 {
18252 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
18253 	struct bpf_subprog_info *sub;
18254 	struct bpf_line_info *linfo;
18255 	struct bpf_prog *prog;
18256 	const struct btf *btf;
18257 	bpfptr_t ulinfo;
18258 	int err;
18259 
18260 	nr_linfo = attr->line_info_cnt;
18261 	if (!nr_linfo)
18262 		return 0;
18263 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
18264 		return -EINVAL;
18265 
18266 	rec_size = attr->line_info_rec_size;
18267 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
18268 	    rec_size > MAX_LINEINFO_REC_SIZE ||
18269 	    rec_size & (sizeof(u32) - 1))
18270 		return -EINVAL;
18271 
18272 	/* Need to zero it in case the userspace may
18273 	 * pass in a smaller bpf_line_info object.
18274 	 */
18275 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
18276 			 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18277 	if (!linfo)
18278 		return -ENOMEM;
18279 
18280 	prog = env->prog;
18281 	btf = prog->aux->btf;
18282 
18283 	s = 0;
18284 	sub = env->subprog_info;
18285 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
18286 	expected_size = sizeof(struct bpf_line_info);
18287 	ncopy = min_t(u32, expected_size, rec_size);
18288 	for (i = 0; i < nr_linfo; i++) {
18289 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
18290 		if (err) {
18291 			if (err == -E2BIG) {
18292 				verbose(env, "nonzero tailing record in line_info");
18293 				if (copy_to_bpfptr_offset(uattr,
18294 							  offsetof(union bpf_attr, line_info_rec_size),
18295 							  &expected_size, sizeof(expected_size)))
18296 					err = -EFAULT;
18297 			}
18298 			goto err_free;
18299 		}
18300 
18301 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
18302 			err = -EFAULT;
18303 			goto err_free;
18304 		}
18305 
18306 		/*
18307 		 * Check insn_off to ensure
18308 		 * 1) strictly increasing AND
18309 		 * 2) bounded by prog->len
18310 		 *
18311 		 * The linfo[0].insn_off == 0 check logically falls into
18312 		 * the later "missing bpf_line_info for func..." case
18313 		 * because the first linfo[0].insn_off must be the
18314 		 * first sub also and the first sub must have
18315 		 * subprog_info[0].start == 0.
18316 		 */
18317 		if ((i && linfo[i].insn_off <= prev_offset) ||
18318 		    linfo[i].insn_off >= prog->len) {
18319 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
18320 				i, linfo[i].insn_off, prev_offset,
18321 				prog->len);
18322 			err = -EINVAL;
18323 			goto err_free;
18324 		}
18325 
18326 		if (!prog->insnsi[linfo[i].insn_off].code) {
18327 			verbose(env,
18328 				"Invalid insn code at line_info[%u].insn_off\n",
18329 				i);
18330 			err = -EINVAL;
18331 			goto err_free;
18332 		}
18333 
18334 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
18335 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
18336 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
18337 			err = -EINVAL;
18338 			goto err_free;
18339 		}
18340 
18341 		if (s != env->subprog_cnt) {
18342 			if (linfo[i].insn_off == sub[s].start) {
18343 				sub[s].linfo_idx = i;
18344 				s++;
18345 			} else if (sub[s].start < linfo[i].insn_off) {
18346 				verbose(env, "missing bpf_line_info for func#%u\n", s);
18347 				err = -EINVAL;
18348 				goto err_free;
18349 			}
18350 		}
18351 
18352 		prev_offset = linfo[i].insn_off;
18353 		bpfptr_add(&ulinfo, rec_size);
18354 	}
18355 
18356 	if (s != env->subprog_cnt) {
18357 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
18358 			env->subprog_cnt - s, s);
18359 		err = -EINVAL;
18360 		goto err_free;
18361 	}
18362 
18363 	prog->aux->linfo = linfo;
18364 	prog->aux->nr_linfo = nr_linfo;
18365 
18366 	return 0;
18367 
18368 err_free:
18369 	kvfree(linfo);
18370 	return err;
18371 }
18372 
18373 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
18374 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
18375 
18376 static int check_core_relo(struct bpf_verifier_env *env,
18377 			   const union bpf_attr *attr,
18378 			   bpfptr_t uattr)
18379 {
18380 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
18381 	struct bpf_core_relo core_relo = {};
18382 	struct bpf_prog *prog = env->prog;
18383 	const struct btf *btf = prog->aux->btf;
18384 	struct bpf_core_ctx ctx = {
18385 		.log = &env->log,
18386 		.btf = btf,
18387 	};
18388 	bpfptr_t u_core_relo;
18389 	int err;
18390 
18391 	nr_core_relo = attr->core_relo_cnt;
18392 	if (!nr_core_relo)
18393 		return 0;
18394 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
18395 		return -EINVAL;
18396 
18397 	rec_size = attr->core_relo_rec_size;
18398 	if (rec_size < MIN_CORE_RELO_SIZE ||
18399 	    rec_size > MAX_CORE_RELO_SIZE ||
18400 	    rec_size % sizeof(u32))
18401 		return -EINVAL;
18402 
18403 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
18404 	expected_size = sizeof(struct bpf_core_relo);
18405 	ncopy = min_t(u32, expected_size, rec_size);
18406 
18407 	/* Unlike func_info and line_info, copy and apply each CO-RE
18408 	 * relocation record one at a time.
18409 	 */
18410 	for (i = 0; i < nr_core_relo; i++) {
18411 		/* future proofing when sizeof(bpf_core_relo) changes */
18412 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
18413 		if (err) {
18414 			if (err == -E2BIG) {
18415 				verbose(env, "nonzero tailing record in core_relo");
18416 				if (copy_to_bpfptr_offset(uattr,
18417 							  offsetof(union bpf_attr, core_relo_rec_size),
18418 							  &expected_size, sizeof(expected_size)))
18419 					err = -EFAULT;
18420 			}
18421 			break;
18422 		}
18423 
18424 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
18425 			err = -EFAULT;
18426 			break;
18427 		}
18428 
18429 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
18430 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
18431 				i, core_relo.insn_off, prog->len);
18432 			err = -EINVAL;
18433 			break;
18434 		}
18435 
18436 		err = bpf_core_apply(&ctx, &core_relo, i,
18437 				     &prog->insnsi[core_relo.insn_off / 8]);
18438 		if (err)
18439 			break;
18440 		bpfptr_add(&u_core_relo, rec_size);
18441 	}
18442 	return err;
18443 }
18444 
18445 static int check_btf_info_early(struct bpf_verifier_env *env,
18446 				const union bpf_attr *attr,
18447 				bpfptr_t uattr)
18448 {
18449 	struct btf *btf;
18450 	int err;
18451 
18452 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18453 		if (check_abnormal_return(env))
18454 			return -EINVAL;
18455 		return 0;
18456 	}
18457 
18458 	btf = btf_get_by_fd(attr->prog_btf_fd);
18459 	if (IS_ERR(btf))
18460 		return PTR_ERR(btf);
18461 	if (btf_is_kernel(btf)) {
18462 		btf_put(btf);
18463 		return -EACCES;
18464 	}
18465 	env->prog->aux->btf = btf;
18466 
18467 	err = check_btf_func_early(env, attr, uattr);
18468 	if (err)
18469 		return err;
18470 	return 0;
18471 }
18472 
18473 static int check_btf_info(struct bpf_verifier_env *env,
18474 			  const union bpf_attr *attr,
18475 			  bpfptr_t uattr)
18476 {
18477 	int err;
18478 
18479 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18480 		if (check_abnormal_return(env))
18481 			return -EINVAL;
18482 		return 0;
18483 	}
18484 
18485 	err = check_btf_func(env, attr, uattr);
18486 	if (err)
18487 		return err;
18488 
18489 	err = check_btf_line(env, attr, uattr);
18490 	if (err)
18491 		return err;
18492 
18493 	err = check_core_relo(env, attr, uattr);
18494 	if (err)
18495 		return err;
18496 
18497 	return 0;
18498 }
18499 
18500 /* check %cur's range satisfies %old's */
18501 static bool range_within(const struct bpf_reg_state *old,
18502 			 const struct bpf_reg_state *cur)
18503 {
18504 	return old->umin_value <= cur->umin_value &&
18505 	       old->umax_value >= cur->umax_value &&
18506 	       old->smin_value <= cur->smin_value &&
18507 	       old->smax_value >= cur->smax_value &&
18508 	       old->u32_min_value <= cur->u32_min_value &&
18509 	       old->u32_max_value >= cur->u32_max_value &&
18510 	       old->s32_min_value <= cur->s32_min_value &&
18511 	       old->s32_max_value >= cur->s32_max_value;
18512 }
18513 
18514 /* If in the old state two registers had the same id, then they need to have
18515  * the same id in the new state as well.  But that id could be different from
18516  * the old state, so we need to track the mapping from old to new ids.
18517  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
18518  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
18519  * regs with a different old id could still have new id 9, we don't care about
18520  * that.
18521  * So we look through our idmap to see if this old id has been seen before.  If
18522  * so, we require the new id to match; otherwise, we add the id pair to the map.
18523  */
18524 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18525 {
18526 	struct bpf_id_pair *map = idmap->map;
18527 	unsigned int i;
18528 
18529 	/* either both IDs should be set or both should be zero */
18530 	if (!!old_id != !!cur_id)
18531 		return false;
18532 
18533 	if (old_id == 0) /* cur_id == 0 as well */
18534 		return true;
18535 
18536 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
18537 		if (!map[i].old) {
18538 			/* Reached an empty slot; haven't seen this id before */
18539 			map[i].old = old_id;
18540 			map[i].cur = cur_id;
18541 			return true;
18542 		}
18543 		if (map[i].old == old_id)
18544 			return map[i].cur == cur_id;
18545 		if (map[i].cur == cur_id)
18546 			return false;
18547 	}
18548 	/* We ran out of idmap slots, which should be impossible */
18549 	WARN_ON_ONCE(1);
18550 	return false;
18551 }
18552 
18553 /* Similar to check_ids(), but allocate a unique temporary ID
18554  * for 'old_id' or 'cur_id' of zero.
18555  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
18556  */
18557 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18558 {
18559 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
18560 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
18561 
18562 	return check_ids(old_id, cur_id, idmap);
18563 }
18564 
18565 static void clean_func_state(struct bpf_verifier_env *env,
18566 			     struct bpf_func_state *st,
18567 			     u32 ip)
18568 {
18569 	u16 live_regs = env->insn_aux_data[ip].live_regs_before;
18570 	int i, j;
18571 
18572 	for (i = 0; i < BPF_REG_FP; i++) {
18573 		/* liveness must not touch this register anymore */
18574 		if (!(live_regs & BIT(i)))
18575 			/* since the register is unused, clear its state
18576 			 * to make further comparison simpler
18577 			 */
18578 			__mark_reg_not_init(env, &st->regs[i]);
18579 	}
18580 
18581 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
18582 		if (!bpf_stack_slot_alive(env, st->frameno, i)) {
18583 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
18584 			for (j = 0; j < BPF_REG_SIZE; j++)
18585 				st->stack[i].slot_type[j] = STACK_INVALID;
18586 		}
18587 	}
18588 }
18589 
18590 static void clean_verifier_state(struct bpf_verifier_env *env,
18591 				 struct bpf_verifier_state *st)
18592 {
18593 	int i, ip;
18594 
18595 	bpf_live_stack_query_init(env, st);
18596 	st->cleaned = true;
18597 	for (i = 0; i <= st->curframe; i++) {
18598 		ip = frame_insn_idx(st, i);
18599 		clean_func_state(env, st->frame[i], ip);
18600 	}
18601 }
18602 
18603 /* the parentage chains form a tree.
18604  * the verifier states are added to state lists at given insn and
18605  * pushed into state stack for future exploration.
18606  * when the verifier reaches bpf_exit insn some of the verifier states
18607  * stored in the state lists have their final liveness state already,
18608  * but a lot of states will get revised from liveness point of view when
18609  * the verifier explores other branches.
18610  * Example:
18611  * 1: *(u64)(r10 - 8) = 1
18612  * 2: if r1 == 100 goto pc+1
18613  * 3: *(u64)(r10 - 8) = 2
18614  * 4: r0 = *(u64)(r10 - 8)
18615  * 5: exit
18616  * when the verifier reaches exit insn the stack slot -8 in the state list of
18617  * insn 2 is not yet marked alive. Then the verifier pops the other_branch
18618  * of insn 2 and goes exploring further. After the insn 4 read, liveness
18619  * analysis would propagate read mark for -8 at insn 2.
18620  *
18621  * Since the verifier pushes the branch states as it sees them while exploring
18622  * the program the condition of walking the branch instruction for the second
18623  * time means that all states below this branch were already explored and
18624  * their final liveness marks are already propagated.
18625  * Hence when the verifier completes the search of state list in is_state_visited()
18626  * we can call this clean_live_states() function to clear dead the registers and stack
18627  * slots to simplify state merging.
18628  *
18629  * Important note here that walking the same branch instruction in the callee
18630  * doesn't meant that the states are DONE. The verifier has to compare
18631  * the callsites
18632  */
18633 static void clean_live_states(struct bpf_verifier_env *env, int insn,
18634 			      struct bpf_verifier_state *cur)
18635 {
18636 	struct bpf_verifier_state_list *sl;
18637 	struct list_head *pos, *head;
18638 
18639 	head = explored_state(env, insn);
18640 	list_for_each(pos, head) {
18641 		sl = container_of(pos, struct bpf_verifier_state_list, node);
18642 		if (sl->state.branches)
18643 			continue;
18644 		if (sl->state.insn_idx != insn ||
18645 		    !same_callsites(&sl->state, cur))
18646 			continue;
18647 		if (sl->state.cleaned)
18648 			/* all regs in this state in all frames were already marked */
18649 			continue;
18650 		if (incomplete_read_marks(env, &sl->state))
18651 			continue;
18652 		clean_verifier_state(env, &sl->state);
18653 	}
18654 }
18655 
18656 static bool regs_exact(const struct bpf_reg_state *rold,
18657 		       const struct bpf_reg_state *rcur,
18658 		       struct bpf_idmap *idmap)
18659 {
18660 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
18661 	       check_ids(rold->id, rcur->id, idmap) &&
18662 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
18663 }
18664 
18665 enum exact_level {
18666 	NOT_EXACT,
18667 	EXACT,
18668 	RANGE_WITHIN
18669 };
18670 
18671 /* Returns true if (rold safe implies rcur safe) */
18672 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
18673 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
18674 		    enum exact_level exact)
18675 {
18676 	if (exact == EXACT)
18677 		return regs_exact(rold, rcur, idmap);
18678 
18679 	if (rold->type == NOT_INIT) {
18680 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
18681 			/* explored state can't have used this */
18682 			return true;
18683 	}
18684 
18685 	/* Enforce that register types have to match exactly, including their
18686 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
18687 	 * rule.
18688 	 *
18689 	 * One can make a point that using a pointer register as unbounded
18690 	 * SCALAR would be technically acceptable, but this could lead to
18691 	 * pointer leaks because scalars are allowed to leak while pointers
18692 	 * are not. We could make this safe in special cases if root is
18693 	 * calling us, but it's probably not worth the hassle.
18694 	 *
18695 	 * Also, register types that are *not* MAYBE_NULL could technically be
18696 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
18697 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
18698 	 * to the same map).
18699 	 * However, if the old MAYBE_NULL register then got NULL checked,
18700 	 * doing so could have affected others with the same id, and we can't
18701 	 * check for that because we lost the id when we converted to
18702 	 * a non-MAYBE_NULL variant.
18703 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
18704 	 * non-MAYBE_NULL registers as well.
18705 	 */
18706 	if (rold->type != rcur->type)
18707 		return false;
18708 
18709 	switch (base_type(rold->type)) {
18710 	case SCALAR_VALUE:
18711 		if (env->explore_alu_limits) {
18712 			/* explore_alu_limits disables tnum_in() and range_within()
18713 			 * logic and requires everything to be strict
18714 			 */
18715 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
18716 			       check_scalar_ids(rold->id, rcur->id, idmap);
18717 		}
18718 		if (!rold->precise && exact == NOT_EXACT)
18719 			return true;
18720 		if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
18721 			return false;
18722 		if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
18723 			return false;
18724 		/* Why check_ids() for scalar registers?
18725 		 *
18726 		 * Consider the following BPF code:
18727 		 *   1: r6 = ... unbound scalar, ID=a ...
18728 		 *   2: r7 = ... unbound scalar, ID=b ...
18729 		 *   3: if (r6 > r7) goto +1
18730 		 *   4: r6 = r7
18731 		 *   5: if (r6 > X) goto ...
18732 		 *   6: ... memory operation using r7 ...
18733 		 *
18734 		 * First verification path is [1-6]:
18735 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
18736 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
18737 		 *   r7 <= X, because r6 and r7 share same id.
18738 		 * Next verification path is [1-4, 6].
18739 		 *
18740 		 * Instruction (6) would be reached in two states:
18741 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
18742 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
18743 		 *
18744 		 * Use check_ids() to distinguish these states.
18745 		 * ---
18746 		 * Also verify that new value satisfies old value range knowledge.
18747 		 */
18748 		return range_within(rold, rcur) &&
18749 		       tnum_in(rold->var_off, rcur->var_off) &&
18750 		       check_scalar_ids(rold->id, rcur->id, idmap);
18751 	case PTR_TO_MAP_KEY:
18752 	case PTR_TO_MAP_VALUE:
18753 	case PTR_TO_MEM:
18754 	case PTR_TO_BUF:
18755 	case PTR_TO_TP_BUFFER:
18756 		/* If the new min/max/var_off satisfy the old ones and
18757 		 * everything else matches, we are OK.
18758 		 */
18759 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
18760 		       range_within(rold, rcur) &&
18761 		       tnum_in(rold->var_off, rcur->var_off) &&
18762 		       check_ids(rold->id, rcur->id, idmap) &&
18763 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
18764 	case PTR_TO_PACKET_META:
18765 	case PTR_TO_PACKET:
18766 		/* We must have at least as much range as the old ptr
18767 		 * did, so that any accesses which were safe before are
18768 		 * still safe.  This is true even if old range < old off,
18769 		 * since someone could have accessed through (ptr - k), or
18770 		 * even done ptr -= k in a register, to get a safe access.
18771 		 */
18772 		if (rold->range > rcur->range)
18773 			return false;
18774 		/* If the offsets don't match, we can't trust our alignment;
18775 		 * nor can we be sure that we won't fall out of range.
18776 		 */
18777 		if (rold->off != rcur->off)
18778 			return false;
18779 		/* id relations must be preserved */
18780 		if (!check_ids(rold->id, rcur->id, idmap))
18781 			return false;
18782 		/* new val must satisfy old val knowledge */
18783 		return range_within(rold, rcur) &&
18784 		       tnum_in(rold->var_off, rcur->var_off);
18785 	case PTR_TO_STACK:
18786 		/* two stack pointers are equal only if they're pointing to
18787 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
18788 		 */
18789 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
18790 	case PTR_TO_ARENA:
18791 		return true;
18792 	default:
18793 		return regs_exact(rold, rcur, idmap);
18794 	}
18795 }
18796 
18797 static struct bpf_reg_state unbound_reg;
18798 
18799 static __init int unbound_reg_init(void)
18800 {
18801 	__mark_reg_unknown_imprecise(&unbound_reg);
18802 	return 0;
18803 }
18804 late_initcall(unbound_reg_init);
18805 
18806 static bool is_stack_all_misc(struct bpf_verifier_env *env,
18807 			      struct bpf_stack_state *stack)
18808 {
18809 	u32 i;
18810 
18811 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
18812 		if ((stack->slot_type[i] == STACK_MISC) ||
18813 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
18814 			continue;
18815 		return false;
18816 	}
18817 
18818 	return true;
18819 }
18820 
18821 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
18822 						  struct bpf_stack_state *stack)
18823 {
18824 	if (is_spilled_scalar_reg64(stack))
18825 		return &stack->spilled_ptr;
18826 
18827 	if (is_stack_all_misc(env, stack))
18828 		return &unbound_reg;
18829 
18830 	return NULL;
18831 }
18832 
18833 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
18834 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
18835 		      enum exact_level exact)
18836 {
18837 	int i, spi;
18838 
18839 	/* walk slots of the explored stack and ignore any additional
18840 	 * slots in the current stack, since explored(safe) state
18841 	 * didn't use them
18842 	 */
18843 	for (i = 0; i < old->allocated_stack; i++) {
18844 		struct bpf_reg_state *old_reg, *cur_reg;
18845 
18846 		spi = i / BPF_REG_SIZE;
18847 
18848 		if (exact != NOT_EXACT &&
18849 		    (i >= cur->allocated_stack ||
18850 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
18851 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
18852 			return false;
18853 
18854 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
18855 			continue;
18856 
18857 		if (env->allow_uninit_stack &&
18858 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
18859 			continue;
18860 
18861 		/* explored stack has more populated slots than current stack
18862 		 * and these slots were used
18863 		 */
18864 		if (i >= cur->allocated_stack)
18865 			return false;
18866 
18867 		/* 64-bit scalar spill vs all slots MISC and vice versa.
18868 		 * Load from all slots MISC produces unbound scalar.
18869 		 * Construct a fake register for such stack and call
18870 		 * regsafe() to ensure scalar ids are compared.
18871 		 */
18872 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
18873 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
18874 		if (old_reg && cur_reg) {
18875 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
18876 				return false;
18877 			i += BPF_REG_SIZE - 1;
18878 			continue;
18879 		}
18880 
18881 		/* if old state was safe with misc data in the stack
18882 		 * it will be safe with zero-initialized stack.
18883 		 * The opposite is not true
18884 		 */
18885 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
18886 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
18887 			continue;
18888 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
18889 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
18890 			/* Ex: old explored (safe) state has STACK_SPILL in
18891 			 * this stack slot, but current has STACK_MISC ->
18892 			 * this verifier states are not equivalent,
18893 			 * return false to continue verification of this path
18894 			 */
18895 			return false;
18896 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
18897 			continue;
18898 		/* Both old and cur are having same slot_type */
18899 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
18900 		case STACK_SPILL:
18901 			/* when explored and current stack slot are both storing
18902 			 * spilled registers, check that stored pointers types
18903 			 * are the same as well.
18904 			 * Ex: explored safe path could have stored
18905 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
18906 			 * but current path has stored:
18907 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
18908 			 * such verifier states are not equivalent.
18909 			 * return false to continue verification of this path
18910 			 */
18911 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
18912 				     &cur->stack[spi].spilled_ptr, idmap, exact))
18913 				return false;
18914 			break;
18915 		case STACK_DYNPTR:
18916 			old_reg = &old->stack[spi].spilled_ptr;
18917 			cur_reg = &cur->stack[spi].spilled_ptr;
18918 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
18919 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
18920 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18921 				return false;
18922 			break;
18923 		case STACK_ITER:
18924 			old_reg = &old->stack[spi].spilled_ptr;
18925 			cur_reg = &cur->stack[spi].spilled_ptr;
18926 			/* iter.depth is not compared between states as it
18927 			 * doesn't matter for correctness and would otherwise
18928 			 * prevent convergence; we maintain it only to prevent
18929 			 * infinite loop check triggering, see
18930 			 * iter_active_depths_differ()
18931 			 */
18932 			if (old_reg->iter.btf != cur_reg->iter.btf ||
18933 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
18934 			    old_reg->iter.state != cur_reg->iter.state ||
18935 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
18936 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18937 				return false;
18938 			break;
18939 		case STACK_IRQ_FLAG:
18940 			old_reg = &old->stack[spi].spilled_ptr;
18941 			cur_reg = &cur->stack[spi].spilled_ptr;
18942 			if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) ||
18943 			    old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class)
18944 				return false;
18945 			break;
18946 		case STACK_MISC:
18947 		case STACK_ZERO:
18948 		case STACK_INVALID:
18949 			continue;
18950 		/* Ensure that new unhandled slot types return false by default */
18951 		default:
18952 			return false;
18953 		}
18954 	}
18955 	return true;
18956 }
18957 
18958 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
18959 		    struct bpf_idmap *idmap)
18960 {
18961 	int i;
18962 
18963 	if (old->acquired_refs != cur->acquired_refs)
18964 		return false;
18965 
18966 	if (old->active_locks != cur->active_locks)
18967 		return false;
18968 
18969 	if (old->active_preempt_locks != cur->active_preempt_locks)
18970 		return false;
18971 
18972 	if (old->active_rcu_lock != cur->active_rcu_lock)
18973 		return false;
18974 
18975 	if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
18976 		return false;
18977 
18978 	if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) ||
18979 	    old->active_lock_ptr != cur->active_lock_ptr)
18980 		return false;
18981 
18982 	for (i = 0; i < old->acquired_refs; i++) {
18983 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
18984 		    old->refs[i].type != cur->refs[i].type)
18985 			return false;
18986 		switch (old->refs[i].type) {
18987 		case REF_TYPE_PTR:
18988 		case REF_TYPE_IRQ:
18989 			break;
18990 		case REF_TYPE_LOCK:
18991 		case REF_TYPE_RES_LOCK:
18992 		case REF_TYPE_RES_LOCK_IRQ:
18993 			if (old->refs[i].ptr != cur->refs[i].ptr)
18994 				return false;
18995 			break;
18996 		default:
18997 			WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
18998 			return false;
18999 		}
19000 	}
19001 
19002 	return true;
19003 }
19004 
19005 /* compare two verifier states
19006  *
19007  * all states stored in state_list are known to be valid, since
19008  * verifier reached 'bpf_exit' instruction through them
19009  *
19010  * this function is called when verifier exploring different branches of
19011  * execution popped from the state stack. If it sees an old state that has
19012  * more strict register state and more strict stack state then this execution
19013  * branch doesn't need to be explored further, since verifier already
19014  * concluded that more strict state leads to valid finish.
19015  *
19016  * Therefore two states are equivalent if register state is more conservative
19017  * and explored stack state is more conservative than the current one.
19018  * Example:
19019  *       explored                   current
19020  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
19021  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
19022  *
19023  * In other words if current stack state (one being explored) has more
19024  * valid slots than old one that already passed validation, it means
19025  * the verifier can stop exploring and conclude that current state is valid too
19026  *
19027  * Similarly with registers. If explored state has register type as invalid
19028  * whereas register type in current state is meaningful, it means that
19029  * the current state will reach 'bpf_exit' instruction safely
19030  */
19031 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
19032 			      struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact)
19033 {
19034 	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
19035 	u16 i;
19036 
19037 	if (old->callback_depth > cur->callback_depth)
19038 		return false;
19039 
19040 	for (i = 0; i < MAX_BPF_REG; i++)
19041 		if (((1 << i) & live_regs) &&
19042 		    !regsafe(env, &old->regs[i], &cur->regs[i],
19043 			     &env->idmap_scratch, exact))
19044 			return false;
19045 
19046 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
19047 		return false;
19048 
19049 	return true;
19050 }
19051 
19052 static void reset_idmap_scratch(struct bpf_verifier_env *env)
19053 {
19054 	env->idmap_scratch.tmp_id_gen = env->id_gen;
19055 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
19056 }
19057 
19058 static bool states_equal(struct bpf_verifier_env *env,
19059 			 struct bpf_verifier_state *old,
19060 			 struct bpf_verifier_state *cur,
19061 			 enum exact_level exact)
19062 {
19063 	u32 insn_idx;
19064 	int i;
19065 
19066 	if (old->curframe != cur->curframe)
19067 		return false;
19068 
19069 	reset_idmap_scratch(env);
19070 
19071 	/* Verification state from speculative execution simulation
19072 	 * must never prune a non-speculative execution one.
19073 	 */
19074 	if (old->speculative && !cur->speculative)
19075 		return false;
19076 
19077 	if (old->in_sleepable != cur->in_sleepable)
19078 		return false;
19079 
19080 	if (!refsafe(old, cur, &env->idmap_scratch))
19081 		return false;
19082 
19083 	/* for states to be equal callsites have to be the same
19084 	 * and all frame states need to be equivalent
19085 	 */
19086 	for (i = 0; i <= old->curframe; i++) {
19087 		insn_idx = frame_insn_idx(old, i);
19088 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
19089 			return false;
19090 		if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
19091 			return false;
19092 	}
19093 	return true;
19094 }
19095 
19096 /* find precise scalars in the previous equivalent state and
19097  * propagate them into the current state
19098  */
19099 static int propagate_precision(struct bpf_verifier_env *env,
19100 			       const struct bpf_verifier_state *old,
19101 			       struct bpf_verifier_state *cur,
19102 			       bool *changed)
19103 {
19104 	struct bpf_reg_state *state_reg;
19105 	struct bpf_func_state *state;
19106 	int i, err = 0, fr;
19107 	bool first;
19108 
19109 	for (fr = old->curframe; fr >= 0; fr--) {
19110 		state = old->frame[fr];
19111 		state_reg = state->regs;
19112 		first = true;
19113 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
19114 			if (state_reg->type != SCALAR_VALUE ||
19115 			    !state_reg->precise)
19116 				continue;
19117 			if (env->log.level & BPF_LOG_LEVEL2) {
19118 				if (first)
19119 					verbose(env, "frame %d: propagating r%d", fr, i);
19120 				else
19121 					verbose(env, ",r%d", i);
19122 			}
19123 			bt_set_frame_reg(&env->bt, fr, i);
19124 			first = false;
19125 		}
19126 
19127 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19128 			if (!is_spilled_reg(&state->stack[i]))
19129 				continue;
19130 			state_reg = &state->stack[i].spilled_ptr;
19131 			if (state_reg->type != SCALAR_VALUE ||
19132 			    !state_reg->precise)
19133 				continue;
19134 			if (env->log.level & BPF_LOG_LEVEL2) {
19135 				if (first)
19136 					verbose(env, "frame %d: propagating fp%d",
19137 						fr, (-i - 1) * BPF_REG_SIZE);
19138 				else
19139 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
19140 			}
19141 			bt_set_frame_slot(&env->bt, fr, i);
19142 			first = false;
19143 		}
19144 		if (!first)
19145 			verbose(env, "\n");
19146 	}
19147 
19148 	err = __mark_chain_precision(env, cur, -1, changed);
19149 	if (err < 0)
19150 		return err;
19151 
19152 	return 0;
19153 }
19154 
19155 #define MAX_BACKEDGE_ITERS 64
19156 
19157 /* Propagate read and precision marks from visit->backedges[*].state->equal_state
19158  * to corresponding parent states of visit->backedges[*].state until fixed point is reached,
19159  * then free visit->backedges.
19160  * After execution of this function incomplete_read_marks() will return false
19161  * for all states corresponding to @visit->callchain.
19162  */
19163 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit)
19164 {
19165 	struct bpf_scc_backedge *backedge;
19166 	struct bpf_verifier_state *st;
19167 	bool changed;
19168 	int i, err;
19169 
19170 	i = 0;
19171 	do {
19172 		if (i++ > MAX_BACKEDGE_ITERS) {
19173 			if (env->log.level & BPF_LOG_LEVEL2)
19174 				verbose(env, "%s: too many iterations\n", __func__);
19175 			for (backedge = visit->backedges; backedge; backedge = backedge->next)
19176 				mark_all_scalars_precise(env, &backedge->state);
19177 			break;
19178 		}
19179 		changed = false;
19180 		for (backedge = visit->backedges; backedge; backedge = backedge->next) {
19181 			st = &backedge->state;
19182 			err = propagate_precision(env, st->equal_state, st, &changed);
19183 			if (err)
19184 				return err;
19185 		}
19186 	} while (changed);
19187 
19188 	free_backedges(visit);
19189 	return 0;
19190 }
19191 
19192 static bool states_maybe_looping(struct bpf_verifier_state *old,
19193 				 struct bpf_verifier_state *cur)
19194 {
19195 	struct bpf_func_state *fold, *fcur;
19196 	int i, fr = cur->curframe;
19197 
19198 	if (old->curframe != fr)
19199 		return false;
19200 
19201 	fold = old->frame[fr];
19202 	fcur = cur->frame[fr];
19203 	for (i = 0; i < MAX_BPF_REG; i++)
19204 		if (memcmp(&fold->regs[i], &fcur->regs[i],
19205 			   offsetof(struct bpf_reg_state, frameno)))
19206 			return false;
19207 	return true;
19208 }
19209 
19210 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
19211 {
19212 	return env->insn_aux_data[insn_idx].is_iter_next;
19213 }
19214 
19215 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
19216  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
19217  * states to match, which otherwise would look like an infinite loop. So while
19218  * iter_next() calls are taken care of, we still need to be careful and
19219  * prevent erroneous and too eager declaration of "infinite loop", when
19220  * iterators are involved.
19221  *
19222  * Here's a situation in pseudo-BPF assembly form:
19223  *
19224  *   0: again:                          ; set up iter_next() call args
19225  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
19226  *   2:   call bpf_iter_num_next        ; this is iter_next() call
19227  *   3:   if r0 == 0 goto done
19228  *   4:   ... something useful here ...
19229  *   5:   goto again                    ; another iteration
19230  *   6: done:
19231  *   7:   r1 = &it
19232  *   8:   call bpf_iter_num_destroy     ; clean up iter state
19233  *   9:   exit
19234  *
19235  * This is a typical loop. Let's assume that we have a prune point at 1:,
19236  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
19237  * again`, assuming other heuristics don't get in a way).
19238  *
19239  * When we first time come to 1:, let's say we have some state X. We proceed
19240  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
19241  * Now we come back to validate that forked ACTIVE state. We proceed through
19242  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
19243  * are converging. But the problem is that we don't know that yet, as this
19244  * convergence has to happen at iter_next() call site only. So if nothing is
19245  * done, at 1: verifier will use bounded loop logic and declare infinite
19246  * looping (and would be *technically* correct, if not for iterator's
19247  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
19248  * don't want that. So what we do in process_iter_next_call() when we go on
19249  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
19250  * a different iteration. So when we suspect an infinite loop, we additionally
19251  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
19252  * pretend we are not looping and wait for next iter_next() call.
19253  *
19254  * This only applies to ACTIVE state. In DRAINED state we don't expect to
19255  * loop, because that would actually mean infinite loop, as DRAINED state is
19256  * "sticky", and so we'll keep returning into the same instruction with the
19257  * same state (at least in one of possible code paths).
19258  *
19259  * This approach allows to keep infinite loop heuristic even in the face of
19260  * active iterator. E.g., C snippet below is and will be detected as
19261  * infinitely looping:
19262  *
19263  *   struct bpf_iter_num it;
19264  *   int *p, x;
19265  *
19266  *   bpf_iter_num_new(&it, 0, 10);
19267  *   while ((p = bpf_iter_num_next(&t))) {
19268  *       x = p;
19269  *       while (x--) {} // <<-- infinite loop here
19270  *   }
19271  *
19272  */
19273 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
19274 {
19275 	struct bpf_reg_state *slot, *cur_slot;
19276 	struct bpf_func_state *state;
19277 	int i, fr;
19278 
19279 	for (fr = old->curframe; fr >= 0; fr--) {
19280 		state = old->frame[fr];
19281 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19282 			if (state->stack[i].slot_type[0] != STACK_ITER)
19283 				continue;
19284 
19285 			slot = &state->stack[i].spilled_ptr;
19286 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
19287 				continue;
19288 
19289 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
19290 			if (cur_slot->iter.depth != slot->iter.depth)
19291 				return true;
19292 		}
19293 	}
19294 	return false;
19295 }
19296 
19297 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
19298 {
19299 	struct bpf_verifier_state_list *new_sl;
19300 	struct bpf_verifier_state_list *sl;
19301 	struct bpf_verifier_state *cur = env->cur_state, *new;
19302 	bool force_new_state, add_new_state, loop;
19303 	int n, err, states_cnt = 0;
19304 	struct list_head *pos, *tmp, *head;
19305 
19306 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
19307 			  /* Avoid accumulating infinitely long jmp history */
19308 			  cur->jmp_history_cnt > 40;
19309 
19310 	/* bpf progs typically have pruning point every 4 instructions
19311 	 * http://vger.kernel.org/bpfconf2019.html#session-1
19312 	 * Do not add new state for future pruning if the verifier hasn't seen
19313 	 * at least 2 jumps and at least 8 instructions.
19314 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
19315 	 * In tests that amounts to up to 50% reduction into total verifier
19316 	 * memory consumption and 20% verifier time speedup.
19317 	 */
19318 	add_new_state = force_new_state;
19319 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
19320 	    env->insn_processed - env->prev_insn_processed >= 8)
19321 		add_new_state = true;
19322 
19323 	clean_live_states(env, insn_idx, cur);
19324 
19325 	loop = false;
19326 	head = explored_state(env, insn_idx);
19327 	list_for_each_safe(pos, tmp, head) {
19328 		sl = container_of(pos, struct bpf_verifier_state_list, node);
19329 		states_cnt++;
19330 		if (sl->state.insn_idx != insn_idx)
19331 			continue;
19332 
19333 		if (sl->state.branches) {
19334 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
19335 
19336 			if (frame->in_async_callback_fn &&
19337 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
19338 				/* Different async_entry_cnt means that the verifier is
19339 				 * processing another entry into async callback.
19340 				 * Seeing the same state is not an indication of infinite
19341 				 * loop or infinite recursion.
19342 				 * But finding the same state doesn't mean that it's safe
19343 				 * to stop processing the current state. The previous state
19344 				 * hasn't yet reached bpf_exit, since state.branches > 0.
19345 				 * Checking in_async_callback_fn alone is not enough either.
19346 				 * Since the verifier still needs to catch infinite loops
19347 				 * inside async callbacks.
19348 				 */
19349 				goto skip_inf_loop_check;
19350 			}
19351 			/* BPF open-coded iterators loop detection is special.
19352 			 * states_maybe_looping() logic is too simplistic in detecting
19353 			 * states that *might* be equivalent, because it doesn't know
19354 			 * about ID remapping, so don't even perform it.
19355 			 * See process_iter_next_call() and iter_active_depths_differ()
19356 			 * for overview of the logic. When current and one of parent
19357 			 * states are detected as equivalent, it's a good thing: we prove
19358 			 * convergence and can stop simulating further iterations.
19359 			 * It's safe to assume that iterator loop will finish, taking into
19360 			 * account iter_next() contract of eventually returning
19361 			 * sticky NULL result.
19362 			 *
19363 			 * Note, that states have to be compared exactly in this case because
19364 			 * read and precision marks might not be finalized inside the loop.
19365 			 * E.g. as in the program below:
19366 			 *
19367 			 *     1. r7 = -16
19368 			 *     2. r6 = bpf_get_prandom_u32()
19369 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
19370 			 *     4.   if (r6 != 42) {
19371 			 *     5.     r7 = -32
19372 			 *     6.     r6 = bpf_get_prandom_u32()
19373 			 *     7.     continue
19374 			 *     8.   }
19375 			 *     9.   r0 = r10
19376 			 *    10.   r0 += r7
19377 			 *    11.   r8 = *(u64 *)(r0 + 0)
19378 			 *    12.   r6 = bpf_get_prandom_u32()
19379 			 *    13. }
19380 			 *
19381 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
19382 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
19383 			 * not have read or precision mark for r7 yet, thus inexact states
19384 			 * comparison would discard current state with r7=-32
19385 			 * => unsafe memory access at 11 would not be caught.
19386 			 */
19387 			if (is_iter_next_insn(env, insn_idx)) {
19388 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19389 					struct bpf_func_state *cur_frame;
19390 					struct bpf_reg_state *iter_state, *iter_reg;
19391 					int spi;
19392 
19393 					cur_frame = cur->frame[cur->curframe];
19394 					/* btf_check_iter_kfuncs() enforces that
19395 					 * iter state pointer is always the first arg
19396 					 */
19397 					iter_reg = &cur_frame->regs[BPF_REG_1];
19398 					/* current state is valid due to states_equal(),
19399 					 * so we can assume valid iter and reg state,
19400 					 * no need for extra (re-)validations
19401 					 */
19402 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
19403 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
19404 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
19405 						loop = true;
19406 						goto hit;
19407 					}
19408 				}
19409 				goto skip_inf_loop_check;
19410 			}
19411 			if (is_may_goto_insn_at(env, insn_idx)) {
19412 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
19413 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19414 					loop = true;
19415 					goto hit;
19416 				}
19417 			}
19418 			if (bpf_calls_callback(env, insn_idx)) {
19419 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
19420 					goto hit;
19421 				goto skip_inf_loop_check;
19422 			}
19423 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
19424 			if (states_maybe_looping(&sl->state, cur) &&
19425 			    states_equal(env, &sl->state, cur, EXACT) &&
19426 			    !iter_active_depths_differ(&sl->state, cur) &&
19427 			    sl->state.may_goto_depth == cur->may_goto_depth &&
19428 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
19429 				verbose_linfo(env, insn_idx, "; ");
19430 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
19431 				verbose(env, "cur state:");
19432 				print_verifier_state(env, cur, cur->curframe, true);
19433 				verbose(env, "old state:");
19434 				print_verifier_state(env, &sl->state, cur->curframe, true);
19435 				return -EINVAL;
19436 			}
19437 			/* if the verifier is processing a loop, avoid adding new state
19438 			 * too often, since different loop iterations have distinct
19439 			 * states and may not help future pruning.
19440 			 * This threshold shouldn't be too low to make sure that
19441 			 * a loop with large bound will be rejected quickly.
19442 			 * The most abusive loop will be:
19443 			 * r1 += 1
19444 			 * if r1 < 1000000 goto pc-2
19445 			 * 1M insn_procssed limit / 100 == 10k peak states.
19446 			 * This threshold shouldn't be too high either, since states
19447 			 * at the end of the loop are likely to be useful in pruning.
19448 			 */
19449 skip_inf_loop_check:
19450 			if (!force_new_state &&
19451 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
19452 			    env->insn_processed - env->prev_insn_processed < 100)
19453 				add_new_state = false;
19454 			goto miss;
19455 		}
19456 		/* See comments for mark_all_regs_read_and_precise() */
19457 		loop = incomplete_read_marks(env, &sl->state);
19458 		if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) {
19459 hit:
19460 			sl->hit_cnt++;
19461 
19462 			/* if previous state reached the exit with precision and
19463 			 * current state is equivalent to it (except precision marks)
19464 			 * the precision needs to be propagated back in
19465 			 * the current state.
19466 			 */
19467 			err = 0;
19468 			if (is_jmp_point(env, env->insn_idx))
19469 				err = push_jmp_history(env, cur, 0, 0);
19470 			err = err ? : propagate_precision(env, &sl->state, cur, NULL);
19471 			if (err)
19472 				return err;
19473 			/* When processing iterator based loops above propagate_liveness and
19474 			 * propagate_precision calls are not sufficient to transfer all relevant
19475 			 * read and precision marks. E.g. consider the following case:
19476 			 *
19477 			 *  .-> A --.  Assume the states are visited in the order A, B, C.
19478 			 *  |   |   |  Assume that state B reaches a state equivalent to state A.
19479 			 *  |   v   v  At this point, state C is not processed yet, so state A
19480 			 *  '-- B   C  has not received any read or precision marks from C.
19481 			 *             Thus, marks propagated from A to B are incomplete.
19482 			 *
19483 			 * The verifier mitigates this by performing the following steps:
19484 			 *
19485 			 * - Prior to the main verification pass, strongly connected components
19486 			 *   (SCCs) are computed over the program's control flow graph,
19487 			 *   intraprocedurally.
19488 			 *
19489 			 * - During the main verification pass, `maybe_enter_scc()` checks
19490 			 *   whether the current verifier state is entering an SCC. If so, an
19491 			 *   instance of a `bpf_scc_visit` object is created, and the state
19492 			 *   entering the SCC is recorded as the entry state.
19493 			 *
19494 			 * - This instance is associated not with the SCC itself, but with a
19495 			 *   `bpf_scc_callchain`: a tuple consisting of the call sites leading to
19496 			 *   the SCC and the SCC id. See `compute_scc_callchain()`.
19497 			 *
19498 			 * - When a verification path encounters a `states_equal(...,
19499 			 *   RANGE_WITHIN)` condition, there exists a call chain describing the
19500 			 *   current state and a corresponding `bpf_scc_visit` instance. A copy
19501 			 *   of the current state is created and added to
19502 			 *   `bpf_scc_visit->backedges`.
19503 			 *
19504 			 * - When a verification path terminates, `maybe_exit_scc()` is called
19505 			 *   from `update_branch_counts()`. For states with `branches == 0`, it
19506 			 *   checks whether the state is the entry state of any `bpf_scc_visit`
19507 			 *   instance. If it is, this indicates that all paths originating from
19508 			 *   this SCC visit have been explored. `propagate_backedges()` is then
19509 			 *   called, which propagates read and precision marks through the
19510 			 *   backedges until a fixed point is reached.
19511 			 *   (In the earlier example, this would propagate marks from A to B,
19512 			 *    from C to A, and then again from A to B.)
19513 			 *
19514 			 * A note on callchains
19515 			 * --------------------
19516 			 *
19517 			 * Consider the following example:
19518 			 *
19519 			 *     void foo() { loop { ... SCC#1 ... } }
19520 			 *     void main() {
19521 			 *       A: foo();
19522 			 *       B: ...
19523 			 *       C: foo();
19524 			 *     }
19525 			 *
19526 			 * Here, there are two distinct callchains leading to SCC#1:
19527 			 * - (A, SCC#1)
19528 			 * - (C, SCC#1)
19529 			 *
19530 			 * Each callchain identifies a separate `bpf_scc_visit` instance that
19531 			 * accumulates backedge states. The `propagate_{liveness,precision}()`
19532 			 * functions traverse the parent state of each backedge state, which
19533 			 * means these parent states must remain valid (i.e., not freed) while
19534 			 * the corresponding `bpf_scc_visit` instance exists.
19535 			 *
19536 			 * Associating `bpf_scc_visit` instances directly with SCCs instead of
19537 			 * callchains would break this invariant:
19538 			 * - States explored during `C: foo()` would contribute backedges to
19539 			 *   SCC#1, but SCC#1 would only be exited once the exploration of
19540 			 *   `A: foo()` completes.
19541 			 * - By that time, the states explored between `A: foo()` and `C: foo()`
19542 			 *   (i.e., `B: ...`) may have already been freed, causing the parent
19543 			 *   links for states from `C: foo()` to become invalid.
19544 			 */
19545 			if (loop) {
19546 				struct bpf_scc_backedge *backedge;
19547 
19548 				backedge = kzalloc(sizeof(*backedge), GFP_KERNEL_ACCOUNT);
19549 				if (!backedge)
19550 					return -ENOMEM;
19551 				err = copy_verifier_state(&backedge->state, cur);
19552 				backedge->state.equal_state = &sl->state;
19553 				backedge->state.insn_idx = insn_idx;
19554 				err = err ?: add_scc_backedge(env, &sl->state, backedge);
19555 				if (err) {
19556 					free_verifier_state(&backedge->state, false);
19557 					kfree(backedge);
19558 					return err;
19559 				}
19560 			}
19561 			return 1;
19562 		}
19563 miss:
19564 		/* when new state is not going to be added do not increase miss count.
19565 		 * Otherwise several loop iterations will remove the state
19566 		 * recorded earlier. The goal of these heuristics is to have
19567 		 * states from some iterations of the loop (some in the beginning
19568 		 * and some at the end) to help pruning.
19569 		 */
19570 		if (add_new_state)
19571 			sl->miss_cnt++;
19572 		/* heuristic to determine whether this state is beneficial
19573 		 * to keep checking from state equivalence point of view.
19574 		 * Higher numbers increase max_states_per_insn and verification time,
19575 		 * but do not meaningfully decrease insn_processed.
19576 		 * 'n' controls how many times state could miss before eviction.
19577 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
19578 		 * too early would hinder iterator convergence.
19579 		 */
19580 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
19581 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
19582 			/* the state is unlikely to be useful. Remove it to
19583 			 * speed up verification
19584 			 */
19585 			sl->in_free_list = true;
19586 			list_del(&sl->node);
19587 			list_add(&sl->node, &env->free_list);
19588 			env->free_list_size++;
19589 			env->explored_states_size--;
19590 			maybe_free_verifier_state(env, sl);
19591 		}
19592 	}
19593 
19594 	if (env->max_states_per_insn < states_cnt)
19595 		env->max_states_per_insn = states_cnt;
19596 
19597 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
19598 		return 0;
19599 
19600 	if (!add_new_state)
19601 		return 0;
19602 
19603 	/* There were no equivalent states, remember the current one.
19604 	 * Technically the current state is not proven to be safe yet,
19605 	 * but it will either reach outer most bpf_exit (which means it's safe)
19606 	 * or it will be rejected. When there are no loops the verifier won't be
19607 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
19608 	 * again on the way to bpf_exit.
19609 	 * When looping the sl->state.branches will be > 0 and this state
19610 	 * will not be considered for equivalence until branches == 0.
19611 	 */
19612 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL_ACCOUNT);
19613 	if (!new_sl)
19614 		return -ENOMEM;
19615 	env->total_states++;
19616 	env->explored_states_size++;
19617 	update_peak_states(env);
19618 	env->prev_jmps_processed = env->jmps_processed;
19619 	env->prev_insn_processed = env->insn_processed;
19620 
19621 	/* forget precise markings we inherited, see __mark_chain_precision */
19622 	if (env->bpf_capable)
19623 		mark_all_scalars_imprecise(env, cur);
19624 
19625 	/* add new state to the head of linked list */
19626 	new = &new_sl->state;
19627 	err = copy_verifier_state(new, cur);
19628 	if (err) {
19629 		free_verifier_state(new, false);
19630 		kfree(new_sl);
19631 		return err;
19632 	}
19633 	new->insn_idx = insn_idx;
19634 	verifier_bug_if(new->branches != 1, env,
19635 			"%s:branches_to_explore=%d insn %d",
19636 			__func__, new->branches, insn_idx);
19637 	err = maybe_enter_scc(env, new);
19638 	if (err) {
19639 		free_verifier_state(new, false);
19640 		kfree(new_sl);
19641 		return err;
19642 	}
19643 
19644 	cur->parent = new;
19645 	cur->first_insn_idx = insn_idx;
19646 	cur->dfs_depth = new->dfs_depth + 1;
19647 	clear_jmp_history(cur);
19648 	list_add(&new_sl->node, head);
19649 	return 0;
19650 }
19651 
19652 /* Return true if it's OK to have the same insn return a different type. */
19653 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
19654 {
19655 	switch (base_type(type)) {
19656 	case PTR_TO_CTX:
19657 	case PTR_TO_SOCKET:
19658 	case PTR_TO_SOCK_COMMON:
19659 	case PTR_TO_TCP_SOCK:
19660 	case PTR_TO_XDP_SOCK:
19661 	case PTR_TO_BTF_ID:
19662 	case PTR_TO_ARENA:
19663 		return false;
19664 	default:
19665 		return true;
19666 	}
19667 }
19668 
19669 /* If an instruction was previously used with particular pointer types, then we
19670  * need to be careful to avoid cases such as the below, where it may be ok
19671  * for one branch accessing the pointer, but not ok for the other branch:
19672  *
19673  * R1 = sock_ptr
19674  * goto X;
19675  * ...
19676  * R1 = some_other_valid_ptr;
19677  * goto X;
19678  * ...
19679  * R2 = *(u32 *)(R1 + 0);
19680  */
19681 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
19682 {
19683 	return src != prev && (!reg_type_mismatch_ok(src) ||
19684 			       !reg_type_mismatch_ok(prev));
19685 }
19686 
19687 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
19688 {
19689 	switch (base_type(type)) {
19690 	case PTR_TO_MEM:
19691 	case PTR_TO_BTF_ID:
19692 		return true;
19693 	default:
19694 		return false;
19695 	}
19696 }
19697 
19698 static bool is_ptr_to_mem(enum bpf_reg_type type)
19699 {
19700 	return base_type(type) == PTR_TO_MEM;
19701 }
19702 
19703 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
19704 			     bool allow_trust_mismatch)
19705 {
19706 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
19707 	enum bpf_reg_type merged_type;
19708 
19709 	if (*prev_type == NOT_INIT) {
19710 		/* Saw a valid insn
19711 		 * dst_reg = *(u32 *)(src_reg + off)
19712 		 * save type to validate intersecting paths
19713 		 */
19714 		*prev_type = type;
19715 	} else if (reg_type_mismatch(type, *prev_type)) {
19716 		/* Abuser program is trying to use the same insn
19717 		 * dst_reg = *(u32*) (src_reg + off)
19718 		 * with different pointer types:
19719 		 * src_reg == ctx in one branch and
19720 		 * src_reg == stack|map in some other branch.
19721 		 * Reject it.
19722 		 */
19723 		if (allow_trust_mismatch &&
19724 		    is_ptr_to_mem_or_btf_id(type) &&
19725 		    is_ptr_to_mem_or_btf_id(*prev_type)) {
19726 			/*
19727 			 * Have to support a use case when one path through
19728 			 * the program yields TRUSTED pointer while another
19729 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
19730 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
19731 			 * Same behavior of MEM_RDONLY flag.
19732 			 */
19733 			if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type))
19734 				merged_type = PTR_TO_MEM;
19735 			else
19736 				merged_type = PTR_TO_BTF_ID;
19737 			if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED))
19738 				merged_type |= PTR_UNTRUSTED;
19739 			if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY))
19740 				merged_type |= MEM_RDONLY;
19741 			*prev_type = merged_type;
19742 		} else {
19743 			verbose(env, "same insn cannot be used with different pointers\n");
19744 			return -EINVAL;
19745 		}
19746 	}
19747 
19748 	return 0;
19749 }
19750 
19751 enum {
19752 	PROCESS_BPF_EXIT = 1
19753 };
19754 
19755 static int process_bpf_exit_full(struct bpf_verifier_env *env,
19756 				 bool *do_print_state,
19757 				 bool exception_exit)
19758 {
19759 	/* We must do check_reference_leak here before
19760 	 * prepare_func_exit to handle the case when
19761 	 * state->curframe > 0, it may be a callback function,
19762 	 * for which reference_state must match caller reference
19763 	 * state when it exits.
19764 	 */
19765 	int err = check_resource_leak(env, exception_exit,
19766 				      !env->cur_state->curframe,
19767 				      "BPF_EXIT instruction in main prog");
19768 	if (err)
19769 		return err;
19770 
19771 	/* The side effect of the prepare_func_exit which is
19772 	 * being skipped is that it frees bpf_func_state.
19773 	 * Typically, process_bpf_exit will only be hit with
19774 	 * outermost exit. copy_verifier_state in pop_stack will
19775 	 * handle freeing of any extra bpf_func_state left over
19776 	 * from not processing all nested function exits. We
19777 	 * also skip return code checks as they are not needed
19778 	 * for exceptional exits.
19779 	 */
19780 	if (exception_exit)
19781 		return PROCESS_BPF_EXIT;
19782 
19783 	if (env->cur_state->curframe) {
19784 		err = bpf_update_live_stack(env);
19785 		if (err)
19786 			return err;
19787 		/* exit from nested function */
19788 		err = prepare_func_exit(env, &env->insn_idx);
19789 		if (err)
19790 			return err;
19791 		*do_print_state = true;
19792 		return 0;
19793 	}
19794 
19795 	err = check_return_code(env, BPF_REG_0, "R0");
19796 	if (err)
19797 		return err;
19798 	return PROCESS_BPF_EXIT;
19799 }
19800 
19801 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
19802 {
19803 	int err;
19804 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
19805 	u8 class = BPF_CLASS(insn->code);
19806 
19807 	if (class == BPF_ALU || class == BPF_ALU64) {
19808 		err = check_alu_op(env, insn);
19809 		if (err)
19810 			return err;
19811 
19812 	} else if (class == BPF_LDX) {
19813 		bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX;
19814 
19815 		/* Check for reserved fields is already done in
19816 		 * resolve_pseudo_ldimm64().
19817 		 */
19818 		err = check_load_mem(env, insn, false, is_ldsx, true, "ldx");
19819 		if (err)
19820 			return err;
19821 	} else if (class == BPF_STX) {
19822 		if (BPF_MODE(insn->code) == BPF_ATOMIC) {
19823 			err = check_atomic(env, insn);
19824 			if (err)
19825 				return err;
19826 			env->insn_idx++;
19827 			return 0;
19828 		}
19829 
19830 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
19831 			verbose(env, "BPF_STX uses reserved fields\n");
19832 			return -EINVAL;
19833 		}
19834 
19835 		err = check_store_reg(env, insn, false);
19836 		if (err)
19837 			return err;
19838 	} else if (class == BPF_ST) {
19839 		enum bpf_reg_type dst_reg_type;
19840 
19841 		if (BPF_MODE(insn->code) != BPF_MEM ||
19842 		    insn->src_reg != BPF_REG_0) {
19843 			verbose(env, "BPF_ST uses reserved fields\n");
19844 			return -EINVAL;
19845 		}
19846 		/* check src operand */
19847 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
19848 		if (err)
19849 			return err;
19850 
19851 		dst_reg_type = cur_regs(env)[insn->dst_reg].type;
19852 
19853 		/* check that memory (dst_reg + off) is writeable */
19854 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
19855 				       insn->off, BPF_SIZE(insn->code),
19856 				       BPF_WRITE, -1, false, false);
19857 		if (err)
19858 			return err;
19859 
19860 		err = save_aux_ptr_type(env, dst_reg_type, false);
19861 		if (err)
19862 			return err;
19863 	} else if (class == BPF_JMP || class == BPF_JMP32) {
19864 		u8 opcode = BPF_OP(insn->code);
19865 
19866 		env->jmps_processed++;
19867 		if (opcode == BPF_CALL) {
19868 			if (BPF_SRC(insn->code) != BPF_K ||
19869 			    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL &&
19870 			     insn->off != 0) ||
19871 			    (insn->src_reg != BPF_REG_0 &&
19872 			     insn->src_reg != BPF_PSEUDO_CALL &&
19873 			     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
19874 			    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
19875 				verbose(env, "BPF_CALL uses reserved fields\n");
19876 				return -EINVAL;
19877 			}
19878 
19879 			if (env->cur_state->active_locks) {
19880 				if ((insn->src_reg == BPF_REG_0 &&
19881 				     insn->imm != BPF_FUNC_spin_unlock) ||
19882 				    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
19883 				     (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
19884 					verbose(env,
19885 						"function calls are not allowed while holding a lock\n");
19886 					return -EINVAL;
19887 				}
19888 			}
19889 			if (insn->src_reg == BPF_PSEUDO_CALL) {
19890 				err = check_func_call(env, insn, &env->insn_idx);
19891 			} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19892 				err = check_kfunc_call(env, insn, &env->insn_idx);
19893 				if (!err && is_bpf_throw_kfunc(insn))
19894 					return process_bpf_exit_full(env, do_print_state, true);
19895 			} else {
19896 				err = check_helper_call(env, insn, &env->insn_idx);
19897 			}
19898 			if (err)
19899 				return err;
19900 
19901 			mark_reg_scratched(env, BPF_REG_0);
19902 		} else if (opcode == BPF_JA) {
19903 			if (BPF_SRC(insn->code) != BPF_K ||
19904 			    insn->src_reg != BPF_REG_0 ||
19905 			    insn->dst_reg != BPF_REG_0 ||
19906 			    (class == BPF_JMP && insn->imm != 0) ||
19907 			    (class == BPF_JMP32 && insn->off != 0)) {
19908 				verbose(env, "BPF_JA uses reserved fields\n");
19909 				return -EINVAL;
19910 			}
19911 
19912 			if (class == BPF_JMP)
19913 				env->insn_idx += insn->off + 1;
19914 			else
19915 				env->insn_idx += insn->imm + 1;
19916 			return 0;
19917 		} else if (opcode == BPF_EXIT) {
19918 			if (BPF_SRC(insn->code) != BPF_K ||
19919 			    insn->imm != 0 ||
19920 			    insn->src_reg != BPF_REG_0 ||
19921 			    insn->dst_reg != BPF_REG_0 ||
19922 			    class == BPF_JMP32) {
19923 				verbose(env, "BPF_EXIT uses reserved fields\n");
19924 				return -EINVAL;
19925 			}
19926 			return process_bpf_exit_full(env, do_print_state, false);
19927 		} else {
19928 			err = check_cond_jmp_op(env, insn, &env->insn_idx);
19929 			if (err)
19930 				return err;
19931 		}
19932 	} else if (class == BPF_LD) {
19933 		u8 mode = BPF_MODE(insn->code);
19934 
19935 		if (mode == BPF_ABS || mode == BPF_IND) {
19936 			err = check_ld_abs(env, insn);
19937 			if (err)
19938 				return err;
19939 
19940 		} else if (mode == BPF_IMM) {
19941 			err = check_ld_imm(env, insn);
19942 			if (err)
19943 				return err;
19944 
19945 			env->insn_idx++;
19946 			sanitize_mark_insn_seen(env);
19947 		} else {
19948 			verbose(env, "invalid BPF_LD mode\n");
19949 			return -EINVAL;
19950 		}
19951 	} else {
19952 		verbose(env, "unknown insn class %d\n", class);
19953 		return -EINVAL;
19954 	}
19955 
19956 	env->insn_idx++;
19957 	return 0;
19958 }
19959 
19960 static int do_check(struct bpf_verifier_env *env)
19961 {
19962 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19963 	struct bpf_verifier_state *state = env->cur_state;
19964 	struct bpf_insn *insns = env->prog->insnsi;
19965 	int insn_cnt = env->prog->len;
19966 	bool do_print_state = false;
19967 	int prev_insn_idx = -1;
19968 
19969 	for (;;) {
19970 		struct bpf_insn *insn;
19971 		struct bpf_insn_aux_data *insn_aux;
19972 		int err, marks_err;
19973 
19974 		/* reset current history entry on each new instruction */
19975 		env->cur_hist_ent = NULL;
19976 
19977 		env->prev_insn_idx = prev_insn_idx;
19978 		if (env->insn_idx >= insn_cnt) {
19979 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
19980 				env->insn_idx, insn_cnt);
19981 			return -EFAULT;
19982 		}
19983 
19984 		insn = &insns[env->insn_idx];
19985 		insn_aux = &env->insn_aux_data[env->insn_idx];
19986 
19987 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
19988 			verbose(env,
19989 				"BPF program is too large. Processed %d insn\n",
19990 				env->insn_processed);
19991 			return -E2BIG;
19992 		}
19993 
19994 		state->last_insn_idx = env->prev_insn_idx;
19995 		state->insn_idx = env->insn_idx;
19996 
19997 		if (is_prune_point(env, env->insn_idx)) {
19998 			err = is_state_visited(env, env->insn_idx);
19999 			if (err < 0)
20000 				return err;
20001 			if (err == 1) {
20002 				/* found equivalent state, can prune the search */
20003 				if (env->log.level & BPF_LOG_LEVEL) {
20004 					if (do_print_state)
20005 						verbose(env, "\nfrom %d to %d%s: safe\n",
20006 							env->prev_insn_idx, env->insn_idx,
20007 							env->cur_state->speculative ?
20008 							" (speculative execution)" : "");
20009 					else
20010 						verbose(env, "%d: safe\n", env->insn_idx);
20011 				}
20012 				goto process_bpf_exit;
20013 			}
20014 		}
20015 
20016 		if (is_jmp_point(env, env->insn_idx)) {
20017 			err = push_jmp_history(env, state, 0, 0);
20018 			if (err)
20019 				return err;
20020 		}
20021 
20022 		if (signal_pending(current))
20023 			return -EAGAIN;
20024 
20025 		if (need_resched())
20026 			cond_resched();
20027 
20028 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
20029 			verbose(env, "\nfrom %d to %d%s:",
20030 				env->prev_insn_idx, env->insn_idx,
20031 				env->cur_state->speculative ?
20032 				" (speculative execution)" : "");
20033 			print_verifier_state(env, state, state->curframe, true);
20034 			do_print_state = false;
20035 		}
20036 
20037 		if (env->log.level & BPF_LOG_LEVEL) {
20038 			if (verifier_state_scratched(env))
20039 				print_insn_state(env, state, state->curframe);
20040 
20041 			verbose_linfo(env, env->insn_idx, "; ");
20042 			env->prev_log_pos = env->log.end_pos;
20043 			verbose(env, "%d: ", env->insn_idx);
20044 			verbose_insn(env, insn);
20045 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
20046 			env->prev_log_pos = env->log.end_pos;
20047 		}
20048 
20049 		if (bpf_prog_is_offloaded(env->prog->aux)) {
20050 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
20051 							   env->prev_insn_idx);
20052 			if (err)
20053 				return err;
20054 		}
20055 
20056 		sanitize_mark_insn_seen(env);
20057 		prev_insn_idx = env->insn_idx;
20058 
20059 		/* Reduce verification complexity by stopping speculative path
20060 		 * verification when a nospec is encountered.
20061 		 */
20062 		if (state->speculative && insn_aux->nospec)
20063 			goto process_bpf_exit;
20064 
20065 		err = bpf_reset_stack_write_marks(env, env->insn_idx);
20066 		if (err)
20067 			return err;
20068 		err = do_check_insn(env, &do_print_state);
20069 		if (err >= 0 || error_recoverable_with_nospec(err)) {
20070 			marks_err = bpf_commit_stack_write_marks(env);
20071 			if (marks_err)
20072 				return marks_err;
20073 		}
20074 		if (error_recoverable_with_nospec(err) && state->speculative) {
20075 			/* Prevent this speculative path from ever reaching the
20076 			 * insn that would have been unsafe to execute.
20077 			 */
20078 			insn_aux->nospec = true;
20079 			/* If it was an ADD/SUB insn, potentially remove any
20080 			 * markings for alu sanitization.
20081 			 */
20082 			insn_aux->alu_state = 0;
20083 			goto process_bpf_exit;
20084 		} else if (err < 0) {
20085 			return err;
20086 		} else if (err == PROCESS_BPF_EXIT) {
20087 			goto process_bpf_exit;
20088 		}
20089 		WARN_ON_ONCE(err);
20090 
20091 		if (state->speculative && insn_aux->nospec_result) {
20092 			/* If we are on a path that performed a jump-op, this
20093 			 * may skip a nospec patched-in after the jump. This can
20094 			 * currently never happen because nospec_result is only
20095 			 * used for the write-ops
20096 			 * `*(size*)(dst_reg+off)=src_reg|imm32` which must
20097 			 * never skip the following insn. Still, add a warning
20098 			 * to document this in case nospec_result is used
20099 			 * elsewhere in the future.
20100 			 *
20101 			 * All non-branch instructions have a single
20102 			 * fall-through edge. For these, nospec_result should
20103 			 * already work.
20104 			 */
20105 			if (verifier_bug_if(BPF_CLASS(insn->code) == BPF_JMP ||
20106 					    BPF_CLASS(insn->code) == BPF_JMP32, env,
20107 					    "speculation barrier after jump instruction may not have the desired effect"))
20108 				return -EFAULT;
20109 process_bpf_exit:
20110 			mark_verifier_state_scratched(env);
20111 			err = update_branch_counts(env, env->cur_state);
20112 			if (err)
20113 				return err;
20114 			err = bpf_update_live_stack(env);
20115 			if (err)
20116 				return err;
20117 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
20118 					pop_log);
20119 			if (err < 0) {
20120 				if (err != -ENOENT)
20121 					return err;
20122 				break;
20123 			} else {
20124 				do_print_state = true;
20125 				continue;
20126 			}
20127 		}
20128 	}
20129 
20130 	return 0;
20131 }
20132 
20133 static int find_btf_percpu_datasec(struct btf *btf)
20134 {
20135 	const struct btf_type *t;
20136 	const char *tname;
20137 	int i, n;
20138 
20139 	/*
20140 	 * Both vmlinux and module each have their own ".data..percpu"
20141 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
20142 	 * types to look at only module's own BTF types.
20143 	 */
20144 	n = btf_nr_types(btf);
20145 	if (btf_is_module(btf))
20146 		i = btf_nr_types(btf_vmlinux);
20147 	else
20148 		i = 1;
20149 
20150 	for(; i < n; i++) {
20151 		t = btf_type_by_id(btf, i);
20152 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
20153 			continue;
20154 
20155 		tname = btf_name_by_offset(btf, t->name_off);
20156 		if (!strcmp(tname, ".data..percpu"))
20157 			return i;
20158 	}
20159 
20160 	return -ENOENT;
20161 }
20162 
20163 /*
20164  * Add btf to the used_btfs array and return the index. (If the btf was
20165  * already added, then just return the index.) Upon successful insertion
20166  * increase btf refcnt, and, if present, also refcount the corresponding
20167  * kernel module.
20168  */
20169 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
20170 {
20171 	struct btf_mod_pair *btf_mod;
20172 	int i;
20173 
20174 	/* check whether we recorded this BTF (and maybe module) already */
20175 	for (i = 0; i < env->used_btf_cnt; i++)
20176 		if (env->used_btfs[i].btf == btf)
20177 			return i;
20178 
20179 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
20180 		verbose(env, "The total number of btfs per program has reached the limit of %u\n",
20181 			MAX_USED_BTFS);
20182 		return -E2BIG;
20183 	}
20184 
20185 	btf_get(btf);
20186 
20187 	btf_mod = &env->used_btfs[env->used_btf_cnt];
20188 	btf_mod->btf = btf;
20189 	btf_mod->module = NULL;
20190 
20191 	/* if we reference variables from kernel module, bump its refcount */
20192 	if (btf_is_module(btf)) {
20193 		btf_mod->module = btf_try_get_module(btf);
20194 		if (!btf_mod->module) {
20195 			btf_put(btf);
20196 			return -ENXIO;
20197 		}
20198 	}
20199 
20200 	return env->used_btf_cnt++;
20201 }
20202 
20203 /* replace pseudo btf_id with kernel symbol address */
20204 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
20205 				 struct bpf_insn *insn,
20206 				 struct bpf_insn_aux_data *aux,
20207 				 struct btf *btf)
20208 {
20209 	const struct btf_var_secinfo *vsi;
20210 	const struct btf_type *datasec;
20211 	const struct btf_type *t;
20212 	const char *sym_name;
20213 	bool percpu = false;
20214 	u32 type, id = insn->imm;
20215 	s32 datasec_id;
20216 	u64 addr;
20217 	int i;
20218 
20219 	t = btf_type_by_id(btf, id);
20220 	if (!t) {
20221 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
20222 		return -ENOENT;
20223 	}
20224 
20225 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
20226 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
20227 		return -EINVAL;
20228 	}
20229 
20230 	sym_name = btf_name_by_offset(btf, t->name_off);
20231 	addr = kallsyms_lookup_name(sym_name);
20232 	if (!addr) {
20233 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
20234 			sym_name);
20235 		return -ENOENT;
20236 	}
20237 	insn[0].imm = (u32)addr;
20238 	insn[1].imm = addr >> 32;
20239 
20240 	if (btf_type_is_func(t)) {
20241 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20242 		aux->btf_var.mem_size = 0;
20243 		return 0;
20244 	}
20245 
20246 	datasec_id = find_btf_percpu_datasec(btf);
20247 	if (datasec_id > 0) {
20248 		datasec = btf_type_by_id(btf, datasec_id);
20249 		for_each_vsi(i, datasec, vsi) {
20250 			if (vsi->type == id) {
20251 				percpu = true;
20252 				break;
20253 			}
20254 		}
20255 	}
20256 
20257 	type = t->type;
20258 	t = btf_type_skip_modifiers(btf, type, NULL);
20259 	if (percpu) {
20260 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
20261 		aux->btf_var.btf = btf;
20262 		aux->btf_var.btf_id = type;
20263 	} else if (!btf_type_is_struct(t)) {
20264 		const struct btf_type *ret;
20265 		const char *tname;
20266 		u32 tsize;
20267 
20268 		/* resolve the type size of ksym. */
20269 		ret = btf_resolve_size(btf, t, &tsize);
20270 		if (IS_ERR(ret)) {
20271 			tname = btf_name_by_offset(btf, t->name_off);
20272 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
20273 				tname, PTR_ERR(ret));
20274 			return -EINVAL;
20275 		}
20276 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20277 		aux->btf_var.mem_size = tsize;
20278 	} else {
20279 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
20280 		aux->btf_var.btf = btf;
20281 		aux->btf_var.btf_id = type;
20282 	}
20283 
20284 	return 0;
20285 }
20286 
20287 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
20288 			       struct bpf_insn *insn,
20289 			       struct bpf_insn_aux_data *aux)
20290 {
20291 	struct btf *btf;
20292 	int btf_fd;
20293 	int err;
20294 
20295 	btf_fd = insn[1].imm;
20296 	if (btf_fd) {
20297 		CLASS(fd, f)(btf_fd);
20298 
20299 		btf = __btf_get_by_fd(f);
20300 		if (IS_ERR(btf)) {
20301 			verbose(env, "invalid module BTF object FD specified.\n");
20302 			return -EINVAL;
20303 		}
20304 	} else {
20305 		if (!btf_vmlinux) {
20306 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
20307 			return -EINVAL;
20308 		}
20309 		btf = btf_vmlinux;
20310 	}
20311 
20312 	err = __check_pseudo_btf_id(env, insn, aux, btf);
20313 	if (err)
20314 		return err;
20315 
20316 	err = __add_used_btf(env, btf);
20317 	if (err < 0)
20318 		return err;
20319 	return 0;
20320 }
20321 
20322 static bool is_tracing_prog_type(enum bpf_prog_type type)
20323 {
20324 	switch (type) {
20325 	case BPF_PROG_TYPE_KPROBE:
20326 	case BPF_PROG_TYPE_TRACEPOINT:
20327 	case BPF_PROG_TYPE_PERF_EVENT:
20328 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
20329 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
20330 		return true;
20331 	default:
20332 		return false;
20333 	}
20334 }
20335 
20336 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
20337 {
20338 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
20339 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
20340 }
20341 
20342 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
20343 					struct bpf_map *map,
20344 					struct bpf_prog *prog)
20345 
20346 {
20347 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
20348 
20349 	if (map->excl_prog_sha &&
20350 	    memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) {
20351 		verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
20352 		return -EACCES;
20353 	}
20354 
20355 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
20356 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
20357 		if (is_tracing_prog_type(prog_type)) {
20358 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
20359 			return -EINVAL;
20360 		}
20361 	}
20362 
20363 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
20364 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
20365 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
20366 			return -EINVAL;
20367 		}
20368 
20369 		if (is_tracing_prog_type(prog_type)) {
20370 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
20371 			return -EINVAL;
20372 		}
20373 	}
20374 
20375 	if (btf_record_has_field(map->record, BPF_TIMER)) {
20376 		if (is_tracing_prog_type(prog_type)) {
20377 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
20378 			return -EINVAL;
20379 		}
20380 	}
20381 
20382 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
20383 		if (is_tracing_prog_type(prog_type)) {
20384 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
20385 			return -EINVAL;
20386 		}
20387 	}
20388 
20389 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
20390 	    !bpf_offload_prog_map_match(prog, map)) {
20391 		verbose(env, "offload device mismatch between prog and map\n");
20392 		return -EINVAL;
20393 	}
20394 
20395 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
20396 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
20397 		return -EINVAL;
20398 	}
20399 
20400 	if (prog->sleepable)
20401 		switch (map->map_type) {
20402 		case BPF_MAP_TYPE_HASH:
20403 		case BPF_MAP_TYPE_LRU_HASH:
20404 		case BPF_MAP_TYPE_ARRAY:
20405 		case BPF_MAP_TYPE_PERCPU_HASH:
20406 		case BPF_MAP_TYPE_PERCPU_ARRAY:
20407 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
20408 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
20409 		case BPF_MAP_TYPE_HASH_OF_MAPS:
20410 		case BPF_MAP_TYPE_RINGBUF:
20411 		case BPF_MAP_TYPE_USER_RINGBUF:
20412 		case BPF_MAP_TYPE_INODE_STORAGE:
20413 		case BPF_MAP_TYPE_SK_STORAGE:
20414 		case BPF_MAP_TYPE_TASK_STORAGE:
20415 		case BPF_MAP_TYPE_CGRP_STORAGE:
20416 		case BPF_MAP_TYPE_QUEUE:
20417 		case BPF_MAP_TYPE_STACK:
20418 		case BPF_MAP_TYPE_ARENA:
20419 			break;
20420 		default:
20421 			verbose(env,
20422 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
20423 			return -EINVAL;
20424 		}
20425 
20426 	if (bpf_map_is_cgroup_storage(map) &&
20427 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
20428 		verbose(env, "only one cgroup storage of each type is allowed\n");
20429 		return -EBUSY;
20430 	}
20431 
20432 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
20433 		if (env->prog->aux->arena) {
20434 			verbose(env, "Only one arena per program\n");
20435 			return -EBUSY;
20436 		}
20437 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
20438 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
20439 			return -EPERM;
20440 		}
20441 		if (!env->prog->jit_requested) {
20442 			verbose(env, "JIT is required to use arena\n");
20443 			return -EOPNOTSUPP;
20444 		}
20445 		if (!bpf_jit_supports_arena()) {
20446 			verbose(env, "JIT doesn't support arena\n");
20447 			return -EOPNOTSUPP;
20448 		}
20449 		env->prog->aux->arena = (void *)map;
20450 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
20451 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
20452 			return -EINVAL;
20453 		}
20454 	}
20455 
20456 	return 0;
20457 }
20458 
20459 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
20460 {
20461 	int i, err;
20462 
20463 	/* check whether we recorded this map already */
20464 	for (i = 0; i < env->used_map_cnt; i++)
20465 		if (env->used_maps[i] == map)
20466 			return i;
20467 
20468 	if (env->used_map_cnt >= MAX_USED_MAPS) {
20469 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
20470 			MAX_USED_MAPS);
20471 		return -E2BIG;
20472 	}
20473 
20474 	err = check_map_prog_compatibility(env, map, env->prog);
20475 	if (err)
20476 		return err;
20477 
20478 	if (env->prog->sleepable)
20479 		atomic64_inc(&map->sleepable_refcnt);
20480 
20481 	/* hold the map. If the program is rejected by verifier,
20482 	 * the map will be released by release_maps() or it
20483 	 * will be used by the valid program until it's unloaded
20484 	 * and all maps are released in bpf_free_used_maps()
20485 	 */
20486 	bpf_map_inc(map);
20487 
20488 	env->used_maps[env->used_map_cnt++] = map;
20489 
20490 	return env->used_map_cnt - 1;
20491 }
20492 
20493 /* Add map behind fd to used maps list, if it's not already there, and return
20494  * its index.
20495  * Returns <0 on error, or >= 0 index, on success.
20496  */
20497 static int add_used_map(struct bpf_verifier_env *env, int fd)
20498 {
20499 	struct bpf_map *map;
20500 	CLASS(fd, f)(fd);
20501 
20502 	map = __bpf_map_get(f);
20503 	if (IS_ERR(map)) {
20504 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
20505 		return PTR_ERR(map);
20506 	}
20507 
20508 	return __add_used_map(env, map);
20509 }
20510 
20511 /* find and rewrite pseudo imm in ld_imm64 instructions:
20512  *
20513  * 1. if it accesses map FD, replace it with actual map pointer.
20514  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
20515  *
20516  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
20517  */
20518 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
20519 {
20520 	struct bpf_insn *insn = env->prog->insnsi;
20521 	int insn_cnt = env->prog->len;
20522 	int i, err;
20523 
20524 	err = bpf_prog_calc_tag(env->prog);
20525 	if (err)
20526 		return err;
20527 
20528 	for (i = 0; i < insn_cnt; i++, insn++) {
20529 		if (BPF_CLASS(insn->code) == BPF_LDX &&
20530 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
20531 		    insn->imm != 0)) {
20532 			verbose(env, "BPF_LDX uses reserved fields\n");
20533 			return -EINVAL;
20534 		}
20535 
20536 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
20537 			struct bpf_insn_aux_data *aux;
20538 			struct bpf_map *map;
20539 			int map_idx;
20540 			u64 addr;
20541 			u32 fd;
20542 
20543 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
20544 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
20545 			    insn[1].off != 0) {
20546 				verbose(env, "invalid bpf_ld_imm64 insn\n");
20547 				return -EINVAL;
20548 			}
20549 
20550 			if (insn[0].src_reg == 0)
20551 				/* valid generic load 64-bit imm */
20552 				goto next_insn;
20553 
20554 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
20555 				aux = &env->insn_aux_data[i];
20556 				err = check_pseudo_btf_id(env, insn, aux);
20557 				if (err)
20558 					return err;
20559 				goto next_insn;
20560 			}
20561 
20562 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
20563 				aux = &env->insn_aux_data[i];
20564 				aux->ptr_type = PTR_TO_FUNC;
20565 				goto next_insn;
20566 			}
20567 
20568 			/* In final convert_pseudo_ld_imm64() step, this is
20569 			 * converted into regular 64-bit imm load insn.
20570 			 */
20571 			switch (insn[0].src_reg) {
20572 			case BPF_PSEUDO_MAP_VALUE:
20573 			case BPF_PSEUDO_MAP_IDX_VALUE:
20574 				break;
20575 			case BPF_PSEUDO_MAP_FD:
20576 			case BPF_PSEUDO_MAP_IDX:
20577 				if (insn[1].imm == 0)
20578 					break;
20579 				fallthrough;
20580 			default:
20581 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
20582 				return -EINVAL;
20583 			}
20584 
20585 			switch (insn[0].src_reg) {
20586 			case BPF_PSEUDO_MAP_IDX_VALUE:
20587 			case BPF_PSEUDO_MAP_IDX:
20588 				if (bpfptr_is_null(env->fd_array)) {
20589 					verbose(env, "fd_idx without fd_array is invalid\n");
20590 					return -EPROTO;
20591 				}
20592 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
20593 							    insn[0].imm * sizeof(fd),
20594 							    sizeof(fd)))
20595 					return -EFAULT;
20596 				break;
20597 			default:
20598 				fd = insn[0].imm;
20599 				break;
20600 			}
20601 
20602 			map_idx = add_used_map(env, fd);
20603 			if (map_idx < 0)
20604 				return map_idx;
20605 			map = env->used_maps[map_idx];
20606 
20607 			aux = &env->insn_aux_data[i];
20608 			aux->map_index = map_idx;
20609 
20610 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
20611 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
20612 				addr = (unsigned long)map;
20613 			} else {
20614 				u32 off = insn[1].imm;
20615 
20616 				if (off >= BPF_MAX_VAR_OFF) {
20617 					verbose(env, "direct value offset of %u is not allowed\n", off);
20618 					return -EINVAL;
20619 				}
20620 
20621 				if (!map->ops->map_direct_value_addr) {
20622 					verbose(env, "no direct value access support for this map type\n");
20623 					return -EINVAL;
20624 				}
20625 
20626 				err = map->ops->map_direct_value_addr(map, &addr, off);
20627 				if (err) {
20628 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
20629 						map->value_size, off);
20630 					return err;
20631 				}
20632 
20633 				aux->map_off = off;
20634 				addr += off;
20635 			}
20636 
20637 			insn[0].imm = (u32)addr;
20638 			insn[1].imm = addr >> 32;
20639 
20640 next_insn:
20641 			insn++;
20642 			i++;
20643 			continue;
20644 		}
20645 
20646 		/* Basic sanity check before we invest more work here. */
20647 		if (!bpf_opcode_in_insntable(insn->code)) {
20648 			verbose(env, "unknown opcode %02x\n", insn->code);
20649 			return -EINVAL;
20650 		}
20651 	}
20652 
20653 	/* now all pseudo BPF_LD_IMM64 instructions load valid
20654 	 * 'struct bpf_map *' into a register instead of user map_fd.
20655 	 * These pointers will be used later by verifier to validate map access.
20656 	 */
20657 	return 0;
20658 }
20659 
20660 /* drop refcnt of maps used by the rejected program */
20661 static void release_maps(struct bpf_verifier_env *env)
20662 {
20663 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
20664 			     env->used_map_cnt);
20665 }
20666 
20667 /* drop refcnt of maps used by the rejected program */
20668 static void release_btfs(struct bpf_verifier_env *env)
20669 {
20670 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
20671 }
20672 
20673 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
20674 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
20675 {
20676 	struct bpf_insn *insn = env->prog->insnsi;
20677 	int insn_cnt = env->prog->len;
20678 	int i;
20679 
20680 	for (i = 0; i < insn_cnt; i++, insn++) {
20681 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
20682 			continue;
20683 		if (insn->src_reg == BPF_PSEUDO_FUNC)
20684 			continue;
20685 		insn->src_reg = 0;
20686 	}
20687 }
20688 
20689 /* single env->prog->insni[off] instruction was replaced with the range
20690  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
20691  * [0, off) and [off, end) to new locations, so the patched range stays zero
20692  */
20693 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
20694 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
20695 {
20696 	struct bpf_insn_aux_data *data = env->insn_aux_data;
20697 	struct bpf_insn *insn = new_prog->insnsi;
20698 	u32 old_seen = data[off].seen;
20699 	u32 prog_len;
20700 	int i;
20701 
20702 	/* aux info at OFF always needs adjustment, no matter fast path
20703 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
20704 	 * original insn at old prog.
20705 	 */
20706 	data[off].zext_dst = insn_has_def32(insn + off + cnt - 1);
20707 
20708 	if (cnt == 1)
20709 		return;
20710 	prog_len = new_prog->len;
20711 
20712 	memmove(data + off + cnt - 1, data + off,
20713 		sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
20714 	memset(data + off, 0, sizeof(struct bpf_insn_aux_data) * (cnt - 1));
20715 	for (i = off; i < off + cnt - 1; i++) {
20716 		/* Expand insni[off]'s seen count to the patched range. */
20717 		data[i].seen = old_seen;
20718 		data[i].zext_dst = insn_has_def32(insn + i);
20719 	}
20720 }
20721 
20722 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
20723 {
20724 	int i;
20725 
20726 	if (len == 1)
20727 		return;
20728 	/* NOTE: fake 'exit' subprog should be updated as well. */
20729 	for (i = 0; i <= env->subprog_cnt; i++) {
20730 		if (env->subprog_info[i].start <= off)
20731 			continue;
20732 		env->subprog_info[i].start += len - 1;
20733 	}
20734 }
20735 
20736 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
20737 {
20738 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
20739 	int i, sz = prog->aux->size_poke_tab;
20740 	struct bpf_jit_poke_descriptor *desc;
20741 
20742 	for (i = 0; i < sz; i++) {
20743 		desc = &tab[i];
20744 		if (desc->insn_idx <= off)
20745 			continue;
20746 		desc->insn_idx += len - 1;
20747 	}
20748 }
20749 
20750 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
20751 					    const struct bpf_insn *patch, u32 len)
20752 {
20753 	struct bpf_prog *new_prog;
20754 	struct bpf_insn_aux_data *new_data = NULL;
20755 
20756 	if (len > 1) {
20757 		new_data = vrealloc(env->insn_aux_data,
20758 				    array_size(env->prog->len + len - 1,
20759 					       sizeof(struct bpf_insn_aux_data)),
20760 				    GFP_KERNEL_ACCOUNT | __GFP_ZERO);
20761 		if (!new_data)
20762 			return NULL;
20763 
20764 		env->insn_aux_data = new_data;
20765 	}
20766 
20767 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
20768 	if (IS_ERR(new_prog)) {
20769 		if (PTR_ERR(new_prog) == -ERANGE)
20770 			verbose(env,
20771 				"insn %d cannot be patched due to 16-bit range\n",
20772 				env->insn_aux_data[off].orig_idx);
20773 		return NULL;
20774 	}
20775 	adjust_insn_aux_data(env, new_prog, off, len);
20776 	adjust_subprog_starts(env, off, len);
20777 	adjust_poke_descs(new_prog, off, len);
20778 	return new_prog;
20779 }
20780 
20781 /*
20782  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
20783  * jump offset by 'delta'.
20784  */
20785 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
20786 {
20787 	struct bpf_insn *insn = prog->insnsi;
20788 	u32 insn_cnt = prog->len, i;
20789 	s32 imm;
20790 	s16 off;
20791 
20792 	for (i = 0; i < insn_cnt; i++, insn++) {
20793 		u8 code = insn->code;
20794 
20795 		if (tgt_idx <= i && i < tgt_idx + delta)
20796 			continue;
20797 
20798 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
20799 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
20800 			continue;
20801 
20802 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
20803 			if (i + 1 + insn->imm != tgt_idx)
20804 				continue;
20805 			if (check_add_overflow(insn->imm, delta, &imm))
20806 				return -ERANGE;
20807 			insn->imm = imm;
20808 		} else {
20809 			if (i + 1 + insn->off != tgt_idx)
20810 				continue;
20811 			if (check_add_overflow(insn->off, delta, &off))
20812 				return -ERANGE;
20813 			insn->off = off;
20814 		}
20815 	}
20816 	return 0;
20817 }
20818 
20819 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
20820 					      u32 off, u32 cnt)
20821 {
20822 	int i, j;
20823 
20824 	/* find first prog starting at or after off (first to remove) */
20825 	for (i = 0; i < env->subprog_cnt; i++)
20826 		if (env->subprog_info[i].start >= off)
20827 			break;
20828 	/* find first prog starting at or after off + cnt (first to stay) */
20829 	for (j = i; j < env->subprog_cnt; j++)
20830 		if (env->subprog_info[j].start >= off + cnt)
20831 			break;
20832 	/* if j doesn't start exactly at off + cnt, we are just removing
20833 	 * the front of previous prog
20834 	 */
20835 	if (env->subprog_info[j].start != off + cnt)
20836 		j--;
20837 
20838 	if (j > i) {
20839 		struct bpf_prog_aux *aux = env->prog->aux;
20840 		int move;
20841 
20842 		/* move fake 'exit' subprog as well */
20843 		move = env->subprog_cnt + 1 - j;
20844 
20845 		memmove(env->subprog_info + i,
20846 			env->subprog_info + j,
20847 			sizeof(*env->subprog_info) * move);
20848 		env->subprog_cnt -= j - i;
20849 
20850 		/* remove func_info */
20851 		if (aux->func_info) {
20852 			move = aux->func_info_cnt - j;
20853 
20854 			memmove(aux->func_info + i,
20855 				aux->func_info + j,
20856 				sizeof(*aux->func_info) * move);
20857 			aux->func_info_cnt -= j - i;
20858 			/* func_info->insn_off is set after all code rewrites,
20859 			 * in adjust_btf_func() - no need to adjust
20860 			 */
20861 		}
20862 	} else {
20863 		/* convert i from "first prog to remove" to "first to adjust" */
20864 		if (env->subprog_info[i].start == off)
20865 			i++;
20866 	}
20867 
20868 	/* update fake 'exit' subprog as well */
20869 	for (; i <= env->subprog_cnt; i++)
20870 		env->subprog_info[i].start -= cnt;
20871 
20872 	return 0;
20873 }
20874 
20875 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
20876 				      u32 cnt)
20877 {
20878 	struct bpf_prog *prog = env->prog;
20879 	u32 i, l_off, l_cnt, nr_linfo;
20880 	struct bpf_line_info *linfo;
20881 
20882 	nr_linfo = prog->aux->nr_linfo;
20883 	if (!nr_linfo)
20884 		return 0;
20885 
20886 	linfo = prog->aux->linfo;
20887 
20888 	/* find first line info to remove, count lines to be removed */
20889 	for (i = 0; i < nr_linfo; i++)
20890 		if (linfo[i].insn_off >= off)
20891 			break;
20892 
20893 	l_off = i;
20894 	l_cnt = 0;
20895 	for (; i < nr_linfo; i++)
20896 		if (linfo[i].insn_off < off + cnt)
20897 			l_cnt++;
20898 		else
20899 			break;
20900 
20901 	/* First live insn doesn't match first live linfo, it needs to "inherit"
20902 	 * last removed linfo.  prog is already modified, so prog->len == off
20903 	 * means no live instructions after (tail of the program was removed).
20904 	 */
20905 	if (prog->len != off && l_cnt &&
20906 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
20907 		l_cnt--;
20908 		linfo[--i].insn_off = off + cnt;
20909 	}
20910 
20911 	/* remove the line info which refer to the removed instructions */
20912 	if (l_cnt) {
20913 		memmove(linfo + l_off, linfo + i,
20914 			sizeof(*linfo) * (nr_linfo - i));
20915 
20916 		prog->aux->nr_linfo -= l_cnt;
20917 		nr_linfo = prog->aux->nr_linfo;
20918 	}
20919 
20920 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
20921 	for (i = l_off; i < nr_linfo; i++)
20922 		linfo[i].insn_off -= cnt;
20923 
20924 	/* fix up all subprogs (incl. 'exit') which start >= off */
20925 	for (i = 0; i <= env->subprog_cnt; i++)
20926 		if (env->subprog_info[i].linfo_idx > l_off) {
20927 			/* program may have started in the removed region but
20928 			 * may not be fully removed
20929 			 */
20930 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
20931 				env->subprog_info[i].linfo_idx -= l_cnt;
20932 			else
20933 				env->subprog_info[i].linfo_idx = l_off;
20934 		}
20935 
20936 	return 0;
20937 }
20938 
20939 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
20940 {
20941 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20942 	unsigned int orig_prog_len = env->prog->len;
20943 	int err;
20944 
20945 	if (bpf_prog_is_offloaded(env->prog->aux))
20946 		bpf_prog_offload_remove_insns(env, off, cnt);
20947 
20948 	err = bpf_remove_insns(env->prog, off, cnt);
20949 	if (err)
20950 		return err;
20951 
20952 	err = adjust_subprog_starts_after_remove(env, off, cnt);
20953 	if (err)
20954 		return err;
20955 
20956 	err = bpf_adj_linfo_after_remove(env, off, cnt);
20957 	if (err)
20958 		return err;
20959 
20960 	memmove(aux_data + off,	aux_data + off + cnt,
20961 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
20962 
20963 	return 0;
20964 }
20965 
20966 /* The verifier does more data flow analysis than llvm and will not
20967  * explore branches that are dead at run time. Malicious programs can
20968  * have dead code too. Therefore replace all dead at-run-time code
20969  * with 'ja -1'.
20970  *
20971  * Just nops are not optimal, e.g. if they would sit at the end of the
20972  * program and through another bug we would manage to jump there, then
20973  * we'd execute beyond program memory otherwise. Returning exception
20974  * code also wouldn't work since we can have subprogs where the dead
20975  * code could be located.
20976  */
20977 static void sanitize_dead_code(struct bpf_verifier_env *env)
20978 {
20979 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20980 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
20981 	struct bpf_insn *insn = env->prog->insnsi;
20982 	const int insn_cnt = env->prog->len;
20983 	int i;
20984 
20985 	for (i = 0; i < insn_cnt; i++) {
20986 		if (aux_data[i].seen)
20987 			continue;
20988 		memcpy(insn + i, &trap, sizeof(trap));
20989 		aux_data[i].zext_dst = false;
20990 	}
20991 }
20992 
20993 static bool insn_is_cond_jump(u8 code)
20994 {
20995 	u8 op;
20996 
20997 	op = BPF_OP(code);
20998 	if (BPF_CLASS(code) == BPF_JMP32)
20999 		return op != BPF_JA;
21000 
21001 	if (BPF_CLASS(code) != BPF_JMP)
21002 		return false;
21003 
21004 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
21005 }
21006 
21007 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
21008 {
21009 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21010 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21011 	struct bpf_insn *insn = env->prog->insnsi;
21012 	const int insn_cnt = env->prog->len;
21013 	int i;
21014 
21015 	for (i = 0; i < insn_cnt; i++, insn++) {
21016 		if (!insn_is_cond_jump(insn->code))
21017 			continue;
21018 
21019 		if (!aux_data[i + 1].seen)
21020 			ja.off = insn->off;
21021 		else if (!aux_data[i + 1 + insn->off].seen)
21022 			ja.off = 0;
21023 		else
21024 			continue;
21025 
21026 		if (bpf_prog_is_offloaded(env->prog->aux))
21027 			bpf_prog_offload_replace_insn(env, i, &ja);
21028 
21029 		memcpy(insn, &ja, sizeof(ja));
21030 	}
21031 }
21032 
21033 static int opt_remove_dead_code(struct bpf_verifier_env *env)
21034 {
21035 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21036 	int insn_cnt = env->prog->len;
21037 	int i, err;
21038 
21039 	for (i = 0; i < insn_cnt; i++) {
21040 		int j;
21041 
21042 		j = 0;
21043 		while (i + j < insn_cnt && !aux_data[i + j].seen)
21044 			j++;
21045 		if (!j)
21046 			continue;
21047 
21048 		err = verifier_remove_insns(env, i, j);
21049 		if (err)
21050 			return err;
21051 		insn_cnt = env->prog->len;
21052 	}
21053 
21054 	return 0;
21055 }
21056 
21057 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21058 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0);
21059 
21060 static int opt_remove_nops(struct bpf_verifier_env *env)
21061 {
21062 	struct bpf_insn *insn = env->prog->insnsi;
21063 	int insn_cnt = env->prog->len;
21064 	bool is_may_goto_0, is_ja;
21065 	int i, err;
21066 
21067 	for (i = 0; i < insn_cnt; i++) {
21068 		is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
21069 		is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP));
21070 
21071 		if (!is_may_goto_0 && !is_ja)
21072 			continue;
21073 
21074 		err = verifier_remove_insns(env, i, 1);
21075 		if (err)
21076 			return err;
21077 		insn_cnt--;
21078 		/* Go back one insn to catch may_goto +1; may_goto +0 sequence */
21079 		i -= (is_may_goto_0 && i > 0) ? 2 : 1;
21080 	}
21081 
21082 	return 0;
21083 }
21084 
21085 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
21086 					 const union bpf_attr *attr)
21087 {
21088 	struct bpf_insn *patch;
21089 	/* use env->insn_buf as two independent buffers */
21090 	struct bpf_insn *zext_patch = env->insn_buf;
21091 	struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2];
21092 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
21093 	int i, patch_len, delta = 0, len = env->prog->len;
21094 	struct bpf_insn *insns = env->prog->insnsi;
21095 	struct bpf_prog *new_prog;
21096 	bool rnd_hi32;
21097 
21098 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
21099 	zext_patch[1] = BPF_ZEXT_REG(0);
21100 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
21101 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
21102 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
21103 	for (i = 0; i < len; i++) {
21104 		int adj_idx = i + delta;
21105 		struct bpf_insn insn;
21106 		int load_reg;
21107 
21108 		insn = insns[adj_idx];
21109 		load_reg = insn_def_regno(&insn);
21110 		if (!aux[adj_idx].zext_dst) {
21111 			u8 code, class;
21112 			u32 imm_rnd;
21113 
21114 			if (!rnd_hi32)
21115 				continue;
21116 
21117 			code = insn.code;
21118 			class = BPF_CLASS(code);
21119 			if (load_reg == -1)
21120 				continue;
21121 
21122 			/* NOTE: arg "reg" (the fourth one) is only used for
21123 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
21124 			 *       here.
21125 			 */
21126 			if (is_reg64(&insn, load_reg, NULL, DST_OP)) {
21127 				if (class == BPF_LD &&
21128 				    BPF_MODE(code) == BPF_IMM)
21129 					i++;
21130 				continue;
21131 			}
21132 
21133 			/* ctx load could be transformed into wider load. */
21134 			if (class == BPF_LDX &&
21135 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
21136 				continue;
21137 
21138 			imm_rnd = get_random_u32();
21139 			rnd_hi32_patch[0] = insn;
21140 			rnd_hi32_patch[1].imm = imm_rnd;
21141 			rnd_hi32_patch[3].dst_reg = load_reg;
21142 			patch = rnd_hi32_patch;
21143 			patch_len = 4;
21144 			goto apply_patch_buffer;
21145 		}
21146 
21147 		/* Add in an zero-extend instruction if a) the JIT has requested
21148 		 * it or b) it's a CMPXCHG.
21149 		 *
21150 		 * The latter is because: BPF_CMPXCHG always loads a value into
21151 		 * R0, therefore always zero-extends. However some archs'
21152 		 * equivalent instruction only does this load when the
21153 		 * comparison is successful. This detail of CMPXCHG is
21154 		 * orthogonal to the general zero-extension behaviour of the
21155 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
21156 		 */
21157 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
21158 			continue;
21159 
21160 		/* Zero-extension is done by the caller. */
21161 		if (bpf_pseudo_kfunc_call(&insn))
21162 			continue;
21163 
21164 		if (verifier_bug_if(load_reg == -1, env,
21165 				    "zext_dst is set, but no reg is defined"))
21166 			return -EFAULT;
21167 
21168 		zext_patch[0] = insn;
21169 		zext_patch[1].dst_reg = load_reg;
21170 		zext_patch[1].src_reg = load_reg;
21171 		patch = zext_patch;
21172 		patch_len = 2;
21173 apply_patch_buffer:
21174 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
21175 		if (!new_prog)
21176 			return -ENOMEM;
21177 		env->prog = new_prog;
21178 		insns = new_prog->insnsi;
21179 		aux = env->insn_aux_data;
21180 		delta += patch_len - 1;
21181 	}
21182 
21183 	return 0;
21184 }
21185 
21186 /* convert load instructions that access fields of a context type into a
21187  * sequence of instructions that access fields of the underlying structure:
21188  *     struct __sk_buff    -> struct sk_buff
21189  *     struct bpf_sock_ops -> struct sock
21190  */
21191 static int convert_ctx_accesses(struct bpf_verifier_env *env)
21192 {
21193 	struct bpf_subprog_info *subprogs = env->subprog_info;
21194 	const struct bpf_verifier_ops *ops = env->ops;
21195 	int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
21196 	const int insn_cnt = env->prog->len;
21197 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
21198 	struct bpf_insn *insn_buf = env->insn_buf;
21199 	struct bpf_insn *insn;
21200 	u32 target_size, size_default, off;
21201 	struct bpf_prog *new_prog;
21202 	enum bpf_access_type type;
21203 	bool is_narrower_load;
21204 	int epilogue_idx = 0;
21205 
21206 	if (ops->gen_epilogue) {
21207 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
21208 						 -(subprogs[0].stack_depth + 8));
21209 		if (epilogue_cnt >= INSN_BUF_SIZE) {
21210 			verifier_bug(env, "epilogue is too long");
21211 			return -EFAULT;
21212 		} else if (epilogue_cnt) {
21213 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
21214 			cnt = 0;
21215 			subprogs[0].stack_depth += 8;
21216 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
21217 						      -subprogs[0].stack_depth);
21218 			insn_buf[cnt++] = env->prog->insnsi[0];
21219 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21220 			if (!new_prog)
21221 				return -ENOMEM;
21222 			env->prog = new_prog;
21223 			delta += cnt - 1;
21224 
21225 			ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
21226 			if (ret < 0)
21227 				return ret;
21228 		}
21229 	}
21230 
21231 	if (ops->gen_prologue || env->seen_direct_write) {
21232 		if (!ops->gen_prologue) {
21233 			verifier_bug(env, "gen_prologue is null");
21234 			return -EFAULT;
21235 		}
21236 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
21237 					env->prog);
21238 		if (cnt >= INSN_BUF_SIZE) {
21239 			verifier_bug(env, "prologue is too long");
21240 			return -EFAULT;
21241 		} else if (cnt) {
21242 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21243 			if (!new_prog)
21244 				return -ENOMEM;
21245 
21246 			env->prog = new_prog;
21247 			delta += cnt - 1;
21248 
21249 			ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
21250 			if (ret < 0)
21251 				return ret;
21252 		}
21253 	}
21254 
21255 	if (delta)
21256 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
21257 
21258 	if (bpf_prog_is_offloaded(env->prog->aux))
21259 		return 0;
21260 
21261 	insn = env->prog->insnsi + delta;
21262 
21263 	for (i = 0; i < insn_cnt; i++, insn++) {
21264 		bpf_convert_ctx_access_t convert_ctx_access;
21265 		u8 mode;
21266 
21267 		if (env->insn_aux_data[i + delta].nospec) {
21268 			WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state);
21269 			struct bpf_insn *patch = insn_buf;
21270 
21271 			*patch++ = BPF_ST_NOSPEC();
21272 			*patch++ = *insn;
21273 			cnt = patch - insn_buf;
21274 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21275 			if (!new_prog)
21276 				return -ENOMEM;
21277 
21278 			delta    += cnt - 1;
21279 			env->prog = new_prog;
21280 			insn      = new_prog->insnsi + i + delta;
21281 			/* This can not be easily merged with the
21282 			 * nospec_result-case, because an insn may require a
21283 			 * nospec before and after itself. Therefore also do not
21284 			 * 'continue' here but potentially apply further
21285 			 * patching to insn. *insn should equal patch[1] now.
21286 			 */
21287 		}
21288 
21289 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
21290 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
21291 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
21292 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
21293 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
21294 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
21295 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
21296 			type = BPF_READ;
21297 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
21298 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
21299 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
21300 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
21301 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
21302 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
21303 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
21304 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
21305 			type = BPF_WRITE;
21306 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) ||
21307 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) ||
21308 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
21309 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
21310 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
21311 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
21312 			env->prog->aux->num_exentries++;
21313 			continue;
21314 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
21315 			   epilogue_cnt &&
21316 			   i + delta < subprogs[1].start) {
21317 			/* Generate epilogue for the main prog */
21318 			if (epilogue_idx) {
21319 				/* jump back to the earlier generated epilogue */
21320 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
21321 				cnt = 1;
21322 			} else {
21323 				memcpy(insn_buf, epilogue_buf,
21324 				       epilogue_cnt * sizeof(*epilogue_buf));
21325 				cnt = epilogue_cnt;
21326 				/* epilogue_idx cannot be 0. It must have at
21327 				 * least one ctx ptr saving insn before the
21328 				 * epilogue.
21329 				 */
21330 				epilogue_idx = i + delta;
21331 			}
21332 			goto patch_insn_buf;
21333 		} else {
21334 			continue;
21335 		}
21336 
21337 		if (type == BPF_WRITE &&
21338 		    env->insn_aux_data[i + delta].nospec_result) {
21339 			/* nospec_result is only used to mitigate Spectre v4 and
21340 			 * to limit verification-time for Spectre v1.
21341 			 */
21342 			struct bpf_insn *patch = insn_buf;
21343 
21344 			*patch++ = *insn;
21345 			*patch++ = BPF_ST_NOSPEC();
21346 			cnt = patch - insn_buf;
21347 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21348 			if (!new_prog)
21349 				return -ENOMEM;
21350 
21351 			delta    += cnt - 1;
21352 			env->prog = new_prog;
21353 			insn      = new_prog->insnsi + i + delta;
21354 			continue;
21355 		}
21356 
21357 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
21358 		case PTR_TO_CTX:
21359 			if (!ops->convert_ctx_access)
21360 				continue;
21361 			convert_ctx_access = ops->convert_ctx_access;
21362 			break;
21363 		case PTR_TO_SOCKET:
21364 		case PTR_TO_SOCK_COMMON:
21365 			convert_ctx_access = bpf_sock_convert_ctx_access;
21366 			break;
21367 		case PTR_TO_TCP_SOCK:
21368 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
21369 			break;
21370 		case PTR_TO_XDP_SOCK:
21371 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
21372 			break;
21373 		case PTR_TO_BTF_ID:
21374 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
21375 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
21376 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
21377 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
21378 		 * any faults for loads into such types. BPF_WRITE is disallowed
21379 		 * for this case.
21380 		 */
21381 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
21382 		case PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED:
21383 			if (type == BPF_READ) {
21384 				if (BPF_MODE(insn->code) == BPF_MEM)
21385 					insn->code = BPF_LDX | BPF_PROBE_MEM |
21386 						     BPF_SIZE((insn)->code);
21387 				else
21388 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
21389 						     BPF_SIZE((insn)->code);
21390 				env->prog->aux->num_exentries++;
21391 			}
21392 			continue;
21393 		case PTR_TO_ARENA:
21394 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
21395 				if (!bpf_jit_supports_insn(insn, true)) {
21396 					verbose(env, "sign extending loads from arena are not supported yet\n");
21397 					return -EOPNOTSUPP;
21398 				}
21399 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32SX | BPF_SIZE(insn->code);
21400 			} else {
21401 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
21402 			}
21403 			env->prog->aux->num_exentries++;
21404 			continue;
21405 		default:
21406 			continue;
21407 		}
21408 
21409 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
21410 		size = BPF_LDST_BYTES(insn);
21411 		mode = BPF_MODE(insn->code);
21412 
21413 		/* If the read access is a narrower load of the field,
21414 		 * convert to a 4/8-byte load, to minimum program type specific
21415 		 * convert_ctx_access changes. If conversion is successful,
21416 		 * we will apply proper mask to the result.
21417 		 */
21418 		is_narrower_load = size < ctx_field_size;
21419 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
21420 		off = insn->off;
21421 		if (is_narrower_load) {
21422 			u8 size_code;
21423 
21424 			if (type == BPF_WRITE) {
21425 				verifier_bug(env, "narrow ctx access misconfigured");
21426 				return -EFAULT;
21427 			}
21428 
21429 			size_code = BPF_H;
21430 			if (ctx_field_size == 4)
21431 				size_code = BPF_W;
21432 			else if (ctx_field_size == 8)
21433 				size_code = BPF_DW;
21434 
21435 			insn->off = off & ~(size_default - 1);
21436 			insn->code = BPF_LDX | BPF_MEM | size_code;
21437 		}
21438 
21439 		target_size = 0;
21440 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
21441 					 &target_size);
21442 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
21443 		    (ctx_field_size && !target_size)) {
21444 			verifier_bug(env, "error during ctx access conversion (%d)", cnt);
21445 			return -EFAULT;
21446 		}
21447 
21448 		if (is_narrower_load && size < target_size) {
21449 			u8 shift = bpf_ctx_narrow_access_offset(
21450 				off, size, size_default) * 8;
21451 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
21452 				verifier_bug(env, "narrow ctx load misconfigured");
21453 				return -EFAULT;
21454 			}
21455 			if (ctx_field_size <= 4) {
21456 				if (shift)
21457 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
21458 									insn->dst_reg,
21459 									shift);
21460 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
21461 								(1 << size * 8) - 1);
21462 			} else {
21463 				if (shift)
21464 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
21465 									insn->dst_reg,
21466 									shift);
21467 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
21468 								(1ULL << size * 8) - 1);
21469 			}
21470 		}
21471 		if (mode == BPF_MEMSX)
21472 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
21473 						       insn->dst_reg, insn->dst_reg,
21474 						       size * 8, 0);
21475 
21476 patch_insn_buf:
21477 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21478 		if (!new_prog)
21479 			return -ENOMEM;
21480 
21481 		delta += cnt - 1;
21482 
21483 		/* keep walking new program and skip insns we just inserted */
21484 		env->prog = new_prog;
21485 		insn      = new_prog->insnsi + i + delta;
21486 	}
21487 
21488 	return 0;
21489 }
21490 
21491 static int jit_subprogs(struct bpf_verifier_env *env)
21492 {
21493 	struct bpf_prog *prog = env->prog, **func, *tmp;
21494 	int i, j, subprog_start, subprog_end = 0, len, subprog;
21495 	struct bpf_map *map_ptr;
21496 	struct bpf_insn *insn;
21497 	void *old_bpf_func;
21498 	int err, num_exentries;
21499 
21500 	if (env->subprog_cnt <= 1)
21501 		return 0;
21502 
21503 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21504 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
21505 			continue;
21506 
21507 		/* Upon error here we cannot fall back to interpreter but
21508 		 * need a hard reject of the program. Thus -EFAULT is
21509 		 * propagated in any case.
21510 		 */
21511 		subprog = find_subprog(env, i + insn->imm + 1);
21512 		if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d",
21513 				    i + insn->imm + 1))
21514 			return -EFAULT;
21515 		/* temporarily remember subprog id inside insn instead of
21516 		 * aux_data, since next loop will split up all insns into funcs
21517 		 */
21518 		insn->off = subprog;
21519 		/* remember original imm in case JIT fails and fallback
21520 		 * to interpreter will be needed
21521 		 */
21522 		env->insn_aux_data[i].call_imm = insn->imm;
21523 		/* point imm to __bpf_call_base+1 from JITs point of view */
21524 		insn->imm = 1;
21525 		if (bpf_pseudo_func(insn)) {
21526 #if defined(MODULES_VADDR)
21527 			u64 addr = MODULES_VADDR;
21528 #else
21529 			u64 addr = VMALLOC_START;
21530 #endif
21531 			/* jit (e.g. x86_64) may emit fewer instructions
21532 			 * if it learns a u32 imm is the same as a u64 imm.
21533 			 * Set close enough to possible prog address.
21534 			 */
21535 			insn[0].imm = (u32)addr;
21536 			insn[1].imm = addr >> 32;
21537 		}
21538 	}
21539 
21540 	err = bpf_prog_alloc_jited_linfo(prog);
21541 	if (err)
21542 		goto out_undo_insn;
21543 
21544 	err = -ENOMEM;
21545 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
21546 	if (!func)
21547 		goto out_undo_insn;
21548 
21549 	for (i = 0; i < env->subprog_cnt; i++) {
21550 		subprog_start = subprog_end;
21551 		subprog_end = env->subprog_info[i + 1].start;
21552 
21553 		len = subprog_end - subprog_start;
21554 		/* bpf_prog_run() doesn't call subprogs directly,
21555 		 * hence main prog stats include the runtime of subprogs.
21556 		 * subprogs don't have IDs and not reachable via prog_get_next_id
21557 		 * func[i]->stats will never be accessed and stays NULL
21558 		 */
21559 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
21560 		if (!func[i])
21561 			goto out_free;
21562 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
21563 		       len * sizeof(struct bpf_insn));
21564 		func[i]->type = prog->type;
21565 		func[i]->len = len;
21566 		if (bpf_prog_calc_tag(func[i]))
21567 			goto out_free;
21568 		func[i]->is_func = 1;
21569 		func[i]->sleepable = prog->sleepable;
21570 		func[i]->aux->func_idx = i;
21571 		/* Below members will be freed only at prog->aux */
21572 		func[i]->aux->btf = prog->aux->btf;
21573 		func[i]->aux->func_info = prog->aux->func_info;
21574 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
21575 		func[i]->aux->poke_tab = prog->aux->poke_tab;
21576 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
21577 		func[i]->aux->main_prog_aux = prog->aux;
21578 
21579 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
21580 			struct bpf_jit_poke_descriptor *poke;
21581 
21582 			poke = &prog->aux->poke_tab[j];
21583 			if (poke->insn_idx < subprog_end &&
21584 			    poke->insn_idx >= subprog_start)
21585 				poke->aux = func[i]->aux;
21586 		}
21587 
21588 		func[i]->aux->name[0] = 'F';
21589 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
21590 		if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
21591 			func[i]->aux->jits_use_priv_stack = true;
21592 
21593 		func[i]->jit_requested = 1;
21594 		func[i]->blinding_requested = prog->blinding_requested;
21595 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
21596 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
21597 		func[i]->aux->linfo = prog->aux->linfo;
21598 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
21599 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
21600 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
21601 		func[i]->aux->arena = prog->aux->arena;
21602 		num_exentries = 0;
21603 		insn = func[i]->insnsi;
21604 		for (j = 0; j < func[i]->len; j++, insn++) {
21605 			if (BPF_CLASS(insn->code) == BPF_LDX &&
21606 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
21607 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
21608 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32SX ||
21609 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
21610 				num_exentries++;
21611 			if ((BPF_CLASS(insn->code) == BPF_STX ||
21612 			     BPF_CLASS(insn->code) == BPF_ST) &&
21613 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
21614 				num_exentries++;
21615 			if (BPF_CLASS(insn->code) == BPF_STX &&
21616 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
21617 				num_exentries++;
21618 		}
21619 		func[i]->aux->num_exentries = num_exentries;
21620 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
21621 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
21622 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
21623 		func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
21624 		if (!i)
21625 			func[i]->aux->exception_boundary = env->seen_exception;
21626 		func[i] = bpf_int_jit_compile(func[i]);
21627 		if (!func[i]->jited) {
21628 			err = -ENOTSUPP;
21629 			goto out_free;
21630 		}
21631 		cond_resched();
21632 	}
21633 
21634 	/* at this point all bpf functions were successfully JITed
21635 	 * now populate all bpf_calls with correct addresses and
21636 	 * run last pass of JIT
21637 	 */
21638 	for (i = 0; i < env->subprog_cnt; i++) {
21639 		insn = func[i]->insnsi;
21640 		for (j = 0; j < func[i]->len; j++, insn++) {
21641 			if (bpf_pseudo_func(insn)) {
21642 				subprog = insn->off;
21643 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
21644 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
21645 				continue;
21646 			}
21647 			if (!bpf_pseudo_call(insn))
21648 				continue;
21649 			subprog = insn->off;
21650 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
21651 		}
21652 
21653 		/* we use the aux data to keep a list of the start addresses
21654 		 * of the JITed images for each function in the program
21655 		 *
21656 		 * for some architectures, such as powerpc64, the imm field
21657 		 * might not be large enough to hold the offset of the start
21658 		 * address of the callee's JITed image from __bpf_call_base
21659 		 *
21660 		 * in such cases, we can lookup the start address of a callee
21661 		 * by using its subprog id, available from the off field of
21662 		 * the call instruction, as an index for this list
21663 		 */
21664 		func[i]->aux->func = func;
21665 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
21666 		func[i]->aux->real_func_cnt = env->subprog_cnt;
21667 	}
21668 	for (i = 0; i < env->subprog_cnt; i++) {
21669 		old_bpf_func = func[i]->bpf_func;
21670 		tmp = bpf_int_jit_compile(func[i]);
21671 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
21672 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
21673 			err = -ENOTSUPP;
21674 			goto out_free;
21675 		}
21676 		cond_resched();
21677 	}
21678 
21679 	/* finally lock prog and jit images for all functions and
21680 	 * populate kallsysm. Begin at the first subprogram, since
21681 	 * bpf_prog_load will add the kallsyms for the main program.
21682 	 */
21683 	for (i = 1; i < env->subprog_cnt; i++) {
21684 		err = bpf_prog_lock_ro(func[i]);
21685 		if (err)
21686 			goto out_free;
21687 	}
21688 
21689 	for (i = 1; i < env->subprog_cnt; i++)
21690 		bpf_prog_kallsyms_add(func[i]);
21691 
21692 	/* Last step: make now unused interpreter insns from main
21693 	 * prog consistent for later dump requests, so they can
21694 	 * later look the same as if they were interpreted only.
21695 	 */
21696 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21697 		if (bpf_pseudo_func(insn)) {
21698 			insn[0].imm = env->insn_aux_data[i].call_imm;
21699 			insn[1].imm = insn->off;
21700 			insn->off = 0;
21701 			continue;
21702 		}
21703 		if (!bpf_pseudo_call(insn))
21704 			continue;
21705 		insn->off = env->insn_aux_data[i].call_imm;
21706 		subprog = find_subprog(env, i + insn->off + 1);
21707 		insn->imm = subprog;
21708 	}
21709 
21710 	prog->jited = 1;
21711 	prog->bpf_func = func[0]->bpf_func;
21712 	prog->jited_len = func[0]->jited_len;
21713 	prog->aux->extable = func[0]->aux->extable;
21714 	prog->aux->num_exentries = func[0]->aux->num_exentries;
21715 	prog->aux->func = func;
21716 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
21717 	prog->aux->real_func_cnt = env->subprog_cnt;
21718 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
21719 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
21720 	bpf_prog_jit_attempt_done(prog);
21721 	return 0;
21722 out_free:
21723 	/* We failed JIT'ing, so at this point we need to unregister poke
21724 	 * descriptors from subprogs, so that kernel is not attempting to
21725 	 * patch it anymore as we're freeing the subprog JIT memory.
21726 	 */
21727 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
21728 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
21729 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
21730 	}
21731 	/* At this point we're guaranteed that poke descriptors are not
21732 	 * live anymore. We can just unlink its descriptor table as it's
21733 	 * released with the main prog.
21734 	 */
21735 	for (i = 0; i < env->subprog_cnt; i++) {
21736 		if (!func[i])
21737 			continue;
21738 		func[i]->aux->poke_tab = NULL;
21739 		bpf_jit_free(func[i]);
21740 	}
21741 	kfree(func);
21742 out_undo_insn:
21743 	/* cleanup main prog to be interpreted */
21744 	prog->jit_requested = 0;
21745 	prog->blinding_requested = 0;
21746 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21747 		if (!bpf_pseudo_call(insn))
21748 			continue;
21749 		insn->off = 0;
21750 		insn->imm = env->insn_aux_data[i].call_imm;
21751 	}
21752 	bpf_prog_jit_attempt_done(prog);
21753 	return err;
21754 }
21755 
21756 static int fixup_call_args(struct bpf_verifier_env *env)
21757 {
21758 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
21759 	struct bpf_prog *prog = env->prog;
21760 	struct bpf_insn *insn = prog->insnsi;
21761 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
21762 	int i, depth;
21763 #endif
21764 	int err = 0;
21765 
21766 	if (env->prog->jit_requested &&
21767 	    !bpf_prog_is_offloaded(env->prog->aux)) {
21768 		err = jit_subprogs(env);
21769 		if (err == 0)
21770 			return 0;
21771 		if (err == -EFAULT)
21772 			return err;
21773 	}
21774 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
21775 	if (has_kfunc_call) {
21776 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
21777 		return -EINVAL;
21778 	}
21779 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
21780 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
21781 		 * have to be rejected, since interpreter doesn't support them yet.
21782 		 */
21783 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
21784 		return -EINVAL;
21785 	}
21786 	for (i = 0; i < prog->len; i++, insn++) {
21787 		if (bpf_pseudo_func(insn)) {
21788 			/* When JIT fails the progs with callback calls
21789 			 * have to be rejected, since interpreter doesn't support them yet.
21790 			 */
21791 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
21792 			return -EINVAL;
21793 		}
21794 
21795 		if (!bpf_pseudo_call(insn))
21796 			continue;
21797 		depth = get_callee_stack_depth(env, insn, i);
21798 		if (depth < 0)
21799 			return depth;
21800 		bpf_patch_call_args(insn, depth);
21801 	}
21802 	err = 0;
21803 #endif
21804 	return err;
21805 }
21806 
21807 /* replace a generic kfunc with a specialized version if necessary */
21808 static void specialize_kfunc(struct bpf_verifier_env *env,
21809 			     u32 func_id, u16 offset, unsigned long *addr)
21810 {
21811 	struct bpf_prog *prog = env->prog;
21812 	bool seen_direct_write;
21813 	void *xdp_kfunc;
21814 	bool is_rdonly;
21815 
21816 	if (bpf_dev_bound_kfunc_id(func_id)) {
21817 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
21818 		if (xdp_kfunc) {
21819 			*addr = (unsigned long)xdp_kfunc;
21820 			return;
21821 		}
21822 		/* fallback to default kfunc when not supported by netdev */
21823 	}
21824 
21825 	if (offset)
21826 		return;
21827 
21828 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
21829 		seen_direct_write = env->seen_direct_write;
21830 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
21831 
21832 		if (is_rdonly)
21833 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
21834 
21835 		/* restore env->seen_direct_write to its original value, since
21836 		 * may_access_direct_pkt_data mutates it
21837 		 */
21838 		env->seen_direct_write = seen_direct_write;
21839 	}
21840 
21841 	if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr] &&
21842 	    bpf_lsm_has_d_inode_locked(prog))
21843 		*addr = (unsigned long)bpf_set_dentry_xattr_locked;
21844 
21845 	if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr] &&
21846 	    bpf_lsm_has_d_inode_locked(prog))
21847 		*addr = (unsigned long)bpf_remove_dentry_xattr_locked;
21848 }
21849 
21850 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
21851 					    u16 struct_meta_reg,
21852 					    u16 node_offset_reg,
21853 					    struct bpf_insn *insn,
21854 					    struct bpf_insn *insn_buf,
21855 					    int *cnt)
21856 {
21857 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
21858 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
21859 
21860 	insn_buf[0] = addr[0];
21861 	insn_buf[1] = addr[1];
21862 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
21863 	insn_buf[3] = *insn;
21864 	*cnt = 4;
21865 }
21866 
21867 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
21868 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
21869 {
21870 	const struct bpf_kfunc_desc *desc;
21871 
21872 	if (!insn->imm) {
21873 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
21874 		return -EINVAL;
21875 	}
21876 
21877 	*cnt = 0;
21878 
21879 	/* insn->imm has the btf func_id. Replace it with an offset relative to
21880 	 * __bpf_call_base, unless the JIT needs to call functions that are
21881 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
21882 	 */
21883 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
21884 	if (!desc) {
21885 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
21886 			     insn->imm);
21887 		return -EFAULT;
21888 	}
21889 
21890 	if (!bpf_jit_supports_far_kfunc_call())
21891 		insn->imm = BPF_CALL_IMM(desc->addr);
21892 	if (insn->off)
21893 		return 0;
21894 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
21895 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
21896 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21897 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
21898 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
21899 
21900 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
21901 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
21902 				     insn_idx);
21903 			return -EFAULT;
21904 		}
21905 
21906 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
21907 		insn_buf[1] = addr[0];
21908 		insn_buf[2] = addr[1];
21909 		insn_buf[3] = *insn;
21910 		*cnt = 4;
21911 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
21912 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
21913 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
21914 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21915 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
21916 
21917 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
21918 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
21919 				     insn_idx);
21920 			return -EFAULT;
21921 		}
21922 
21923 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
21924 		    !kptr_struct_meta) {
21925 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
21926 				     insn_idx);
21927 			return -EFAULT;
21928 		}
21929 
21930 		insn_buf[0] = addr[0];
21931 		insn_buf[1] = addr[1];
21932 		insn_buf[2] = *insn;
21933 		*cnt = 3;
21934 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
21935 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
21936 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
21937 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21938 		int struct_meta_reg = BPF_REG_3;
21939 		int node_offset_reg = BPF_REG_4;
21940 
21941 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
21942 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
21943 			struct_meta_reg = BPF_REG_4;
21944 			node_offset_reg = BPF_REG_5;
21945 		}
21946 
21947 		if (!kptr_struct_meta) {
21948 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
21949 				     insn_idx);
21950 			return -EFAULT;
21951 		}
21952 
21953 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
21954 						node_offset_reg, insn, insn_buf, cnt);
21955 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
21956 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
21957 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
21958 		*cnt = 1;
21959 	}
21960 
21961 	if (env->insn_aux_data[insn_idx].arg_prog) {
21962 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
21963 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
21964 		int idx = *cnt;
21965 
21966 		insn_buf[idx++] = ld_addrs[0];
21967 		insn_buf[idx++] = ld_addrs[1];
21968 		insn_buf[idx++] = *insn;
21969 		*cnt = idx;
21970 	}
21971 	return 0;
21972 }
21973 
21974 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
21975 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
21976 {
21977 	struct bpf_subprog_info *info = env->subprog_info;
21978 	int cnt = env->subprog_cnt;
21979 	struct bpf_prog *prog;
21980 
21981 	/* We only reserve one slot for hidden subprogs in subprog_info. */
21982 	if (env->hidden_subprog_cnt) {
21983 		verifier_bug(env, "only one hidden subprog supported");
21984 		return -EFAULT;
21985 	}
21986 	/* We're not patching any existing instruction, just appending the new
21987 	 * ones for the hidden subprog. Hence all of the adjustment operations
21988 	 * in bpf_patch_insn_data are no-ops.
21989 	 */
21990 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
21991 	if (!prog)
21992 		return -ENOMEM;
21993 	env->prog = prog;
21994 	info[cnt + 1].start = info[cnt].start;
21995 	info[cnt].start = prog->len - len + 1;
21996 	env->subprog_cnt++;
21997 	env->hidden_subprog_cnt++;
21998 	return 0;
21999 }
22000 
22001 /* Do various post-verification rewrites in a single program pass.
22002  * These rewrites simplify JIT and interpreter implementations.
22003  */
22004 static int do_misc_fixups(struct bpf_verifier_env *env)
22005 {
22006 	struct bpf_prog *prog = env->prog;
22007 	enum bpf_attach_type eatype = prog->expected_attach_type;
22008 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
22009 	struct bpf_insn *insn = prog->insnsi;
22010 	const struct bpf_func_proto *fn;
22011 	const int insn_cnt = prog->len;
22012 	const struct bpf_map_ops *ops;
22013 	struct bpf_insn_aux_data *aux;
22014 	struct bpf_insn *insn_buf = env->insn_buf;
22015 	struct bpf_prog *new_prog;
22016 	struct bpf_map *map_ptr;
22017 	int i, ret, cnt, delta = 0, cur_subprog = 0;
22018 	struct bpf_subprog_info *subprogs = env->subprog_info;
22019 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
22020 	u16 stack_depth_extra = 0;
22021 
22022 	if (env->seen_exception && !env->exception_callback_subprog) {
22023 		struct bpf_insn *patch = insn_buf;
22024 
22025 		*patch++ = env->prog->insnsi[insn_cnt - 1];
22026 		*patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
22027 		*patch++ = BPF_EXIT_INSN();
22028 		ret = add_hidden_subprog(env, insn_buf, patch - insn_buf);
22029 		if (ret < 0)
22030 			return ret;
22031 		prog = env->prog;
22032 		insn = prog->insnsi;
22033 
22034 		env->exception_callback_subprog = env->subprog_cnt - 1;
22035 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
22036 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
22037 	}
22038 
22039 	for (i = 0; i < insn_cnt;) {
22040 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
22041 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
22042 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
22043 				/* convert to 32-bit mov that clears upper 32-bit */
22044 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
22045 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
22046 				insn->off = 0;
22047 				insn->imm = 0;
22048 			} /* cast from as(0) to as(1) should be handled by JIT */
22049 			goto next_insn;
22050 		}
22051 
22052 		if (env->insn_aux_data[i + delta].needs_zext)
22053 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
22054 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
22055 
22056 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
22057 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
22058 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
22059 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
22060 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
22061 		    insn->off == 1 && insn->imm == -1) {
22062 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22063 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22064 			struct bpf_insn *patch = insn_buf;
22065 
22066 			if (isdiv)
22067 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22068 							BPF_NEG | BPF_K, insn->dst_reg,
22069 							0, 0, 0);
22070 			else
22071 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22072 
22073 			cnt = patch - insn_buf;
22074 
22075 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22076 			if (!new_prog)
22077 				return -ENOMEM;
22078 
22079 			delta    += cnt - 1;
22080 			env->prog = prog = new_prog;
22081 			insn      = new_prog->insnsi + i + delta;
22082 			goto next_insn;
22083 		}
22084 
22085 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
22086 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
22087 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
22088 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
22089 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
22090 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22091 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22092 			bool is_sdiv = isdiv && insn->off == 1;
22093 			bool is_smod = !isdiv && insn->off == 1;
22094 			struct bpf_insn *patch = insn_buf;
22095 
22096 			if (is_sdiv) {
22097 				/* [R,W]x sdiv 0 -> 0
22098 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
22099 				 * INT_MIN sdiv -1 -> INT_MIN
22100 				 */
22101 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22102 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22103 							BPF_ADD | BPF_K, BPF_REG_AX,
22104 							0, 0, 1);
22105 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22106 							BPF_JGT | BPF_K, BPF_REG_AX,
22107 							0, 4, 1);
22108 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22109 							BPF_JEQ | BPF_K, BPF_REG_AX,
22110 							0, 1, 0);
22111 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22112 							BPF_MOV | BPF_K, insn->dst_reg,
22113 							0, 0, 0);
22114 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
22115 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22116 							BPF_NEG | BPF_K, insn->dst_reg,
22117 							0, 0, 0);
22118 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22119 				*patch++ = *insn;
22120 				cnt = patch - insn_buf;
22121 			} else if (is_smod) {
22122 				/* [R,W]x mod 0 -> [R,W]x */
22123 				/* [R,W]x mod -1 -> 0 */
22124 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22125 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22126 							BPF_ADD | BPF_K, BPF_REG_AX,
22127 							0, 0, 1);
22128 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22129 							BPF_JGT | BPF_K, BPF_REG_AX,
22130 							0, 3, 1);
22131 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22132 							BPF_JEQ | BPF_K, BPF_REG_AX,
22133 							0, 3 + (is64 ? 0 : 1), 1);
22134 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22135 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22136 				*patch++ = *insn;
22137 
22138 				if (!is64) {
22139 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22140 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22141 				}
22142 				cnt = patch - insn_buf;
22143 			} else if (isdiv) {
22144 				/* [R,W]x div 0 -> 0 */
22145 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22146 							BPF_JNE | BPF_K, insn->src_reg,
22147 							0, 2, 0);
22148 				*patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg);
22149 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22150 				*patch++ = *insn;
22151 				cnt = patch - insn_buf;
22152 			} else {
22153 				/* [R,W]x mod 0 -> [R,W]x */
22154 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22155 							BPF_JEQ | BPF_K, insn->src_reg,
22156 							0, 1 + (is64 ? 0 : 1), 0);
22157 				*patch++ = *insn;
22158 
22159 				if (!is64) {
22160 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22161 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22162 				}
22163 				cnt = patch - insn_buf;
22164 			}
22165 
22166 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22167 			if (!new_prog)
22168 				return -ENOMEM;
22169 
22170 			delta    += cnt - 1;
22171 			env->prog = prog = new_prog;
22172 			insn      = new_prog->insnsi + i + delta;
22173 			goto next_insn;
22174 		}
22175 
22176 		/* Make it impossible to de-reference a userspace address */
22177 		if (BPF_CLASS(insn->code) == BPF_LDX &&
22178 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22179 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
22180 			struct bpf_insn *patch = insn_buf;
22181 			u64 uaddress_limit = bpf_arch_uaddress_limit();
22182 
22183 			if (!uaddress_limit)
22184 				goto next_insn;
22185 
22186 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22187 			if (insn->off)
22188 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
22189 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
22190 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
22191 			*patch++ = *insn;
22192 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22193 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
22194 
22195 			cnt = patch - insn_buf;
22196 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22197 			if (!new_prog)
22198 				return -ENOMEM;
22199 
22200 			delta    += cnt - 1;
22201 			env->prog = prog = new_prog;
22202 			insn      = new_prog->insnsi + i + delta;
22203 			goto next_insn;
22204 		}
22205 
22206 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
22207 		if (BPF_CLASS(insn->code) == BPF_LD &&
22208 		    (BPF_MODE(insn->code) == BPF_ABS ||
22209 		     BPF_MODE(insn->code) == BPF_IND)) {
22210 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
22211 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
22212 				verifier_bug(env, "%d insns generated for ld_abs", cnt);
22213 				return -EFAULT;
22214 			}
22215 
22216 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22217 			if (!new_prog)
22218 				return -ENOMEM;
22219 
22220 			delta    += cnt - 1;
22221 			env->prog = prog = new_prog;
22222 			insn      = new_prog->insnsi + i + delta;
22223 			goto next_insn;
22224 		}
22225 
22226 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
22227 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
22228 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
22229 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
22230 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
22231 			struct bpf_insn *patch = insn_buf;
22232 			bool issrc, isneg, isimm;
22233 			u32 off_reg;
22234 
22235 			aux = &env->insn_aux_data[i + delta];
22236 			if (!aux->alu_state ||
22237 			    aux->alu_state == BPF_ALU_NON_POINTER)
22238 				goto next_insn;
22239 
22240 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
22241 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
22242 				BPF_ALU_SANITIZE_SRC;
22243 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
22244 
22245 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
22246 			if (isimm) {
22247 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22248 			} else {
22249 				if (isneg)
22250 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22251 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22252 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
22253 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
22254 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
22255 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
22256 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
22257 			}
22258 			if (!issrc)
22259 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
22260 			insn->src_reg = BPF_REG_AX;
22261 			if (isneg)
22262 				insn->code = insn->code == code_add ?
22263 					     code_sub : code_add;
22264 			*patch++ = *insn;
22265 			if (issrc && isneg && !isimm)
22266 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22267 			cnt = patch - insn_buf;
22268 
22269 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22270 			if (!new_prog)
22271 				return -ENOMEM;
22272 
22273 			delta    += cnt - 1;
22274 			env->prog = prog = new_prog;
22275 			insn      = new_prog->insnsi + i + delta;
22276 			goto next_insn;
22277 		}
22278 
22279 		if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) {
22280 			int stack_off_cnt = -stack_depth - 16;
22281 
22282 			/*
22283 			 * Two 8 byte slots, depth-16 stores the count, and
22284 			 * depth-8 stores the start timestamp of the loop.
22285 			 *
22286 			 * The starting value of count is BPF_MAX_TIMED_LOOPS
22287 			 * (0xffff).  Every iteration loads it and subs it by 1,
22288 			 * until the value becomes 0 in AX (thus, 1 in stack),
22289 			 * after which we call arch_bpf_timed_may_goto, which
22290 			 * either sets AX to 0xffff to keep looping, or to 0
22291 			 * upon timeout. AX is then stored into the stack. In
22292 			 * the next iteration, we either see 0 and break out, or
22293 			 * continue iterating until the next time value is 0
22294 			 * after subtraction, rinse and repeat.
22295 			 */
22296 			stack_depth_extra = 16;
22297 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt);
22298 			if (insn->off >= 0)
22299 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5);
22300 			else
22301 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22302 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22303 			insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
22304 			/*
22305 			 * AX is used as an argument to pass in stack_off_cnt
22306 			 * (to add to r10/fp), and also as the return value of
22307 			 * the call to arch_bpf_timed_may_goto.
22308 			 */
22309 			insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt);
22310 			insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
22311 			insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt);
22312 			cnt = 7;
22313 
22314 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22315 			if (!new_prog)
22316 				return -ENOMEM;
22317 
22318 			delta += cnt - 1;
22319 			env->prog = prog = new_prog;
22320 			insn = new_prog->insnsi + i + delta;
22321 			goto next_insn;
22322 		} else if (is_may_goto_insn(insn)) {
22323 			int stack_off = -stack_depth - 8;
22324 
22325 			stack_depth_extra = 8;
22326 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
22327 			if (insn->off >= 0)
22328 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
22329 			else
22330 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22331 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22332 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
22333 			cnt = 4;
22334 
22335 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22336 			if (!new_prog)
22337 				return -ENOMEM;
22338 
22339 			delta += cnt - 1;
22340 			env->prog = prog = new_prog;
22341 			insn = new_prog->insnsi + i + delta;
22342 			goto next_insn;
22343 		}
22344 
22345 		if (insn->code != (BPF_JMP | BPF_CALL))
22346 			goto next_insn;
22347 		if (insn->src_reg == BPF_PSEUDO_CALL)
22348 			goto next_insn;
22349 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
22350 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
22351 			if (ret)
22352 				return ret;
22353 			if (cnt == 0)
22354 				goto next_insn;
22355 
22356 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22357 			if (!new_prog)
22358 				return -ENOMEM;
22359 
22360 			delta	 += cnt - 1;
22361 			env->prog = prog = new_prog;
22362 			insn	  = new_prog->insnsi + i + delta;
22363 			goto next_insn;
22364 		}
22365 
22366 		/* Skip inlining the helper call if the JIT does it. */
22367 		if (bpf_jit_inlines_helper_call(insn->imm))
22368 			goto next_insn;
22369 
22370 		if (insn->imm == BPF_FUNC_get_route_realm)
22371 			prog->dst_needed = 1;
22372 		if (insn->imm == BPF_FUNC_get_prandom_u32)
22373 			bpf_user_rnd_init_once();
22374 		if (insn->imm == BPF_FUNC_override_return)
22375 			prog->kprobe_override = 1;
22376 		if (insn->imm == BPF_FUNC_tail_call) {
22377 			/* If we tail call into other programs, we
22378 			 * cannot make any assumptions since they can
22379 			 * be replaced dynamically during runtime in
22380 			 * the program array.
22381 			 */
22382 			prog->cb_access = 1;
22383 			if (!allow_tail_call_in_subprogs(env))
22384 				prog->aux->stack_depth = MAX_BPF_STACK;
22385 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
22386 
22387 			/* mark bpf_tail_call as different opcode to avoid
22388 			 * conditional branch in the interpreter for every normal
22389 			 * call and to prevent accidental JITing by JIT compiler
22390 			 * that doesn't support bpf_tail_call yet
22391 			 */
22392 			insn->imm = 0;
22393 			insn->code = BPF_JMP | BPF_TAIL_CALL;
22394 
22395 			aux = &env->insn_aux_data[i + delta];
22396 			if (env->bpf_capable && !prog->blinding_requested &&
22397 			    prog->jit_requested &&
22398 			    !bpf_map_key_poisoned(aux) &&
22399 			    !bpf_map_ptr_poisoned(aux) &&
22400 			    !bpf_map_ptr_unpriv(aux)) {
22401 				struct bpf_jit_poke_descriptor desc = {
22402 					.reason = BPF_POKE_REASON_TAIL_CALL,
22403 					.tail_call.map = aux->map_ptr_state.map_ptr,
22404 					.tail_call.key = bpf_map_key_immediate(aux),
22405 					.insn_idx = i + delta,
22406 				};
22407 
22408 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
22409 				if (ret < 0) {
22410 					verbose(env, "adding tail call poke descriptor failed\n");
22411 					return ret;
22412 				}
22413 
22414 				insn->imm = ret + 1;
22415 				goto next_insn;
22416 			}
22417 
22418 			if (!bpf_map_ptr_unpriv(aux))
22419 				goto next_insn;
22420 
22421 			/* instead of changing every JIT dealing with tail_call
22422 			 * emit two extra insns:
22423 			 * if (index >= max_entries) goto out;
22424 			 * index &= array->index_mask;
22425 			 * to avoid out-of-bounds cpu speculation
22426 			 */
22427 			if (bpf_map_ptr_poisoned(aux)) {
22428 				verbose(env, "tail_call abusing map_ptr\n");
22429 				return -EINVAL;
22430 			}
22431 
22432 			map_ptr = aux->map_ptr_state.map_ptr;
22433 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
22434 						  map_ptr->max_entries, 2);
22435 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
22436 						    container_of(map_ptr,
22437 								 struct bpf_array,
22438 								 map)->index_mask);
22439 			insn_buf[2] = *insn;
22440 			cnt = 3;
22441 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22442 			if (!new_prog)
22443 				return -ENOMEM;
22444 
22445 			delta    += cnt - 1;
22446 			env->prog = prog = new_prog;
22447 			insn      = new_prog->insnsi + i + delta;
22448 			goto next_insn;
22449 		}
22450 
22451 		if (insn->imm == BPF_FUNC_timer_set_callback) {
22452 			/* The verifier will process callback_fn as many times as necessary
22453 			 * with different maps and the register states prepared by
22454 			 * set_timer_callback_state will be accurate.
22455 			 *
22456 			 * The following use case is valid:
22457 			 *   map1 is shared by prog1, prog2, prog3.
22458 			 *   prog1 calls bpf_timer_init for some map1 elements
22459 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
22460 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
22461 			 *   prog3 calls bpf_timer_start for some map1 elements.
22462 			 *     Those that were not both bpf_timer_init-ed and
22463 			 *     bpf_timer_set_callback-ed will return -EINVAL.
22464 			 */
22465 			struct bpf_insn ld_addrs[2] = {
22466 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
22467 			};
22468 
22469 			insn_buf[0] = ld_addrs[0];
22470 			insn_buf[1] = ld_addrs[1];
22471 			insn_buf[2] = *insn;
22472 			cnt = 3;
22473 
22474 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22475 			if (!new_prog)
22476 				return -ENOMEM;
22477 
22478 			delta    += cnt - 1;
22479 			env->prog = prog = new_prog;
22480 			insn      = new_prog->insnsi + i + delta;
22481 			goto patch_call_imm;
22482 		}
22483 
22484 		if (is_storage_get_function(insn->imm)) {
22485 			if (!in_sleepable(env) ||
22486 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
22487 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
22488 			else
22489 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
22490 			insn_buf[1] = *insn;
22491 			cnt = 2;
22492 
22493 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22494 			if (!new_prog)
22495 				return -ENOMEM;
22496 
22497 			delta += cnt - 1;
22498 			env->prog = prog = new_prog;
22499 			insn = new_prog->insnsi + i + delta;
22500 			goto patch_call_imm;
22501 		}
22502 
22503 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
22504 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
22505 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
22506 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
22507 			 */
22508 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
22509 			insn_buf[1] = *insn;
22510 			cnt = 2;
22511 
22512 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22513 			if (!new_prog)
22514 				return -ENOMEM;
22515 
22516 			delta += cnt - 1;
22517 			env->prog = prog = new_prog;
22518 			insn = new_prog->insnsi + i + delta;
22519 			goto patch_call_imm;
22520 		}
22521 
22522 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
22523 		 * and other inlining handlers are currently limited to 64 bit
22524 		 * only.
22525 		 */
22526 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22527 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
22528 		     insn->imm == BPF_FUNC_map_update_elem ||
22529 		     insn->imm == BPF_FUNC_map_delete_elem ||
22530 		     insn->imm == BPF_FUNC_map_push_elem   ||
22531 		     insn->imm == BPF_FUNC_map_pop_elem    ||
22532 		     insn->imm == BPF_FUNC_map_peek_elem   ||
22533 		     insn->imm == BPF_FUNC_redirect_map    ||
22534 		     insn->imm == BPF_FUNC_for_each_map_elem ||
22535 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
22536 			aux = &env->insn_aux_data[i + delta];
22537 			if (bpf_map_ptr_poisoned(aux))
22538 				goto patch_call_imm;
22539 
22540 			map_ptr = aux->map_ptr_state.map_ptr;
22541 			ops = map_ptr->ops;
22542 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
22543 			    ops->map_gen_lookup) {
22544 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
22545 				if (cnt == -EOPNOTSUPP)
22546 					goto patch_map_ops_generic;
22547 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
22548 					verifier_bug(env, "%d insns generated for map lookup", cnt);
22549 					return -EFAULT;
22550 				}
22551 
22552 				new_prog = bpf_patch_insn_data(env, i + delta,
22553 							       insn_buf, cnt);
22554 				if (!new_prog)
22555 					return -ENOMEM;
22556 
22557 				delta    += cnt - 1;
22558 				env->prog = prog = new_prog;
22559 				insn      = new_prog->insnsi + i + delta;
22560 				goto next_insn;
22561 			}
22562 
22563 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
22564 				     (void *(*)(struct bpf_map *map, void *key))NULL));
22565 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
22566 				     (long (*)(struct bpf_map *map, void *key))NULL));
22567 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
22568 				     (long (*)(struct bpf_map *map, void *key, void *value,
22569 					      u64 flags))NULL));
22570 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
22571 				     (long (*)(struct bpf_map *map, void *value,
22572 					      u64 flags))NULL));
22573 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
22574 				     (long (*)(struct bpf_map *map, void *value))NULL));
22575 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
22576 				     (long (*)(struct bpf_map *map, void *value))NULL));
22577 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
22578 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
22579 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
22580 				     (long (*)(struct bpf_map *map,
22581 					      bpf_callback_t callback_fn,
22582 					      void *callback_ctx,
22583 					      u64 flags))NULL));
22584 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
22585 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
22586 
22587 patch_map_ops_generic:
22588 			switch (insn->imm) {
22589 			case BPF_FUNC_map_lookup_elem:
22590 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
22591 				goto next_insn;
22592 			case BPF_FUNC_map_update_elem:
22593 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
22594 				goto next_insn;
22595 			case BPF_FUNC_map_delete_elem:
22596 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
22597 				goto next_insn;
22598 			case BPF_FUNC_map_push_elem:
22599 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
22600 				goto next_insn;
22601 			case BPF_FUNC_map_pop_elem:
22602 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
22603 				goto next_insn;
22604 			case BPF_FUNC_map_peek_elem:
22605 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
22606 				goto next_insn;
22607 			case BPF_FUNC_redirect_map:
22608 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
22609 				goto next_insn;
22610 			case BPF_FUNC_for_each_map_elem:
22611 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
22612 				goto next_insn;
22613 			case BPF_FUNC_map_lookup_percpu_elem:
22614 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
22615 				goto next_insn;
22616 			}
22617 
22618 			goto patch_call_imm;
22619 		}
22620 
22621 		/* Implement bpf_jiffies64 inline. */
22622 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22623 		    insn->imm == BPF_FUNC_jiffies64) {
22624 			struct bpf_insn ld_jiffies_addr[2] = {
22625 				BPF_LD_IMM64(BPF_REG_0,
22626 					     (unsigned long)&jiffies),
22627 			};
22628 
22629 			insn_buf[0] = ld_jiffies_addr[0];
22630 			insn_buf[1] = ld_jiffies_addr[1];
22631 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
22632 						  BPF_REG_0, 0);
22633 			cnt = 3;
22634 
22635 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
22636 						       cnt);
22637 			if (!new_prog)
22638 				return -ENOMEM;
22639 
22640 			delta    += cnt - 1;
22641 			env->prog = prog = new_prog;
22642 			insn      = new_prog->insnsi + i + delta;
22643 			goto next_insn;
22644 		}
22645 
22646 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
22647 		/* Implement bpf_get_smp_processor_id() inline. */
22648 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
22649 		    verifier_inlines_helper_call(env, insn->imm)) {
22650 			/* BPF_FUNC_get_smp_processor_id inlining is an
22651 			 * optimization, so if cpu_number is ever
22652 			 * changed in some incompatible and hard to support
22653 			 * way, it's fine to back out this inlining logic
22654 			 */
22655 #ifdef CONFIG_SMP
22656 			insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number);
22657 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
22658 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
22659 			cnt = 3;
22660 #else
22661 			insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
22662 			cnt = 1;
22663 #endif
22664 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22665 			if (!new_prog)
22666 				return -ENOMEM;
22667 
22668 			delta    += cnt - 1;
22669 			env->prog = prog = new_prog;
22670 			insn      = new_prog->insnsi + i + delta;
22671 			goto next_insn;
22672 		}
22673 #endif
22674 		/* Implement bpf_get_func_arg inline. */
22675 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22676 		    insn->imm == BPF_FUNC_get_func_arg) {
22677 			/* Load nr_args from ctx - 8 */
22678 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22679 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
22680 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
22681 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
22682 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
22683 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
22684 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
22685 			insn_buf[7] = BPF_JMP_A(1);
22686 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
22687 			cnt = 9;
22688 
22689 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22690 			if (!new_prog)
22691 				return -ENOMEM;
22692 
22693 			delta    += cnt - 1;
22694 			env->prog = prog = new_prog;
22695 			insn      = new_prog->insnsi + i + delta;
22696 			goto next_insn;
22697 		}
22698 
22699 		/* Implement bpf_get_func_ret inline. */
22700 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22701 		    insn->imm == BPF_FUNC_get_func_ret) {
22702 			if (eatype == BPF_TRACE_FEXIT ||
22703 			    eatype == BPF_MODIFY_RETURN) {
22704 				/* Load nr_args from ctx - 8 */
22705 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22706 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
22707 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
22708 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
22709 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
22710 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
22711 				cnt = 6;
22712 			} else {
22713 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
22714 				cnt = 1;
22715 			}
22716 
22717 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22718 			if (!new_prog)
22719 				return -ENOMEM;
22720 
22721 			delta    += cnt - 1;
22722 			env->prog = prog = new_prog;
22723 			insn      = new_prog->insnsi + i + delta;
22724 			goto next_insn;
22725 		}
22726 
22727 		/* Implement get_func_arg_cnt inline. */
22728 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22729 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
22730 			/* Load nr_args from ctx - 8 */
22731 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22732 
22733 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
22734 			if (!new_prog)
22735 				return -ENOMEM;
22736 
22737 			env->prog = prog = new_prog;
22738 			insn      = new_prog->insnsi + i + delta;
22739 			goto next_insn;
22740 		}
22741 
22742 		/* Implement bpf_get_func_ip inline. */
22743 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22744 		    insn->imm == BPF_FUNC_get_func_ip) {
22745 			/* Load IP address from ctx - 16 */
22746 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
22747 
22748 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
22749 			if (!new_prog)
22750 				return -ENOMEM;
22751 
22752 			env->prog = prog = new_prog;
22753 			insn      = new_prog->insnsi + i + delta;
22754 			goto next_insn;
22755 		}
22756 
22757 		/* Implement bpf_get_branch_snapshot inline. */
22758 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
22759 		    prog->jit_requested && BITS_PER_LONG == 64 &&
22760 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
22761 			/* We are dealing with the following func protos:
22762 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
22763 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
22764 			 */
22765 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
22766 
22767 			/* struct perf_branch_entry is part of UAPI and is
22768 			 * used as an array element, so extremely unlikely to
22769 			 * ever grow or shrink
22770 			 */
22771 			BUILD_BUG_ON(br_entry_size != 24);
22772 
22773 			/* if (unlikely(flags)) return -EINVAL */
22774 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
22775 
22776 			/* Transform size (bytes) into number of entries (cnt = size / 24).
22777 			 * But to avoid expensive division instruction, we implement
22778 			 * divide-by-3 through multiplication, followed by further
22779 			 * division by 8 through 3-bit right shift.
22780 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
22781 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
22782 			 *
22783 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
22784 			 */
22785 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
22786 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
22787 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
22788 
22789 			/* call perf_snapshot_branch_stack implementation */
22790 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
22791 			/* if (entry_cnt == 0) return -ENOENT */
22792 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
22793 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
22794 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
22795 			insn_buf[7] = BPF_JMP_A(3);
22796 			/* return -EINVAL; */
22797 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
22798 			insn_buf[9] = BPF_JMP_A(1);
22799 			/* return -ENOENT; */
22800 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
22801 			cnt = 11;
22802 
22803 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22804 			if (!new_prog)
22805 				return -ENOMEM;
22806 
22807 			delta    += cnt - 1;
22808 			env->prog = prog = new_prog;
22809 			insn      = new_prog->insnsi + i + delta;
22810 			goto next_insn;
22811 		}
22812 
22813 		/* Implement bpf_kptr_xchg inline */
22814 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22815 		    insn->imm == BPF_FUNC_kptr_xchg &&
22816 		    bpf_jit_supports_ptr_xchg()) {
22817 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
22818 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
22819 			cnt = 2;
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 patch_call_imm:
22831 		fn = env->ops->get_func_proto(insn->imm, env->prog);
22832 		/* all functions that have prototype and verifier allowed
22833 		 * programs to call them, must be real in-kernel functions
22834 		 */
22835 		if (!fn->func) {
22836 			verifier_bug(env,
22837 				     "not inlined functions %s#%d is missing func",
22838 				     func_id_name(insn->imm), insn->imm);
22839 			return -EFAULT;
22840 		}
22841 		insn->imm = fn->func - __bpf_call_base;
22842 next_insn:
22843 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
22844 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
22845 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
22846 
22847 			stack_depth = subprogs[cur_subprog].stack_depth;
22848 			if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) {
22849 				verbose(env, "stack size %d(extra %d) is too large\n",
22850 					stack_depth, stack_depth_extra);
22851 				return -EINVAL;
22852 			}
22853 			cur_subprog++;
22854 			stack_depth = subprogs[cur_subprog].stack_depth;
22855 			stack_depth_extra = 0;
22856 		}
22857 		i++;
22858 		insn++;
22859 	}
22860 
22861 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
22862 	for (i = 0; i < env->subprog_cnt; i++) {
22863 		int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1;
22864 		int subprog_start = subprogs[i].start;
22865 		int stack_slots = subprogs[i].stack_extra / 8;
22866 		int slots = delta, cnt = 0;
22867 
22868 		if (!stack_slots)
22869 			continue;
22870 		/* We need two slots in case timed may_goto is supported. */
22871 		if (stack_slots > slots) {
22872 			verifier_bug(env, "stack_slots supports may_goto only");
22873 			return -EFAULT;
22874 		}
22875 
22876 		stack_depth = subprogs[i].stack_depth;
22877 		if (bpf_jit_supports_timed_may_goto()) {
22878 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
22879 						     BPF_MAX_TIMED_LOOPS);
22880 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0);
22881 		} else {
22882 			/* Add ST insn to subprog prologue to init extra stack */
22883 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
22884 						     BPF_MAX_LOOPS);
22885 		}
22886 		/* Copy first actual insn to preserve it */
22887 		insn_buf[cnt++] = env->prog->insnsi[subprog_start];
22888 
22889 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt);
22890 		if (!new_prog)
22891 			return -ENOMEM;
22892 		env->prog = prog = new_prog;
22893 		/*
22894 		 * If may_goto is a first insn of a prog there could be a jmp
22895 		 * insn that points to it, hence adjust all such jmps to point
22896 		 * to insn after BPF_ST that inits may_goto count.
22897 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
22898 		 */
22899 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta));
22900 	}
22901 
22902 	/* Since poke tab is now finalized, publish aux to tracker. */
22903 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
22904 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
22905 		if (!map_ptr->ops->map_poke_track ||
22906 		    !map_ptr->ops->map_poke_untrack ||
22907 		    !map_ptr->ops->map_poke_run) {
22908 			verifier_bug(env, "poke tab is misconfigured");
22909 			return -EFAULT;
22910 		}
22911 
22912 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
22913 		if (ret < 0) {
22914 			verbose(env, "tracking tail call prog failed\n");
22915 			return ret;
22916 		}
22917 	}
22918 
22919 	sort_kfunc_descs_by_imm_off(env->prog);
22920 
22921 	return 0;
22922 }
22923 
22924 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
22925 					int position,
22926 					s32 stack_base,
22927 					u32 callback_subprogno,
22928 					u32 *total_cnt)
22929 {
22930 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
22931 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
22932 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
22933 	int reg_loop_max = BPF_REG_6;
22934 	int reg_loop_cnt = BPF_REG_7;
22935 	int reg_loop_ctx = BPF_REG_8;
22936 
22937 	struct bpf_insn *insn_buf = env->insn_buf;
22938 	struct bpf_prog *new_prog;
22939 	u32 callback_start;
22940 	u32 call_insn_offset;
22941 	s32 callback_offset;
22942 	u32 cnt = 0;
22943 
22944 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
22945 	 * be careful to modify this code in sync.
22946 	 */
22947 
22948 	/* Return error and jump to the end of the patch if
22949 	 * expected number of iterations is too big.
22950 	 */
22951 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
22952 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
22953 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
22954 	/* spill R6, R7, R8 to use these as loop vars */
22955 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
22956 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
22957 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
22958 	/* initialize loop vars */
22959 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
22960 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
22961 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
22962 	/* loop header,
22963 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
22964 	 */
22965 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
22966 	/* callback call,
22967 	 * correct callback offset would be set after patching
22968 	 */
22969 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
22970 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
22971 	insn_buf[cnt++] = BPF_CALL_REL(0);
22972 	/* increment loop counter */
22973 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
22974 	/* jump to loop header if callback returned 0 */
22975 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
22976 	/* return value of bpf_loop,
22977 	 * set R0 to the number of iterations
22978 	 */
22979 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
22980 	/* restore original values of R6, R7, R8 */
22981 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
22982 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
22983 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
22984 
22985 	*total_cnt = cnt;
22986 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
22987 	if (!new_prog)
22988 		return new_prog;
22989 
22990 	/* callback start is known only after patching */
22991 	callback_start = env->subprog_info[callback_subprogno].start;
22992 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
22993 	call_insn_offset = position + 12;
22994 	callback_offset = callback_start - call_insn_offset - 1;
22995 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
22996 
22997 	return new_prog;
22998 }
22999 
23000 static bool is_bpf_loop_call(struct bpf_insn *insn)
23001 {
23002 	return insn->code == (BPF_JMP | BPF_CALL) &&
23003 		insn->src_reg == 0 &&
23004 		insn->imm == BPF_FUNC_loop;
23005 }
23006 
23007 /* For all sub-programs in the program (including main) check
23008  * insn_aux_data to see if there are bpf_loop calls that require
23009  * inlining. If such calls are found the calls are replaced with a
23010  * sequence of instructions produced by `inline_bpf_loop` function and
23011  * subprog stack_depth is increased by the size of 3 registers.
23012  * This stack space is used to spill values of the R6, R7, R8.  These
23013  * registers are used to store the loop bound, counter and context
23014  * variables.
23015  */
23016 static int optimize_bpf_loop(struct bpf_verifier_env *env)
23017 {
23018 	struct bpf_subprog_info *subprogs = env->subprog_info;
23019 	int i, cur_subprog = 0, cnt, delta = 0;
23020 	struct bpf_insn *insn = env->prog->insnsi;
23021 	int insn_cnt = env->prog->len;
23022 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
23023 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23024 	u16 stack_depth_extra = 0;
23025 
23026 	for (i = 0; i < insn_cnt; i++, insn++) {
23027 		struct bpf_loop_inline_state *inline_state =
23028 			&env->insn_aux_data[i + delta].loop_inline_state;
23029 
23030 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
23031 			struct bpf_prog *new_prog;
23032 
23033 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
23034 			new_prog = inline_bpf_loop(env,
23035 						   i + delta,
23036 						   -(stack_depth + stack_depth_extra),
23037 						   inline_state->callback_subprogno,
23038 						   &cnt);
23039 			if (!new_prog)
23040 				return -ENOMEM;
23041 
23042 			delta     += cnt - 1;
23043 			env->prog  = new_prog;
23044 			insn       = new_prog->insnsi + i + delta;
23045 		}
23046 
23047 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
23048 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
23049 			cur_subprog++;
23050 			stack_depth = subprogs[cur_subprog].stack_depth;
23051 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23052 			stack_depth_extra = 0;
23053 		}
23054 	}
23055 
23056 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23057 
23058 	return 0;
23059 }
23060 
23061 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
23062  * adjust subprograms stack depth when possible.
23063  */
23064 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
23065 {
23066 	struct bpf_subprog_info *subprog = env->subprog_info;
23067 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
23068 	struct bpf_insn *insn = env->prog->insnsi;
23069 	int insn_cnt = env->prog->len;
23070 	u32 spills_num;
23071 	bool modified = false;
23072 	int i, j;
23073 
23074 	for (i = 0; i < insn_cnt; i++, insn++) {
23075 		if (aux[i].fastcall_spills_num > 0) {
23076 			spills_num = aux[i].fastcall_spills_num;
23077 			/* NOPs would be removed by opt_remove_nops() */
23078 			for (j = 1; j <= spills_num; ++j) {
23079 				*(insn - j) = NOP;
23080 				*(insn + j) = NOP;
23081 			}
23082 			modified = true;
23083 		}
23084 		if ((subprog + 1)->start == i + 1) {
23085 			if (modified && !subprog->keep_fastcall_stack)
23086 				subprog->stack_depth = -subprog->fastcall_stack_off;
23087 			subprog++;
23088 			modified = false;
23089 		}
23090 	}
23091 
23092 	return 0;
23093 }
23094 
23095 static void free_states(struct bpf_verifier_env *env)
23096 {
23097 	struct bpf_verifier_state_list *sl;
23098 	struct list_head *head, *pos, *tmp;
23099 	struct bpf_scc_info *info;
23100 	int i, j;
23101 
23102 	free_verifier_state(env->cur_state, true);
23103 	env->cur_state = NULL;
23104 	while (!pop_stack(env, NULL, NULL, false));
23105 
23106 	list_for_each_safe(pos, tmp, &env->free_list) {
23107 		sl = container_of(pos, struct bpf_verifier_state_list, node);
23108 		free_verifier_state(&sl->state, false);
23109 		kfree(sl);
23110 	}
23111 	INIT_LIST_HEAD(&env->free_list);
23112 
23113 	for (i = 0; i < env->scc_cnt; ++i) {
23114 		info = env->scc_info[i];
23115 		if (!info)
23116 			continue;
23117 		for (j = 0; j < info->num_visits; j++)
23118 			free_backedges(&info->visits[j]);
23119 		kvfree(info);
23120 		env->scc_info[i] = NULL;
23121 	}
23122 
23123 	if (!env->explored_states)
23124 		return;
23125 
23126 	for (i = 0; i < state_htab_size(env); i++) {
23127 		head = &env->explored_states[i];
23128 
23129 		list_for_each_safe(pos, tmp, head) {
23130 			sl = container_of(pos, struct bpf_verifier_state_list, node);
23131 			free_verifier_state(&sl->state, false);
23132 			kfree(sl);
23133 		}
23134 		INIT_LIST_HEAD(&env->explored_states[i]);
23135 	}
23136 }
23137 
23138 static int do_check_common(struct bpf_verifier_env *env, int subprog)
23139 {
23140 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
23141 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
23142 	struct bpf_prog_aux *aux = env->prog->aux;
23143 	struct bpf_verifier_state *state;
23144 	struct bpf_reg_state *regs;
23145 	int ret, i;
23146 
23147 	env->prev_linfo = NULL;
23148 	env->pass_cnt++;
23149 
23150 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL_ACCOUNT);
23151 	if (!state)
23152 		return -ENOMEM;
23153 	state->curframe = 0;
23154 	state->speculative = false;
23155 	state->branches = 1;
23156 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL_ACCOUNT);
23157 	if (!state->frame[0]) {
23158 		kfree(state);
23159 		return -ENOMEM;
23160 	}
23161 	env->cur_state = state;
23162 	init_func_state(env, state->frame[0],
23163 			BPF_MAIN_FUNC /* callsite */,
23164 			0 /* frameno */,
23165 			subprog);
23166 	state->first_insn_idx = env->subprog_info[subprog].start;
23167 	state->last_insn_idx = -1;
23168 
23169 	regs = state->frame[state->curframe]->regs;
23170 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
23171 		const char *sub_name = subprog_name(env, subprog);
23172 		struct bpf_subprog_arg_info *arg;
23173 		struct bpf_reg_state *reg;
23174 
23175 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
23176 		ret = btf_prepare_func_args(env, subprog);
23177 		if (ret)
23178 			goto out;
23179 
23180 		if (subprog_is_exc_cb(env, subprog)) {
23181 			state->frame[0]->in_exception_callback_fn = true;
23182 			/* We have already ensured that the callback returns an integer, just
23183 			 * like all global subprogs. We need to determine it only has a single
23184 			 * scalar argument.
23185 			 */
23186 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
23187 				verbose(env, "exception cb only supports single integer argument\n");
23188 				ret = -EINVAL;
23189 				goto out;
23190 			}
23191 		}
23192 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
23193 			arg = &sub->args[i - BPF_REG_1];
23194 			reg = &regs[i];
23195 
23196 			if (arg->arg_type == ARG_PTR_TO_CTX) {
23197 				reg->type = PTR_TO_CTX;
23198 				mark_reg_known_zero(env, regs, i);
23199 			} else if (arg->arg_type == ARG_ANYTHING) {
23200 				reg->type = SCALAR_VALUE;
23201 				mark_reg_unknown(env, regs, i);
23202 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
23203 				/* assume unspecial LOCAL dynptr type */
23204 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
23205 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
23206 				reg->type = PTR_TO_MEM;
23207 				reg->type |= arg->arg_type &
23208 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
23209 				mark_reg_known_zero(env, regs, i);
23210 				reg->mem_size = arg->mem_size;
23211 				if (arg->arg_type & PTR_MAYBE_NULL)
23212 					reg->id = ++env->id_gen;
23213 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
23214 				reg->type = PTR_TO_BTF_ID;
23215 				if (arg->arg_type & PTR_MAYBE_NULL)
23216 					reg->type |= PTR_MAYBE_NULL;
23217 				if (arg->arg_type & PTR_UNTRUSTED)
23218 					reg->type |= PTR_UNTRUSTED;
23219 				if (arg->arg_type & PTR_TRUSTED)
23220 					reg->type |= PTR_TRUSTED;
23221 				mark_reg_known_zero(env, regs, i);
23222 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
23223 				reg->btf_id = arg->btf_id;
23224 				reg->id = ++env->id_gen;
23225 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
23226 				/* caller can pass either PTR_TO_ARENA or SCALAR */
23227 				mark_reg_unknown(env, regs, i);
23228 			} else {
23229 				verifier_bug(env, "unhandled arg#%d type %d",
23230 					     i - BPF_REG_1, arg->arg_type);
23231 				ret = -EFAULT;
23232 				goto out;
23233 			}
23234 		}
23235 	} else {
23236 		/* if main BPF program has associated BTF info, validate that
23237 		 * it's matching expected signature, and otherwise mark BTF
23238 		 * info for main program as unreliable
23239 		 */
23240 		if (env->prog->aux->func_info_aux) {
23241 			ret = btf_prepare_func_args(env, 0);
23242 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
23243 				env->prog->aux->func_info_aux[0].unreliable = true;
23244 		}
23245 
23246 		/* 1st arg to a function */
23247 		regs[BPF_REG_1].type = PTR_TO_CTX;
23248 		mark_reg_known_zero(env, regs, BPF_REG_1);
23249 	}
23250 
23251 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
23252 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
23253 		for (i = 0; i < aux->ctx_arg_info_size; i++)
23254 			aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ?
23255 							  acquire_reference(env, 0) : 0;
23256 	}
23257 
23258 	ret = do_check(env);
23259 out:
23260 	if (!ret && pop_log)
23261 		bpf_vlog_reset(&env->log, 0);
23262 	free_states(env);
23263 	return ret;
23264 }
23265 
23266 /* Lazily verify all global functions based on their BTF, if they are called
23267  * from main BPF program or any of subprograms transitively.
23268  * BPF global subprogs called from dead code are not validated.
23269  * All callable global functions must pass verification.
23270  * Otherwise the whole program is rejected.
23271  * Consider:
23272  * int bar(int);
23273  * int foo(int f)
23274  * {
23275  *    return bar(f);
23276  * }
23277  * int bar(int b)
23278  * {
23279  *    ...
23280  * }
23281  * foo() will be verified first for R1=any_scalar_value. During verification it
23282  * will be assumed that bar() already verified successfully and call to bar()
23283  * from foo() will be checked for type match only. Later bar() will be verified
23284  * independently to check that it's safe for R1=any_scalar_value.
23285  */
23286 static int do_check_subprogs(struct bpf_verifier_env *env)
23287 {
23288 	struct bpf_prog_aux *aux = env->prog->aux;
23289 	struct bpf_func_info_aux *sub_aux;
23290 	int i, ret, new_cnt;
23291 
23292 	if (!aux->func_info)
23293 		return 0;
23294 
23295 	/* exception callback is presumed to be always called */
23296 	if (env->exception_callback_subprog)
23297 		subprog_aux(env, env->exception_callback_subprog)->called = true;
23298 
23299 again:
23300 	new_cnt = 0;
23301 	for (i = 1; i < env->subprog_cnt; i++) {
23302 		if (!subprog_is_global(env, i))
23303 			continue;
23304 
23305 		sub_aux = subprog_aux(env, i);
23306 		if (!sub_aux->called || sub_aux->verified)
23307 			continue;
23308 
23309 		env->insn_idx = env->subprog_info[i].start;
23310 		WARN_ON_ONCE(env->insn_idx == 0);
23311 		ret = do_check_common(env, i);
23312 		if (ret) {
23313 			return ret;
23314 		} else if (env->log.level & BPF_LOG_LEVEL) {
23315 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
23316 				i, subprog_name(env, i));
23317 		}
23318 
23319 		/* We verified new global subprog, it might have called some
23320 		 * more global subprogs that we haven't verified yet, so we
23321 		 * need to do another pass over subprogs to verify those.
23322 		 */
23323 		sub_aux->verified = true;
23324 		new_cnt++;
23325 	}
23326 
23327 	/* We can't loop forever as we verify at least one global subprog on
23328 	 * each pass.
23329 	 */
23330 	if (new_cnt)
23331 		goto again;
23332 
23333 	return 0;
23334 }
23335 
23336 static int do_check_main(struct bpf_verifier_env *env)
23337 {
23338 	int ret;
23339 
23340 	env->insn_idx = 0;
23341 	ret = do_check_common(env, 0);
23342 	if (!ret)
23343 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23344 	return ret;
23345 }
23346 
23347 
23348 static void print_verification_stats(struct bpf_verifier_env *env)
23349 {
23350 	int i;
23351 
23352 	if (env->log.level & BPF_LOG_STATS) {
23353 		verbose(env, "verification time %lld usec\n",
23354 			div_u64(env->verification_time, 1000));
23355 		verbose(env, "stack depth ");
23356 		for (i = 0; i < env->subprog_cnt; i++) {
23357 			u32 depth = env->subprog_info[i].stack_depth;
23358 
23359 			verbose(env, "%d", depth);
23360 			if (i + 1 < env->subprog_cnt)
23361 				verbose(env, "+");
23362 		}
23363 		verbose(env, "\n");
23364 	}
23365 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
23366 		"total_states %d peak_states %d mark_read %d\n",
23367 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
23368 		env->max_states_per_insn, env->total_states,
23369 		env->peak_states, env->longest_mark_read_walk);
23370 }
23371 
23372 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
23373 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
23374 {
23375 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
23376 	prog->aux->ctx_arg_info_size = cnt;
23377 
23378 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
23379 }
23380 
23381 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
23382 {
23383 	const struct btf_type *t, *func_proto;
23384 	const struct bpf_struct_ops_desc *st_ops_desc;
23385 	const struct bpf_struct_ops *st_ops;
23386 	const struct btf_member *member;
23387 	struct bpf_prog *prog = env->prog;
23388 	bool has_refcounted_arg = false;
23389 	u32 btf_id, member_idx, member_off;
23390 	struct btf *btf;
23391 	const char *mname;
23392 	int i, err;
23393 
23394 	if (!prog->gpl_compatible) {
23395 		verbose(env, "struct ops programs must have a GPL compatible license\n");
23396 		return -EINVAL;
23397 	}
23398 
23399 	if (!prog->aux->attach_btf_id)
23400 		return -ENOTSUPP;
23401 
23402 	btf = prog->aux->attach_btf;
23403 	if (btf_is_module(btf)) {
23404 		/* Make sure st_ops is valid through the lifetime of env */
23405 		env->attach_btf_mod = btf_try_get_module(btf);
23406 		if (!env->attach_btf_mod) {
23407 			verbose(env, "struct_ops module %s is not found\n",
23408 				btf_get_name(btf));
23409 			return -ENOTSUPP;
23410 		}
23411 	}
23412 
23413 	btf_id = prog->aux->attach_btf_id;
23414 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
23415 	if (!st_ops_desc) {
23416 		verbose(env, "attach_btf_id %u is not a supported struct\n",
23417 			btf_id);
23418 		return -ENOTSUPP;
23419 	}
23420 	st_ops = st_ops_desc->st_ops;
23421 
23422 	t = st_ops_desc->type;
23423 	member_idx = prog->expected_attach_type;
23424 	if (member_idx >= btf_type_vlen(t)) {
23425 		verbose(env, "attach to invalid member idx %u of struct %s\n",
23426 			member_idx, st_ops->name);
23427 		return -EINVAL;
23428 	}
23429 
23430 	member = &btf_type_member(t)[member_idx];
23431 	mname = btf_name_by_offset(btf, member->name_off);
23432 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
23433 					       NULL);
23434 	if (!func_proto) {
23435 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
23436 			mname, member_idx, st_ops->name);
23437 		return -EINVAL;
23438 	}
23439 
23440 	member_off = __btf_member_bit_offset(t, member) / 8;
23441 	err = bpf_struct_ops_supported(st_ops, member_off);
23442 	if (err) {
23443 		verbose(env, "attach to unsupported member %s of struct %s\n",
23444 			mname, st_ops->name);
23445 		return err;
23446 	}
23447 
23448 	if (st_ops->check_member) {
23449 		err = st_ops->check_member(t, member, prog);
23450 
23451 		if (err) {
23452 			verbose(env, "attach to unsupported member %s of struct %s\n",
23453 				mname, st_ops->name);
23454 			return err;
23455 		}
23456 	}
23457 
23458 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
23459 		verbose(env, "Private stack not supported by jit\n");
23460 		return -EACCES;
23461 	}
23462 
23463 	for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) {
23464 		if (st_ops_desc->arg_info[member_idx].info->refcounted) {
23465 			has_refcounted_arg = true;
23466 			break;
23467 		}
23468 	}
23469 
23470 	/* Tail call is not allowed for programs with refcounted arguments since we
23471 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
23472 	 */
23473 	for (i = 0; i < env->subprog_cnt; i++) {
23474 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
23475 			verbose(env, "program with __ref argument cannot tail call\n");
23476 			return -EINVAL;
23477 		}
23478 	}
23479 
23480 	prog->aux->st_ops = st_ops;
23481 	prog->aux->attach_st_ops_member_off = member_off;
23482 
23483 	prog->aux->attach_func_proto = func_proto;
23484 	prog->aux->attach_func_name = mname;
23485 	env->ops = st_ops->verifier_ops;
23486 
23487 	return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info,
23488 					  st_ops_desc->arg_info[member_idx].cnt);
23489 }
23490 #define SECURITY_PREFIX "security_"
23491 
23492 static int check_attach_modify_return(unsigned long addr, const char *func_name)
23493 {
23494 	if (within_error_injection_list(addr) ||
23495 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
23496 		return 0;
23497 
23498 	return -EINVAL;
23499 }
23500 
23501 /* list of non-sleepable functions that are otherwise on
23502  * ALLOW_ERROR_INJECTION list
23503  */
23504 BTF_SET_START(btf_non_sleepable_error_inject)
23505 /* Three functions below can be called from sleepable and non-sleepable context.
23506  * Assume non-sleepable from bpf safety point of view.
23507  */
23508 BTF_ID(func, __filemap_add_folio)
23509 #ifdef CONFIG_FAIL_PAGE_ALLOC
23510 BTF_ID(func, should_fail_alloc_page)
23511 #endif
23512 #ifdef CONFIG_FAILSLAB
23513 BTF_ID(func, should_failslab)
23514 #endif
23515 BTF_SET_END(btf_non_sleepable_error_inject)
23516 
23517 static int check_non_sleepable_error_inject(u32 btf_id)
23518 {
23519 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
23520 }
23521 
23522 int bpf_check_attach_target(struct bpf_verifier_log *log,
23523 			    const struct bpf_prog *prog,
23524 			    const struct bpf_prog *tgt_prog,
23525 			    u32 btf_id,
23526 			    struct bpf_attach_target_info *tgt_info)
23527 {
23528 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
23529 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
23530 	char trace_symbol[KSYM_SYMBOL_LEN];
23531 	const char prefix[] = "btf_trace_";
23532 	struct bpf_raw_event_map *btp;
23533 	int ret = 0, subprog = -1, i;
23534 	const struct btf_type *t;
23535 	bool conservative = true;
23536 	const char *tname, *fname;
23537 	struct btf *btf;
23538 	long addr = 0;
23539 	struct module *mod = NULL;
23540 
23541 	if (!btf_id) {
23542 		bpf_log(log, "Tracing programs must provide btf_id\n");
23543 		return -EINVAL;
23544 	}
23545 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
23546 	if (!btf) {
23547 		bpf_log(log,
23548 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
23549 		return -EINVAL;
23550 	}
23551 	t = btf_type_by_id(btf, btf_id);
23552 	if (!t) {
23553 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
23554 		return -EINVAL;
23555 	}
23556 	tname = btf_name_by_offset(btf, t->name_off);
23557 	if (!tname) {
23558 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
23559 		return -EINVAL;
23560 	}
23561 	if (tgt_prog) {
23562 		struct bpf_prog_aux *aux = tgt_prog->aux;
23563 		bool tgt_changes_pkt_data;
23564 		bool tgt_might_sleep;
23565 
23566 		if (bpf_prog_is_dev_bound(prog->aux) &&
23567 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
23568 			bpf_log(log, "Target program bound device mismatch");
23569 			return -EINVAL;
23570 		}
23571 
23572 		for (i = 0; i < aux->func_info_cnt; i++)
23573 			if (aux->func_info[i].type_id == btf_id) {
23574 				subprog = i;
23575 				break;
23576 			}
23577 		if (subprog == -1) {
23578 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
23579 			return -EINVAL;
23580 		}
23581 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
23582 			bpf_log(log,
23583 				"%s programs cannot attach to exception callback\n",
23584 				prog_extension ? "Extension" : "FENTRY/FEXIT");
23585 			return -EINVAL;
23586 		}
23587 		conservative = aux->func_info_aux[subprog].unreliable;
23588 		if (prog_extension) {
23589 			if (conservative) {
23590 				bpf_log(log,
23591 					"Cannot replace static functions\n");
23592 				return -EINVAL;
23593 			}
23594 			if (!prog->jit_requested) {
23595 				bpf_log(log,
23596 					"Extension programs should be JITed\n");
23597 				return -EINVAL;
23598 			}
23599 			tgt_changes_pkt_data = aux->func
23600 					       ? aux->func[subprog]->aux->changes_pkt_data
23601 					       : aux->changes_pkt_data;
23602 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
23603 				bpf_log(log,
23604 					"Extension program changes packet data, while original does not\n");
23605 				return -EINVAL;
23606 			}
23607 
23608 			tgt_might_sleep = aux->func
23609 					  ? aux->func[subprog]->aux->might_sleep
23610 					  : aux->might_sleep;
23611 			if (prog->aux->might_sleep && !tgt_might_sleep) {
23612 				bpf_log(log,
23613 					"Extension program may sleep, while original does not\n");
23614 				return -EINVAL;
23615 			}
23616 		}
23617 		if (!tgt_prog->jited) {
23618 			bpf_log(log, "Can attach to only JITed progs\n");
23619 			return -EINVAL;
23620 		}
23621 		if (prog_tracing) {
23622 			if (aux->attach_tracing_prog) {
23623 				/*
23624 				 * Target program is an fentry/fexit which is already attached
23625 				 * to another tracing program. More levels of nesting
23626 				 * attachment are not allowed.
23627 				 */
23628 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
23629 				return -EINVAL;
23630 			}
23631 		} else if (tgt_prog->type == prog->type) {
23632 			/*
23633 			 * To avoid potential call chain cycles, prevent attaching of a
23634 			 * program extension to another extension. It's ok to attach
23635 			 * fentry/fexit to extension program.
23636 			 */
23637 			bpf_log(log, "Cannot recursively attach\n");
23638 			return -EINVAL;
23639 		}
23640 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
23641 		    prog_extension &&
23642 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
23643 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
23644 			/* Program extensions can extend all program types
23645 			 * except fentry/fexit. The reason is the following.
23646 			 * The fentry/fexit programs are used for performance
23647 			 * analysis, stats and can be attached to any program
23648 			 * type. When extension program is replacing XDP function
23649 			 * it is necessary to allow performance analysis of all
23650 			 * functions. Both original XDP program and its program
23651 			 * extension. Hence attaching fentry/fexit to
23652 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
23653 			 * fentry/fexit was allowed it would be possible to create
23654 			 * long call chain fentry->extension->fentry->extension
23655 			 * beyond reasonable stack size. Hence extending fentry
23656 			 * is not allowed.
23657 			 */
23658 			bpf_log(log, "Cannot extend fentry/fexit\n");
23659 			return -EINVAL;
23660 		}
23661 	} else {
23662 		if (prog_extension) {
23663 			bpf_log(log, "Cannot replace kernel functions\n");
23664 			return -EINVAL;
23665 		}
23666 	}
23667 
23668 	switch (prog->expected_attach_type) {
23669 	case BPF_TRACE_RAW_TP:
23670 		if (tgt_prog) {
23671 			bpf_log(log,
23672 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
23673 			return -EINVAL;
23674 		}
23675 		if (!btf_type_is_typedef(t)) {
23676 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
23677 				btf_id);
23678 			return -EINVAL;
23679 		}
23680 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
23681 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
23682 				btf_id, tname);
23683 			return -EINVAL;
23684 		}
23685 		tname += sizeof(prefix) - 1;
23686 
23687 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
23688 		 * names. Thus using bpf_raw_event_map to get argument names.
23689 		 */
23690 		btp = bpf_get_raw_tracepoint(tname);
23691 		if (!btp)
23692 			return -EINVAL;
23693 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
23694 					trace_symbol);
23695 		bpf_put_raw_tracepoint(btp);
23696 
23697 		if (fname)
23698 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
23699 
23700 		if (!fname || ret < 0) {
23701 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
23702 				prefix, tname);
23703 			t = btf_type_by_id(btf, t->type);
23704 			if (!btf_type_is_ptr(t))
23705 				/* should never happen in valid vmlinux build */
23706 				return -EINVAL;
23707 		} else {
23708 			t = btf_type_by_id(btf, ret);
23709 			if (!btf_type_is_func(t))
23710 				/* should never happen in valid vmlinux build */
23711 				return -EINVAL;
23712 		}
23713 
23714 		t = btf_type_by_id(btf, t->type);
23715 		if (!btf_type_is_func_proto(t))
23716 			/* should never happen in valid vmlinux build */
23717 			return -EINVAL;
23718 
23719 		break;
23720 	case BPF_TRACE_ITER:
23721 		if (!btf_type_is_func(t)) {
23722 			bpf_log(log, "attach_btf_id %u is not a function\n",
23723 				btf_id);
23724 			return -EINVAL;
23725 		}
23726 		t = btf_type_by_id(btf, t->type);
23727 		if (!btf_type_is_func_proto(t))
23728 			return -EINVAL;
23729 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
23730 		if (ret)
23731 			return ret;
23732 		break;
23733 	default:
23734 		if (!prog_extension)
23735 			return -EINVAL;
23736 		fallthrough;
23737 	case BPF_MODIFY_RETURN:
23738 	case BPF_LSM_MAC:
23739 	case BPF_LSM_CGROUP:
23740 	case BPF_TRACE_FENTRY:
23741 	case BPF_TRACE_FEXIT:
23742 		if (!btf_type_is_func(t)) {
23743 			bpf_log(log, "attach_btf_id %u is not a function\n",
23744 				btf_id);
23745 			return -EINVAL;
23746 		}
23747 		if (prog_extension &&
23748 		    btf_check_type_match(log, prog, btf, t))
23749 			return -EINVAL;
23750 		t = btf_type_by_id(btf, t->type);
23751 		if (!btf_type_is_func_proto(t))
23752 			return -EINVAL;
23753 
23754 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
23755 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
23756 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
23757 			return -EINVAL;
23758 
23759 		if (tgt_prog && conservative)
23760 			t = NULL;
23761 
23762 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
23763 		if (ret < 0)
23764 			return ret;
23765 
23766 		if (tgt_prog) {
23767 			if (subprog == 0)
23768 				addr = (long) tgt_prog->bpf_func;
23769 			else
23770 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
23771 		} else {
23772 			if (btf_is_module(btf)) {
23773 				mod = btf_try_get_module(btf);
23774 				if (mod)
23775 					addr = find_kallsyms_symbol_value(mod, tname);
23776 				else
23777 					addr = 0;
23778 			} else {
23779 				addr = kallsyms_lookup_name(tname);
23780 			}
23781 			if (!addr) {
23782 				module_put(mod);
23783 				bpf_log(log,
23784 					"The address of function %s cannot be found\n",
23785 					tname);
23786 				return -ENOENT;
23787 			}
23788 		}
23789 
23790 		if (prog->sleepable) {
23791 			ret = -EINVAL;
23792 			switch (prog->type) {
23793 			case BPF_PROG_TYPE_TRACING:
23794 
23795 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
23796 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
23797 				 */
23798 				if (!check_non_sleepable_error_inject(btf_id) &&
23799 				    within_error_injection_list(addr))
23800 					ret = 0;
23801 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
23802 				 * in the fmodret id set with the KF_SLEEPABLE flag.
23803 				 */
23804 				else {
23805 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
23806 										prog);
23807 
23808 					if (flags && (*flags & KF_SLEEPABLE))
23809 						ret = 0;
23810 				}
23811 				break;
23812 			case BPF_PROG_TYPE_LSM:
23813 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
23814 				 * Only some of them are sleepable.
23815 				 */
23816 				if (bpf_lsm_is_sleepable_hook(btf_id))
23817 					ret = 0;
23818 				break;
23819 			default:
23820 				break;
23821 			}
23822 			if (ret) {
23823 				module_put(mod);
23824 				bpf_log(log, "%s is not sleepable\n", tname);
23825 				return ret;
23826 			}
23827 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
23828 			if (tgt_prog) {
23829 				module_put(mod);
23830 				bpf_log(log, "can't modify return codes of BPF programs\n");
23831 				return -EINVAL;
23832 			}
23833 			ret = -EINVAL;
23834 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
23835 			    !check_attach_modify_return(addr, tname))
23836 				ret = 0;
23837 			if (ret) {
23838 				module_put(mod);
23839 				bpf_log(log, "%s() is not modifiable\n", tname);
23840 				return ret;
23841 			}
23842 		}
23843 
23844 		break;
23845 	}
23846 	tgt_info->tgt_addr = addr;
23847 	tgt_info->tgt_name = tname;
23848 	tgt_info->tgt_type = t;
23849 	tgt_info->tgt_mod = mod;
23850 	return 0;
23851 }
23852 
23853 BTF_SET_START(btf_id_deny)
23854 BTF_ID_UNUSED
23855 #ifdef CONFIG_SMP
23856 BTF_ID(func, ___migrate_enable)
23857 BTF_ID(func, migrate_disable)
23858 BTF_ID(func, migrate_enable)
23859 #endif
23860 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
23861 BTF_ID(func, rcu_read_unlock_strict)
23862 #endif
23863 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
23864 BTF_ID(func, preempt_count_add)
23865 BTF_ID(func, preempt_count_sub)
23866 #endif
23867 #ifdef CONFIG_PREEMPT_RCU
23868 BTF_ID(func, __rcu_read_lock)
23869 BTF_ID(func, __rcu_read_unlock)
23870 #endif
23871 BTF_SET_END(btf_id_deny)
23872 
23873 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
23874  * Currently, we must manually list all __noreturn functions here. Once a more
23875  * robust solution is implemented, this workaround can be removed.
23876  */
23877 BTF_SET_START(noreturn_deny)
23878 #ifdef CONFIG_IA32_EMULATION
23879 BTF_ID(func, __ia32_sys_exit)
23880 BTF_ID(func, __ia32_sys_exit_group)
23881 #endif
23882 #ifdef CONFIG_KUNIT
23883 BTF_ID(func, __kunit_abort)
23884 BTF_ID(func, kunit_try_catch_throw)
23885 #endif
23886 #ifdef CONFIG_MODULES
23887 BTF_ID(func, __module_put_and_kthread_exit)
23888 #endif
23889 #ifdef CONFIG_X86_64
23890 BTF_ID(func, __x64_sys_exit)
23891 BTF_ID(func, __x64_sys_exit_group)
23892 #endif
23893 BTF_ID(func, do_exit)
23894 BTF_ID(func, do_group_exit)
23895 BTF_ID(func, kthread_complete_and_exit)
23896 BTF_ID(func, kthread_exit)
23897 BTF_ID(func, make_task_dead)
23898 BTF_SET_END(noreturn_deny)
23899 
23900 static bool can_be_sleepable(struct bpf_prog *prog)
23901 {
23902 	if (prog->type == BPF_PROG_TYPE_TRACING) {
23903 		switch (prog->expected_attach_type) {
23904 		case BPF_TRACE_FENTRY:
23905 		case BPF_TRACE_FEXIT:
23906 		case BPF_MODIFY_RETURN:
23907 		case BPF_TRACE_ITER:
23908 			return true;
23909 		default:
23910 			return false;
23911 		}
23912 	}
23913 	return prog->type == BPF_PROG_TYPE_LSM ||
23914 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
23915 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
23916 }
23917 
23918 static int check_attach_btf_id(struct bpf_verifier_env *env)
23919 {
23920 	struct bpf_prog *prog = env->prog;
23921 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
23922 	struct bpf_attach_target_info tgt_info = {};
23923 	u32 btf_id = prog->aux->attach_btf_id;
23924 	struct bpf_trampoline *tr;
23925 	int ret;
23926 	u64 key;
23927 
23928 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
23929 		if (prog->sleepable)
23930 			/* attach_btf_id checked to be zero already */
23931 			return 0;
23932 		verbose(env, "Syscall programs can only be sleepable\n");
23933 		return -EINVAL;
23934 	}
23935 
23936 	if (prog->sleepable && !can_be_sleepable(prog)) {
23937 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
23938 		return -EINVAL;
23939 	}
23940 
23941 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
23942 		return check_struct_ops_btf_id(env);
23943 
23944 	if (prog->type != BPF_PROG_TYPE_TRACING &&
23945 	    prog->type != BPF_PROG_TYPE_LSM &&
23946 	    prog->type != BPF_PROG_TYPE_EXT)
23947 		return 0;
23948 
23949 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
23950 	if (ret)
23951 		return ret;
23952 
23953 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
23954 		/* to make freplace equivalent to their targets, they need to
23955 		 * inherit env->ops and expected_attach_type for the rest of the
23956 		 * verification
23957 		 */
23958 		env->ops = bpf_verifier_ops[tgt_prog->type];
23959 		prog->expected_attach_type = tgt_prog->expected_attach_type;
23960 	}
23961 
23962 	/* store info about the attachment target that will be used later */
23963 	prog->aux->attach_func_proto = tgt_info.tgt_type;
23964 	prog->aux->attach_func_name = tgt_info.tgt_name;
23965 	prog->aux->mod = tgt_info.tgt_mod;
23966 
23967 	if (tgt_prog) {
23968 		prog->aux->saved_dst_prog_type = tgt_prog->type;
23969 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
23970 	}
23971 
23972 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
23973 		prog->aux->attach_btf_trace = true;
23974 		return 0;
23975 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
23976 		return bpf_iter_prog_supported(prog);
23977 	}
23978 
23979 	if (prog->type == BPF_PROG_TYPE_LSM) {
23980 		ret = bpf_lsm_verify_prog(&env->log, prog);
23981 		if (ret < 0)
23982 			return ret;
23983 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
23984 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
23985 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
23986 			tgt_info.tgt_name);
23987 		return -EINVAL;
23988 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
23989 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
23990 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
23991 		verbose(env, "Attaching fexit/fmod_ret to __noreturn function '%s' is rejected.\n",
23992 			tgt_info.tgt_name);
23993 		return -EINVAL;
23994 	}
23995 
23996 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
23997 	tr = bpf_trampoline_get(key, &tgt_info);
23998 	if (!tr)
23999 		return -ENOMEM;
24000 
24001 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
24002 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
24003 
24004 	prog->aux->dst_trampoline = tr;
24005 	return 0;
24006 }
24007 
24008 struct btf *bpf_get_btf_vmlinux(void)
24009 {
24010 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
24011 		mutex_lock(&bpf_verifier_lock);
24012 		if (!btf_vmlinux)
24013 			btf_vmlinux = btf_parse_vmlinux();
24014 		mutex_unlock(&bpf_verifier_lock);
24015 	}
24016 	return btf_vmlinux;
24017 }
24018 
24019 /*
24020  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
24021  * this case expect that every file descriptor in the array is either a map or
24022  * a BTF. Everything else is considered to be trash.
24023  */
24024 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
24025 {
24026 	struct bpf_map *map;
24027 	struct btf *btf;
24028 	CLASS(fd, f)(fd);
24029 	int err;
24030 
24031 	map = __bpf_map_get(f);
24032 	if (!IS_ERR(map)) {
24033 		err = __add_used_map(env, map);
24034 		if (err < 0)
24035 			return err;
24036 		return 0;
24037 	}
24038 
24039 	btf = __btf_get_by_fd(f);
24040 	if (!IS_ERR(btf)) {
24041 		err = __add_used_btf(env, btf);
24042 		if (err < 0)
24043 			return err;
24044 		return 0;
24045 	}
24046 
24047 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
24048 	return PTR_ERR(map);
24049 }
24050 
24051 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
24052 {
24053 	size_t size = sizeof(int);
24054 	int ret;
24055 	int fd;
24056 	u32 i;
24057 
24058 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
24059 
24060 	/*
24061 	 * The only difference between old (no fd_array_cnt is given) and new
24062 	 * APIs is that in the latter case the fd_array is expected to be
24063 	 * continuous and is scanned for map fds right away
24064 	 */
24065 	if (!attr->fd_array_cnt)
24066 		return 0;
24067 
24068 	/* Check for integer overflow */
24069 	if (attr->fd_array_cnt >= (U32_MAX / size)) {
24070 		verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
24071 		return -EINVAL;
24072 	}
24073 
24074 	for (i = 0; i < attr->fd_array_cnt; i++) {
24075 		if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
24076 			return -EFAULT;
24077 
24078 		ret = add_fd_from_fd_array(env, fd);
24079 		if (ret)
24080 			return ret;
24081 	}
24082 
24083 	return 0;
24084 }
24085 
24086 /* Each field is a register bitmask */
24087 struct insn_live_regs {
24088 	u16 use;	/* registers read by instruction */
24089 	u16 def;	/* registers written by instruction */
24090 	u16 in;		/* registers that may be alive before instruction */
24091 	u16 out;	/* registers that may be alive after instruction */
24092 };
24093 
24094 /* Bitmask with 1s for all caller saved registers */
24095 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
24096 
24097 /* Compute info->{use,def} fields for the instruction */
24098 static void compute_insn_live_regs(struct bpf_verifier_env *env,
24099 				   struct bpf_insn *insn,
24100 				   struct insn_live_regs *info)
24101 {
24102 	struct call_summary cs;
24103 	u8 class = BPF_CLASS(insn->code);
24104 	u8 code = BPF_OP(insn->code);
24105 	u8 mode = BPF_MODE(insn->code);
24106 	u16 src = BIT(insn->src_reg);
24107 	u16 dst = BIT(insn->dst_reg);
24108 	u16 r0  = BIT(0);
24109 	u16 def = 0;
24110 	u16 use = 0xffff;
24111 
24112 	switch (class) {
24113 	case BPF_LD:
24114 		switch (mode) {
24115 		case BPF_IMM:
24116 			if (BPF_SIZE(insn->code) == BPF_DW) {
24117 				def = dst;
24118 				use = 0;
24119 			}
24120 			break;
24121 		case BPF_LD | BPF_ABS:
24122 		case BPF_LD | BPF_IND:
24123 			/* stick with defaults */
24124 			break;
24125 		}
24126 		break;
24127 	case BPF_LDX:
24128 		switch (mode) {
24129 		case BPF_MEM:
24130 		case BPF_MEMSX:
24131 			def = dst;
24132 			use = src;
24133 			break;
24134 		}
24135 		break;
24136 	case BPF_ST:
24137 		switch (mode) {
24138 		case BPF_MEM:
24139 			def = 0;
24140 			use = dst;
24141 			break;
24142 		}
24143 		break;
24144 	case BPF_STX:
24145 		switch (mode) {
24146 		case BPF_MEM:
24147 			def = 0;
24148 			use = dst | src;
24149 			break;
24150 		case BPF_ATOMIC:
24151 			switch (insn->imm) {
24152 			case BPF_CMPXCHG:
24153 				use = r0 | dst | src;
24154 				def = r0;
24155 				break;
24156 			case BPF_LOAD_ACQ:
24157 				def = dst;
24158 				use = src;
24159 				break;
24160 			case BPF_STORE_REL:
24161 				def = 0;
24162 				use = dst | src;
24163 				break;
24164 			default:
24165 				use = dst | src;
24166 				if (insn->imm & BPF_FETCH)
24167 					def = src;
24168 				else
24169 					def = 0;
24170 			}
24171 			break;
24172 		}
24173 		break;
24174 	case BPF_ALU:
24175 	case BPF_ALU64:
24176 		switch (code) {
24177 		case BPF_END:
24178 			use = dst;
24179 			def = dst;
24180 			break;
24181 		case BPF_MOV:
24182 			def = dst;
24183 			if (BPF_SRC(insn->code) == BPF_K)
24184 				use = 0;
24185 			else
24186 				use = src;
24187 			break;
24188 		default:
24189 			def = dst;
24190 			if (BPF_SRC(insn->code) == BPF_K)
24191 				use = dst;
24192 			else
24193 				use = dst | src;
24194 		}
24195 		break;
24196 	case BPF_JMP:
24197 	case BPF_JMP32:
24198 		switch (code) {
24199 		case BPF_JA:
24200 		case BPF_JCOND:
24201 			def = 0;
24202 			use = 0;
24203 			break;
24204 		case BPF_EXIT:
24205 			def = 0;
24206 			use = r0;
24207 			break;
24208 		case BPF_CALL:
24209 			def = ALL_CALLER_SAVED_REGS;
24210 			use = def & ~BIT(BPF_REG_0);
24211 			if (get_call_summary(env, insn, &cs))
24212 				use = GENMASK(cs.num_params, 1);
24213 			break;
24214 		default:
24215 			def = 0;
24216 			if (BPF_SRC(insn->code) == BPF_K)
24217 				use = dst;
24218 			else
24219 				use = dst | src;
24220 		}
24221 		break;
24222 	}
24223 
24224 	info->def = def;
24225 	info->use = use;
24226 }
24227 
24228 /* Compute may-live registers after each instruction in the program.
24229  * The register is live after the instruction I if it is read by some
24230  * instruction S following I during program execution and is not
24231  * overwritten between I and S.
24232  *
24233  * Store result in env->insn_aux_data[i].live_regs.
24234  */
24235 static int compute_live_registers(struct bpf_verifier_env *env)
24236 {
24237 	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
24238 	struct bpf_insn *insns = env->prog->insnsi;
24239 	struct insn_live_regs *state;
24240 	int insn_cnt = env->prog->len;
24241 	int err = 0, i, j;
24242 	bool changed;
24243 
24244 	/* Use the following algorithm:
24245 	 * - define the following:
24246 	 *   - I.use : a set of all registers read by instruction I;
24247 	 *   - I.def : a set of all registers written by instruction I;
24248 	 *   - I.in  : a set of all registers that may be alive before I execution;
24249 	 *   - I.out : a set of all registers that may be alive after I execution;
24250 	 *   - insn_successors(I): a set of instructions S that might immediately
24251 	 *                         follow I for some program execution;
24252 	 * - associate separate empty sets 'I.in' and 'I.out' with each instruction;
24253 	 * - visit each instruction in a postorder and update
24254 	 *   state[i].in, state[i].out as follows:
24255 	 *
24256 	 *       state[i].out = U [state[s].in for S in insn_successors(i)]
24257 	 *       state[i].in  = (state[i].out / state[i].def) U state[i].use
24258 	 *
24259 	 *   (where U stands for set union, / stands for set difference)
24260 	 * - repeat the computation while {in,out} fields changes for
24261 	 *   any instruction.
24262 	 */
24263 	state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL_ACCOUNT);
24264 	if (!state) {
24265 		err = -ENOMEM;
24266 		goto out;
24267 	}
24268 
24269 	for (i = 0; i < insn_cnt; ++i)
24270 		compute_insn_live_regs(env, &insns[i], &state[i]);
24271 
24272 	changed = true;
24273 	while (changed) {
24274 		changed = false;
24275 		for (i = 0; i < env->cfg.cur_postorder; ++i) {
24276 			int insn_idx = env->cfg.insn_postorder[i];
24277 			struct insn_live_regs *live = &state[insn_idx];
24278 			int succ_num;
24279 			u32 succ[2];
24280 			u16 new_out = 0;
24281 			u16 new_in = 0;
24282 
24283 			succ_num = bpf_insn_successors(env->prog, insn_idx, succ);
24284 			for (int s = 0; s < succ_num; ++s)
24285 				new_out |= state[succ[s]].in;
24286 			new_in = (new_out & ~live->def) | live->use;
24287 			if (new_out != live->out || new_in != live->in) {
24288 				live->in = new_in;
24289 				live->out = new_out;
24290 				changed = true;
24291 			}
24292 		}
24293 	}
24294 
24295 	for (i = 0; i < insn_cnt; ++i)
24296 		insn_aux[i].live_regs_before = state[i].in;
24297 
24298 	if (env->log.level & BPF_LOG_LEVEL2) {
24299 		verbose(env, "Live regs before insn:\n");
24300 		for (i = 0; i < insn_cnt; ++i) {
24301 			if (env->insn_aux_data[i].scc)
24302 				verbose(env, "%3d ", env->insn_aux_data[i].scc);
24303 			else
24304 				verbose(env, "    ");
24305 			verbose(env, "%3d: ", i);
24306 			for (j = BPF_REG_0; j < BPF_REG_10; ++j)
24307 				if (insn_aux[i].live_regs_before & BIT(j))
24308 					verbose(env, "%d", j);
24309 				else
24310 					verbose(env, ".");
24311 			verbose(env, " ");
24312 			verbose_insn(env, &insns[i]);
24313 			if (bpf_is_ldimm64(&insns[i]))
24314 				i++;
24315 		}
24316 	}
24317 
24318 out:
24319 	kvfree(state);
24320 	return err;
24321 }
24322 
24323 /*
24324  * Compute strongly connected components (SCCs) on the CFG.
24325  * Assign an SCC number to each instruction, recorded in env->insn_aux[*].scc.
24326  * If instruction is a sole member of its SCC and there are no self edges,
24327  * assign it SCC number of zero.
24328  * Uses a non-recursive adaptation of Tarjan's algorithm for SCC computation.
24329  */
24330 static int compute_scc(struct bpf_verifier_env *env)
24331 {
24332 	const u32 NOT_ON_STACK = U32_MAX;
24333 
24334 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
24335 	const u32 insn_cnt = env->prog->len;
24336 	int stack_sz, dfs_sz, err = 0;
24337 	u32 *stack, *pre, *low, *dfs;
24338 	u32 succ_cnt, i, j, t, w;
24339 	u32 next_preorder_num;
24340 	u32 next_scc_id;
24341 	bool assign_scc;
24342 	u32 succ[2];
24343 
24344 	next_preorder_num = 1;
24345 	next_scc_id = 1;
24346 	/*
24347 	 * - 'stack' accumulates vertices in DFS order, see invariant comment below;
24348 	 * - 'pre[t] == p' => preorder number of vertex 't' is 'p';
24349 	 * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n';
24350 	 * - 'dfs' DFS traversal stack, used to emulate explicit recursion.
24351 	 */
24352 	stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24353 	pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24354 	low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24355 	dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT);
24356 	if (!stack || !pre || !low || !dfs) {
24357 		err = -ENOMEM;
24358 		goto exit;
24359 	}
24360 	/*
24361 	 * References:
24362 	 * [1] R. Tarjan "Depth-First Search and Linear Graph Algorithms"
24363 	 * [2] D. J. Pearce "A Space-Efficient Algorithm for Finding Strongly Connected Components"
24364 	 *
24365 	 * The algorithm maintains the following invariant:
24366 	 * - suppose there is a path 'u' ~> 'v', such that 'pre[v] < pre[u]';
24367 	 * - then, vertex 'u' remains on stack while vertex 'v' is on stack.
24368 	 *
24369 	 * Consequently:
24370 	 * - If 'low[v] < pre[v]', there is a path from 'v' to some vertex 'u',
24371 	 *   such that 'pre[u] == low[v]'; vertex 'u' is currently on the stack,
24372 	 *   and thus there is an SCC (loop) containing both 'u' and 'v'.
24373 	 * - If 'low[v] == pre[v]', loops containing 'v' have been explored,
24374 	 *   and 'v' can be considered the root of some SCC.
24375 	 *
24376 	 * Here is a pseudo-code for an explicitly recursive version of the algorithm:
24377 	 *
24378 	 *    NOT_ON_STACK = insn_cnt + 1
24379 	 *    pre = [0] * insn_cnt
24380 	 *    low = [0] * insn_cnt
24381 	 *    scc = [0] * insn_cnt
24382 	 *    stack = []
24383 	 *
24384 	 *    next_preorder_num = 1
24385 	 *    next_scc_id = 1
24386 	 *
24387 	 *    def recur(w):
24388 	 *        nonlocal next_preorder_num
24389 	 *        nonlocal next_scc_id
24390 	 *
24391 	 *        pre[w] = next_preorder_num
24392 	 *        low[w] = next_preorder_num
24393 	 *        next_preorder_num += 1
24394 	 *        stack.append(w)
24395 	 *        for s in successors(w):
24396 	 *            # Note: for classic algorithm the block below should look as:
24397 	 *            #
24398 	 *            # if pre[s] == 0:
24399 	 *            #     recur(s)
24400 	 *            #	    low[w] = min(low[w], low[s])
24401 	 *            # elif low[s] != NOT_ON_STACK:
24402 	 *            #     low[w] = min(low[w], pre[s])
24403 	 *            #
24404 	 *            # But replacing both 'min' instructions with 'low[w] = min(low[w], low[s])'
24405 	 *            # does not break the invariant and makes itartive version of the algorithm
24406 	 *            # simpler. See 'Algorithm #3' from [2].
24407 	 *
24408 	 *            # 's' not yet visited
24409 	 *            if pre[s] == 0:
24410 	 *                recur(s)
24411 	 *            # if 's' is on stack, pick lowest reachable preorder number from it;
24412 	 *            # if 's' is not on stack 'low[s] == NOT_ON_STACK > low[w]',
24413 	 *            # so 'min' would be a noop.
24414 	 *            low[w] = min(low[w], low[s])
24415 	 *
24416 	 *        if low[w] == pre[w]:
24417 	 *            # 'w' is the root of an SCC, pop all vertices
24418 	 *            # below 'w' on stack and assign same SCC to them.
24419 	 *            while True:
24420 	 *                t = stack.pop()
24421 	 *                low[t] = NOT_ON_STACK
24422 	 *                scc[t] = next_scc_id
24423 	 *                if t == w:
24424 	 *                    break
24425 	 *            next_scc_id += 1
24426 	 *
24427 	 *    for i in range(0, insn_cnt):
24428 	 *        if pre[i] == 0:
24429 	 *            recur(i)
24430 	 *
24431 	 * Below implementation replaces explicit recursion with array 'dfs'.
24432 	 */
24433 	for (i = 0; i < insn_cnt; i++) {
24434 		if (pre[i])
24435 			continue;
24436 		stack_sz = 0;
24437 		dfs_sz = 1;
24438 		dfs[0] = i;
24439 dfs_continue:
24440 		while (dfs_sz) {
24441 			w = dfs[dfs_sz - 1];
24442 			if (pre[w] == 0) {
24443 				low[w] = next_preorder_num;
24444 				pre[w] = next_preorder_num;
24445 				next_preorder_num++;
24446 				stack[stack_sz++] = w;
24447 			}
24448 			/* Visit 'w' successors */
24449 			succ_cnt = bpf_insn_successors(env->prog, w, succ);
24450 			for (j = 0; j < succ_cnt; ++j) {
24451 				if (pre[succ[j]]) {
24452 					low[w] = min(low[w], low[succ[j]]);
24453 				} else {
24454 					dfs[dfs_sz++] = succ[j];
24455 					goto dfs_continue;
24456 				}
24457 			}
24458 			/*
24459 			 * Preserve the invariant: if some vertex above in the stack
24460 			 * is reachable from 'w', keep 'w' on the stack.
24461 			 */
24462 			if (low[w] < pre[w]) {
24463 				dfs_sz--;
24464 				goto dfs_continue;
24465 			}
24466 			/*
24467 			 * Assign SCC number only if component has two or more elements,
24468 			 * or if component has a self reference.
24469 			 */
24470 			assign_scc = stack[stack_sz - 1] != w;
24471 			for (j = 0; j < succ_cnt; ++j) {
24472 				if (succ[j] == w) {
24473 					assign_scc = true;
24474 					break;
24475 				}
24476 			}
24477 			/* Pop component elements from stack */
24478 			do {
24479 				t = stack[--stack_sz];
24480 				low[t] = NOT_ON_STACK;
24481 				if (assign_scc)
24482 					aux[t].scc = next_scc_id;
24483 			} while (t != w);
24484 			if (assign_scc)
24485 				next_scc_id++;
24486 			dfs_sz--;
24487 		}
24488 	}
24489 	env->scc_info = kvcalloc(next_scc_id, sizeof(*env->scc_info), GFP_KERNEL_ACCOUNT);
24490 	if (!env->scc_info) {
24491 		err = -ENOMEM;
24492 		goto exit;
24493 	}
24494 	env->scc_cnt = next_scc_id;
24495 exit:
24496 	kvfree(stack);
24497 	kvfree(pre);
24498 	kvfree(low);
24499 	kvfree(dfs);
24500 	return err;
24501 }
24502 
24503 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
24504 {
24505 	u64 start_time = ktime_get_ns();
24506 	struct bpf_verifier_env *env;
24507 	int i, len, ret = -EINVAL, err;
24508 	u32 log_true_size;
24509 	bool is_priv;
24510 
24511 	BTF_TYPE_EMIT(enum bpf_features);
24512 
24513 	/* no program is valid */
24514 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
24515 		return -EINVAL;
24516 
24517 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
24518 	 * allocate/free it every time bpf_check() is called
24519 	 */
24520 	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL_ACCOUNT);
24521 	if (!env)
24522 		return -ENOMEM;
24523 
24524 	env->bt.env = env;
24525 
24526 	len = (*prog)->len;
24527 	env->insn_aux_data =
24528 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
24529 	ret = -ENOMEM;
24530 	if (!env->insn_aux_data)
24531 		goto err_free_env;
24532 	for (i = 0; i < len; i++)
24533 		env->insn_aux_data[i].orig_idx = i;
24534 	env->prog = *prog;
24535 	env->ops = bpf_verifier_ops[env->prog->type];
24536 
24537 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
24538 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
24539 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
24540 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
24541 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
24542 
24543 	bpf_get_btf_vmlinux();
24544 
24545 	/* grab the mutex to protect few globals used by verifier */
24546 	if (!is_priv)
24547 		mutex_lock(&bpf_verifier_lock);
24548 
24549 	/* user could have requested verbose verifier output
24550 	 * and supplied buffer to store the verification trace
24551 	 */
24552 	ret = bpf_vlog_init(&env->log, attr->log_level,
24553 			    (char __user *) (unsigned long) attr->log_buf,
24554 			    attr->log_size);
24555 	if (ret)
24556 		goto err_unlock;
24557 
24558 	ret = process_fd_array(env, attr, uattr);
24559 	if (ret)
24560 		goto skip_full_check;
24561 
24562 	mark_verifier_state_clean(env);
24563 
24564 	if (IS_ERR(btf_vmlinux)) {
24565 		/* Either gcc or pahole or kernel are broken. */
24566 		verbose(env, "in-kernel BTF is malformed\n");
24567 		ret = PTR_ERR(btf_vmlinux);
24568 		goto skip_full_check;
24569 	}
24570 
24571 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
24572 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
24573 		env->strict_alignment = true;
24574 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
24575 		env->strict_alignment = false;
24576 
24577 	if (is_priv)
24578 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
24579 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
24580 
24581 	env->explored_states = kvcalloc(state_htab_size(env),
24582 				       sizeof(struct list_head),
24583 				       GFP_KERNEL_ACCOUNT);
24584 	ret = -ENOMEM;
24585 	if (!env->explored_states)
24586 		goto skip_full_check;
24587 
24588 	for (i = 0; i < state_htab_size(env); i++)
24589 		INIT_LIST_HEAD(&env->explored_states[i]);
24590 	INIT_LIST_HEAD(&env->free_list);
24591 
24592 	ret = check_btf_info_early(env, attr, uattr);
24593 	if (ret < 0)
24594 		goto skip_full_check;
24595 
24596 	ret = add_subprog_and_kfunc(env);
24597 	if (ret < 0)
24598 		goto skip_full_check;
24599 
24600 	ret = check_subprogs(env);
24601 	if (ret < 0)
24602 		goto skip_full_check;
24603 
24604 	ret = check_btf_info(env, attr, uattr);
24605 	if (ret < 0)
24606 		goto skip_full_check;
24607 
24608 	ret = resolve_pseudo_ldimm64(env);
24609 	if (ret < 0)
24610 		goto skip_full_check;
24611 
24612 	if (bpf_prog_is_offloaded(env->prog->aux)) {
24613 		ret = bpf_prog_offload_verifier_prep(env->prog);
24614 		if (ret)
24615 			goto skip_full_check;
24616 	}
24617 
24618 	ret = check_cfg(env);
24619 	if (ret < 0)
24620 		goto skip_full_check;
24621 
24622 	ret = compute_postorder(env);
24623 	if (ret < 0)
24624 		goto skip_full_check;
24625 
24626 	ret = bpf_stack_liveness_init(env);
24627 	if (ret)
24628 		goto skip_full_check;
24629 
24630 	ret = check_attach_btf_id(env);
24631 	if (ret)
24632 		goto skip_full_check;
24633 
24634 	ret = compute_scc(env);
24635 	if (ret < 0)
24636 		goto skip_full_check;
24637 
24638 	ret = compute_live_registers(env);
24639 	if (ret < 0)
24640 		goto skip_full_check;
24641 
24642 	ret = mark_fastcall_patterns(env);
24643 	if (ret < 0)
24644 		goto skip_full_check;
24645 
24646 	ret = do_check_main(env);
24647 	ret = ret ?: do_check_subprogs(env);
24648 
24649 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
24650 		ret = bpf_prog_offload_finalize(env);
24651 
24652 skip_full_check:
24653 	kvfree(env->explored_states);
24654 
24655 	/* might decrease stack depth, keep it before passes that
24656 	 * allocate additional slots.
24657 	 */
24658 	if (ret == 0)
24659 		ret = remove_fastcall_spills_fills(env);
24660 
24661 	if (ret == 0)
24662 		ret = check_max_stack_depth(env);
24663 
24664 	/* instruction rewrites happen after this point */
24665 	if (ret == 0)
24666 		ret = optimize_bpf_loop(env);
24667 
24668 	if (is_priv) {
24669 		if (ret == 0)
24670 			opt_hard_wire_dead_code_branches(env);
24671 		if (ret == 0)
24672 			ret = opt_remove_dead_code(env);
24673 		if (ret == 0)
24674 			ret = opt_remove_nops(env);
24675 	} else {
24676 		if (ret == 0)
24677 			sanitize_dead_code(env);
24678 	}
24679 
24680 	if (ret == 0)
24681 		/* program is valid, convert *(u32*)(ctx + off) accesses */
24682 		ret = convert_ctx_accesses(env);
24683 
24684 	if (ret == 0)
24685 		ret = do_misc_fixups(env);
24686 
24687 	/* do 32-bit optimization after insn patching has done so those patched
24688 	 * insns could be handled correctly.
24689 	 */
24690 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
24691 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
24692 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
24693 								     : false;
24694 	}
24695 
24696 	if (ret == 0)
24697 		ret = fixup_call_args(env);
24698 
24699 	env->verification_time = ktime_get_ns() - start_time;
24700 	print_verification_stats(env);
24701 	env->prog->aux->verified_insns = env->insn_processed;
24702 
24703 	/* preserve original error even if log finalization is successful */
24704 	err = bpf_vlog_finalize(&env->log, &log_true_size);
24705 	if (err)
24706 		ret = err;
24707 
24708 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
24709 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
24710 				  &log_true_size, sizeof(log_true_size))) {
24711 		ret = -EFAULT;
24712 		goto err_release_maps;
24713 	}
24714 
24715 	if (ret)
24716 		goto err_release_maps;
24717 
24718 	if (env->used_map_cnt) {
24719 		/* if program passed verifier, update used_maps in bpf_prog_info */
24720 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
24721 							  sizeof(env->used_maps[0]),
24722 							  GFP_KERNEL_ACCOUNT);
24723 
24724 		if (!env->prog->aux->used_maps) {
24725 			ret = -ENOMEM;
24726 			goto err_release_maps;
24727 		}
24728 
24729 		memcpy(env->prog->aux->used_maps, env->used_maps,
24730 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
24731 		env->prog->aux->used_map_cnt = env->used_map_cnt;
24732 	}
24733 	if (env->used_btf_cnt) {
24734 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
24735 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
24736 							  sizeof(env->used_btfs[0]),
24737 							  GFP_KERNEL_ACCOUNT);
24738 		if (!env->prog->aux->used_btfs) {
24739 			ret = -ENOMEM;
24740 			goto err_release_maps;
24741 		}
24742 
24743 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
24744 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
24745 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
24746 	}
24747 	if (env->used_map_cnt || env->used_btf_cnt) {
24748 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
24749 		 * bpf_ld_imm64 instructions
24750 		 */
24751 		convert_pseudo_ld_imm64(env);
24752 	}
24753 
24754 	adjust_btf_func(env);
24755 
24756 err_release_maps:
24757 	if (!env->prog->aux->used_maps)
24758 		/* if we didn't copy map pointers into bpf_prog_info, release
24759 		 * them now. Otherwise free_used_maps() will release them.
24760 		 */
24761 		release_maps(env);
24762 	if (!env->prog->aux->used_btfs)
24763 		release_btfs(env);
24764 
24765 	/* extension progs temporarily inherit the attach_type of their targets
24766 	   for verification purposes, so set it back to zero before returning
24767 	 */
24768 	if (env->prog->type == BPF_PROG_TYPE_EXT)
24769 		env->prog->expected_attach_type = 0;
24770 
24771 	*prog = env->prog;
24772 
24773 	module_put(env->attach_btf_mod);
24774 err_unlock:
24775 	if (!is_priv)
24776 		mutex_unlock(&bpf_verifier_lock);
24777 	vfree(env->insn_aux_data);
24778 err_free_env:
24779 	bpf_stack_liveness_free(env);
24780 	kvfree(env->cfg.insn_postorder);
24781 	kvfree(env->scc_info);
24782 	kvfree(env);
24783 	return ret;
24784 }
24785