xref: /linux/kernel/bpf/verifier.c (revision 115e74a29b530d121891238e9551c4bcdf7b04b5)
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 struct bpf_mem_alloc bpf_global_percpu_ma;
48 static bool bpf_global_percpu_ma_set;
49 
50 /* bpf_check() is a static code analyzer that walks eBPF program
51  * instruction by instruction and updates register/stack state.
52  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
53  *
54  * The first pass is depth-first-search to check that the program is a DAG.
55  * It rejects the following programs:
56  * - larger than BPF_MAXINSNS insns
57  * - if loop is present (detected via back-edge)
58  * - unreachable insns exist (shouldn't be a forest. program = one function)
59  * - out of bounds or malformed jumps
60  * The second pass is all possible path descent from the 1st insn.
61  * Since it's analyzing all paths through the program, the length of the
62  * analysis is limited to 64k insn, which may be hit even if total number of
63  * insn is less then 4K, but there are too many branches that change stack/regs.
64  * Number of 'branches to be analyzed' is limited to 1k
65  *
66  * On entry to each instruction, each register has a type, and the instruction
67  * changes the types of the registers depending on instruction semantics.
68  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
69  * copied to R1.
70  *
71  * All registers are 64-bit.
72  * R0 - return register
73  * R1-R5 argument passing registers
74  * R6-R9 callee saved registers
75  * R10 - frame pointer read-only
76  *
77  * At the start of BPF program the register R1 contains a pointer to bpf_context
78  * and has type PTR_TO_CTX.
79  *
80  * Verifier tracks arithmetic operations on pointers in case:
81  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
82  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
83  * 1st insn copies R10 (which has FRAME_PTR) type into R1
84  * and 2nd arithmetic instruction is pattern matched to recognize
85  * that it wants to construct a pointer to some element within stack.
86  * So after 2nd insn, the register R1 has type PTR_TO_STACK
87  * (and -20 constant is saved for further stack bounds checking).
88  * Meaning that this reg is a pointer to stack plus known immediate constant.
89  *
90  * Most of the time the registers have SCALAR_VALUE type, which
91  * means the register has some value, but it's not a valid pointer.
92  * (like pointer plus pointer becomes SCALAR_VALUE type)
93  *
94  * When verifier sees load or store instructions the type of base register
95  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
96  * four pointer types recognized by check_mem_access() function.
97  *
98  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
99  * and the range of [ptr, ptr + map's value_size) is accessible.
100  *
101  * registers used to pass values to function calls are checked against
102  * function argument constraints.
103  *
104  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
105  * It means that the register type passed to this function must be
106  * PTR_TO_STACK and it will be used inside the function as
107  * 'pointer to map element key'
108  *
109  * For example the argument constraints for bpf_map_lookup_elem():
110  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
111  *   .arg1_type = ARG_CONST_MAP_PTR,
112  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
113  *
114  * ret_type says that this function returns 'pointer to map elem value or null'
115  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
116  * 2nd argument should be a pointer to stack, which will be used inside
117  * the helper function as a pointer to map element key.
118  *
119  * On the kernel side the helper function looks like:
120  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
121  * {
122  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
123  *    void *key = (void *) (unsigned long) r2;
124  *    void *value;
125  *
126  *    here kernel can access 'key' and 'map' pointers safely, knowing that
127  *    [key, key + map->key_size) bytes are valid and were initialized on
128  *    the stack of eBPF program.
129  * }
130  *
131  * Corresponding eBPF program may look like:
132  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
133  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
134  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
135  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
136  * here verifier looks at prototype of map_lookup_elem() and sees:
137  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
138  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
139  *
140  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
141  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
142  * and were initialized prior to this call.
143  * If it's ok, then verifier allows this BPF_CALL insn and looks at
144  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
145  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
146  * returns either pointer to map value or NULL.
147  *
148  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
149  * insn, the register holding that pointer in the true branch changes state to
150  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
151  * branch. See check_cond_jmp_op().
152  *
153  * After the call R0 is set to return type of the function and registers R1-R5
154  * are set to NOT_INIT to indicate that they are no longer readable.
155  *
156  * The following reference types represent a potential reference to a kernel
157  * resource which, after first being allocated, must be checked and freed by
158  * the BPF program:
159  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
160  *
161  * When the verifier sees a helper call return a reference type, it allocates a
162  * pointer id for the reference and stores it in the current function state.
163  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
164  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
165  * passes through a NULL-check conditional. For the branch wherein the state is
166  * changed to CONST_IMM, the verifier releases the reference.
167  *
168  * For each helper function that allocates a reference, such as
169  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
170  * bpf_sk_release(). When a reference type passes into the release function,
171  * the verifier also releases the reference. If any unchecked or unreleased
172  * reference remains at the end of the program, the verifier rejects it.
173  */
174 
175 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
176 struct bpf_verifier_stack_elem {
177 	/* verifier state is 'st'
178 	 * before processing instruction 'insn_idx'
179 	 * and after processing instruction 'prev_insn_idx'
180 	 */
181 	struct bpf_verifier_state st;
182 	int insn_idx;
183 	int prev_insn_idx;
184 	struct bpf_verifier_stack_elem *next;
185 	/* length of verifier log at the time this state was pushed on stack */
186 	u32 log_pos;
187 };
188 
189 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
190 #define BPF_COMPLEXITY_LIMIT_STATES	64
191 
192 #define BPF_MAP_KEY_POISON	(1ULL << 63)
193 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
194 
195 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
196 
197 #define BPF_PRIV_STACK_MIN_SIZE		64
198 
199 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx);
200 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id);
201 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
202 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
203 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
204 static int ref_set_non_owning(struct bpf_verifier_env *env,
205 			      struct bpf_reg_state *reg);
206 static void specialize_kfunc(struct bpf_verifier_env *env,
207 			     u32 func_id, u16 offset, unsigned long *addr);
208 static bool is_trusted_reg(const struct bpf_reg_state *reg);
209 
210 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
211 {
212 	return aux->map_ptr_state.poison;
213 }
214 
215 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
216 {
217 	return aux->map_ptr_state.unpriv;
218 }
219 
220 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
221 			      struct bpf_map *map,
222 			      bool unpriv, bool poison)
223 {
224 	unpriv |= bpf_map_ptr_unpriv(aux);
225 	aux->map_ptr_state.unpriv = unpriv;
226 	aux->map_ptr_state.poison = poison;
227 	aux->map_ptr_state.map_ptr = map;
228 }
229 
230 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
231 {
232 	return aux->map_key_state & BPF_MAP_KEY_POISON;
233 }
234 
235 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
236 {
237 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
238 }
239 
240 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
241 {
242 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
243 }
244 
245 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
246 {
247 	bool poisoned = bpf_map_key_poisoned(aux);
248 
249 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
250 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
251 }
252 
253 static bool bpf_helper_call(const struct bpf_insn *insn)
254 {
255 	return insn->code == (BPF_JMP | BPF_CALL) &&
256 	       insn->src_reg == 0;
257 }
258 
259 static bool bpf_pseudo_call(const struct bpf_insn *insn)
260 {
261 	return insn->code == (BPF_JMP | BPF_CALL) &&
262 	       insn->src_reg == BPF_PSEUDO_CALL;
263 }
264 
265 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
266 {
267 	return insn->code == (BPF_JMP | BPF_CALL) &&
268 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
269 }
270 
271 struct bpf_call_arg_meta {
272 	struct bpf_map *map_ptr;
273 	bool raw_mode;
274 	bool pkt_access;
275 	u8 release_regno;
276 	int regno;
277 	int access_size;
278 	int mem_size;
279 	u64 msize_max_value;
280 	int ref_obj_id;
281 	int dynptr_id;
282 	int map_uid;
283 	int func_id;
284 	struct btf *btf;
285 	u32 btf_id;
286 	struct btf *ret_btf;
287 	u32 ret_btf_id;
288 	u32 subprogno;
289 	struct btf_field *kptr_field;
290 	s64 const_map_key;
291 };
292 
293 struct bpf_kfunc_call_arg_meta {
294 	/* In parameters */
295 	struct btf *btf;
296 	u32 func_id;
297 	u32 kfunc_flags;
298 	const struct btf_type *func_proto;
299 	const char *func_name;
300 	/* Out parameters */
301 	u32 ref_obj_id;
302 	u8 release_regno;
303 	bool r0_rdonly;
304 	u32 ret_btf_id;
305 	u64 r0_size;
306 	u32 subprogno;
307 	struct {
308 		u64 value;
309 		bool found;
310 	} arg_constant;
311 
312 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
313 	 * generally to pass info about user-defined local kptr types to later
314 	 * verification logic
315 	 *   bpf_obj_drop/bpf_percpu_obj_drop
316 	 *     Record the local kptr type to be drop'd
317 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
318 	 *     Record the local kptr type to be refcount_incr'd and use
319 	 *     arg_owning_ref to determine whether refcount_acquire should be
320 	 *     fallible
321 	 */
322 	struct btf *arg_btf;
323 	u32 arg_btf_id;
324 	bool arg_owning_ref;
325 	bool arg_prog;
326 
327 	struct {
328 		struct btf_field *field;
329 	} arg_list_head;
330 	struct {
331 		struct btf_field *field;
332 	} arg_rbtree_root;
333 	struct {
334 		enum bpf_dynptr_type type;
335 		u32 id;
336 		u32 ref_obj_id;
337 	} initialized_dynptr;
338 	struct {
339 		u8 spi;
340 		u8 frameno;
341 	} iter;
342 	struct {
343 		struct bpf_map *ptr;
344 		int uid;
345 	} map;
346 	u64 mem_size;
347 };
348 
349 struct btf *btf_vmlinux;
350 
351 static const char *btf_type_name(const struct btf *btf, u32 id)
352 {
353 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
354 }
355 
356 static DEFINE_MUTEX(bpf_verifier_lock);
357 static DEFINE_MUTEX(bpf_percpu_ma_lock);
358 
359 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
360 {
361 	struct bpf_verifier_env *env = private_data;
362 	va_list args;
363 
364 	if (!bpf_verifier_log_needed(&env->log))
365 		return;
366 
367 	va_start(args, fmt);
368 	bpf_verifier_vlog(&env->log, fmt, args);
369 	va_end(args);
370 }
371 
372 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
373 				   struct bpf_reg_state *reg,
374 				   struct bpf_retval_range range, const char *ctx,
375 				   const char *reg_name)
376 {
377 	bool unknown = true;
378 
379 	verbose(env, "%s the register %s has", ctx, reg_name);
380 	if (reg->smin_value > S64_MIN) {
381 		verbose(env, " smin=%lld", reg->smin_value);
382 		unknown = false;
383 	}
384 	if (reg->smax_value < S64_MAX) {
385 		verbose(env, " smax=%lld", reg->smax_value);
386 		unknown = false;
387 	}
388 	if (unknown)
389 		verbose(env, " unknown scalar value");
390 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
391 }
392 
393 static bool reg_not_null(const struct bpf_reg_state *reg)
394 {
395 	enum bpf_reg_type type;
396 
397 	type = reg->type;
398 	if (type_may_be_null(type))
399 		return false;
400 
401 	type = base_type(type);
402 	return type == PTR_TO_SOCKET ||
403 		type == PTR_TO_TCP_SOCK ||
404 		type == PTR_TO_MAP_VALUE ||
405 		type == PTR_TO_MAP_KEY ||
406 		type == PTR_TO_SOCK_COMMON ||
407 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
408 		type == PTR_TO_MEM;
409 }
410 
411 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
412 {
413 	struct btf_record *rec = NULL;
414 	struct btf_struct_meta *meta;
415 
416 	if (reg->type == PTR_TO_MAP_VALUE) {
417 		rec = reg->map_ptr->record;
418 	} else if (type_is_ptr_alloc_obj(reg->type)) {
419 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
420 		if (meta)
421 			rec = meta->record;
422 	}
423 	return rec;
424 }
425 
426 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
427 {
428 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
429 
430 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
431 }
432 
433 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
434 {
435 	struct bpf_func_info *info;
436 
437 	if (!env->prog->aux->func_info)
438 		return "";
439 
440 	info = &env->prog->aux->func_info[subprog];
441 	return btf_type_name(env->prog->aux->btf, info->type_id);
442 }
443 
444 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
445 {
446 	struct bpf_subprog_info *info = subprog_info(env, subprog);
447 
448 	info->is_cb = true;
449 	info->is_async_cb = true;
450 	info->is_exception_cb = true;
451 }
452 
453 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
454 {
455 	return subprog_info(env, subprog)->is_exception_cb;
456 }
457 
458 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
459 {
460 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
461 }
462 
463 static bool type_is_rdonly_mem(u32 type)
464 {
465 	return type & MEM_RDONLY;
466 }
467 
468 static bool is_acquire_function(enum bpf_func_id func_id,
469 				const struct bpf_map *map)
470 {
471 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
472 
473 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
474 	    func_id == BPF_FUNC_sk_lookup_udp ||
475 	    func_id == BPF_FUNC_skc_lookup_tcp ||
476 	    func_id == BPF_FUNC_ringbuf_reserve ||
477 	    func_id == BPF_FUNC_kptr_xchg)
478 		return true;
479 
480 	if (func_id == BPF_FUNC_map_lookup_elem &&
481 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
482 	     map_type == BPF_MAP_TYPE_SOCKHASH))
483 		return true;
484 
485 	return false;
486 }
487 
488 static bool is_ptr_cast_function(enum bpf_func_id func_id)
489 {
490 	return func_id == BPF_FUNC_tcp_sock ||
491 		func_id == BPF_FUNC_sk_fullsock ||
492 		func_id == BPF_FUNC_skc_to_tcp_sock ||
493 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
494 		func_id == BPF_FUNC_skc_to_udp6_sock ||
495 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
496 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
497 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
498 }
499 
500 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
501 {
502 	return func_id == BPF_FUNC_dynptr_data;
503 }
504 
505 static bool is_sync_callback_calling_kfunc(u32 btf_id);
506 static bool is_async_callback_calling_kfunc(u32 btf_id);
507 static bool is_callback_calling_kfunc(u32 btf_id);
508 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
509 
510 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
511 
512 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
513 {
514 	return func_id == BPF_FUNC_for_each_map_elem ||
515 	       func_id == BPF_FUNC_find_vma ||
516 	       func_id == BPF_FUNC_loop ||
517 	       func_id == BPF_FUNC_user_ringbuf_drain;
518 }
519 
520 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
521 {
522 	return func_id == BPF_FUNC_timer_set_callback;
523 }
524 
525 static bool is_callback_calling_function(enum bpf_func_id func_id)
526 {
527 	return is_sync_callback_calling_function(func_id) ||
528 	       is_async_callback_calling_function(func_id);
529 }
530 
531 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
532 {
533 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
534 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
535 }
536 
537 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
538 {
539 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
540 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
541 }
542 
543 static bool is_may_goto_insn(struct bpf_insn *insn)
544 {
545 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
546 }
547 
548 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
549 {
550 	return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
551 }
552 
553 static bool is_storage_get_function(enum bpf_func_id func_id)
554 {
555 	return func_id == BPF_FUNC_sk_storage_get ||
556 	       func_id == BPF_FUNC_inode_storage_get ||
557 	       func_id == BPF_FUNC_task_storage_get ||
558 	       func_id == BPF_FUNC_cgrp_storage_get;
559 }
560 
561 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
562 					const struct bpf_map *map)
563 {
564 	int ref_obj_uses = 0;
565 
566 	if (is_ptr_cast_function(func_id))
567 		ref_obj_uses++;
568 	if (is_acquire_function(func_id, map))
569 		ref_obj_uses++;
570 	if (is_dynptr_ref_function(func_id))
571 		ref_obj_uses++;
572 
573 	return ref_obj_uses > 1;
574 }
575 
576 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
577 {
578 	return BPF_CLASS(insn->code) == BPF_STX &&
579 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
580 	       insn->imm == BPF_CMPXCHG;
581 }
582 
583 static bool is_atomic_load_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_LOAD_ACQ;
588 }
589 
590 static int __get_spi(s32 off)
591 {
592 	return (-off - 1) / BPF_REG_SIZE;
593 }
594 
595 static struct bpf_func_state *func(struct bpf_verifier_env *env,
596 				   const struct bpf_reg_state *reg)
597 {
598 	struct bpf_verifier_state *cur = env->cur_state;
599 
600 	return cur->frame[reg->frameno];
601 }
602 
603 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
604 {
605        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
606 
607        /* We need to check that slots between [spi - nr_slots + 1, spi] are
608 	* within [0, allocated_stack).
609 	*
610 	* Please note that the spi grows downwards. For example, a dynptr
611 	* takes the size of two stack slots; the first slot will be at
612 	* spi and the second slot will be at spi - 1.
613 	*/
614        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
615 }
616 
617 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
618 			          const char *obj_kind, int nr_slots)
619 {
620 	int off, spi;
621 
622 	if (!tnum_is_const(reg->var_off)) {
623 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
624 		return -EINVAL;
625 	}
626 
627 	off = reg->off + reg->var_off.value;
628 	if (off % BPF_REG_SIZE) {
629 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
630 		return -EINVAL;
631 	}
632 
633 	spi = __get_spi(off);
634 	if (spi + 1 < nr_slots) {
635 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
636 		return -EINVAL;
637 	}
638 
639 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
640 		return -ERANGE;
641 	return spi;
642 }
643 
644 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
645 {
646 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
647 }
648 
649 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
650 {
651 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
652 }
653 
654 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
655 {
656 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
657 }
658 
659 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
660 {
661 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
662 	case DYNPTR_TYPE_LOCAL:
663 		return BPF_DYNPTR_TYPE_LOCAL;
664 	case DYNPTR_TYPE_RINGBUF:
665 		return BPF_DYNPTR_TYPE_RINGBUF;
666 	case DYNPTR_TYPE_SKB:
667 		return BPF_DYNPTR_TYPE_SKB;
668 	case DYNPTR_TYPE_XDP:
669 		return BPF_DYNPTR_TYPE_XDP;
670 	default:
671 		return BPF_DYNPTR_TYPE_INVALID;
672 	}
673 }
674 
675 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
676 {
677 	switch (type) {
678 	case BPF_DYNPTR_TYPE_LOCAL:
679 		return DYNPTR_TYPE_LOCAL;
680 	case BPF_DYNPTR_TYPE_RINGBUF:
681 		return DYNPTR_TYPE_RINGBUF;
682 	case BPF_DYNPTR_TYPE_SKB:
683 		return DYNPTR_TYPE_SKB;
684 	case BPF_DYNPTR_TYPE_XDP:
685 		return DYNPTR_TYPE_XDP;
686 	default:
687 		return 0;
688 	}
689 }
690 
691 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
692 {
693 	return type == BPF_DYNPTR_TYPE_RINGBUF;
694 }
695 
696 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
697 			      enum bpf_dynptr_type type,
698 			      bool first_slot, int dynptr_id);
699 
700 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
701 				struct bpf_reg_state *reg);
702 
703 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
704 				   struct bpf_reg_state *sreg1,
705 				   struct bpf_reg_state *sreg2,
706 				   enum bpf_dynptr_type type)
707 {
708 	int id = ++env->id_gen;
709 
710 	__mark_dynptr_reg(sreg1, type, true, id);
711 	__mark_dynptr_reg(sreg2, type, false, id);
712 }
713 
714 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
715 			       struct bpf_reg_state *reg,
716 			       enum bpf_dynptr_type type)
717 {
718 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
719 }
720 
721 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
722 				        struct bpf_func_state *state, int spi);
723 
724 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
725 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
726 {
727 	struct bpf_func_state *state = func(env, reg);
728 	enum bpf_dynptr_type type;
729 	int spi, i, err;
730 
731 	spi = dynptr_get_spi(env, reg);
732 	if (spi < 0)
733 		return spi;
734 
735 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
736 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
737 	 * to ensure that for the following example:
738 	 *	[d1][d1][d2][d2]
739 	 * spi    3   2   1   0
740 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
741 	 * case they do belong to same dynptr, second call won't see slot_type
742 	 * as STACK_DYNPTR and will simply skip destruction.
743 	 */
744 	err = destroy_if_dynptr_stack_slot(env, state, spi);
745 	if (err)
746 		return err;
747 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
748 	if (err)
749 		return err;
750 
751 	for (i = 0; i < BPF_REG_SIZE; i++) {
752 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
753 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
754 	}
755 
756 	type = arg_to_dynptr_type(arg_type);
757 	if (type == BPF_DYNPTR_TYPE_INVALID)
758 		return -EINVAL;
759 
760 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
761 			       &state->stack[spi - 1].spilled_ptr, type);
762 
763 	if (dynptr_type_refcounted(type)) {
764 		/* The id is used to track proper releasing */
765 		int id;
766 
767 		if (clone_ref_obj_id)
768 			id = clone_ref_obj_id;
769 		else
770 			id = acquire_reference(env, insn_idx);
771 
772 		if (id < 0)
773 			return id;
774 
775 		state->stack[spi].spilled_ptr.ref_obj_id = id;
776 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
777 	}
778 
779 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
780 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
781 
782 	return 0;
783 }
784 
785 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
786 {
787 	int i;
788 
789 	for (i = 0; i < BPF_REG_SIZE; i++) {
790 		state->stack[spi].slot_type[i] = STACK_INVALID;
791 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
792 	}
793 
794 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
795 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
796 
797 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
798 	 *
799 	 * While we don't allow reading STACK_INVALID, it is still possible to
800 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
801 	 * helpers or insns can do partial read of that part without failing,
802 	 * but check_stack_range_initialized, check_stack_read_var_off, and
803 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
804 	 * the slot conservatively. Hence we need to prevent those liveness
805 	 * marking walks.
806 	 *
807 	 * This was not a problem before because STACK_INVALID is only set by
808 	 * default (where the default reg state has its reg->parent as NULL), or
809 	 * in clean_live_states after REG_LIVE_DONE (at which point
810 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
811 	 * verifier state exploration (like we did above). Hence, for our case
812 	 * parentage chain will still be live (i.e. reg->parent may be
813 	 * non-NULL), while earlier reg->parent was NULL, so we need
814 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
815 	 * done later on reads or by mark_dynptr_read as well to unnecessary
816 	 * mark registers in verifier state.
817 	 */
818 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
819 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
820 }
821 
822 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
823 {
824 	struct bpf_func_state *state = func(env, reg);
825 	int spi, ref_obj_id, i;
826 
827 	spi = dynptr_get_spi(env, reg);
828 	if (spi < 0)
829 		return spi;
830 
831 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
832 		invalidate_dynptr(env, state, spi);
833 		return 0;
834 	}
835 
836 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
837 
838 	/* If the dynptr has a ref_obj_id, then we need to invalidate
839 	 * two things:
840 	 *
841 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
842 	 * 2) Any slices derived from this dynptr.
843 	 */
844 
845 	/* Invalidate any slices associated with this dynptr */
846 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
847 
848 	/* Invalidate any dynptr clones */
849 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
850 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
851 			continue;
852 
853 		/* it should always be the case that if the ref obj id
854 		 * matches then the stack slot also belongs to a
855 		 * dynptr
856 		 */
857 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
858 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
859 			return -EFAULT;
860 		}
861 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
862 			invalidate_dynptr(env, state, i);
863 	}
864 
865 	return 0;
866 }
867 
868 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
869 			       struct bpf_reg_state *reg);
870 
871 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
872 {
873 	if (!env->allow_ptr_leaks)
874 		__mark_reg_not_init(env, reg);
875 	else
876 		__mark_reg_unknown(env, reg);
877 }
878 
879 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
880 				        struct bpf_func_state *state, int spi)
881 {
882 	struct bpf_func_state *fstate;
883 	struct bpf_reg_state *dreg;
884 	int i, dynptr_id;
885 
886 	/* We always ensure that STACK_DYNPTR is never set partially,
887 	 * hence just checking for slot_type[0] is enough. This is
888 	 * different for STACK_SPILL, where it may be only set for
889 	 * 1 byte, so code has to use is_spilled_reg.
890 	 */
891 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
892 		return 0;
893 
894 	/* Reposition spi to first slot */
895 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
896 		spi = spi + 1;
897 
898 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
899 		verbose(env, "cannot overwrite referenced dynptr\n");
900 		return -EINVAL;
901 	}
902 
903 	mark_stack_slot_scratched(env, spi);
904 	mark_stack_slot_scratched(env, spi - 1);
905 
906 	/* Writing partially to one dynptr stack slot destroys both. */
907 	for (i = 0; i < BPF_REG_SIZE; i++) {
908 		state->stack[spi].slot_type[i] = STACK_INVALID;
909 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
910 	}
911 
912 	dynptr_id = state->stack[spi].spilled_ptr.id;
913 	/* Invalidate any slices associated with this dynptr */
914 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
915 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
916 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
917 			continue;
918 		if (dreg->dynptr_id == dynptr_id)
919 			mark_reg_invalid(env, dreg);
920 	}));
921 
922 	/* Do not release reference state, we are destroying dynptr on stack,
923 	 * not using some helper to release it. Just reset register.
924 	 */
925 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
926 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
927 
928 	/* Same reason as unmark_stack_slots_dynptr above */
929 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
930 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
931 
932 	return 0;
933 }
934 
935 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
936 {
937 	int spi;
938 
939 	if (reg->type == CONST_PTR_TO_DYNPTR)
940 		return false;
941 
942 	spi = dynptr_get_spi(env, reg);
943 
944 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
945 	 * error because this just means the stack state hasn't been updated yet.
946 	 * We will do check_mem_access to check and update stack bounds later.
947 	 */
948 	if (spi < 0 && spi != -ERANGE)
949 		return false;
950 
951 	/* We don't need to check if the stack slots are marked by previous
952 	 * dynptr initializations because we allow overwriting existing unreferenced
953 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
954 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
955 	 * touching are completely destructed before we reinitialize them for a new
956 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
957 	 * instead of delaying it until the end where the user will get "Unreleased
958 	 * reference" error.
959 	 */
960 	return true;
961 }
962 
963 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
964 {
965 	struct bpf_func_state *state = func(env, reg);
966 	int i, spi;
967 
968 	/* This already represents first slot of initialized bpf_dynptr.
969 	 *
970 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
971 	 * check_func_arg_reg_off's logic, so we don't need to check its
972 	 * offset and alignment.
973 	 */
974 	if (reg->type == CONST_PTR_TO_DYNPTR)
975 		return true;
976 
977 	spi = dynptr_get_spi(env, reg);
978 	if (spi < 0)
979 		return false;
980 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
981 		return false;
982 
983 	for (i = 0; i < BPF_REG_SIZE; i++) {
984 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
985 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
986 			return false;
987 	}
988 
989 	return true;
990 }
991 
992 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
993 				    enum bpf_arg_type arg_type)
994 {
995 	struct bpf_func_state *state = func(env, reg);
996 	enum bpf_dynptr_type dynptr_type;
997 	int spi;
998 
999 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1000 	if (arg_type == ARG_PTR_TO_DYNPTR)
1001 		return true;
1002 
1003 	dynptr_type = arg_to_dynptr_type(arg_type);
1004 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1005 		return reg->dynptr.type == dynptr_type;
1006 	} else {
1007 		spi = dynptr_get_spi(env, reg);
1008 		if (spi < 0)
1009 			return false;
1010 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1011 	}
1012 }
1013 
1014 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1015 
1016 static bool in_rcu_cs(struct bpf_verifier_env *env);
1017 
1018 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1019 
1020 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1021 				 struct bpf_kfunc_call_arg_meta *meta,
1022 				 struct bpf_reg_state *reg, int insn_idx,
1023 				 struct btf *btf, u32 btf_id, int nr_slots)
1024 {
1025 	struct bpf_func_state *state = func(env, reg);
1026 	int spi, i, j, id;
1027 
1028 	spi = iter_get_spi(env, reg, nr_slots);
1029 	if (spi < 0)
1030 		return spi;
1031 
1032 	id = acquire_reference(env, insn_idx);
1033 	if (id < 0)
1034 		return id;
1035 
1036 	for (i = 0; i < nr_slots; i++) {
1037 		struct bpf_stack_state *slot = &state->stack[spi - i];
1038 		struct bpf_reg_state *st = &slot->spilled_ptr;
1039 
1040 		__mark_reg_known_zero(st);
1041 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1042 		if (is_kfunc_rcu_protected(meta)) {
1043 			if (in_rcu_cs(env))
1044 				st->type |= MEM_RCU;
1045 			else
1046 				st->type |= PTR_UNTRUSTED;
1047 		}
1048 		st->live |= REG_LIVE_WRITTEN;
1049 		st->ref_obj_id = i == 0 ? id : 0;
1050 		st->iter.btf = btf;
1051 		st->iter.btf_id = btf_id;
1052 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1053 		st->iter.depth = 0;
1054 
1055 		for (j = 0; j < BPF_REG_SIZE; j++)
1056 			slot->slot_type[j] = STACK_ITER;
1057 
1058 		mark_stack_slot_scratched(env, spi - i);
1059 	}
1060 
1061 	return 0;
1062 }
1063 
1064 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1065 				   struct bpf_reg_state *reg, int nr_slots)
1066 {
1067 	struct bpf_func_state *state = func(env, reg);
1068 	int spi, i, j;
1069 
1070 	spi = iter_get_spi(env, reg, nr_slots);
1071 	if (spi < 0)
1072 		return spi;
1073 
1074 	for (i = 0; i < nr_slots; i++) {
1075 		struct bpf_stack_state *slot = &state->stack[spi - i];
1076 		struct bpf_reg_state *st = &slot->spilled_ptr;
1077 
1078 		if (i == 0)
1079 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1080 
1081 		__mark_reg_not_init(env, st);
1082 
1083 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1084 		st->live |= REG_LIVE_WRITTEN;
1085 
1086 		for (j = 0; j < BPF_REG_SIZE; j++)
1087 			slot->slot_type[j] = STACK_INVALID;
1088 
1089 		mark_stack_slot_scratched(env, spi - i);
1090 	}
1091 
1092 	return 0;
1093 }
1094 
1095 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1096 				     struct bpf_reg_state *reg, int nr_slots)
1097 {
1098 	struct bpf_func_state *state = func(env, reg);
1099 	int spi, i, j;
1100 
1101 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1102 	 * will do check_mem_access to check and update stack bounds later, so
1103 	 * return true for that case.
1104 	 */
1105 	spi = iter_get_spi(env, reg, nr_slots);
1106 	if (spi == -ERANGE)
1107 		return true;
1108 	if (spi < 0)
1109 		return false;
1110 
1111 	for (i = 0; i < nr_slots; i++) {
1112 		struct bpf_stack_state *slot = &state->stack[spi - i];
1113 
1114 		for (j = 0; j < BPF_REG_SIZE; j++)
1115 			if (slot->slot_type[j] == STACK_ITER)
1116 				return false;
1117 	}
1118 
1119 	return true;
1120 }
1121 
1122 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1123 				   struct btf *btf, u32 btf_id, int nr_slots)
1124 {
1125 	struct bpf_func_state *state = func(env, reg);
1126 	int spi, i, j;
1127 
1128 	spi = iter_get_spi(env, reg, nr_slots);
1129 	if (spi < 0)
1130 		return -EINVAL;
1131 
1132 	for (i = 0; i < nr_slots; i++) {
1133 		struct bpf_stack_state *slot = &state->stack[spi - i];
1134 		struct bpf_reg_state *st = &slot->spilled_ptr;
1135 
1136 		if (st->type & PTR_UNTRUSTED)
1137 			return -EPROTO;
1138 		/* only main (first) slot has ref_obj_id set */
1139 		if (i == 0 && !st->ref_obj_id)
1140 			return -EINVAL;
1141 		if (i != 0 && st->ref_obj_id)
1142 			return -EINVAL;
1143 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1144 			return -EINVAL;
1145 
1146 		for (j = 0; j < BPF_REG_SIZE; j++)
1147 			if (slot->slot_type[j] != STACK_ITER)
1148 				return -EINVAL;
1149 	}
1150 
1151 	return 0;
1152 }
1153 
1154 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1155 static int release_irq_state(struct bpf_verifier_state *state, int id);
1156 
1157 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1158 				     struct bpf_kfunc_call_arg_meta *meta,
1159 				     struct bpf_reg_state *reg, int insn_idx,
1160 				     int kfunc_class)
1161 {
1162 	struct bpf_func_state *state = func(env, reg);
1163 	struct bpf_stack_state *slot;
1164 	struct bpf_reg_state *st;
1165 	int spi, i, id;
1166 
1167 	spi = irq_flag_get_spi(env, reg);
1168 	if (spi < 0)
1169 		return spi;
1170 
1171 	id = acquire_irq_state(env, insn_idx);
1172 	if (id < 0)
1173 		return id;
1174 
1175 	slot = &state->stack[spi];
1176 	st = &slot->spilled_ptr;
1177 
1178 	__mark_reg_known_zero(st);
1179 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1180 	st->live |= REG_LIVE_WRITTEN;
1181 	st->ref_obj_id = id;
1182 	st->irq.kfunc_class = kfunc_class;
1183 
1184 	for (i = 0; i < BPF_REG_SIZE; i++)
1185 		slot->slot_type[i] = STACK_IRQ_FLAG;
1186 
1187 	mark_stack_slot_scratched(env, spi);
1188 	return 0;
1189 }
1190 
1191 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1192 				      int kfunc_class)
1193 {
1194 	struct bpf_func_state *state = func(env, reg);
1195 	struct bpf_stack_state *slot;
1196 	struct bpf_reg_state *st;
1197 	int spi, i, err;
1198 
1199 	spi = irq_flag_get_spi(env, reg);
1200 	if (spi < 0)
1201 		return spi;
1202 
1203 	slot = &state->stack[spi];
1204 	st = &slot->spilled_ptr;
1205 
1206 	if (st->irq.kfunc_class != kfunc_class) {
1207 		const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1208 		const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1209 
1210 		verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1211 			flag_kfunc, used_kfunc);
1212 		return -EINVAL;
1213 	}
1214 
1215 	err = release_irq_state(env->cur_state, st->ref_obj_id);
1216 	WARN_ON_ONCE(err && err != -EACCES);
1217 	if (err) {
1218 		int insn_idx = 0;
1219 
1220 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1221 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1222 				insn_idx = env->cur_state->refs[i].insn_idx;
1223 				break;
1224 			}
1225 		}
1226 
1227 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1228 			env->cur_state->active_irq_id, insn_idx);
1229 		return err;
1230 	}
1231 
1232 	__mark_reg_not_init(env, st);
1233 
1234 	/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1235 	st->live |= REG_LIVE_WRITTEN;
1236 
1237 	for (i = 0; i < BPF_REG_SIZE; i++)
1238 		slot->slot_type[i] = STACK_INVALID;
1239 
1240 	mark_stack_slot_scratched(env, spi);
1241 	return 0;
1242 }
1243 
1244 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1245 {
1246 	struct bpf_func_state *state = func(env, reg);
1247 	struct bpf_stack_state *slot;
1248 	int spi, i;
1249 
1250 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1251 	 * will do check_mem_access to check and update stack bounds later, so
1252 	 * return true for that case.
1253 	 */
1254 	spi = irq_flag_get_spi(env, reg);
1255 	if (spi == -ERANGE)
1256 		return true;
1257 	if (spi < 0)
1258 		return false;
1259 
1260 	slot = &state->stack[spi];
1261 
1262 	for (i = 0; i < BPF_REG_SIZE; i++)
1263 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1264 			return false;
1265 	return true;
1266 }
1267 
1268 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1269 {
1270 	struct bpf_func_state *state = func(env, reg);
1271 	struct bpf_stack_state *slot;
1272 	struct bpf_reg_state *st;
1273 	int spi, i;
1274 
1275 	spi = irq_flag_get_spi(env, reg);
1276 	if (spi < 0)
1277 		return -EINVAL;
1278 
1279 	slot = &state->stack[spi];
1280 	st = &slot->spilled_ptr;
1281 
1282 	if (!st->ref_obj_id)
1283 		return -EINVAL;
1284 
1285 	for (i = 0; i < BPF_REG_SIZE; i++)
1286 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1287 			return -EINVAL;
1288 	return 0;
1289 }
1290 
1291 /* Check if given stack slot is "special":
1292  *   - spilled register state (STACK_SPILL);
1293  *   - dynptr state (STACK_DYNPTR);
1294  *   - iter state (STACK_ITER).
1295  *   - irq flag state (STACK_IRQ_FLAG)
1296  */
1297 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1298 {
1299 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1300 
1301 	switch (type) {
1302 	case STACK_SPILL:
1303 	case STACK_DYNPTR:
1304 	case STACK_ITER:
1305 	case STACK_IRQ_FLAG:
1306 		return true;
1307 	case STACK_INVALID:
1308 	case STACK_MISC:
1309 	case STACK_ZERO:
1310 		return false;
1311 	default:
1312 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1313 		return true;
1314 	}
1315 }
1316 
1317 /* The reg state of a pointer or a bounded scalar was saved when
1318  * it was spilled to the stack.
1319  */
1320 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1321 {
1322 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1323 }
1324 
1325 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1326 {
1327 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1328 	       stack->spilled_ptr.type == SCALAR_VALUE;
1329 }
1330 
1331 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1332 {
1333 	return stack->slot_type[0] == STACK_SPILL &&
1334 	       stack->spilled_ptr.type == SCALAR_VALUE;
1335 }
1336 
1337 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1338  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1339  * more precise STACK_ZERO.
1340  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1341  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1342  * unnecessary as both are considered equivalent when loading data and pruning,
1343  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1344  * slots.
1345  */
1346 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1347 {
1348 	if (*stype == STACK_ZERO)
1349 		return;
1350 	if (*stype == STACK_INVALID)
1351 		return;
1352 	*stype = STACK_MISC;
1353 }
1354 
1355 static void scrub_spilled_slot(u8 *stype)
1356 {
1357 	if (*stype != STACK_INVALID)
1358 		*stype = STACK_MISC;
1359 }
1360 
1361 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1362  * small to hold src. This is different from krealloc since we don't want to preserve
1363  * the contents of dst.
1364  *
1365  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1366  * not be allocated.
1367  */
1368 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1369 {
1370 	size_t alloc_bytes;
1371 	void *orig = dst;
1372 	size_t bytes;
1373 
1374 	if (ZERO_OR_NULL_PTR(src))
1375 		goto out;
1376 
1377 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1378 		return NULL;
1379 
1380 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1381 	dst = krealloc(orig, alloc_bytes, flags);
1382 	if (!dst) {
1383 		kfree(orig);
1384 		return NULL;
1385 	}
1386 
1387 	memcpy(dst, src, bytes);
1388 out:
1389 	return dst ? dst : ZERO_SIZE_PTR;
1390 }
1391 
1392 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1393  * small to hold new_n items. new items are zeroed out if the array grows.
1394  *
1395  * Contrary to krealloc_array, does not free arr if new_n is zero.
1396  */
1397 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1398 {
1399 	size_t alloc_size;
1400 	void *new_arr;
1401 
1402 	if (!new_n || old_n == new_n)
1403 		goto out;
1404 
1405 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1406 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1407 	if (!new_arr) {
1408 		kfree(arr);
1409 		return NULL;
1410 	}
1411 	arr = new_arr;
1412 
1413 	if (new_n > old_n)
1414 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1415 
1416 out:
1417 	return arr ? arr : ZERO_SIZE_PTR;
1418 }
1419 
1420 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1421 {
1422 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1423 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1424 	if (!dst->refs)
1425 		return -ENOMEM;
1426 
1427 	dst->acquired_refs = src->acquired_refs;
1428 	dst->active_locks = src->active_locks;
1429 	dst->active_preempt_locks = src->active_preempt_locks;
1430 	dst->active_rcu_lock = src->active_rcu_lock;
1431 	dst->active_irq_id = src->active_irq_id;
1432 	dst->active_lock_id = src->active_lock_id;
1433 	dst->active_lock_ptr = src->active_lock_ptr;
1434 	return 0;
1435 }
1436 
1437 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1438 {
1439 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1440 
1441 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1442 				GFP_KERNEL);
1443 	if (!dst->stack)
1444 		return -ENOMEM;
1445 
1446 	dst->allocated_stack = src->allocated_stack;
1447 	return 0;
1448 }
1449 
1450 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1451 {
1452 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1453 				    sizeof(struct bpf_reference_state));
1454 	if (!state->refs)
1455 		return -ENOMEM;
1456 
1457 	state->acquired_refs = n;
1458 	return 0;
1459 }
1460 
1461 /* Possibly update state->allocated_stack to be at least size bytes. Also
1462  * possibly update the function's high-water mark in its bpf_subprog_info.
1463  */
1464 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1465 {
1466 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1467 
1468 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1469 	size = round_up(size, BPF_REG_SIZE);
1470 	n = size / BPF_REG_SIZE;
1471 
1472 	if (old_n >= n)
1473 		return 0;
1474 
1475 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1476 	if (!state->stack)
1477 		return -ENOMEM;
1478 
1479 	state->allocated_stack = size;
1480 
1481 	/* update known max for given subprogram */
1482 	if (env->subprog_info[state->subprogno].stack_depth < size)
1483 		env->subprog_info[state->subprogno].stack_depth = size;
1484 
1485 	return 0;
1486 }
1487 
1488 /* Acquire a pointer id from the env and update the state->refs to include
1489  * this new pointer reference.
1490  * On success, returns a valid pointer id to associate with the register
1491  * On failure, returns a negative errno.
1492  */
1493 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1494 {
1495 	struct bpf_verifier_state *state = env->cur_state;
1496 	int new_ofs = state->acquired_refs;
1497 	int err;
1498 
1499 	err = resize_reference_state(state, state->acquired_refs + 1);
1500 	if (err)
1501 		return NULL;
1502 	state->refs[new_ofs].insn_idx = insn_idx;
1503 
1504 	return &state->refs[new_ofs];
1505 }
1506 
1507 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx)
1508 {
1509 	struct bpf_reference_state *s;
1510 
1511 	s = acquire_reference_state(env, insn_idx);
1512 	if (!s)
1513 		return -ENOMEM;
1514 	s->type = REF_TYPE_PTR;
1515 	s->id = ++env->id_gen;
1516 	return s->id;
1517 }
1518 
1519 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1520 			      int id, void *ptr)
1521 {
1522 	struct bpf_verifier_state *state = env->cur_state;
1523 	struct bpf_reference_state *s;
1524 
1525 	s = acquire_reference_state(env, insn_idx);
1526 	if (!s)
1527 		return -ENOMEM;
1528 	s->type = type;
1529 	s->id = id;
1530 	s->ptr = ptr;
1531 
1532 	state->active_locks++;
1533 	state->active_lock_id = id;
1534 	state->active_lock_ptr = ptr;
1535 	return 0;
1536 }
1537 
1538 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1539 {
1540 	struct bpf_verifier_state *state = env->cur_state;
1541 	struct bpf_reference_state *s;
1542 
1543 	s = acquire_reference_state(env, insn_idx);
1544 	if (!s)
1545 		return -ENOMEM;
1546 	s->type = REF_TYPE_IRQ;
1547 	s->id = ++env->id_gen;
1548 
1549 	state->active_irq_id = s->id;
1550 	return s->id;
1551 }
1552 
1553 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1554 {
1555 	int last_idx;
1556 	size_t rem;
1557 
1558 	/* IRQ state requires the relative ordering of elements remaining the
1559 	 * same, since it relies on the refs array to behave as a stack, so that
1560 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1561 	 * the array instead of swapping the final element into the deleted idx.
1562 	 */
1563 	last_idx = state->acquired_refs - 1;
1564 	rem = state->acquired_refs - idx - 1;
1565 	if (last_idx && idx != last_idx)
1566 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1567 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1568 	state->acquired_refs--;
1569 	return;
1570 }
1571 
1572 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id)
1573 {
1574 	int i;
1575 
1576 	for (i = 0; i < state->acquired_refs; i++)
1577 		if (state->refs[i].id == ptr_id)
1578 			return true;
1579 
1580 	return false;
1581 }
1582 
1583 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
1584 {
1585 	void *prev_ptr = NULL;
1586 	u32 prev_id = 0;
1587 	int i;
1588 
1589 	for (i = 0; i < state->acquired_refs; i++) {
1590 		if (state->refs[i].type == type && state->refs[i].id == id &&
1591 		    state->refs[i].ptr == ptr) {
1592 			release_reference_state(state, i);
1593 			state->active_locks--;
1594 			/* Reassign active lock (id, ptr). */
1595 			state->active_lock_id = prev_id;
1596 			state->active_lock_ptr = prev_ptr;
1597 			return 0;
1598 		}
1599 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1600 			prev_id = state->refs[i].id;
1601 			prev_ptr = state->refs[i].ptr;
1602 		}
1603 	}
1604 	return -EINVAL;
1605 }
1606 
1607 static int release_irq_state(struct bpf_verifier_state *state, int id)
1608 {
1609 	u32 prev_id = 0;
1610 	int i;
1611 
1612 	if (id != state->active_irq_id)
1613 		return -EACCES;
1614 
1615 	for (i = 0; i < state->acquired_refs; i++) {
1616 		if (state->refs[i].type != REF_TYPE_IRQ)
1617 			continue;
1618 		if (state->refs[i].id == id) {
1619 			release_reference_state(state, i);
1620 			state->active_irq_id = prev_id;
1621 			return 0;
1622 		} else {
1623 			prev_id = state->refs[i].id;
1624 		}
1625 	}
1626 	return -EINVAL;
1627 }
1628 
1629 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1630 						   int id, void *ptr)
1631 {
1632 	int i;
1633 
1634 	for (i = 0; i < state->acquired_refs; i++) {
1635 		struct bpf_reference_state *s = &state->refs[i];
1636 
1637 		if (!(s->type & type))
1638 			continue;
1639 
1640 		if (s->id == id && s->ptr == ptr)
1641 			return s;
1642 	}
1643 	return NULL;
1644 }
1645 
1646 static void update_peak_states(struct bpf_verifier_env *env)
1647 {
1648 	u32 cur_states;
1649 
1650 	cur_states = env->explored_states_size + env->free_list_size;
1651 	env->peak_states = max(env->peak_states, cur_states);
1652 }
1653 
1654 static void free_func_state(struct bpf_func_state *state)
1655 {
1656 	if (!state)
1657 		return;
1658 	kfree(state->stack);
1659 	kfree(state);
1660 }
1661 
1662 static void free_verifier_state(struct bpf_verifier_state *state,
1663 				bool free_self)
1664 {
1665 	int i;
1666 
1667 	for (i = 0; i <= state->curframe; i++) {
1668 		free_func_state(state->frame[i]);
1669 		state->frame[i] = NULL;
1670 	}
1671 	kfree(state->refs);
1672 	if (free_self)
1673 		kfree(state);
1674 }
1675 
1676 /* struct bpf_verifier_state->{parent,loop_entry} refer to states
1677  * that are in either of env->{expored_states,free_list}.
1678  * In both cases the state is contained in struct bpf_verifier_state_list.
1679  */
1680 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st)
1681 {
1682 	if (st->parent)
1683 		return container_of(st->parent, struct bpf_verifier_state_list, state);
1684 	return NULL;
1685 }
1686 
1687 static struct bpf_verifier_state_list *state_loop_entry_as_list(struct bpf_verifier_state *st)
1688 {
1689 	if (st->loop_entry)
1690 		return container_of(st->loop_entry, struct bpf_verifier_state_list, state);
1691 	return NULL;
1692 }
1693 
1694 /* A state can be freed if it is no longer referenced:
1695  * - is in the env->free_list;
1696  * - has no children states;
1697  * - is not used as loop_entry.
1698  *
1699  * Freeing a state can make it's loop_entry free-able.
1700  */
1701 static void maybe_free_verifier_state(struct bpf_verifier_env *env,
1702 				      struct bpf_verifier_state_list *sl)
1703 {
1704 	struct bpf_verifier_state_list *loop_entry_sl;
1705 
1706 	while (sl && sl->in_free_list &&
1707 		     sl->state.branches == 0 &&
1708 		     sl->state.used_as_loop_entry == 0) {
1709 		loop_entry_sl = state_loop_entry_as_list(&sl->state);
1710 		if (loop_entry_sl)
1711 			loop_entry_sl->state.used_as_loop_entry--;
1712 		list_del(&sl->node);
1713 		free_verifier_state(&sl->state, false);
1714 		kfree(sl);
1715 		env->free_list_size--;
1716 		sl = loop_entry_sl;
1717 	}
1718 }
1719 
1720 /* copy verifier state from src to dst growing dst stack space
1721  * when necessary to accommodate larger src stack
1722  */
1723 static int copy_func_state(struct bpf_func_state *dst,
1724 			   const struct bpf_func_state *src)
1725 {
1726 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1727 	return copy_stack_state(dst, src);
1728 }
1729 
1730 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1731 			       const struct bpf_verifier_state *src)
1732 {
1733 	struct bpf_func_state *dst;
1734 	int i, err;
1735 
1736 	/* if dst has more stack frames then src frame, free them, this is also
1737 	 * necessary in case of exceptional exits using bpf_throw.
1738 	 */
1739 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1740 		free_func_state(dst_state->frame[i]);
1741 		dst_state->frame[i] = NULL;
1742 	}
1743 	err = copy_reference_state(dst_state, src);
1744 	if (err)
1745 		return err;
1746 	dst_state->speculative = src->speculative;
1747 	dst_state->in_sleepable = src->in_sleepable;
1748 	dst_state->curframe = src->curframe;
1749 	dst_state->branches = src->branches;
1750 	dst_state->parent = src->parent;
1751 	dst_state->first_insn_idx = src->first_insn_idx;
1752 	dst_state->last_insn_idx = src->last_insn_idx;
1753 	dst_state->insn_hist_start = src->insn_hist_start;
1754 	dst_state->insn_hist_end = src->insn_hist_end;
1755 	dst_state->dfs_depth = src->dfs_depth;
1756 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1757 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1758 	dst_state->may_goto_depth = src->may_goto_depth;
1759 	dst_state->loop_entry = src->loop_entry;
1760 	for (i = 0; i <= src->curframe; i++) {
1761 		dst = dst_state->frame[i];
1762 		if (!dst) {
1763 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1764 			if (!dst)
1765 				return -ENOMEM;
1766 			dst_state->frame[i] = dst;
1767 		}
1768 		err = copy_func_state(dst, src->frame[i]);
1769 		if (err)
1770 			return err;
1771 	}
1772 	return 0;
1773 }
1774 
1775 static u32 state_htab_size(struct bpf_verifier_env *env)
1776 {
1777 	return env->prog->len;
1778 }
1779 
1780 static struct list_head *explored_state(struct bpf_verifier_env *env, int idx)
1781 {
1782 	struct bpf_verifier_state *cur = env->cur_state;
1783 	struct bpf_func_state *state = cur->frame[cur->curframe];
1784 
1785 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1786 }
1787 
1788 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1789 {
1790 	int fr;
1791 
1792 	if (a->curframe != b->curframe)
1793 		return false;
1794 
1795 	for (fr = a->curframe; fr >= 0; fr--)
1796 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1797 			return false;
1798 
1799 	return true;
1800 }
1801 
1802 /* Open coded iterators allow back-edges in the state graph in order to
1803  * check unbounded loops that iterators.
1804  *
1805  * In is_state_visited() it is necessary to know if explored states are
1806  * part of some loops in order to decide whether non-exact states
1807  * comparison could be used:
1808  * - non-exact states comparison establishes sub-state relation and uses
1809  *   read and precision marks to do so, these marks are propagated from
1810  *   children states and thus are not guaranteed to be final in a loop;
1811  * - exact states comparison just checks if current and explored states
1812  *   are identical (and thus form a back-edge).
1813  *
1814  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1815  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1816  * algorithm for loop structure detection and gives an overview of
1817  * relevant terminology. It also has helpful illustrations.
1818  *
1819  * [1] https://api.semanticscholar.org/CorpusID:15784067
1820  *
1821  * We use a similar algorithm but because loop nested structure is
1822  * irrelevant for verifier ours is significantly simpler and resembles
1823  * strongly connected components algorithm from Sedgewick's textbook.
1824  *
1825  * Define topmost loop entry as a first node of the loop traversed in a
1826  * depth first search starting from initial state. The goal of the loop
1827  * tracking algorithm is to associate topmost loop entries with states
1828  * derived from these entries.
1829  *
1830  * For each step in the DFS states traversal algorithm needs to identify
1831  * the following situations:
1832  *
1833  *          initial                     initial                   initial
1834  *            |                           |                         |
1835  *            V                           V                         V
1836  *           ...                         ...           .---------> hdr
1837  *            |                           |            |            |
1838  *            V                           V            |            V
1839  *           cur                     .-> succ          |    .------...
1840  *            |                      |    |            |    |       |
1841  *            V                      |    V            |    V       V
1842  *           succ                    '-- cur           |   ...     ...
1843  *                                                     |    |       |
1844  *                                                     |    V       V
1845  *                                                     |   succ <- cur
1846  *                                                     |    |
1847  *                                                     |    V
1848  *                                                     |   ...
1849  *                                                     |    |
1850  *                                                     '----'
1851  *
1852  *  (A) successor state of cur   (B) successor state of cur or it's entry
1853  *      not yet traversed            are in current DFS path, thus cur and succ
1854  *                                   are members of the same outermost loop
1855  *
1856  *                      initial                  initial
1857  *                        |                        |
1858  *                        V                        V
1859  *                       ...                      ...
1860  *                        |                        |
1861  *                        V                        V
1862  *                .------...               .------...
1863  *                |       |                |       |
1864  *                V       V                V       V
1865  *           .-> hdr     ...              ...     ...
1866  *           |    |       |                |       |
1867  *           |    V       V                V       V
1868  *           |   succ <- cur              succ <- cur
1869  *           |    |                        |
1870  *           |    V                        V
1871  *           |   ...                      ...
1872  *           |    |                        |
1873  *           '----'                       exit
1874  *
1875  * (C) successor state of cur is a part of some loop but this loop
1876  *     does not include cur or successor state is not in a loop at all.
1877  *
1878  * Algorithm could be described as the following python code:
1879  *
1880  *     traversed = set()   # Set of traversed nodes
1881  *     entries = {}        # Mapping from node to loop entry
1882  *     depths = {}         # Depth level assigned to graph node
1883  *     path = set()        # Current DFS path
1884  *
1885  *     # Find outermost loop entry known for n
1886  *     def get_loop_entry(n):
1887  *         h = entries.get(n, None)
1888  *         while h in entries:
1889  *             h = entries[h]
1890  *         return h
1891  *
1892  *     # Update n's loop entry if h comes before n in current DFS path.
1893  *     def update_loop_entry(n, h):
1894  *         if h in path and depths[entries.get(n, n)] < depths[n]:
1895  *             entries[n] = h1
1896  *
1897  *     def dfs(n, depth):
1898  *         traversed.add(n)
1899  *         path.add(n)
1900  *         depths[n] = depth
1901  *         for succ in G.successors(n):
1902  *             if succ not in traversed:
1903  *                 # Case A: explore succ and update cur's loop entry
1904  *                 #         only if succ's entry is in current DFS path.
1905  *                 dfs(succ, depth + 1)
1906  *                 h = entries.get(succ, None)
1907  *                 update_loop_entry(n, h)
1908  *             else:
1909  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1910  *                 update_loop_entry(n, succ)
1911  *         path.remove(n)
1912  *
1913  * To adapt this algorithm for use with verifier:
1914  * - use st->branch == 0 as a signal that DFS of succ had been finished
1915  *   and cur's loop entry has to be updated (case A), handle this in
1916  *   update_branch_counts();
1917  * - use st->branch > 0 as a signal that st is in the current DFS path;
1918  * - handle cases B and C in is_state_visited().
1919  */
1920 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_env *env,
1921 						 struct bpf_verifier_state *st)
1922 {
1923 	struct bpf_verifier_state *topmost = st->loop_entry;
1924 	u32 steps = 0;
1925 
1926 	while (topmost && topmost->loop_entry) {
1927 		if (verifier_bug_if(steps++ > st->dfs_depth, env, "infinite loop"))
1928 			return ERR_PTR(-EFAULT);
1929 		topmost = topmost->loop_entry;
1930 	}
1931 	return topmost;
1932 }
1933 
1934 static void update_loop_entry(struct bpf_verifier_env *env,
1935 			      struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1936 {
1937 	/* The hdr->branches check decides between cases B and C in
1938 	 * comment for get_loop_entry(). If hdr->branches == 0 then
1939 	 * head's topmost loop entry is not in current DFS path,
1940 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1941 	 * no need to update cur->loop_entry.
1942 	 */
1943 	if (hdr->branches && hdr->dfs_depth < (cur->loop_entry ?: cur)->dfs_depth) {
1944 		if (cur->loop_entry) {
1945 			cur->loop_entry->used_as_loop_entry--;
1946 			maybe_free_verifier_state(env, state_loop_entry_as_list(cur));
1947 		}
1948 		cur->loop_entry = hdr;
1949 		hdr->used_as_loop_entry++;
1950 	}
1951 }
1952 
1953 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1954 {
1955 	struct bpf_verifier_state_list *sl = NULL, *parent_sl;
1956 	struct bpf_verifier_state *parent;
1957 
1958 	while (st) {
1959 		u32 br = --st->branches;
1960 
1961 		/* br == 0 signals that DFS exploration for 'st' is finished,
1962 		 * thus it is necessary to update parent's loop entry if it
1963 		 * turned out that st is a part of some loop.
1964 		 * This is a part of 'case A' in get_loop_entry() comment.
1965 		 */
1966 		if (br == 0 && st->parent && st->loop_entry)
1967 			update_loop_entry(env, st->parent, st->loop_entry);
1968 
1969 		/* WARN_ON(br > 1) technically makes sense here,
1970 		 * but see comment in push_stack(), hence:
1971 		 */
1972 		WARN_ONCE((int)br < 0,
1973 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1974 			  br);
1975 		if (br)
1976 			break;
1977 		parent = st->parent;
1978 		parent_sl = state_parent_as_list(st);
1979 		if (sl)
1980 			maybe_free_verifier_state(env, sl);
1981 		st = parent;
1982 		sl = parent_sl;
1983 	}
1984 }
1985 
1986 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1987 		     int *insn_idx, bool pop_log)
1988 {
1989 	struct bpf_verifier_state *cur = env->cur_state;
1990 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1991 	int err;
1992 
1993 	if (env->head == NULL)
1994 		return -ENOENT;
1995 
1996 	if (cur) {
1997 		err = copy_verifier_state(cur, &head->st);
1998 		if (err)
1999 			return err;
2000 	}
2001 	if (pop_log)
2002 		bpf_vlog_reset(&env->log, head->log_pos);
2003 	if (insn_idx)
2004 		*insn_idx = head->insn_idx;
2005 	if (prev_insn_idx)
2006 		*prev_insn_idx = head->prev_insn_idx;
2007 	elem = head->next;
2008 	free_verifier_state(&head->st, false);
2009 	kfree(head);
2010 	env->head = elem;
2011 	env->stack_size--;
2012 	return 0;
2013 }
2014 
2015 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2016 					     int insn_idx, int prev_insn_idx,
2017 					     bool speculative)
2018 {
2019 	struct bpf_verifier_state *cur = env->cur_state;
2020 	struct bpf_verifier_stack_elem *elem;
2021 	int err;
2022 
2023 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2024 	if (!elem)
2025 		goto err;
2026 
2027 	elem->insn_idx = insn_idx;
2028 	elem->prev_insn_idx = prev_insn_idx;
2029 	elem->next = env->head;
2030 	elem->log_pos = env->log.end_pos;
2031 	env->head = elem;
2032 	env->stack_size++;
2033 	err = copy_verifier_state(&elem->st, cur);
2034 	if (err)
2035 		goto err;
2036 	elem->st.speculative |= speculative;
2037 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2038 		verbose(env, "The sequence of %d jumps is too complex.\n",
2039 			env->stack_size);
2040 		goto err;
2041 	}
2042 	if (elem->st.parent) {
2043 		++elem->st.parent->branches;
2044 		/* WARN_ON(branches > 2) technically makes sense here,
2045 		 * but
2046 		 * 1. speculative states will bump 'branches' for non-branch
2047 		 * instructions
2048 		 * 2. is_state_visited() heuristics may decide not to create
2049 		 * a new state for a sequence of branches and all such current
2050 		 * and cloned states will be pointing to a single parent state
2051 		 * which might have large 'branches' count.
2052 		 */
2053 	}
2054 	return &elem->st;
2055 err:
2056 	free_verifier_state(env->cur_state, true);
2057 	env->cur_state = NULL;
2058 	/* pop all elements and return */
2059 	while (!pop_stack(env, NULL, NULL, false));
2060 	return NULL;
2061 }
2062 
2063 #define CALLER_SAVED_REGS 6
2064 static const int caller_saved[CALLER_SAVED_REGS] = {
2065 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2066 };
2067 
2068 /* This helper doesn't clear reg->id */
2069 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2070 {
2071 	reg->var_off = tnum_const(imm);
2072 	reg->smin_value = (s64)imm;
2073 	reg->smax_value = (s64)imm;
2074 	reg->umin_value = imm;
2075 	reg->umax_value = imm;
2076 
2077 	reg->s32_min_value = (s32)imm;
2078 	reg->s32_max_value = (s32)imm;
2079 	reg->u32_min_value = (u32)imm;
2080 	reg->u32_max_value = (u32)imm;
2081 }
2082 
2083 /* Mark the unknown part of a register (variable offset or scalar value) as
2084  * known to have the value @imm.
2085  */
2086 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2087 {
2088 	/* Clear off and union(map_ptr, range) */
2089 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2090 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2091 	reg->id = 0;
2092 	reg->ref_obj_id = 0;
2093 	___mark_reg_known(reg, imm);
2094 }
2095 
2096 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2097 {
2098 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2099 	reg->s32_min_value = (s32)imm;
2100 	reg->s32_max_value = (s32)imm;
2101 	reg->u32_min_value = (u32)imm;
2102 	reg->u32_max_value = (u32)imm;
2103 }
2104 
2105 /* Mark the 'variable offset' part of a register as zero.  This should be
2106  * used only on registers holding a pointer type.
2107  */
2108 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2109 {
2110 	__mark_reg_known(reg, 0);
2111 }
2112 
2113 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2114 {
2115 	__mark_reg_known(reg, 0);
2116 	reg->type = SCALAR_VALUE;
2117 	/* all scalars are assumed imprecise initially (unless unprivileged,
2118 	 * in which case everything is forced to be precise)
2119 	 */
2120 	reg->precise = !env->bpf_capable;
2121 }
2122 
2123 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2124 				struct bpf_reg_state *regs, u32 regno)
2125 {
2126 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2127 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2128 		/* Something bad happened, let's kill all regs */
2129 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2130 			__mark_reg_not_init(env, regs + regno);
2131 		return;
2132 	}
2133 	__mark_reg_known_zero(regs + regno);
2134 }
2135 
2136 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2137 			      bool first_slot, int dynptr_id)
2138 {
2139 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2140 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2141 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2142 	 */
2143 	__mark_reg_known_zero(reg);
2144 	reg->type = CONST_PTR_TO_DYNPTR;
2145 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2146 	reg->id = dynptr_id;
2147 	reg->dynptr.type = type;
2148 	reg->dynptr.first_slot = first_slot;
2149 }
2150 
2151 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2152 {
2153 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2154 		const struct bpf_map *map = reg->map_ptr;
2155 
2156 		if (map->inner_map_meta) {
2157 			reg->type = CONST_PTR_TO_MAP;
2158 			reg->map_ptr = map->inner_map_meta;
2159 			/* transfer reg's id which is unique for every map_lookup_elem
2160 			 * as UID of the inner map.
2161 			 */
2162 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2163 				reg->map_uid = reg->id;
2164 			if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE))
2165 				reg->map_uid = reg->id;
2166 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2167 			reg->type = PTR_TO_XDP_SOCK;
2168 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2169 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2170 			reg->type = PTR_TO_SOCKET;
2171 		} else {
2172 			reg->type = PTR_TO_MAP_VALUE;
2173 		}
2174 		return;
2175 	}
2176 
2177 	reg->type &= ~PTR_MAYBE_NULL;
2178 }
2179 
2180 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2181 				struct btf_field_graph_root *ds_head)
2182 {
2183 	__mark_reg_known_zero(&regs[regno]);
2184 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2185 	regs[regno].btf = ds_head->btf;
2186 	regs[regno].btf_id = ds_head->value_btf_id;
2187 	regs[regno].off = ds_head->node_offset;
2188 }
2189 
2190 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2191 {
2192 	return type_is_pkt_pointer(reg->type);
2193 }
2194 
2195 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2196 {
2197 	return reg_is_pkt_pointer(reg) ||
2198 	       reg->type == PTR_TO_PACKET_END;
2199 }
2200 
2201 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2202 {
2203 	return base_type(reg->type) == PTR_TO_MEM &&
2204 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2205 }
2206 
2207 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2208 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2209 				    enum bpf_reg_type which)
2210 {
2211 	/* The register can already have a range from prior markings.
2212 	 * This is fine as long as it hasn't been advanced from its
2213 	 * origin.
2214 	 */
2215 	return reg->type == which &&
2216 	       reg->id == 0 &&
2217 	       reg->off == 0 &&
2218 	       tnum_equals_const(reg->var_off, 0);
2219 }
2220 
2221 /* Reset the min/max bounds of a register */
2222 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2223 {
2224 	reg->smin_value = S64_MIN;
2225 	reg->smax_value = S64_MAX;
2226 	reg->umin_value = 0;
2227 	reg->umax_value = U64_MAX;
2228 
2229 	reg->s32_min_value = S32_MIN;
2230 	reg->s32_max_value = S32_MAX;
2231 	reg->u32_min_value = 0;
2232 	reg->u32_max_value = U32_MAX;
2233 }
2234 
2235 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2236 {
2237 	reg->smin_value = S64_MIN;
2238 	reg->smax_value = S64_MAX;
2239 	reg->umin_value = 0;
2240 	reg->umax_value = U64_MAX;
2241 }
2242 
2243 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2244 {
2245 	reg->s32_min_value = S32_MIN;
2246 	reg->s32_max_value = S32_MAX;
2247 	reg->u32_min_value = 0;
2248 	reg->u32_max_value = U32_MAX;
2249 }
2250 
2251 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2252 {
2253 	struct tnum var32_off = tnum_subreg(reg->var_off);
2254 
2255 	/* min signed is max(sign bit) | min(other bits) */
2256 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2257 			var32_off.value | (var32_off.mask & S32_MIN));
2258 	/* max signed is min(sign bit) | max(other bits) */
2259 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2260 			var32_off.value | (var32_off.mask & S32_MAX));
2261 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2262 	reg->u32_max_value = min(reg->u32_max_value,
2263 				 (u32)(var32_off.value | var32_off.mask));
2264 }
2265 
2266 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2267 {
2268 	/* min signed is max(sign bit) | min(other bits) */
2269 	reg->smin_value = max_t(s64, reg->smin_value,
2270 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2271 	/* max signed is min(sign bit) | max(other bits) */
2272 	reg->smax_value = min_t(s64, reg->smax_value,
2273 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2274 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2275 	reg->umax_value = min(reg->umax_value,
2276 			      reg->var_off.value | reg->var_off.mask);
2277 }
2278 
2279 static void __update_reg_bounds(struct bpf_reg_state *reg)
2280 {
2281 	__update_reg32_bounds(reg);
2282 	__update_reg64_bounds(reg);
2283 }
2284 
2285 /* Uses signed min/max values to inform unsigned, and vice-versa */
2286 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2287 {
2288 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
2289 	 * bits to improve our u32/s32 boundaries.
2290 	 *
2291 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
2292 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
2293 	 * [10, 20] range. But this property holds for any 64-bit range as
2294 	 * long as upper 32 bits in that entire range of values stay the same.
2295 	 *
2296 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
2297 	 * in decimal) has the same upper 32 bits throughout all the values in
2298 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
2299 	 * range.
2300 	 *
2301 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
2302 	 * following the rules outlined below about u64/s64 correspondence
2303 	 * (which equally applies to u32 vs s32 correspondence). In general it
2304 	 * depends on actual hexadecimal values of 32-bit range. They can form
2305 	 * only valid u32, or only valid s32 ranges in some cases.
2306 	 *
2307 	 * So we use all these insights to derive bounds for subregisters here.
2308 	 */
2309 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
2310 		/* u64 to u32 casting preserves validity of low 32 bits as
2311 		 * a range, if upper 32 bits are the same
2312 		 */
2313 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2314 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2315 
2316 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2317 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2318 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2319 		}
2320 	}
2321 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2322 		/* low 32 bits should form a proper u32 range */
2323 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2324 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2325 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2326 		}
2327 		/* low 32 bits should form a proper s32 range */
2328 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2329 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2330 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2331 		}
2332 	}
2333 	/* Special case where upper bits form a small sequence of two
2334 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2335 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2336 	 * going from negative numbers to positive numbers. E.g., let's say we
2337 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2338 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2339 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2340 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2341 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2342 	 * upper 32 bits. As a random example, s64 range
2343 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2344 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2345 	 */
2346 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2347 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2348 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2349 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2350 	}
2351 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2352 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2353 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2354 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2355 	}
2356 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2357 	 * try to learn from that
2358 	 */
2359 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2360 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2361 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2362 	}
2363 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2364 	 * are the same, so combine.  This works even in the negative case, e.g.
2365 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2366 	 */
2367 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2368 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2369 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2370 	}
2371 }
2372 
2373 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2374 {
2375 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2376 	 * try to learn from that. Let's do a bit of ASCII art to see when
2377 	 * this is happening. Let's take u64 range first:
2378 	 *
2379 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2380 	 * |-------------------------------|--------------------------------|
2381 	 *
2382 	 * Valid u64 range is formed when umin and umax are anywhere in the
2383 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2384 	 * straightforward. Let's see how s64 range maps onto the same range
2385 	 * of values, annotated below the line for comparison:
2386 	 *
2387 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2388 	 * |-------------------------------|--------------------------------|
2389 	 * 0                        S64_MAX S64_MIN                        -1
2390 	 *
2391 	 * So s64 values basically start in the middle and they are logically
2392 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2393 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2394 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2395 	 * more visually as mapped to sign-agnostic range of hex values.
2396 	 *
2397 	 *  u64 start                                               u64 end
2398 	 *  _______________________________________________________________
2399 	 * /                                                               \
2400 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2401 	 * |-------------------------------|--------------------------------|
2402 	 * 0                        S64_MAX S64_MIN                        -1
2403 	 *                                / \
2404 	 * >------------------------------   ------------------------------->
2405 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2406 	 *
2407 	 * What this means is that, in general, we can't always derive
2408 	 * something new about u64 from any random s64 range, and vice versa.
2409 	 *
2410 	 * But we can do that in two particular cases. One is when entire
2411 	 * u64/s64 range is *entirely* contained within left half of the above
2412 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2413 	 *
2414 	 * |-------------------------------|--------------------------------|
2415 	 *     ^                   ^            ^                 ^
2416 	 *     A                   B            C                 D
2417 	 *
2418 	 * [A, B] and [C, D] are contained entirely in their respective halves
2419 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2420 	 * will be non-negative both as u64 and s64 (and in fact it will be
2421 	 * identical ranges no matter the signedness). [C, D] treated as s64
2422 	 * will be a range of negative values, while in u64 it will be
2423 	 * non-negative range of values larger than 0x8000000000000000.
2424 	 *
2425 	 * Now, any other range here can't be represented in both u64 and s64
2426 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2427 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2428 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2429 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2430 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2431 	 * ranges as u64. Currently reg_state can't represent two segments per
2432 	 * numeric domain, so in such situations we can only derive maximal
2433 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2434 	 *
2435 	 * So we use these facts to derive umin/umax from smin/smax and vice
2436 	 * versa only if they stay within the same "half". This is equivalent
2437 	 * to checking sign bit: lower half will have sign bit as zero, upper
2438 	 * half have sign bit 1. Below in code we simplify this by just
2439 	 * casting umin/umax as smin/smax and checking if they form valid
2440 	 * range, and vice versa. Those are equivalent checks.
2441 	 */
2442 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2443 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2444 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2445 	}
2446 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2447 	 * are the same, so combine.  This works even in the negative case, e.g.
2448 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2449 	 */
2450 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2451 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2452 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2453 	}
2454 }
2455 
2456 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2457 {
2458 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2459 	 * values on both sides of 64-bit range in hope to have tighter range.
2460 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2461 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2462 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2463 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2464 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2465 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2466 	 * We just need to make sure that derived bounds we are intersecting
2467 	 * with are well-formed ranges in respective s64 or u64 domain, just
2468 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2469 	 */
2470 	__u64 new_umin, new_umax;
2471 	__s64 new_smin, new_smax;
2472 
2473 	/* u32 -> u64 tightening, it's always well-formed */
2474 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2475 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2476 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2477 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2478 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2479 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2480 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2481 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2482 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2483 
2484 	/* if s32 can be treated as valid u32 range, we can use it as well */
2485 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2486 		/* s32 -> u64 tightening */
2487 		new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2488 		new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2489 		reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2490 		reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2491 		/* s32 -> s64 tightening */
2492 		new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2493 		new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2494 		reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2495 		reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2496 	}
2497 
2498 	/* Here we would like to handle a special case after sign extending load,
2499 	 * when upper bits for a 64-bit range are all 1s or all 0s.
2500 	 *
2501 	 * Upper bits are all 1s when register is in a range:
2502 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2503 	 * Upper bits are all 0s when register is in a range:
2504 	 *   [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2505 	 * Together this forms are continuous range:
2506 	 *   [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2507 	 *
2508 	 * Now, suppose that register range is in fact tighter:
2509 	 *   [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2510 	 * Also suppose that it's 32-bit range is positive,
2511 	 * meaning that lower 32-bits of the full 64-bit register
2512 	 * are in the range:
2513 	 *   [0x0000_0000, 0x7fff_ffff] (W)
2514 	 *
2515 	 * If this happens, then any value in a range:
2516 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2517 	 * is smaller than a lowest bound of the range (R):
2518 	 *   0xffff_ffff_8000_0000
2519 	 * which means that upper bits of the full 64-bit register
2520 	 * can't be all 1s, when lower bits are in range (W).
2521 	 *
2522 	 * Note that:
2523 	 *  - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2524 	 *  - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2525 	 * These relations are used in the conditions below.
2526 	 */
2527 	if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2528 		reg->smin_value = reg->s32_min_value;
2529 		reg->smax_value = reg->s32_max_value;
2530 		reg->umin_value = reg->s32_min_value;
2531 		reg->umax_value = reg->s32_max_value;
2532 		reg->var_off = tnum_intersect(reg->var_off,
2533 					      tnum_range(reg->smin_value, reg->smax_value));
2534 	}
2535 }
2536 
2537 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2538 {
2539 	__reg32_deduce_bounds(reg);
2540 	__reg64_deduce_bounds(reg);
2541 	__reg_deduce_mixed_bounds(reg);
2542 }
2543 
2544 /* Attempts to improve var_off based on unsigned min/max information */
2545 static void __reg_bound_offset(struct bpf_reg_state *reg)
2546 {
2547 	struct tnum var64_off = tnum_intersect(reg->var_off,
2548 					       tnum_range(reg->umin_value,
2549 							  reg->umax_value));
2550 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2551 					       tnum_range(reg->u32_min_value,
2552 							  reg->u32_max_value));
2553 
2554 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2555 }
2556 
2557 static void reg_bounds_sync(struct bpf_reg_state *reg)
2558 {
2559 	/* We might have learned new bounds from the var_off. */
2560 	__update_reg_bounds(reg);
2561 	/* We might have learned something about the sign bit. */
2562 	__reg_deduce_bounds(reg);
2563 	__reg_deduce_bounds(reg);
2564 	/* We might have learned some bits from the bounds. */
2565 	__reg_bound_offset(reg);
2566 	/* Intersecting with the old var_off might have improved our bounds
2567 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2568 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2569 	 */
2570 	__update_reg_bounds(reg);
2571 }
2572 
2573 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2574 				   struct bpf_reg_state *reg, const char *ctx)
2575 {
2576 	const char *msg;
2577 
2578 	if (reg->umin_value > reg->umax_value ||
2579 	    reg->smin_value > reg->smax_value ||
2580 	    reg->u32_min_value > reg->u32_max_value ||
2581 	    reg->s32_min_value > reg->s32_max_value) {
2582 		    msg = "range bounds violation";
2583 		    goto out;
2584 	}
2585 
2586 	if (tnum_is_const(reg->var_off)) {
2587 		u64 uval = reg->var_off.value;
2588 		s64 sval = (s64)uval;
2589 
2590 		if (reg->umin_value != uval || reg->umax_value != uval ||
2591 		    reg->smin_value != sval || reg->smax_value != sval) {
2592 			msg = "const tnum out of sync with range bounds";
2593 			goto out;
2594 		}
2595 	}
2596 
2597 	if (tnum_subreg_is_const(reg->var_off)) {
2598 		u32 uval32 = tnum_subreg(reg->var_off).value;
2599 		s32 sval32 = (s32)uval32;
2600 
2601 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2602 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2603 			msg = "const subreg tnum out of sync with range bounds";
2604 			goto out;
2605 		}
2606 	}
2607 
2608 	return 0;
2609 out:
2610 	verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2611 		"s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2612 		ctx, msg, reg->umin_value, reg->umax_value,
2613 		reg->smin_value, reg->smax_value,
2614 		reg->u32_min_value, reg->u32_max_value,
2615 		reg->s32_min_value, reg->s32_max_value,
2616 		reg->var_off.value, reg->var_off.mask);
2617 	if (env->test_reg_invariants)
2618 		return -EFAULT;
2619 	__mark_reg_unbounded(reg);
2620 	return 0;
2621 }
2622 
2623 static bool __reg32_bound_s64(s32 a)
2624 {
2625 	return a >= 0 && a <= S32_MAX;
2626 }
2627 
2628 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2629 {
2630 	reg->umin_value = reg->u32_min_value;
2631 	reg->umax_value = reg->u32_max_value;
2632 
2633 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2634 	 * be positive otherwise set to worse case bounds and refine later
2635 	 * from tnum.
2636 	 */
2637 	if (__reg32_bound_s64(reg->s32_min_value) &&
2638 	    __reg32_bound_s64(reg->s32_max_value)) {
2639 		reg->smin_value = reg->s32_min_value;
2640 		reg->smax_value = reg->s32_max_value;
2641 	} else {
2642 		reg->smin_value = 0;
2643 		reg->smax_value = U32_MAX;
2644 	}
2645 }
2646 
2647 /* Mark a register as having a completely unknown (scalar) value. */
2648 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2649 {
2650 	/*
2651 	 * Clear type, off, and union(map_ptr, range) and
2652 	 * padding between 'type' and union
2653 	 */
2654 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2655 	reg->type = SCALAR_VALUE;
2656 	reg->id = 0;
2657 	reg->ref_obj_id = 0;
2658 	reg->var_off = tnum_unknown;
2659 	reg->frameno = 0;
2660 	reg->precise = false;
2661 	__mark_reg_unbounded(reg);
2662 }
2663 
2664 /* Mark a register as having a completely unknown (scalar) value,
2665  * initialize .precise as true when not bpf capable.
2666  */
2667 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2668 			       struct bpf_reg_state *reg)
2669 {
2670 	__mark_reg_unknown_imprecise(reg);
2671 	reg->precise = !env->bpf_capable;
2672 }
2673 
2674 static void mark_reg_unknown(struct bpf_verifier_env *env,
2675 			     struct bpf_reg_state *regs, u32 regno)
2676 {
2677 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2678 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2679 		/* Something bad happened, let's kill all regs except FP */
2680 		for (regno = 0; regno < BPF_REG_FP; regno++)
2681 			__mark_reg_not_init(env, regs + regno);
2682 		return;
2683 	}
2684 	__mark_reg_unknown(env, regs + regno);
2685 }
2686 
2687 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2688 				struct bpf_reg_state *regs,
2689 				u32 regno,
2690 				s32 s32_min,
2691 				s32 s32_max)
2692 {
2693 	struct bpf_reg_state *reg = regs + regno;
2694 
2695 	reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2696 	reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2697 
2698 	reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2699 	reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2700 
2701 	reg_bounds_sync(reg);
2702 
2703 	return reg_bounds_sanity_check(env, reg, "s32_range");
2704 }
2705 
2706 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2707 				struct bpf_reg_state *reg)
2708 {
2709 	__mark_reg_unknown(env, reg);
2710 	reg->type = NOT_INIT;
2711 }
2712 
2713 static void mark_reg_not_init(struct bpf_verifier_env *env,
2714 			      struct bpf_reg_state *regs, u32 regno)
2715 {
2716 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2717 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2718 		/* Something bad happened, let's kill all regs except FP */
2719 		for (regno = 0; regno < BPF_REG_FP; regno++)
2720 			__mark_reg_not_init(env, regs + regno);
2721 		return;
2722 	}
2723 	__mark_reg_not_init(env, regs + regno);
2724 }
2725 
2726 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2727 			    struct bpf_reg_state *regs, u32 regno,
2728 			    enum bpf_reg_type reg_type,
2729 			    struct btf *btf, u32 btf_id,
2730 			    enum bpf_type_flag flag)
2731 {
2732 	if (reg_type == SCALAR_VALUE) {
2733 		mark_reg_unknown(env, regs, regno);
2734 		return;
2735 	}
2736 	mark_reg_known_zero(env, regs, regno);
2737 	regs[regno].type = PTR_TO_BTF_ID | flag;
2738 	regs[regno].btf = btf;
2739 	regs[regno].btf_id = btf_id;
2740 	if (type_may_be_null(flag))
2741 		regs[regno].id = ++env->id_gen;
2742 }
2743 
2744 #define DEF_NOT_SUBREG	(0)
2745 static void init_reg_state(struct bpf_verifier_env *env,
2746 			   struct bpf_func_state *state)
2747 {
2748 	struct bpf_reg_state *regs = state->regs;
2749 	int i;
2750 
2751 	for (i = 0; i < MAX_BPF_REG; i++) {
2752 		mark_reg_not_init(env, regs, i);
2753 		regs[i].live = REG_LIVE_NONE;
2754 		regs[i].parent = NULL;
2755 		regs[i].subreg_def = DEF_NOT_SUBREG;
2756 	}
2757 
2758 	/* frame pointer */
2759 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2760 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2761 	regs[BPF_REG_FP].frameno = state->frameno;
2762 }
2763 
2764 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2765 {
2766 	return (struct bpf_retval_range){ minval, maxval };
2767 }
2768 
2769 #define BPF_MAIN_FUNC (-1)
2770 static void init_func_state(struct bpf_verifier_env *env,
2771 			    struct bpf_func_state *state,
2772 			    int callsite, int frameno, int subprogno)
2773 {
2774 	state->callsite = callsite;
2775 	state->frameno = frameno;
2776 	state->subprogno = subprogno;
2777 	state->callback_ret_range = retval_range(0, 0);
2778 	init_reg_state(env, state);
2779 	mark_verifier_state_scratched(env);
2780 }
2781 
2782 /* Similar to push_stack(), but for async callbacks */
2783 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2784 						int insn_idx, int prev_insn_idx,
2785 						int subprog, bool is_sleepable)
2786 {
2787 	struct bpf_verifier_stack_elem *elem;
2788 	struct bpf_func_state *frame;
2789 
2790 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2791 	if (!elem)
2792 		goto err;
2793 
2794 	elem->insn_idx = insn_idx;
2795 	elem->prev_insn_idx = prev_insn_idx;
2796 	elem->next = env->head;
2797 	elem->log_pos = env->log.end_pos;
2798 	env->head = elem;
2799 	env->stack_size++;
2800 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2801 		verbose(env,
2802 			"The sequence of %d jumps is too complex for async cb.\n",
2803 			env->stack_size);
2804 		goto err;
2805 	}
2806 	/* Unlike push_stack() do not copy_verifier_state().
2807 	 * The caller state doesn't matter.
2808 	 * This is async callback. It starts in a fresh stack.
2809 	 * Initialize it similar to do_check_common().
2810 	 * But we do need to make sure to not clobber insn_hist, so we keep
2811 	 * chaining insn_hist_start/insn_hist_end indices as for a normal
2812 	 * child state.
2813 	 */
2814 	elem->st.branches = 1;
2815 	elem->st.in_sleepable = is_sleepable;
2816 	elem->st.insn_hist_start = env->cur_state->insn_hist_end;
2817 	elem->st.insn_hist_end = elem->st.insn_hist_start;
2818 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2819 	if (!frame)
2820 		goto err;
2821 	init_func_state(env, frame,
2822 			BPF_MAIN_FUNC /* callsite */,
2823 			0 /* frameno within this callchain */,
2824 			subprog /* subprog number within this prog */);
2825 	elem->st.frame[0] = frame;
2826 	return &elem->st;
2827 err:
2828 	free_verifier_state(env->cur_state, true);
2829 	env->cur_state = NULL;
2830 	/* pop all elements and return */
2831 	while (!pop_stack(env, NULL, NULL, false));
2832 	return NULL;
2833 }
2834 
2835 
2836 enum reg_arg_type {
2837 	SRC_OP,		/* register is used as source operand */
2838 	DST_OP,		/* register is used as destination operand */
2839 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2840 };
2841 
2842 static int cmp_subprogs(const void *a, const void *b)
2843 {
2844 	return ((struct bpf_subprog_info *)a)->start -
2845 	       ((struct bpf_subprog_info *)b)->start;
2846 }
2847 
2848 /* Find subprogram that contains instruction at 'off' */
2849 static struct bpf_subprog_info *find_containing_subprog(struct bpf_verifier_env *env, int off)
2850 {
2851 	struct bpf_subprog_info *vals = env->subprog_info;
2852 	int l, r, m;
2853 
2854 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2855 		return NULL;
2856 
2857 	l = 0;
2858 	r = env->subprog_cnt - 1;
2859 	while (l < r) {
2860 		m = l + (r - l + 1) / 2;
2861 		if (vals[m].start <= off)
2862 			l = m;
2863 		else
2864 			r = m - 1;
2865 	}
2866 	return &vals[l];
2867 }
2868 
2869 /* Find subprogram that starts exactly at 'off' */
2870 static int find_subprog(struct bpf_verifier_env *env, int off)
2871 {
2872 	struct bpf_subprog_info *p;
2873 
2874 	p = find_containing_subprog(env, off);
2875 	if (!p || p->start != off)
2876 		return -ENOENT;
2877 	return p - env->subprog_info;
2878 }
2879 
2880 static int add_subprog(struct bpf_verifier_env *env, int off)
2881 {
2882 	int insn_cnt = env->prog->len;
2883 	int ret;
2884 
2885 	if (off >= insn_cnt || off < 0) {
2886 		verbose(env, "call to invalid destination\n");
2887 		return -EINVAL;
2888 	}
2889 	ret = find_subprog(env, off);
2890 	if (ret >= 0)
2891 		return ret;
2892 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2893 		verbose(env, "too many subprograms\n");
2894 		return -E2BIG;
2895 	}
2896 	/* determine subprog starts. The end is one before the next starts */
2897 	env->subprog_info[env->subprog_cnt++].start = off;
2898 	sort(env->subprog_info, env->subprog_cnt,
2899 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2900 	return env->subprog_cnt - 1;
2901 }
2902 
2903 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2904 {
2905 	struct bpf_prog_aux *aux = env->prog->aux;
2906 	struct btf *btf = aux->btf;
2907 	const struct btf_type *t;
2908 	u32 main_btf_id, id;
2909 	const char *name;
2910 	int ret, i;
2911 
2912 	/* Non-zero func_info_cnt implies valid btf */
2913 	if (!aux->func_info_cnt)
2914 		return 0;
2915 	main_btf_id = aux->func_info[0].type_id;
2916 
2917 	t = btf_type_by_id(btf, main_btf_id);
2918 	if (!t) {
2919 		verbose(env, "invalid btf id for main subprog in func_info\n");
2920 		return -EINVAL;
2921 	}
2922 
2923 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2924 	if (IS_ERR(name)) {
2925 		ret = PTR_ERR(name);
2926 		/* If there is no tag present, there is no exception callback */
2927 		if (ret == -ENOENT)
2928 			ret = 0;
2929 		else if (ret == -EEXIST)
2930 			verbose(env, "multiple exception callback tags for main subprog\n");
2931 		return ret;
2932 	}
2933 
2934 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2935 	if (ret < 0) {
2936 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2937 		return ret;
2938 	}
2939 	id = ret;
2940 	t = btf_type_by_id(btf, id);
2941 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2942 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2943 		return -EINVAL;
2944 	}
2945 	ret = 0;
2946 	for (i = 0; i < aux->func_info_cnt; i++) {
2947 		if (aux->func_info[i].type_id != id)
2948 			continue;
2949 		ret = aux->func_info[i].insn_off;
2950 		/* Further func_info and subprog checks will also happen
2951 		 * later, so assume this is the right insn_off for now.
2952 		 */
2953 		if (!ret) {
2954 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2955 			ret = -EINVAL;
2956 		}
2957 	}
2958 	if (!ret) {
2959 		verbose(env, "exception callback type id not found in func_info\n");
2960 		ret = -EINVAL;
2961 	}
2962 	return ret;
2963 }
2964 
2965 #define MAX_KFUNC_DESCS 256
2966 #define MAX_KFUNC_BTFS	256
2967 
2968 struct bpf_kfunc_desc {
2969 	struct btf_func_model func_model;
2970 	u32 func_id;
2971 	s32 imm;
2972 	u16 offset;
2973 	unsigned long addr;
2974 };
2975 
2976 struct bpf_kfunc_btf {
2977 	struct btf *btf;
2978 	struct module *module;
2979 	u16 offset;
2980 };
2981 
2982 struct bpf_kfunc_desc_tab {
2983 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2984 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2985 	 * available, therefore at the end of verification do_misc_fixups()
2986 	 * sorts this by imm and offset.
2987 	 */
2988 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2989 	u32 nr_descs;
2990 };
2991 
2992 struct bpf_kfunc_btf_tab {
2993 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2994 	u32 nr_descs;
2995 };
2996 
2997 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2998 {
2999 	const struct bpf_kfunc_desc *d0 = a;
3000 	const struct bpf_kfunc_desc *d1 = b;
3001 
3002 	/* func_id is not greater than BTF_MAX_TYPE */
3003 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
3004 }
3005 
3006 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
3007 {
3008 	const struct bpf_kfunc_btf *d0 = a;
3009 	const struct bpf_kfunc_btf *d1 = b;
3010 
3011 	return d0->offset - d1->offset;
3012 }
3013 
3014 static const struct bpf_kfunc_desc *
3015 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
3016 {
3017 	struct bpf_kfunc_desc desc = {
3018 		.func_id = func_id,
3019 		.offset = offset,
3020 	};
3021 	struct bpf_kfunc_desc_tab *tab;
3022 
3023 	tab = prog->aux->kfunc_tab;
3024 	return bsearch(&desc, tab->descs, tab->nr_descs,
3025 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
3026 }
3027 
3028 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3029 		       u16 btf_fd_idx, u8 **func_addr)
3030 {
3031 	const struct bpf_kfunc_desc *desc;
3032 
3033 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
3034 	if (!desc)
3035 		return -EFAULT;
3036 
3037 	*func_addr = (u8 *)desc->addr;
3038 	return 0;
3039 }
3040 
3041 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
3042 					 s16 offset)
3043 {
3044 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
3045 	struct bpf_kfunc_btf_tab *tab;
3046 	struct bpf_kfunc_btf *b;
3047 	struct module *mod;
3048 	struct btf *btf;
3049 	int btf_fd;
3050 
3051 	tab = env->prog->aux->kfunc_btf_tab;
3052 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
3053 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
3054 	if (!b) {
3055 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
3056 			verbose(env, "too many different module BTFs\n");
3057 			return ERR_PTR(-E2BIG);
3058 		}
3059 
3060 		if (bpfptr_is_null(env->fd_array)) {
3061 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
3062 			return ERR_PTR(-EPROTO);
3063 		}
3064 
3065 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
3066 					    offset * sizeof(btf_fd),
3067 					    sizeof(btf_fd)))
3068 			return ERR_PTR(-EFAULT);
3069 
3070 		btf = btf_get_by_fd(btf_fd);
3071 		if (IS_ERR(btf)) {
3072 			verbose(env, "invalid module BTF fd specified\n");
3073 			return btf;
3074 		}
3075 
3076 		if (!btf_is_module(btf)) {
3077 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
3078 			btf_put(btf);
3079 			return ERR_PTR(-EINVAL);
3080 		}
3081 
3082 		mod = btf_try_get_module(btf);
3083 		if (!mod) {
3084 			btf_put(btf);
3085 			return ERR_PTR(-ENXIO);
3086 		}
3087 
3088 		b = &tab->descs[tab->nr_descs++];
3089 		b->btf = btf;
3090 		b->module = mod;
3091 		b->offset = offset;
3092 
3093 		/* sort() reorders entries by value, so b may no longer point
3094 		 * to the right entry after this
3095 		 */
3096 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3097 		     kfunc_btf_cmp_by_off, NULL);
3098 	} else {
3099 		btf = b->btf;
3100 	}
3101 
3102 	return btf;
3103 }
3104 
3105 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
3106 {
3107 	if (!tab)
3108 		return;
3109 
3110 	while (tab->nr_descs--) {
3111 		module_put(tab->descs[tab->nr_descs].module);
3112 		btf_put(tab->descs[tab->nr_descs].btf);
3113 	}
3114 	kfree(tab);
3115 }
3116 
3117 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
3118 {
3119 	if (offset) {
3120 		if (offset < 0) {
3121 			/* In the future, this can be allowed to increase limit
3122 			 * of fd index into fd_array, interpreted as u16.
3123 			 */
3124 			verbose(env, "negative offset disallowed for kernel module function call\n");
3125 			return ERR_PTR(-EINVAL);
3126 		}
3127 
3128 		return __find_kfunc_desc_btf(env, offset);
3129 	}
3130 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
3131 }
3132 
3133 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
3134 {
3135 	const struct btf_type *func, *func_proto;
3136 	struct bpf_kfunc_btf_tab *btf_tab;
3137 	struct bpf_kfunc_desc_tab *tab;
3138 	struct bpf_prog_aux *prog_aux;
3139 	struct bpf_kfunc_desc *desc;
3140 	const char *func_name;
3141 	struct btf *desc_btf;
3142 	unsigned long call_imm;
3143 	unsigned long addr;
3144 	int err;
3145 
3146 	prog_aux = env->prog->aux;
3147 	tab = prog_aux->kfunc_tab;
3148 	btf_tab = prog_aux->kfunc_btf_tab;
3149 	if (!tab) {
3150 		if (!btf_vmlinux) {
3151 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3152 			return -ENOTSUPP;
3153 		}
3154 
3155 		if (!env->prog->jit_requested) {
3156 			verbose(env, "JIT is required for calling kernel function\n");
3157 			return -ENOTSUPP;
3158 		}
3159 
3160 		if (!bpf_jit_supports_kfunc_call()) {
3161 			verbose(env, "JIT does not support calling kernel function\n");
3162 			return -ENOTSUPP;
3163 		}
3164 
3165 		if (!env->prog->gpl_compatible) {
3166 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3167 			return -EINVAL;
3168 		}
3169 
3170 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
3171 		if (!tab)
3172 			return -ENOMEM;
3173 		prog_aux->kfunc_tab = tab;
3174 	}
3175 
3176 	/* func_id == 0 is always invalid, but instead of returning an error, be
3177 	 * conservative and wait until the code elimination pass before returning
3178 	 * error, so that invalid calls that get pruned out can be in BPF programs
3179 	 * loaded from userspace.  It is also required that offset be untouched
3180 	 * for such calls.
3181 	 */
3182 	if (!func_id && !offset)
3183 		return 0;
3184 
3185 	if (!btf_tab && offset) {
3186 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
3187 		if (!btf_tab)
3188 			return -ENOMEM;
3189 		prog_aux->kfunc_btf_tab = btf_tab;
3190 	}
3191 
3192 	desc_btf = find_kfunc_desc_btf(env, offset);
3193 	if (IS_ERR(desc_btf)) {
3194 		verbose(env, "failed to find BTF for kernel function\n");
3195 		return PTR_ERR(desc_btf);
3196 	}
3197 
3198 	if (find_kfunc_desc(env->prog, func_id, offset))
3199 		return 0;
3200 
3201 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
3202 		verbose(env, "too many different kernel function calls\n");
3203 		return -E2BIG;
3204 	}
3205 
3206 	func = btf_type_by_id(desc_btf, func_id);
3207 	if (!func || !btf_type_is_func(func)) {
3208 		verbose(env, "kernel btf_id %u is not a function\n",
3209 			func_id);
3210 		return -EINVAL;
3211 	}
3212 	func_proto = btf_type_by_id(desc_btf, func->type);
3213 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3214 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
3215 			func_id);
3216 		return -EINVAL;
3217 	}
3218 
3219 	func_name = btf_name_by_offset(desc_btf, func->name_off);
3220 	addr = kallsyms_lookup_name(func_name);
3221 	if (!addr) {
3222 		verbose(env, "cannot find address for kernel function %s\n",
3223 			func_name);
3224 		return -EINVAL;
3225 	}
3226 	specialize_kfunc(env, func_id, offset, &addr);
3227 
3228 	if (bpf_jit_supports_far_kfunc_call()) {
3229 		call_imm = func_id;
3230 	} else {
3231 		call_imm = BPF_CALL_IMM(addr);
3232 		/* Check whether the relative offset overflows desc->imm */
3233 		if ((unsigned long)(s32)call_imm != call_imm) {
3234 			verbose(env, "address of kernel function %s is out of range\n",
3235 				func_name);
3236 			return -EINVAL;
3237 		}
3238 	}
3239 
3240 	if (bpf_dev_bound_kfunc_id(func_id)) {
3241 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3242 		if (err)
3243 			return err;
3244 	}
3245 
3246 	desc = &tab->descs[tab->nr_descs++];
3247 	desc->func_id = func_id;
3248 	desc->imm = call_imm;
3249 	desc->offset = offset;
3250 	desc->addr = addr;
3251 	err = btf_distill_func_proto(&env->log, desc_btf,
3252 				     func_proto, func_name,
3253 				     &desc->func_model);
3254 	if (!err)
3255 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3256 		     kfunc_desc_cmp_by_id_off, NULL);
3257 	return err;
3258 }
3259 
3260 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3261 {
3262 	const struct bpf_kfunc_desc *d0 = a;
3263 	const struct bpf_kfunc_desc *d1 = b;
3264 
3265 	if (d0->imm != d1->imm)
3266 		return d0->imm < d1->imm ? -1 : 1;
3267 	if (d0->offset != d1->offset)
3268 		return d0->offset < d1->offset ? -1 : 1;
3269 	return 0;
3270 }
3271 
3272 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
3273 {
3274 	struct bpf_kfunc_desc_tab *tab;
3275 
3276 	tab = prog->aux->kfunc_tab;
3277 	if (!tab)
3278 		return;
3279 
3280 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3281 	     kfunc_desc_cmp_by_imm_off, NULL);
3282 }
3283 
3284 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3285 {
3286 	return !!prog->aux->kfunc_tab;
3287 }
3288 
3289 const struct btf_func_model *
3290 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3291 			 const struct bpf_insn *insn)
3292 {
3293 	const struct bpf_kfunc_desc desc = {
3294 		.imm = insn->imm,
3295 		.offset = insn->off,
3296 	};
3297 	const struct bpf_kfunc_desc *res;
3298 	struct bpf_kfunc_desc_tab *tab;
3299 
3300 	tab = prog->aux->kfunc_tab;
3301 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3302 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3303 
3304 	return res ? &res->func_model : NULL;
3305 }
3306 
3307 static int add_kfunc_in_insns(struct bpf_verifier_env *env,
3308 			      struct bpf_insn *insn, int cnt)
3309 {
3310 	int i, ret;
3311 
3312 	for (i = 0; i < cnt; i++, insn++) {
3313 		if (bpf_pseudo_kfunc_call(insn)) {
3314 			ret = add_kfunc_call(env, insn->imm, insn->off);
3315 			if (ret < 0)
3316 				return ret;
3317 		}
3318 	}
3319 	return 0;
3320 }
3321 
3322 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3323 {
3324 	struct bpf_subprog_info *subprog = env->subprog_info;
3325 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3326 	struct bpf_insn *insn = env->prog->insnsi;
3327 
3328 	/* Add entry function. */
3329 	ret = add_subprog(env, 0);
3330 	if (ret)
3331 		return ret;
3332 
3333 	for (i = 0; i < insn_cnt; i++, insn++) {
3334 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3335 		    !bpf_pseudo_kfunc_call(insn))
3336 			continue;
3337 
3338 		if (!env->bpf_capable) {
3339 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3340 			return -EPERM;
3341 		}
3342 
3343 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3344 			ret = add_subprog(env, i + insn->imm + 1);
3345 		else
3346 			ret = add_kfunc_call(env, insn->imm, insn->off);
3347 
3348 		if (ret < 0)
3349 			return ret;
3350 	}
3351 
3352 	ret = bpf_find_exception_callback_insn_off(env);
3353 	if (ret < 0)
3354 		return ret;
3355 	ex_cb_insn = ret;
3356 
3357 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3358 	 * marked using BTF decl tag to serve as the exception callback.
3359 	 */
3360 	if (ex_cb_insn) {
3361 		ret = add_subprog(env, ex_cb_insn);
3362 		if (ret < 0)
3363 			return ret;
3364 		for (i = 1; i < env->subprog_cnt; i++) {
3365 			if (env->subprog_info[i].start != ex_cb_insn)
3366 				continue;
3367 			env->exception_callback_subprog = i;
3368 			mark_subprog_exc_cb(env, i);
3369 			break;
3370 		}
3371 	}
3372 
3373 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3374 	 * logic. 'subprog_cnt' should not be increased.
3375 	 */
3376 	subprog[env->subprog_cnt].start = insn_cnt;
3377 
3378 	if (env->log.level & BPF_LOG_LEVEL2)
3379 		for (i = 0; i < env->subprog_cnt; i++)
3380 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3381 
3382 	return 0;
3383 }
3384 
3385 static int jmp_offset(struct bpf_insn *insn)
3386 {
3387 	u8 code = insn->code;
3388 
3389 	if (code == (BPF_JMP32 | BPF_JA))
3390 		return insn->imm;
3391 	return insn->off;
3392 }
3393 
3394 static int check_subprogs(struct bpf_verifier_env *env)
3395 {
3396 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3397 	struct bpf_subprog_info *subprog = env->subprog_info;
3398 	struct bpf_insn *insn = env->prog->insnsi;
3399 	int insn_cnt = env->prog->len;
3400 
3401 	/* now check that all jumps are within the same subprog */
3402 	subprog_start = subprog[cur_subprog].start;
3403 	subprog_end = subprog[cur_subprog + 1].start;
3404 	for (i = 0; i < insn_cnt; i++) {
3405 		u8 code = insn[i].code;
3406 
3407 		if (code == (BPF_JMP | BPF_CALL) &&
3408 		    insn[i].src_reg == 0 &&
3409 		    insn[i].imm == BPF_FUNC_tail_call) {
3410 			subprog[cur_subprog].has_tail_call = true;
3411 			subprog[cur_subprog].tail_call_reachable = true;
3412 		}
3413 		if (BPF_CLASS(code) == BPF_LD &&
3414 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3415 			subprog[cur_subprog].has_ld_abs = true;
3416 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3417 			goto next;
3418 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3419 			goto next;
3420 		off = i + jmp_offset(&insn[i]) + 1;
3421 		if (off < subprog_start || off >= subprog_end) {
3422 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3423 			return -EINVAL;
3424 		}
3425 next:
3426 		if (i == subprog_end - 1) {
3427 			/* to avoid fall-through from one subprog into another
3428 			 * the last insn of the subprog should be either exit
3429 			 * or unconditional jump back or bpf_throw call
3430 			 */
3431 			if (code != (BPF_JMP | BPF_EXIT) &&
3432 			    code != (BPF_JMP32 | BPF_JA) &&
3433 			    code != (BPF_JMP | BPF_JA)) {
3434 				verbose(env, "last insn is not an exit or jmp\n");
3435 				return -EINVAL;
3436 			}
3437 			subprog_start = subprog_end;
3438 			cur_subprog++;
3439 			if (cur_subprog < env->subprog_cnt)
3440 				subprog_end = subprog[cur_subprog + 1].start;
3441 		}
3442 	}
3443 	return 0;
3444 }
3445 
3446 /* Parentage chain of this register (or stack slot) should take care of all
3447  * issues like callee-saved registers, stack slot allocation time, etc.
3448  */
3449 static int mark_reg_read(struct bpf_verifier_env *env,
3450 			 const struct bpf_reg_state *state,
3451 			 struct bpf_reg_state *parent, u8 flag)
3452 {
3453 	bool writes = parent == state->parent; /* Observe write marks */
3454 	int cnt = 0;
3455 
3456 	while (parent) {
3457 		/* if read wasn't screened by an earlier write ... */
3458 		if (writes && state->live & REG_LIVE_WRITTEN)
3459 			break;
3460 		if (verifier_bug_if(parent->live & REG_LIVE_DONE, env,
3461 				    "type %s var_off %lld off %d",
3462 				    reg_type_str(env, parent->type),
3463 				    parent->var_off.value, parent->off))
3464 			return -EFAULT;
3465 		/* The first condition is more likely to be true than the
3466 		 * second, checked it first.
3467 		 */
3468 		if ((parent->live & REG_LIVE_READ) == flag ||
3469 		    parent->live & REG_LIVE_READ64)
3470 			/* The parentage chain never changes and
3471 			 * this parent was already marked as LIVE_READ.
3472 			 * There is no need to keep walking the chain again and
3473 			 * keep re-marking all parents as LIVE_READ.
3474 			 * This case happens when the same register is read
3475 			 * multiple times without writes into it in-between.
3476 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3477 			 * then no need to set the weak REG_LIVE_READ32.
3478 			 */
3479 			break;
3480 		/* ... then we depend on parent's value */
3481 		parent->live |= flag;
3482 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3483 		if (flag == REG_LIVE_READ64)
3484 			parent->live &= ~REG_LIVE_READ32;
3485 		state = parent;
3486 		parent = state->parent;
3487 		writes = true;
3488 		cnt++;
3489 	}
3490 
3491 	if (env->longest_mark_read_walk < cnt)
3492 		env->longest_mark_read_walk = cnt;
3493 	return 0;
3494 }
3495 
3496 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3497 				    int spi, int nr_slots)
3498 {
3499 	struct bpf_func_state *state = func(env, reg);
3500 	int err, i;
3501 
3502 	for (i = 0; i < nr_slots; i++) {
3503 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3504 
3505 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3506 		if (err)
3507 			return err;
3508 
3509 		mark_stack_slot_scratched(env, spi - i);
3510 	}
3511 	return 0;
3512 }
3513 
3514 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3515 {
3516 	int spi;
3517 
3518 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3519 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3520 	 * check_kfunc_call.
3521 	 */
3522 	if (reg->type == CONST_PTR_TO_DYNPTR)
3523 		return 0;
3524 	spi = dynptr_get_spi(env, reg);
3525 	if (spi < 0)
3526 		return spi;
3527 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3528 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3529 	 * read.
3530 	 */
3531 	return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS);
3532 }
3533 
3534 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3535 			  int spi, int nr_slots)
3536 {
3537 	return mark_stack_slot_obj_read(env, reg, spi, nr_slots);
3538 }
3539 
3540 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3541 {
3542 	int spi;
3543 
3544 	spi = irq_flag_get_spi(env, reg);
3545 	if (spi < 0)
3546 		return spi;
3547 	return mark_stack_slot_obj_read(env, reg, spi, 1);
3548 }
3549 
3550 /* This function is supposed to be used by the following 32-bit optimization
3551  * code only. It returns TRUE if the source or destination register operates
3552  * on 64-bit, otherwise return FALSE.
3553  */
3554 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3555 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3556 {
3557 	u8 code, class, op;
3558 
3559 	code = insn->code;
3560 	class = BPF_CLASS(code);
3561 	op = BPF_OP(code);
3562 	if (class == BPF_JMP) {
3563 		/* BPF_EXIT for "main" will reach here. Return TRUE
3564 		 * conservatively.
3565 		 */
3566 		if (op == BPF_EXIT)
3567 			return true;
3568 		if (op == BPF_CALL) {
3569 			/* BPF to BPF call will reach here because of marking
3570 			 * caller saved clobber with DST_OP_NO_MARK for which we
3571 			 * don't care the register def because they are anyway
3572 			 * marked as NOT_INIT already.
3573 			 */
3574 			if (insn->src_reg == BPF_PSEUDO_CALL)
3575 				return false;
3576 			/* Helper call will reach here because of arg type
3577 			 * check, conservatively return TRUE.
3578 			 */
3579 			if (t == SRC_OP)
3580 				return true;
3581 
3582 			return false;
3583 		}
3584 	}
3585 
3586 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3587 		return false;
3588 
3589 	if (class == BPF_ALU64 || class == BPF_JMP ||
3590 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3591 		return true;
3592 
3593 	if (class == BPF_ALU || class == BPF_JMP32)
3594 		return false;
3595 
3596 	if (class == BPF_LDX) {
3597 		if (t != SRC_OP)
3598 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3599 		/* LDX source must be ptr. */
3600 		return true;
3601 	}
3602 
3603 	if (class == BPF_STX) {
3604 		/* BPF_STX (including atomic variants) has one or more source
3605 		 * operands, one of which is a ptr. Check whether the caller is
3606 		 * asking about it.
3607 		 */
3608 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3609 			return true;
3610 		return BPF_SIZE(code) == BPF_DW;
3611 	}
3612 
3613 	if (class == BPF_LD) {
3614 		u8 mode = BPF_MODE(code);
3615 
3616 		/* LD_IMM64 */
3617 		if (mode == BPF_IMM)
3618 			return true;
3619 
3620 		/* Both LD_IND and LD_ABS return 32-bit data. */
3621 		if (t != SRC_OP)
3622 			return  false;
3623 
3624 		/* Implicit ctx ptr. */
3625 		if (regno == BPF_REG_6)
3626 			return true;
3627 
3628 		/* Explicit source could be any width. */
3629 		return true;
3630 	}
3631 
3632 	if (class == BPF_ST)
3633 		/* The only source register for BPF_ST is a ptr. */
3634 		return true;
3635 
3636 	/* Conservatively return true at default. */
3637 	return true;
3638 }
3639 
3640 /* Return the regno defined by the insn, or -1. */
3641 static int insn_def_regno(const struct bpf_insn *insn)
3642 {
3643 	switch (BPF_CLASS(insn->code)) {
3644 	case BPF_JMP:
3645 	case BPF_JMP32:
3646 	case BPF_ST:
3647 		return -1;
3648 	case BPF_STX:
3649 		if (BPF_MODE(insn->code) == BPF_ATOMIC ||
3650 		    BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) {
3651 			if (insn->imm == BPF_CMPXCHG)
3652 				return BPF_REG_0;
3653 			else if (insn->imm == BPF_LOAD_ACQ)
3654 				return insn->dst_reg;
3655 			else if (insn->imm & BPF_FETCH)
3656 				return insn->src_reg;
3657 		}
3658 		return -1;
3659 	default:
3660 		return insn->dst_reg;
3661 	}
3662 }
3663 
3664 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3665 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3666 {
3667 	int dst_reg = insn_def_regno(insn);
3668 
3669 	if (dst_reg == -1)
3670 		return false;
3671 
3672 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3673 }
3674 
3675 static void mark_insn_zext(struct bpf_verifier_env *env,
3676 			   struct bpf_reg_state *reg)
3677 {
3678 	s32 def_idx = reg->subreg_def;
3679 
3680 	if (def_idx == DEF_NOT_SUBREG)
3681 		return;
3682 
3683 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3684 	/* The dst will be zero extended, so won't be sub-register anymore. */
3685 	reg->subreg_def = DEF_NOT_SUBREG;
3686 }
3687 
3688 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3689 			   enum reg_arg_type t)
3690 {
3691 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3692 	struct bpf_reg_state *reg;
3693 	bool rw64;
3694 
3695 	if (regno >= MAX_BPF_REG) {
3696 		verbose(env, "R%d is invalid\n", regno);
3697 		return -EINVAL;
3698 	}
3699 
3700 	mark_reg_scratched(env, regno);
3701 
3702 	reg = &regs[regno];
3703 	rw64 = is_reg64(env, insn, regno, reg, t);
3704 	if (t == SRC_OP) {
3705 		/* check whether register used as source operand can be read */
3706 		if (reg->type == NOT_INIT) {
3707 			verbose(env, "R%d !read_ok\n", regno);
3708 			return -EACCES;
3709 		}
3710 		/* We don't need to worry about FP liveness because it's read-only */
3711 		if (regno == BPF_REG_FP)
3712 			return 0;
3713 
3714 		if (rw64)
3715 			mark_insn_zext(env, reg);
3716 
3717 		return mark_reg_read(env, reg, reg->parent,
3718 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3719 	} else {
3720 		/* check whether register used as dest operand can be written to */
3721 		if (regno == BPF_REG_FP) {
3722 			verbose(env, "frame pointer is read only\n");
3723 			return -EACCES;
3724 		}
3725 		reg->live |= REG_LIVE_WRITTEN;
3726 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3727 		if (t == DST_OP)
3728 			mark_reg_unknown(env, regs, regno);
3729 	}
3730 	return 0;
3731 }
3732 
3733 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3734 			 enum reg_arg_type t)
3735 {
3736 	struct bpf_verifier_state *vstate = env->cur_state;
3737 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3738 
3739 	return __check_reg_arg(env, state->regs, regno, t);
3740 }
3741 
3742 static int insn_stack_access_flags(int frameno, int spi)
3743 {
3744 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3745 }
3746 
3747 static int insn_stack_access_spi(int insn_flags)
3748 {
3749 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3750 }
3751 
3752 static int insn_stack_access_frameno(int insn_flags)
3753 {
3754 	return insn_flags & INSN_F_FRAMENO_MASK;
3755 }
3756 
3757 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3758 {
3759 	env->insn_aux_data[idx].jmp_point = true;
3760 }
3761 
3762 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3763 {
3764 	return env->insn_aux_data[insn_idx].jmp_point;
3765 }
3766 
3767 #define LR_FRAMENO_BITS	3
3768 #define LR_SPI_BITS	6
3769 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3770 #define LR_SIZE_BITS	4
3771 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3772 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3773 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3774 #define LR_SPI_OFF	LR_FRAMENO_BITS
3775 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3776 #define LINKED_REGS_MAX	6
3777 
3778 struct linked_reg {
3779 	u8 frameno;
3780 	union {
3781 		u8 spi;
3782 		u8 regno;
3783 	};
3784 	bool is_reg;
3785 };
3786 
3787 struct linked_regs {
3788 	int cnt;
3789 	struct linked_reg entries[LINKED_REGS_MAX];
3790 };
3791 
3792 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3793 {
3794 	if (s->cnt < LINKED_REGS_MAX)
3795 		return &s->entries[s->cnt++];
3796 
3797 	return NULL;
3798 }
3799 
3800 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3801  * number of elements currently in stack.
3802  * Pack one history entry for linked registers as 10 bits in the following format:
3803  * - 3-bits frameno
3804  * - 6-bits spi_or_reg
3805  * - 1-bit  is_reg
3806  */
3807 static u64 linked_regs_pack(struct linked_regs *s)
3808 {
3809 	u64 val = 0;
3810 	int i;
3811 
3812 	for (i = 0; i < s->cnt; ++i) {
3813 		struct linked_reg *e = &s->entries[i];
3814 		u64 tmp = 0;
3815 
3816 		tmp |= e->frameno;
3817 		tmp |= e->spi << LR_SPI_OFF;
3818 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3819 
3820 		val <<= LR_ENTRY_BITS;
3821 		val |= tmp;
3822 	}
3823 	val <<= LR_SIZE_BITS;
3824 	val |= s->cnt;
3825 	return val;
3826 }
3827 
3828 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3829 {
3830 	int i;
3831 
3832 	s->cnt = val & LR_SIZE_MASK;
3833 	val >>= LR_SIZE_BITS;
3834 
3835 	for (i = 0; i < s->cnt; ++i) {
3836 		struct linked_reg *e = &s->entries[i];
3837 
3838 		e->frameno =  val & LR_FRAMENO_MASK;
3839 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3840 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3841 		val >>= LR_ENTRY_BITS;
3842 	}
3843 }
3844 
3845 /* for any branch, call, exit record the history of jmps in the given state */
3846 static int push_insn_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3847 			     int insn_flags, u64 linked_regs)
3848 {
3849 	struct bpf_insn_hist_entry *p;
3850 	size_t alloc_size;
3851 
3852 	/* combine instruction flags if we already recorded this instruction */
3853 	if (env->cur_hist_ent) {
3854 		/* atomic instructions push insn_flags twice, for READ and
3855 		 * WRITE sides, but they should agree on stack slot
3856 		 */
3857 		verifier_bug_if((env->cur_hist_ent->flags & insn_flags) &&
3858 				(env->cur_hist_ent->flags & insn_flags) != insn_flags,
3859 				env, "insn history: insn_idx %d cur flags %x new flags %x",
3860 				env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3861 		env->cur_hist_ent->flags |= insn_flags;
3862 		verifier_bug_if(env->cur_hist_ent->linked_regs != 0, env,
3863 				"insn history: insn_idx %d linked_regs: %#llx",
3864 				env->insn_idx, env->cur_hist_ent->linked_regs);
3865 		env->cur_hist_ent->linked_regs = linked_regs;
3866 		return 0;
3867 	}
3868 
3869 	if (cur->insn_hist_end + 1 > env->insn_hist_cap) {
3870 		alloc_size = size_mul(cur->insn_hist_end + 1, sizeof(*p));
3871 		p = kvrealloc(env->insn_hist, alloc_size, GFP_USER);
3872 		if (!p)
3873 			return -ENOMEM;
3874 		env->insn_hist = p;
3875 		env->insn_hist_cap = alloc_size / sizeof(*p);
3876 	}
3877 
3878 	p = &env->insn_hist[cur->insn_hist_end];
3879 	p->idx = env->insn_idx;
3880 	p->prev_idx = env->prev_insn_idx;
3881 	p->flags = insn_flags;
3882 	p->linked_regs = linked_regs;
3883 
3884 	cur->insn_hist_end++;
3885 	env->cur_hist_ent = p;
3886 
3887 	return 0;
3888 }
3889 
3890 static struct bpf_insn_hist_entry *get_insn_hist_entry(struct bpf_verifier_env *env,
3891 						       u32 hist_start, u32 hist_end, int insn_idx)
3892 {
3893 	if (hist_end > hist_start && env->insn_hist[hist_end - 1].idx == insn_idx)
3894 		return &env->insn_hist[hist_end - 1];
3895 	return NULL;
3896 }
3897 
3898 /* Backtrack one insn at a time. If idx is not at the top of recorded
3899  * history then previous instruction came from straight line execution.
3900  * Return -ENOENT if we exhausted all instructions within given state.
3901  *
3902  * It's legal to have a bit of a looping with the same starting and ending
3903  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3904  * instruction index is the same as state's first_idx doesn't mean we are
3905  * done. If there is still some jump history left, we should keep going. We
3906  * need to take into account that we might have a jump history between given
3907  * state's parent and itself, due to checkpointing. In this case, we'll have
3908  * history entry recording a jump from last instruction of parent state and
3909  * first instruction of given state.
3910  */
3911 static int get_prev_insn_idx(const struct bpf_verifier_env *env,
3912 			     struct bpf_verifier_state *st,
3913 			     int insn_idx, u32 hist_start, u32 *hist_endp)
3914 {
3915 	u32 hist_end = *hist_endp;
3916 	u32 cnt = hist_end - hist_start;
3917 
3918 	if (insn_idx == st->first_insn_idx) {
3919 		if (cnt == 0)
3920 			return -ENOENT;
3921 		if (cnt == 1 && env->insn_hist[hist_start].idx == insn_idx)
3922 			return -ENOENT;
3923 	}
3924 
3925 	if (cnt && env->insn_hist[hist_end - 1].idx == insn_idx) {
3926 		(*hist_endp)--;
3927 		return env->insn_hist[hist_end - 1].prev_idx;
3928 	} else {
3929 		return insn_idx - 1;
3930 	}
3931 }
3932 
3933 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3934 {
3935 	const struct btf_type *func;
3936 	struct btf *desc_btf;
3937 
3938 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3939 		return NULL;
3940 
3941 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3942 	if (IS_ERR(desc_btf))
3943 		return "<error>";
3944 
3945 	func = btf_type_by_id(desc_btf, insn->imm);
3946 	return btf_name_by_offset(desc_btf, func->name_off);
3947 }
3948 
3949 static void verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
3950 {
3951 	const struct bpf_insn_cbs cbs = {
3952 		.cb_call	= disasm_kfunc_name,
3953 		.cb_print	= verbose,
3954 		.private_data	= env,
3955 	};
3956 
3957 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3958 }
3959 
3960 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3961 {
3962 	bt->frame = frame;
3963 }
3964 
3965 static inline void bt_reset(struct backtrack_state *bt)
3966 {
3967 	struct bpf_verifier_env *env = bt->env;
3968 
3969 	memset(bt, 0, sizeof(*bt));
3970 	bt->env = env;
3971 }
3972 
3973 static inline u32 bt_empty(struct backtrack_state *bt)
3974 {
3975 	u64 mask = 0;
3976 	int i;
3977 
3978 	for (i = 0; i <= bt->frame; i++)
3979 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3980 
3981 	return mask == 0;
3982 }
3983 
3984 static inline int bt_subprog_enter(struct backtrack_state *bt)
3985 {
3986 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3987 		verifier_bug(bt->env, "subprog enter from frame %d", bt->frame);
3988 		return -EFAULT;
3989 	}
3990 	bt->frame++;
3991 	return 0;
3992 }
3993 
3994 static inline int bt_subprog_exit(struct backtrack_state *bt)
3995 {
3996 	if (bt->frame == 0) {
3997 		verifier_bug(bt->env, "subprog exit from frame 0");
3998 		return -EFAULT;
3999 	}
4000 	bt->frame--;
4001 	return 0;
4002 }
4003 
4004 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4005 {
4006 	bt->reg_masks[frame] |= 1 << reg;
4007 }
4008 
4009 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4010 {
4011 	bt->reg_masks[frame] &= ~(1 << reg);
4012 }
4013 
4014 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
4015 {
4016 	bt_set_frame_reg(bt, bt->frame, reg);
4017 }
4018 
4019 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
4020 {
4021 	bt_clear_frame_reg(bt, bt->frame, reg);
4022 }
4023 
4024 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4025 {
4026 	bt->stack_masks[frame] |= 1ull << slot;
4027 }
4028 
4029 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4030 {
4031 	bt->stack_masks[frame] &= ~(1ull << slot);
4032 }
4033 
4034 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
4035 {
4036 	return bt->reg_masks[frame];
4037 }
4038 
4039 static inline u32 bt_reg_mask(struct backtrack_state *bt)
4040 {
4041 	return bt->reg_masks[bt->frame];
4042 }
4043 
4044 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
4045 {
4046 	return bt->stack_masks[frame];
4047 }
4048 
4049 static inline u64 bt_stack_mask(struct backtrack_state *bt)
4050 {
4051 	return bt->stack_masks[bt->frame];
4052 }
4053 
4054 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
4055 {
4056 	return bt->reg_masks[bt->frame] & (1 << reg);
4057 }
4058 
4059 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
4060 {
4061 	return bt->reg_masks[frame] & (1 << reg);
4062 }
4063 
4064 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
4065 {
4066 	return bt->stack_masks[frame] & (1ull << slot);
4067 }
4068 
4069 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
4070 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
4071 {
4072 	DECLARE_BITMAP(mask, 64);
4073 	bool first = true;
4074 	int i, n;
4075 
4076 	buf[0] = '\0';
4077 
4078 	bitmap_from_u64(mask, reg_mask);
4079 	for_each_set_bit(i, mask, 32) {
4080 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
4081 		first = false;
4082 		buf += n;
4083 		buf_sz -= n;
4084 		if (buf_sz < 0)
4085 			break;
4086 	}
4087 }
4088 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
4089 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
4090 {
4091 	DECLARE_BITMAP(mask, 64);
4092 	bool first = true;
4093 	int i, n;
4094 
4095 	buf[0] = '\0';
4096 
4097 	bitmap_from_u64(mask, stack_mask);
4098 	for_each_set_bit(i, mask, 64) {
4099 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
4100 		first = false;
4101 		buf += n;
4102 		buf_sz -= n;
4103 		if (buf_sz < 0)
4104 			break;
4105 	}
4106 }
4107 
4108 /* If any register R in hist->linked_regs is marked as precise in bt,
4109  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
4110  */
4111 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_insn_hist_entry *hist)
4112 {
4113 	struct linked_regs linked_regs;
4114 	bool some_precise = false;
4115 	int i;
4116 
4117 	if (!hist || hist->linked_regs == 0)
4118 		return;
4119 
4120 	linked_regs_unpack(hist->linked_regs, &linked_regs);
4121 	for (i = 0; i < linked_regs.cnt; ++i) {
4122 		struct linked_reg *e = &linked_regs.entries[i];
4123 
4124 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
4125 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
4126 			some_precise = true;
4127 			break;
4128 		}
4129 	}
4130 
4131 	if (!some_precise)
4132 		return;
4133 
4134 	for (i = 0; i < linked_regs.cnt; ++i) {
4135 		struct linked_reg *e = &linked_regs.entries[i];
4136 
4137 		if (e->is_reg)
4138 			bt_set_frame_reg(bt, e->frameno, e->regno);
4139 		else
4140 			bt_set_frame_slot(bt, e->frameno, e->spi);
4141 	}
4142 }
4143 
4144 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
4145 
4146 /* For given verifier state backtrack_insn() is called from the last insn to
4147  * the first insn. Its purpose is to compute a bitmask of registers and
4148  * stack slots that needs precision in the parent verifier state.
4149  *
4150  * @idx is an index of the instruction we are currently processing;
4151  * @subseq_idx is an index of the subsequent instruction that:
4152  *   - *would be* executed next, if jump history is viewed in forward order;
4153  *   - *was* processed previously during backtracking.
4154  */
4155 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
4156 			  struct bpf_insn_hist_entry *hist, struct backtrack_state *bt)
4157 {
4158 	struct bpf_insn *insn = env->prog->insnsi + idx;
4159 	u8 class = BPF_CLASS(insn->code);
4160 	u8 opcode = BPF_OP(insn->code);
4161 	u8 mode = BPF_MODE(insn->code);
4162 	u32 dreg = insn->dst_reg;
4163 	u32 sreg = insn->src_reg;
4164 	u32 spi, i, fr;
4165 
4166 	if (insn->code == 0)
4167 		return 0;
4168 	if (env->log.level & BPF_LOG_LEVEL2) {
4169 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
4170 		verbose(env, "mark_precise: frame%d: regs=%s ",
4171 			bt->frame, env->tmp_str_buf);
4172 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
4173 		verbose(env, "stack=%s before ", env->tmp_str_buf);
4174 		verbose(env, "%d: ", idx);
4175 		verbose_insn(env, insn);
4176 	}
4177 
4178 	/* If there is a history record that some registers gained range at this insn,
4179 	 * propagate precision marks to those registers, so that bt_is_reg_set()
4180 	 * accounts for these registers.
4181 	 */
4182 	bt_sync_linked_regs(bt, hist);
4183 
4184 	if (class == BPF_ALU || class == BPF_ALU64) {
4185 		if (!bt_is_reg_set(bt, dreg))
4186 			return 0;
4187 		if (opcode == BPF_END || opcode == BPF_NEG) {
4188 			/* sreg is reserved and unused
4189 			 * dreg still need precision before this insn
4190 			 */
4191 			return 0;
4192 		} else if (opcode == BPF_MOV) {
4193 			if (BPF_SRC(insn->code) == BPF_X) {
4194 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
4195 				 * dreg needs precision after this insn
4196 				 * sreg needs precision before this insn
4197 				 */
4198 				bt_clear_reg(bt, dreg);
4199 				if (sreg != BPF_REG_FP)
4200 					bt_set_reg(bt, sreg);
4201 			} else {
4202 				/* dreg = K
4203 				 * dreg needs precision after this insn.
4204 				 * Corresponding register is already marked
4205 				 * as precise=true in this verifier state.
4206 				 * No further markings in parent are necessary
4207 				 */
4208 				bt_clear_reg(bt, dreg);
4209 			}
4210 		} else {
4211 			if (BPF_SRC(insn->code) == BPF_X) {
4212 				/* dreg += sreg
4213 				 * both dreg and sreg need precision
4214 				 * before this insn
4215 				 */
4216 				if (sreg != BPF_REG_FP)
4217 					bt_set_reg(bt, sreg);
4218 			} /* else dreg += K
4219 			   * dreg still needs precision before this insn
4220 			   */
4221 		}
4222 	} else if (class == BPF_LDX || is_atomic_load_insn(insn)) {
4223 		if (!bt_is_reg_set(bt, dreg))
4224 			return 0;
4225 		bt_clear_reg(bt, dreg);
4226 
4227 		/* scalars can only be spilled into stack w/o losing precision.
4228 		 * Load from any other memory can be zero extended.
4229 		 * The desire to keep that precision is already indicated
4230 		 * by 'precise' mark in corresponding register of this state.
4231 		 * No further tracking necessary.
4232 		 */
4233 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4234 			return 0;
4235 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
4236 		 * that [fp - off] slot contains scalar that needs to be
4237 		 * tracked with precision
4238 		 */
4239 		spi = insn_stack_access_spi(hist->flags);
4240 		fr = insn_stack_access_frameno(hist->flags);
4241 		bt_set_frame_slot(bt, fr, spi);
4242 	} else if (class == BPF_STX || class == BPF_ST) {
4243 		if (bt_is_reg_set(bt, dreg))
4244 			/* stx & st shouldn't be using _scalar_ dst_reg
4245 			 * to access memory. It means backtracking
4246 			 * encountered a case of pointer subtraction.
4247 			 */
4248 			return -ENOTSUPP;
4249 		/* scalars can only be spilled into stack */
4250 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4251 			return 0;
4252 		spi = insn_stack_access_spi(hist->flags);
4253 		fr = insn_stack_access_frameno(hist->flags);
4254 		if (!bt_is_frame_slot_set(bt, fr, spi))
4255 			return 0;
4256 		bt_clear_frame_slot(bt, fr, spi);
4257 		if (class == BPF_STX)
4258 			bt_set_reg(bt, sreg);
4259 	} else if (class == BPF_JMP || class == BPF_JMP32) {
4260 		if (bpf_pseudo_call(insn)) {
4261 			int subprog_insn_idx, subprog;
4262 
4263 			subprog_insn_idx = idx + insn->imm + 1;
4264 			subprog = find_subprog(env, subprog_insn_idx);
4265 			if (subprog < 0)
4266 				return -EFAULT;
4267 
4268 			if (subprog_is_global(env, subprog)) {
4269 				/* check that jump history doesn't have any
4270 				 * extra instructions from subprog; the next
4271 				 * instruction after call to global subprog
4272 				 * should be literally next instruction in
4273 				 * caller program
4274 				 */
4275 				verifier_bug_if(idx + 1 != subseq_idx, env,
4276 						"extra insn from subprog");
4277 				/* r1-r5 are invalidated after subprog call,
4278 				 * so for global func call it shouldn't be set
4279 				 * anymore
4280 				 */
4281 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4282 					verifier_bug(env, "global subprog unexpected regs %x",
4283 						     bt_reg_mask(bt));
4284 					return -EFAULT;
4285 				}
4286 				/* global subprog always sets R0 */
4287 				bt_clear_reg(bt, BPF_REG_0);
4288 				return 0;
4289 			} else {
4290 				/* static subprog call instruction, which
4291 				 * means that we are exiting current subprog,
4292 				 * so only r1-r5 could be still requested as
4293 				 * precise, r0 and r6-r10 or any stack slot in
4294 				 * the current frame should be zero by now
4295 				 */
4296 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4297 					verifier_bug(env, "static subprog unexpected regs %x",
4298 						     bt_reg_mask(bt));
4299 					return -EFAULT;
4300 				}
4301 				/* we are now tracking register spills correctly,
4302 				 * so any instance of leftover slots is a bug
4303 				 */
4304 				if (bt_stack_mask(bt) != 0) {
4305 					verifier_bug(env,
4306 						     "static subprog leftover stack slots %llx",
4307 						     bt_stack_mask(bt));
4308 					return -EFAULT;
4309 				}
4310 				/* propagate r1-r5 to the caller */
4311 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
4312 					if (bt_is_reg_set(bt, i)) {
4313 						bt_clear_reg(bt, i);
4314 						bt_set_frame_reg(bt, bt->frame - 1, i);
4315 					}
4316 				}
4317 				if (bt_subprog_exit(bt))
4318 					return -EFAULT;
4319 				return 0;
4320 			}
4321 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
4322 			/* exit from callback subprog to callback-calling helper or
4323 			 * kfunc call. Use idx/subseq_idx check to discern it from
4324 			 * straight line code backtracking.
4325 			 * Unlike the subprog call handling above, we shouldn't
4326 			 * propagate precision of r1-r5 (if any requested), as they are
4327 			 * not actually arguments passed directly to callback subprogs
4328 			 */
4329 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4330 				verifier_bug(env, "callback unexpected regs %x",
4331 					     bt_reg_mask(bt));
4332 				return -EFAULT;
4333 			}
4334 			if (bt_stack_mask(bt) != 0) {
4335 				verifier_bug(env, "callback leftover stack slots %llx",
4336 					     bt_stack_mask(bt));
4337 				return -EFAULT;
4338 			}
4339 			/* clear r1-r5 in callback subprog's mask */
4340 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4341 				bt_clear_reg(bt, i);
4342 			if (bt_subprog_exit(bt))
4343 				return -EFAULT;
4344 			return 0;
4345 		} else if (opcode == BPF_CALL) {
4346 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
4347 			 * catch this error later. Make backtracking conservative
4348 			 * with ENOTSUPP.
4349 			 */
4350 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
4351 				return -ENOTSUPP;
4352 			/* regular helper call sets R0 */
4353 			bt_clear_reg(bt, BPF_REG_0);
4354 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4355 				/* if backtracking was looking for registers R1-R5
4356 				 * they should have been found already.
4357 				 */
4358 				verifier_bug(env, "backtracking call unexpected regs %x",
4359 					     bt_reg_mask(bt));
4360 				return -EFAULT;
4361 			}
4362 		} else if (opcode == BPF_EXIT) {
4363 			bool r0_precise;
4364 
4365 			/* Backtracking to a nested function call, 'idx' is a part of
4366 			 * the inner frame 'subseq_idx' is a part of the outer frame.
4367 			 * In case of a regular function call, instructions giving
4368 			 * precision to registers R1-R5 should have been found already.
4369 			 * In case of a callback, it is ok to have R1-R5 marked for
4370 			 * backtracking, as these registers are set by the function
4371 			 * invoking callback.
4372 			 */
4373 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
4374 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4375 					bt_clear_reg(bt, i);
4376 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4377 				verifier_bug(env, "backtracking exit unexpected regs %x",
4378 					     bt_reg_mask(bt));
4379 				return -EFAULT;
4380 			}
4381 
4382 			/* BPF_EXIT in subprog or callback always returns
4383 			 * right after the call instruction, so by checking
4384 			 * whether the instruction at subseq_idx-1 is subprog
4385 			 * call or not we can distinguish actual exit from
4386 			 * *subprog* from exit from *callback*. In the former
4387 			 * case, we need to propagate r0 precision, if
4388 			 * necessary. In the former we never do that.
4389 			 */
4390 			r0_precise = subseq_idx - 1 >= 0 &&
4391 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4392 				     bt_is_reg_set(bt, BPF_REG_0);
4393 
4394 			bt_clear_reg(bt, BPF_REG_0);
4395 			if (bt_subprog_enter(bt))
4396 				return -EFAULT;
4397 
4398 			if (r0_precise)
4399 				bt_set_reg(bt, BPF_REG_0);
4400 			/* r6-r9 and stack slots will stay set in caller frame
4401 			 * bitmasks until we return back from callee(s)
4402 			 */
4403 			return 0;
4404 		} else if (BPF_SRC(insn->code) == BPF_X) {
4405 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4406 				return 0;
4407 			/* dreg <cond> sreg
4408 			 * Both dreg and sreg need precision before
4409 			 * this insn. If only sreg was marked precise
4410 			 * before it would be equally necessary to
4411 			 * propagate it to dreg.
4412 			 */
4413 			if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK))
4414 				bt_set_reg(bt, sreg);
4415 			if (!hist || !(hist->flags & INSN_F_DST_REG_STACK))
4416 				bt_set_reg(bt, dreg);
4417 		} else if (BPF_SRC(insn->code) == BPF_K) {
4418 			 /* dreg <cond> K
4419 			  * Only dreg still needs precision before
4420 			  * this insn, so for the K-based conditional
4421 			  * there is nothing new to be marked.
4422 			  */
4423 		}
4424 	} else if (class == BPF_LD) {
4425 		if (!bt_is_reg_set(bt, dreg))
4426 			return 0;
4427 		bt_clear_reg(bt, dreg);
4428 		/* It's ld_imm64 or ld_abs or ld_ind.
4429 		 * For ld_imm64 no further tracking of precision
4430 		 * into parent is necessary
4431 		 */
4432 		if (mode == BPF_IND || mode == BPF_ABS)
4433 			/* to be analyzed */
4434 			return -ENOTSUPP;
4435 	}
4436 	/* Propagate precision marks to linked registers, to account for
4437 	 * registers marked as precise in this function.
4438 	 */
4439 	bt_sync_linked_regs(bt, hist);
4440 	return 0;
4441 }
4442 
4443 /* the scalar precision tracking algorithm:
4444  * . at the start all registers have precise=false.
4445  * . scalar ranges are tracked as normal through alu and jmp insns.
4446  * . once precise value of the scalar register is used in:
4447  *   .  ptr + scalar alu
4448  *   . if (scalar cond K|scalar)
4449  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
4450  *   backtrack through the verifier states and mark all registers and
4451  *   stack slots with spilled constants that these scalar regisers
4452  *   should be precise.
4453  * . during state pruning two registers (or spilled stack slots)
4454  *   are equivalent if both are not precise.
4455  *
4456  * Note the verifier cannot simply walk register parentage chain,
4457  * since many different registers and stack slots could have been
4458  * used to compute single precise scalar.
4459  *
4460  * The approach of starting with precise=true for all registers and then
4461  * backtrack to mark a register as not precise when the verifier detects
4462  * that program doesn't care about specific value (e.g., when helper
4463  * takes register as ARG_ANYTHING parameter) is not safe.
4464  *
4465  * It's ok to walk single parentage chain of the verifier states.
4466  * It's possible that this backtracking will go all the way till 1st insn.
4467  * All other branches will be explored for needing precision later.
4468  *
4469  * The backtracking needs to deal with cases like:
4470  *   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)
4471  * r9 -= r8
4472  * r5 = r9
4473  * if r5 > 0x79f goto pc+7
4474  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4475  * r5 += 1
4476  * ...
4477  * call bpf_perf_event_output#25
4478  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4479  *
4480  * and this case:
4481  * r6 = 1
4482  * call foo // uses callee's r6 inside to compute r0
4483  * r0 += r6
4484  * if r0 == 0 goto
4485  *
4486  * to track above reg_mask/stack_mask needs to be independent for each frame.
4487  *
4488  * Also if parent's curframe > frame where backtracking started,
4489  * the verifier need to mark registers in both frames, otherwise callees
4490  * may incorrectly prune callers. This is similar to
4491  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4492  *
4493  * For now backtracking falls back into conservative marking.
4494  */
4495 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4496 				     struct bpf_verifier_state *st)
4497 {
4498 	struct bpf_func_state *func;
4499 	struct bpf_reg_state *reg;
4500 	int i, j;
4501 
4502 	if (env->log.level & BPF_LOG_LEVEL2) {
4503 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4504 			st->curframe);
4505 	}
4506 
4507 	/* big hammer: mark all scalars precise in this path.
4508 	 * pop_stack may still get !precise scalars.
4509 	 * We also skip current state and go straight to first parent state,
4510 	 * because precision markings in current non-checkpointed state are
4511 	 * not needed. See why in the comment in __mark_chain_precision below.
4512 	 */
4513 	for (st = st->parent; st; st = st->parent) {
4514 		for (i = 0; i <= st->curframe; i++) {
4515 			func = st->frame[i];
4516 			for (j = 0; j < BPF_REG_FP; j++) {
4517 				reg = &func->regs[j];
4518 				if (reg->type != SCALAR_VALUE || reg->precise)
4519 					continue;
4520 				reg->precise = true;
4521 				if (env->log.level & BPF_LOG_LEVEL2) {
4522 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4523 						i, j);
4524 				}
4525 			}
4526 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4527 				if (!is_spilled_reg(&func->stack[j]))
4528 					continue;
4529 				reg = &func->stack[j].spilled_ptr;
4530 				if (reg->type != SCALAR_VALUE || reg->precise)
4531 					continue;
4532 				reg->precise = true;
4533 				if (env->log.level & BPF_LOG_LEVEL2) {
4534 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4535 						i, -(j + 1) * 8);
4536 				}
4537 			}
4538 		}
4539 	}
4540 }
4541 
4542 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4543 {
4544 	struct bpf_func_state *func;
4545 	struct bpf_reg_state *reg;
4546 	int i, j;
4547 
4548 	for (i = 0; i <= st->curframe; i++) {
4549 		func = st->frame[i];
4550 		for (j = 0; j < BPF_REG_FP; j++) {
4551 			reg = &func->regs[j];
4552 			if (reg->type != SCALAR_VALUE)
4553 				continue;
4554 			reg->precise = false;
4555 		}
4556 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4557 			if (!is_spilled_reg(&func->stack[j]))
4558 				continue;
4559 			reg = &func->stack[j].spilled_ptr;
4560 			if (reg->type != SCALAR_VALUE)
4561 				continue;
4562 			reg->precise = false;
4563 		}
4564 	}
4565 }
4566 
4567 /*
4568  * __mark_chain_precision() backtracks BPF program instruction sequence and
4569  * chain of verifier states making sure that register *regno* (if regno >= 0)
4570  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4571  * SCALARS, as well as any other registers and slots that contribute to
4572  * a tracked state of given registers/stack slots, depending on specific BPF
4573  * assembly instructions (see backtrack_insns() for exact instruction handling
4574  * logic). This backtracking relies on recorded insn_hist and is able to
4575  * traverse entire chain of parent states. This process ends only when all the
4576  * necessary registers/slots and their transitive dependencies are marked as
4577  * precise.
4578  *
4579  * One important and subtle aspect is that precise marks *do not matter* in
4580  * the currently verified state (current state). It is important to understand
4581  * why this is the case.
4582  *
4583  * First, note that current state is the state that is not yet "checkpointed",
4584  * i.e., it is not yet put into env->explored_states, and it has no children
4585  * states as well. It's ephemeral, and can end up either a) being discarded if
4586  * compatible explored state is found at some point or BPF_EXIT instruction is
4587  * reached or b) checkpointed and put into env->explored_states, branching out
4588  * into one or more children states.
4589  *
4590  * In the former case, precise markings in current state are completely
4591  * ignored by state comparison code (see regsafe() for details). Only
4592  * checkpointed ("old") state precise markings are important, and if old
4593  * state's register/slot is precise, regsafe() assumes current state's
4594  * register/slot as precise and checks value ranges exactly and precisely. If
4595  * states turn out to be compatible, current state's necessary precise
4596  * markings and any required parent states' precise markings are enforced
4597  * after the fact with propagate_precision() logic, after the fact. But it's
4598  * important to realize that in this case, even after marking current state
4599  * registers/slots as precise, we immediately discard current state. So what
4600  * actually matters is any of the precise markings propagated into current
4601  * state's parent states, which are always checkpointed (due to b) case above).
4602  * As such, for scenario a) it doesn't matter if current state has precise
4603  * markings set or not.
4604  *
4605  * Now, for the scenario b), checkpointing and forking into child(ren)
4606  * state(s). Note that before current state gets to checkpointing step, any
4607  * processed instruction always assumes precise SCALAR register/slot
4608  * knowledge: if precise value or range is useful to prune jump branch, BPF
4609  * verifier takes this opportunity enthusiastically. Similarly, when
4610  * register's value is used to calculate offset or memory address, exact
4611  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4612  * what we mentioned above about state comparison ignoring precise markings
4613  * during state comparison, BPF verifier ignores and also assumes precise
4614  * markings *at will* during instruction verification process. But as verifier
4615  * assumes precision, it also propagates any precision dependencies across
4616  * parent states, which are not yet finalized, so can be further restricted
4617  * based on new knowledge gained from restrictions enforced by their children
4618  * states. This is so that once those parent states are finalized, i.e., when
4619  * they have no more active children state, state comparison logic in
4620  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4621  * required for correctness.
4622  *
4623  * To build a bit more intuition, note also that once a state is checkpointed,
4624  * the path we took to get to that state is not important. This is crucial
4625  * property for state pruning. When state is checkpointed and finalized at
4626  * some instruction index, it can be correctly and safely used to "short
4627  * circuit" any *compatible* state that reaches exactly the same instruction
4628  * index. I.e., if we jumped to that instruction from a completely different
4629  * code path than original finalized state was derived from, it doesn't
4630  * matter, current state can be discarded because from that instruction
4631  * forward having a compatible state will ensure we will safely reach the
4632  * exit. States describe preconditions for further exploration, but completely
4633  * forget the history of how we got here.
4634  *
4635  * This also means that even if we needed precise SCALAR range to get to
4636  * finalized state, but from that point forward *that same* SCALAR register is
4637  * never used in a precise context (i.e., it's precise value is not needed for
4638  * correctness), it's correct and safe to mark such register as "imprecise"
4639  * (i.e., precise marking set to false). This is what we rely on when we do
4640  * not set precise marking in current state. If no child state requires
4641  * precision for any given SCALAR register, it's safe to dictate that it can
4642  * be imprecise. If any child state does require this register to be precise,
4643  * we'll mark it precise later retroactively during precise markings
4644  * propagation from child state to parent states.
4645  *
4646  * Skipping precise marking setting in current state is a mild version of
4647  * relying on the above observation. But we can utilize this property even
4648  * more aggressively by proactively forgetting any precise marking in the
4649  * current state (which we inherited from the parent state), right before we
4650  * checkpoint it and branch off into new child state. This is done by
4651  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4652  * finalized states which help in short circuiting more future states.
4653  */
4654 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4655 {
4656 	struct backtrack_state *bt = &env->bt;
4657 	struct bpf_verifier_state *st = env->cur_state;
4658 	int first_idx = st->first_insn_idx;
4659 	int last_idx = env->insn_idx;
4660 	int subseq_idx = -1;
4661 	struct bpf_func_state *func;
4662 	struct bpf_reg_state *reg;
4663 	bool skip_first = true;
4664 	int i, fr, err;
4665 
4666 	if (!env->bpf_capable)
4667 		return 0;
4668 
4669 	/* set frame number from which we are starting to backtrack */
4670 	bt_init(bt, env->cur_state->curframe);
4671 
4672 	/* Do sanity checks against current state of register and/or stack
4673 	 * slot, but don't set precise flag in current state, as precision
4674 	 * tracking in the current state is unnecessary.
4675 	 */
4676 	func = st->frame[bt->frame];
4677 	if (regno >= 0) {
4678 		reg = &func->regs[regno];
4679 		if (reg->type != SCALAR_VALUE) {
4680 			WARN_ONCE(1, "backtracing misuse");
4681 			return -EFAULT;
4682 		}
4683 		bt_set_reg(bt, regno);
4684 	}
4685 
4686 	if (bt_empty(bt))
4687 		return 0;
4688 
4689 	for (;;) {
4690 		DECLARE_BITMAP(mask, 64);
4691 		u32 hist_start = st->insn_hist_start;
4692 		u32 hist_end = st->insn_hist_end;
4693 		struct bpf_insn_hist_entry *hist;
4694 
4695 		if (env->log.level & BPF_LOG_LEVEL2) {
4696 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4697 				bt->frame, last_idx, first_idx, subseq_idx);
4698 		}
4699 
4700 		if (last_idx < 0) {
4701 			/* we are at the entry into subprog, which
4702 			 * is expected for global funcs, but only if
4703 			 * requested precise registers are R1-R5
4704 			 * (which are global func's input arguments)
4705 			 */
4706 			if (st->curframe == 0 &&
4707 			    st->frame[0]->subprogno > 0 &&
4708 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4709 			    bt_stack_mask(bt) == 0 &&
4710 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4711 				bitmap_from_u64(mask, bt_reg_mask(bt));
4712 				for_each_set_bit(i, mask, 32) {
4713 					reg = &st->frame[0]->regs[i];
4714 					bt_clear_reg(bt, i);
4715 					if (reg->type == SCALAR_VALUE)
4716 						reg->precise = true;
4717 				}
4718 				return 0;
4719 			}
4720 
4721 			verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %llx",
4722 				     st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4723 			return -EFAULT;
4724 		}
4725 
4726 		for (i = last_idx;;) {
4727 			if (skip_first) {
4728 				err = 0;
4729 				skip_first = false;
4730 			} else {
4731 				hist = get_insn_hist_entry(env, hist_start, hist_end, i);
4732 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4733 			}
4734 			if (err == -ENOTSUPP) {
4735 				mark_all_scalars_precise(env, env->cur_state);
4736 				bt_reset(bt);
4737 				return 0;
4738 			} else if (err) {
4739 				return err;
4740 			}
4741 			if (bt_empty(bt))
4742 				/* Found assignment(s) into tracked register in this state.
4743 				 * Since this state is already marked, just return.
4744 				 * Nothing to be tracked further in the parent state.
4745 				 */
4746 				return 0;
4747 			subseq_idx = i;
4748 			i = get_prev_insn_idx(env, st, i, hist_start, &hist_end);
4749 			if (i == -ENOENT)
4750 				break;
4751 			if (i >= env->prog->len) {
4752 				/* This can happen if backtracking reached insn 0
4753 				 * and there are still reg_mask or stack_mask
4754 				 * to backtrack.
4755 				 * It means the backtracking missed the spot where
4756 				 * particular register was initialized with a constant.
4757 				 */
4758 				verifier_bug(env, "backtracking idx %d", i);
4759 				return -EFAULT;
4760 			}
4761 		}
4762 		st = st->parent;
4763 		if (!st)
4764 			break;
4765 
4766 		for (fr = bt->frame; fr >= 0; fr--) {
4767 			func = st->frame[fr];
4768 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4769 			for_each_set_bit(i, mask, 32) {
4770 				reg = &func->regs[i];
4771 				if (reg->type != SCALAR_VALUE) {
4772 					bt_clear_frame_reg(bt, fr, i);
4773 					continue;
4774 				}
4775 				if (reg->precise)
4776 					bt_clear_frame_reg(bt, fr, i);
4777 				else
4778 					reg->precise = true;
4779 			}
4780 
4781 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4782 			for_each_set_bit(i, mask, 64) {
4783 				if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE,
4784 						    env, "stack slot %d, total slots %d",
4785 						    i, func->allocated_stack / BPF_REG_SIZE))
4786 					return -EFAULT;
4787 
4788 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4789 					bt_clear_frame_slot(bt, fr, i);
4790 					continue;
4791 				}
4792 				reg = &func->stack[i].spilled_ptr;
4793 				if (reg->precise)
4794 					bt_clear_frame_slot(bt, fr, i);
4795 				else
4796 					reg->precise = true;
4797 			}
4798 			if (env->log.level & BPF_LOG_LEVEL2) {
4799 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4800 					     bt_frame_reg_mask(bt, fr));
4801 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4802 					fr, env->tmp_str_buf);
4803 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4804 					       bt_frame_stack_mask(bt, fr));
4805 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4806 				print_verifier_state(env, st, fr, true);
4807 			}
4808 		}
4809 
4810 		if (bt_empty(bt))
4811 			return 0;
4812 
4813 		subseq_idx = first_idx;
4814 		last_idx = st->last_insn_idx;
4815 		first_idx = st->first_insn_idx;
4816 	}
4817 
4818 	/* if we still have requested precise regs or slots, we missed
4819 	 * something (e.g., stack access through non-r10 register), so
4820 	 * fallback to marking all precise
4821 	 */
4822 	if (!bt_empty(bt)) {
4823 		mark_all_scalars_precise(env, env->cur_state);
4824 		bt_reset(bt);
4825 	}
4826 
4827 	return 0;
4828 }
4829 
4830 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4831 {
4832 	return __mark_chain_precision(env, regno);
4833 }
4834 
4835 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4836  * desired reg and stack masks across all relevant frames
4837  */
4838 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4839 {
4840 	return __mark_chain_precision(env, -1);
4841 }
4842 
4843 static bool is_spillable_regtype(enum bpf_reg_type type)
4844 {
4845 	switch (base_type(type)) {
4846 	case PTR_TO_MAP_VALUE:
4847 	case PTR_TO_STACK:
4848 	case PTR_TO_CTX:
4849 	case PTR_TO_PACKET:
4850 	case PTR_TO_PACKET_META:
4851 	case PTR_TO_PACKET_END:
4852 	case PTR_TO_FLOW_KEYS:
4853 	case CONST_PTR_TO_MAP:
4854 	case PTR_TO_SOCKET:
4855 	case PTR_TO_SOCK_COMMON:
4856 	case PTR_TO_TCP_SOCK:
4857 	case PTR_TO_XDP_SOCK:
4858 	case PTR_TO_BTF_ID:
4859 	case PTR_TO_BUF:
4860 	case PTR_TO_MEM:
4861 	case PTR_TO_FUNC:
4862 	case PTR_TO_MAP_KEY:
4863 	case PTR_TO_ARENA:
4864 		return true;
4865 	default:
4866 		return false;
4867 	}
4868 }
4869 
4870 /* Does this register contain a constant zero? */
4871 static bool register_is_null(struct bpf_reg_state *reg)
4872 {
4873 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4874 }
4875 
4876 /* check if register is a constant scalar value */
4877 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4878 {
4879 	return reg->type == SCALAR_VALUE &&
4880 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4881 }
4882 
4883 /* assuming is_reg_const() is true, return constant value of a register */
4884 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4885 {
4886 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4887 }
4888 
4889 static bool __is_pointer_value(bool allow_ptr_leaks,
4890 			       const struct bpf_reg_state *reg)
4891 {
4892 	if (allow_ptr_leaks)
4893 		return false;
4894 
4895 	return reg->type != SCALAR_VALUE;
4896 }
4897 
4898 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4899 					struct bpf_reg_state *src_reg)
4900 {
4901 	if (src_reg->type != SCALAR_VALUE)
4902 		return;
4903 
4904 	if (src_reg->id & BPF_ADD_CONST) {
4905 		/*
4906 		 * The verifier is processing rX = rY insn and
4907 		 * rY->id has special linked register already.
4908 		 * Cleared it, since multiple rX += const are not supported.
4909 		 */
4910 		src_reg->id = 0;
4911 		src_reg->off = 0;
4912 	}
4913 
4914 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
4915 		/* Ensure that src_reg has a valid ID that will be copied to
4916 		 * dst_reg and then will be used by sync_linked_regs() to
4917 		 * propagate min/max range.
4918 		 */
4919 		src_reg->id = ++env->id_gen;
4920 }
4921 
4922 /* Copy src state preserving dst->parent and dst->live fields */
4923 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4924 {
4925 	struct bpf_reg_state *parent = dst->parent;
4926 	enum bpf_reg_liveness live = dst->live;
4927 
4928 	*dst = *src;
4929 	dst->parent = parent;
4930 	dst->live = live;
4931 }
4932 
4933 static void save_register_state(struct bpf_verifier_env *env,
4934 				struct bpf_func_state *state,
4935 				int spi, struct bpf_reg_state *reg,
4936 				int size)
4937 {
4938 	int i;
4939 
4940 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4941 	if (size == BPF_REG_SIZE)
4942 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4943 
4944 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4945 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4946 
4947 	/* size < 8 bytes spill */
4948 	for (; i; i--)
4949 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4950 }
4951 
4952 static bool is_bpf_st_mem(struct bpf_insn *insn)
4953 {
4954 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4955 }
4956 
4957 static int get_reg_width(struct bpf_reg_state *reg)
4958 {
4959 	return fls64(reg->umax_value);
4960 }
4961 
4962 /* See comment for mark_fastcall_pattern_for_call() */
4963 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
4964 					  struct bpf_func_state *state, int insn_idx, int off)
4965 {
4966 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4967 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
4968 	int i;
4969 
4970 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
4971 		return;
4972 	/* access to the region [max_stack_depth .. fastcall_stack_off)
4973 	 * from something that is not a part of the fastcall pattern,
4974 	 * disable fastcall rewrites for current subprogram by setting
4975 	 * fastcall_stack_off to a value smaller than any possible offset.
4976 	 */
4977 	subprog->fastcall_stack_off = S16_MIN;
4978 	/* reset fastcall aux flags within subprogram,
4979 	 * happens at most once per subprogram
4980 	 */
4981 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
4982 		aux[i].fastcall_spills_num = 0;
4983 		aux[i].fastcall_pattern = 0;
4984 	}
4985 }
4986 
4987 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4988  * stack boundary and alignment are checked in check_mem_access()
4989  */
4990 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4991 				       /* stack frame we're writing to */
4992 				       struct bpf_func_state *state,
4993 				       int off, int size, int value_regno,
4994 				       int insn_idx)
4995 {
4996 	struct bpf_func_state *cur; /* state of the current function */
4997 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4998 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4999 	struct bpf_reg_state *reg = NULL;
5000 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
5001 
5002 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
5003 	 * so it's aligned access and [off, off + size) are within stack limits
5004 	 */
5005 	if (!env->allow_ptr_leaks &&
5006 	    is_spilled_reg(&state->stack[spi]) &&
5007 	    !is_spilled_scalar_reg(&state->stack[spi]) &&
5008 	    size != BPF_REG_SIZE) {
5009 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
5010 		return -EACCES;
5011 	}
5012 
5013 	cur = env->cur_state->frame[env->cur_state->curframe];
5014 	if (value_regno >= 0)
5015 		reg = &cur->regs[value_regno];
5016 	if (!env->bypass_spec_v4) {
5017 		bool sanitize = reg && is_spillable_regtype(reg->type);
5018 
5019 		for (i = 0; i < size; i++) {
5020 			u8 type = state->stack[spi].slot_type[i];
5021 
5022 			if (type != STACK_MISC && type != STACK_ZERO) {
5023 				sanitize = true;
5024 				break;
5025 			}
5026 		}
5027 
5028 		if (sanitize)
5029 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
5030 	}
5031 
5032 	err = destroy_if_dynptr_stack_slot(env, state, spi);
5033 	if (err)
5034 		return err;
5035 
5036 	check_fastcall_stack_contract(env, state, insn_idx, off);
5037 	mark_stack_slot_scratched(env, spi);
5038 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
5039 		bool reg_value_fits;
5040 
5041 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
5042 		/* Make sure that reg had an ID to build a relation on spill. */
5043 		if (reg_value_fits)
5044 			assign_scalar_id_before_mov(env, reg);
5045 		save_register_state(env, state, spi, reg, size);
5046 		/* Break the relation on a narrowing spill. */
5047 		if (!reg_value_fits)
5048 			state->stack[spi].spilled_ptr.id = 0;
5049 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
5050 		   env->bpf_capable) {
5051 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
5052 
5053 		memset(tmp_reg, 0, sizeof(*tmp_reg));
5054 		__mark_reg_known(tmp_reg, insn->imm);
5055 		tmp_reg->type = SCALAR_VALUE;
5056 		save_register_state(env, state, spi, tmp_reg, size);
5057 	} else if (reg && is_spillable_regtype(reg->type)) {
5058 		/* register containing pointer is being spilled into stack */
5059 		if (size != BPF_REG_SIZE) {
5060 			verbose_linfo(env, insn_idx, "; ");
5061 			verbose(env, "invalid size of register spill\n");
5062 			return -EACCES;
5063 		}
5064 		if (state != cur && reg->type == PTR_TO_STACK) {
5065 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
5066 			return -EINVAL;
5067 		}
5068 		save_register_state(env, state, spi, reg, size);
5069 	} else {
5070 		u8 type = STACK_MISC;
5071 
5072 		/* regular write of data into stack destroys any spilled ptr */
5073 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5074 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
5075 		if (is_stack_slot_special(&state->stack[spi]))
5076 			for (i = 0; i < BPF_REG_SIZE; i++)
5077 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
5078 
5079 		/* only mark the slot as written if all 8 bytes were written
5080 		 * otherwise read propagation may incorrectly stop too soon
5081 		 * when stack slots are partially written.
5082 		 * This heuristic means that read propagation will be
5083 		 * conservative, since it will add reg_live_read marks
5084 		 * to stack slots all the way to first state when programs
5085 		 * writes+reads less than 8 bytes
5086 		 */
5087 		if (size == BPF_REG_SIZE)
5088 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
5089 
5090 		/* when we zero initialize stack slots mark them as such */
5091 		if ((reg && register_is_null(reg)) ||
5092 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
5093 			/* STACK_ZERO case happened because register spill
5094 			 * wasn't properly aligned at the stack slot boundary,
5095 			 * so it's not a register spill anymore; force
5096 			 * originating register to be precise to make
5097 			 * STACK_ZERO correct for subsequent states
5098 			 */
5099 			err = mark_chain_precision(env, value_regno);
5100 			if (err)
5101 				return err;
5102 			type = STACK_ZERO;
5103 		}
5104 
5105 		/* Mark slots affected by this stack write. */
5106 		for (i = 0; i < size; i++)
5107 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
5108 		insn_flags = 0; /* not a register spill */
5109 	}
5110 
5111 	if (insn_flags)
5112 		return push_insn_history(env, env->cur_state, insn_flags, 0);
5113 	return 0;
5114 }
5115 
5116 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
5117  * known to contain a variable offset.
5118  * This function checks whether the write is permitted and conservatively
5119  * tracks the effects of the write, considering that each stack slot in the
5120  * dynamic range is potentially written to.
5121  *
5122  * 'off' includes 'regno->off'.
5123  * 'value_regno' can be -1, meaning that an unknown value is being written to
5124  * the stack.
5125  *
5126  * Spilled pointers in range are not marked as written because we don't know
5127  * what's going to be actually written. This means that read propagation for
5128  * future reads cannot be terminated by this write.
5129  *
5130  * For privileged programs, uninitialized stack slots are considered
5131  * initialized by this write (even though we don't know exactly what offsets
5132  * are going to be written to). The idea is that we don't want the verifier to
5133  * reject future reads that access slots written to through variable offsets.
5134  */
5135 static int check_stack_write_var_off(struct bpf_verifier_env *env,
5136 				     /* func where register points to */
5137 				     struct bpf_func_state *state,
5138 				     int ptr_regno, int off, int size,
5139 				     int value_regno, int insn_idx)
5140 {
5141 	struct bpf_func_state *cur; /* state of the current function */
5142 	int min_off, max_off;
5143 	int i, err;
5144 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
5145 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5146 	bool writing_zero = false;
5147 	/* set if the fact that we're writing a zero is used to let any
5148 	 * stack slots remain STACK_ZERO
5149 	 */
5150 	bool zero_used = false;
5151 
5152 	cur = env->cur_state->frame[env->cur_state->curframe];
5153 	ptr_reg = &cur->regs[ptr_regno];
5154 	min_off = ptr_reg->smin_value + off;
5155 	max_off = ptr_reg->smax_value + off + size;
5156 	if (value_regno >= 0)
5157 		value_reg = &cur->regs[value_regno];
5158 	if ((value_reg && register_is_null(value_reg)) ||
5159 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
5160 		writing_zero = true;
5161 
5162 	for (i = min_off; i < max_off; i++) {
5163 		int spi;
5164 
5165 		spi = __get_spi(i);
5166 		err = destroy_if_dynptr_stack_slot(env, state, spi);
5167 		if (err)
5168 			return err;
5169 	}
5170 
5171 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
5172 	/* Variable offset writes destroy any spilled pointers in range. */
5173 	for (i = min_off; i < max_off; i++) {
5174 		u8 new_type, *stype;
5175 		int slot, spi;
5176 
5177 		slot = -i - 1;
5178 		spi = slot / BPF_REG_SIZE;
5179 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5180 		mark_stack_slot_scratched(env, spi);
5181 
5182 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
5183 			/* Reject the write if range we may write to has not
5184 			 * been initialized beforehand. If we didn't reject
5185 			 * here, the ptr status would be erased below (even
5186 			 * though not all slots are actually overwritten),
5187 			 * possibly opening the door to leaks.
5188 			 *
5189 			 * We do however catch STACK_INVALID case below, and
5190 			 * only allow reading possibly uninitialized memory
5191 			 * later for CAP_PERFMON, as the write may not happen to
5192 			 * that slot.
5193 			 */
5194 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
5195 				insn_idx, i);
5196 			return -EINVAL;
5197 		}
5198 
5199 		/* If writing_zero and the spi slot contains a spill of value 0,
5200 		 * maintain the spill type.
5201 		 */
5202 		if (writing_zero && *stype == STACK_SPILL &&
5203 		    is_spilled_scalar_reg(&state->stack[spi])) {
5204 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
5205 
5206 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
5207 				zero_used = true;
5208 				continue;
5209 			}
5210 		}
5211 
5212 		/* Erase all other spilled pointers. */
5213 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5214 
5215 		/* Update the slot type. */
5216 		new_type = STACK_MISC;
5217 		if (writing_zero && *stype == STACK_ZERO) {
5218 			new_type = STACK_ZERO;
5219 			zero_used = true;
5220 		}
5221 		/* If the slot is STACK_INVALID, we check whether it's OK to
5222 		 * pretend that it will be initialized by this write. The slot
5223 		 * might not actually be written to, and so if we mark it as
5224 		 * initialized future reads might leak uninitialized memory.
5225 		 * For privileged programs, we will accept such reads to slots
5226 		 * that may or may not be written because, if we're reject
5227 		 * them, the error would be too confusing.
5228 		 */
5229 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
5230 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
5231 					insn_idx, i);
5232 			return -EINVAL;
5233 		}
5234 		*stype = new_type;
5235 	}
5236 	if (zero_used) {
5237 		/* backtracking doesn't work for STACK_ZERO yet. */
5238 		err = mark_chain_precision(env, value_regno);
5239 		if (err)
5240 			return err;
5241 	}
5242 	return 0;
5243 }
5244 
5245 /* When register 'dst_regno' is assigned some values from stack[min_off,
5246  * max_off), we set the register's type according to the types of the
5247  * respective stack slots. If all the stack values are known to be zeros, then
5248  * so is the destination reg. Otherwise, the register is considered to be
5249  * SCALAR. This function does not deal with register filling; the caller must
5250  * ensure that all spilled registers in the stack range have been marked as
5251  * read.
5252  */
5253 static void mark_reg_stack_read(struct bpf_verifier_env *env,
5254 				/* func where src register points to */
5255 				struct bpf_func_state *ptr_state,
5256 				int min_off, int max_off, int dst_regno)
5257 {
5258 	struct bpf_verifier_state *vstate = env->cur_state;
5259 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5260 	int i, slot, spi;
5261 	u8 *stype;
5262 	int zeros = 0;
5263 
5264 	for (i = min_off; i < max_off; i++) {
5265 		slot = -i - 1;
5266 		spi = slot / BPF_REG_SIZE;
5267 		mark_stack_slot_scratched(env, spi);
5268 		stype = ptr_state->stack[spi].slot_type;
5269 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
5270 			break;
5271 		zeros++;
5272 	}
5273 	if (zeros == max_off - min_off) {
5274 		/* Any access_size read into register is zero extended,
5275 		 * so the whole register == const_zero.
5276 		 */
5277 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
5278 	} else {
5279 		/* have read misc data from the stack */
5280 		mark_reg_unknown(env, state->regs, dst_regno);
5281 	}
5282 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5283 }
5284 
5285 /* Read the stack at 'off' and put the results into the register indicated by
5286  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
5287  * spilled reg.
5288  *
5289  * 'dst_regno' can be -1, meaning that the read value is not going to a
5290  * register.
5291  *
5292  * The access is assumed to be within the current stack bounds.
5293  */
5294 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
5295 				      /* func where src register points to */
5296 				      struct bpf_func_state *reg_state,
5297 				      int off, int size, int dst_regno)
5298 {
5299 	struct bpf_verifier_state *vstate = env->cur_state;
5300 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5301 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
5302 	struct bpf_reg_state *reg;
5303 	u8 *stype, type;
5304 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
5305 
5306 	stype = reg_state->stack[spi].slot_type;
5307 	reg = &reg_state->stack[spi].spilled_ptr;
5308 
5309 	mark_stack_slot_scratched(env, spi);
5310 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
5311 
5312 	if (is_spilled_reg(&reg_state->stack[spi])) {
5313 		u8 spill_size = 1;
5314 
5315 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
5316 			spill_size++;
5317 
5318 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
5319 			if (reg->type != SCALAR_VALUE) {
5320 				verbose_linfo(env, env->insn_idx, "; ");
5321 				verbose(env, "invalid size of register fill\n");
5322 				return -EACCES;
5323 			}
5324 
5325 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5326 			if (dst_regno < 0)
5327 				return 0;
5328 
5329 			if (size <= spill_size &&
5330 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
5331 				/* The earlier check_reg_arg() has decided the
5332 				 * subreg_def for this insn.  Save it first.
5333 				 */
5334 				s32 subreg_def = state->regs[dst_regno].subreg_def;
5335 
5336 				copy_register_state(&state->regs[dst_regno], reg);
5337 				state->regs[dst_regno].subreg_def = subreg_def;
5338 
5339 				/* Break the relation on a narrowing fill.
5340 				 * coerce_reg_to_size will adjust the boundaries.
5341 				 */
5342 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
5343 					state->regs[dst_regno].id = 0;
5344 			} else {
5345 				int spill_cnt = 0, zero_cnt = 0;
5346 
5347 				for (i = 0; i < size; i++) {
5348 					type = stype[(slot - i) % BPF_REG_SIZE];
5349 					if (type == STACK_SPILL) {
5350 						spill_cnt++;
5351 						continue;
5352 					}
5353 					if (type == STACK_MISC)
5354 						continue;
5355 					if (type == STACK_ZERO) {
5356 						zero_cnt++;
5357 						continue;
5358 					}
5359 					if (type == STACK_INVALID && env->allow_uninit_stack)
5360 						continue;
5361 					verbose(env, "invalid read from stack off %d+%d size %d\n",
5362 						off, i, size);
5363 					return -EACCES;
5364 				}
5365 
5366 				if (spill_cnt == size &&
5367 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
5368 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5369 					/* this IS register fill, so keep insn_flags */
5370 				} else if (zero_cnt == size) {
5371 					/* similarly to mark_reg_stack_read(), preserve zeroes */
5372 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5373 					insn_flags = 0; /* not restoring original register state */
5374 				} else {
5375 					mark_reg_unknown(env, state->regs, dst_regno);
5376 					insn_flags = 0; /* not restoring original register state */
5377 				}
5378 			}
5379 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5380 		} else if (dst_regno >= 0) {
5381 			/* restore register state from stack */
5382 			copy_register_state(&state->regs[dst_regno], reg);
5383 			/* mark reg as written since spilled pointer state likely
5384 			 * has its liveness marks cleared by is_state_visited()
5385 			 * which resets stack/reg liveness for state transitions
5386 			 */
5387 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5388 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5389 			/* If dst_regno==-1, the caller is asking us whether
5390 			 * it is acceptable to use this value as a SCALAR_VALUE
5391 			 * (e.g. for XADD).
5392 			 * We must not allow unprivileged callers to do that
5393 			 * with spilled pointers.
5394 			 */
5395 			verbose(env, "leaking pointer from stack off %d\n",
5396 				off);
5397 			return -EACCES;
5398 		}
5399 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5400 	} else {
5401 		for (i = 0; i < size; i++) {
5402 			type = stype[(slot - i) % BPF_REG_SIZE];
5403 			if (type == STACK_MISC)
5404 				continue;
5405 			if (type == STACK_ZERO)
5406 				continue;
5407 			if (type == STACK_INVALID && env->allow_uninit_stack)
5408 				continue;
5409 			verbose(env, "invalid read from stack off %d+%d size %d\n",
5410 				off, i, size);
5411 			return -EACCES;
5412 		}
5413 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5414 		if (dst_regno >= 0)
5415 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5416 		insn_flags = 0; /* we are not restoring spilled register */
5417 	}
5418 	if (insn_flags)
5419 		return push_insn_history(env, env->cur_state, insn_flags, 0);
5420 	return 0;
5421 }
5422 
5423 enum bpf_access_src {
5424 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5425 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
5426 };
5427 
5428 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5429 					 int regno, int off, int access_size,
5430 					 bool zero_size_allowed,
5431 					 enum bpf_access_type type,
5432 					 struct bpf_call_arg_meta *meta);
5433 
5434 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5435 {
5436 	return cur_regs(env) + regno;
5437 }
5438 
5439 /* Read the stack at 'ptr_regno + off' and put the result into the register
5440  * 'dst_regno'.
5441  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5442  * but not its variable offset.
5443  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5444  *
5445  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5446  * filling registers (i.e. reads of spilled register cannot be detected when
5447  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5448  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5449  * offset; for a fixed offset check_stack_read_fixed_off should be used
5450  * instead.
5451  */
5452 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5453 				    int ptr_regno, int off, int size, int dst_regno)
5454 {
5455 	/* The state of the source register. */
5456 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5457 	struct bpf_func_state *ptr_state = func(env, reg);
5458 	int err;
5459 	int min_off, max_off;
5460 
5461 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5462 	 */
5463 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5464 					    false, BPF_READ, NULL);
5465 	if (err)
5466 		return err;
5467 
5468 	min_off = reg->smin_value + off;
5469 	max_off = reg->smax_value + off;
5470 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5471 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5472 	return 0;
5473 }
5474 
5475 /* check_stack_read dispatches to check_stack_read_fixed_off or
5476  * check_stack_read_var_off.
5477  *
5478  * The caller must ensure that the offset falls within the allocated stack
5479  * bounds.
5480  *
5481  * 'dst_regno' is a register which will receive the value from the stack. It
5482  * can be -1, meaning that the read value is not going to a register.
5483  */
5484 static int check_stack_read(struct bpf_verifier_env *env,
5485 			    int ptr_regno, int off, int size,
5486 			    int dst_regno)
5487 {
5488 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5489 	struct bpf_func_state *state = func(env, reg);
5490 	int err;
5491 	/* Some accesses are only permitted with a static offset. */
5492 	bool var_off = !tnum_is_const(reg->var_off);
5493 
5494 	/* The offset is required to be static when reads don't go to a
5495 	 * register, in order to not leak pointers (see
5496 	 * check_stack_read_fixed_off).
5497 	 */
5498 	if (dst_regno < 0 && var_off) {
5499 		char tn_buf[48];
5500 
5501 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5502 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5503 			tn_buf, off, size);
5504 		return -EACCES;
5505 	}
5506 	/* Variable offset is prohibited for unprivileged mode for simplicity
5507 	 * since it requires corresponding support in Spectre masking for stack
5508 	 * ALU. See also retrieve_ptr_limit(). The check in
5509 	 * check_stack_access_for_ptr_arithmetic() called by
5510 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5511 	 * with variable offsets, therefore no check is required here. Further,
5512 	 * just checking it here would be insufficient as speculative stack
5513 	 * writes could still lead to unsafe speculative behaviour.
5514 	 */
5515 	if (!var_off) {
5516 		off += reg->var_off.value;
5517 		err = check_stack_read_fixed_off(env, state, off, size,
5518 						 dst_regno);
5519 	} else {
5520 		/* Variable offset stack reads need more conservative handling
5521 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5522 		 * branch.
5523 		 */
5524 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5525 					       dst_regno);
5526 	}
5527 	return err;
5528 }
5529 
5530 
5531 /* check_stack_write dispatches to check_stack_write_fixed_off or
5532  * check_stack_write_var_off.
5533  *
5534  * 'ptr_regno' is the register used as a pointer into the stack.
5535  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5536  * 'value_regno' is the register whose value we're writing to the stack. It can
5537  * be -1, meaning that we're not writing from a register.
5538  *
5539  * The caller must ensure that the offset falls within the maximum stack size.
5540  */
5541 static int check_stack_write(struct bpf_verifier_env *env,
5542 			     int ptr_regno, int off, int size,
5543 			     int value_regno, int insn_idx)
5544 {
5545 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5546 	struct bpf_func_state *state = func(env, reg);
5547 	int err;
5548 
5549 	if (tnum_is_const(reg->var_off)) {
5550 		off += reg->var_off.value;
5551 		err = check_stack_write_fixed_off(env, state, off, size,
5552 						  value_regno, insn_idx);
5553 	} else {
5554 		/* Variable offset stack reads need more conservative handling
5555 		 * than fixed offset ones.
5556 		 */
5557 		err = check_stack_write_var_off(env, state,
5558 						ptr_regno, off, size,
5559 						value_regno, insn_idx);
5560 	}
5561 	return err;
5562 }
5563 
5564 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5565 				 int off, int size, enum bpf_access_type type)
5566 {
5567 	struct bpf_reg_state *regs = cur_regs(env);
5568 	struct bpf_map *map = regs[regno].map_ptr;
5569 	u32 cap = bpf_map_flags_to_cap(map);
5570 
5571 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5572 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5573 			map->value_size, off, size);
5574 		return -EACCES;
5575 	}
5576 
5577 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5578 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5579 			map->value_size, off, size);
5580 		return -EACCES;
5581 	}
5582 
5583 	return 0;
5584 }
5585 
5586 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5587 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5588 			      int off, int size, u32 mem_size,
5589 			      bool zero_size_allowed)
5590 {
5591 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5592 	struct bpf_reg_state *reg;
5593 
5594 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5595 		return 0;
5596 
5597 	reg = &cur_regs(env)[regno];
5598 	switch (reg->type) {
5599 	case PTR_TO_MAP_KEY:
5600 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5601 			mem_size, off, size);
5602 		break;
5603 	case PTR_TO_MAP_VALUE:
5604 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5605 			mem_size, off, size);
5606 		break;
5607 	case PTR_TO_PACKET:
5608 	case PTR_TO_PACKET_META:
5609 	case PTR_TO_PACKET_END:
5610 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5611 			off, size, regno, reg->id, off, mem_size);
5612 		break;
5613 	case PTR_TO_MEM:
5614 	default:
5615 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5616 			mem_size, off, size);
5617 	}
5618 
5619 	return -EACCES;
5620 }
5621 
5622 /* check read/write into a memory region with possible variable offset */
5623 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5624 				   int off, int size, u32 mem_size,
5625 				   bool zero_size_allowed)
5626 {
5627 	struct bpf_verifier_state *vstate = env->cur_state;
5628 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5629 	struct bpf_reg_state *reg = &state->regs[regno];
5630 	int err;
5631 
5632 	/* We may have adjusted the register pointing to memory region, so we
5633 	 * need to try adding each of min_value and max_value to off
5634 	 * to make sure our theoretical access will be safe.
5635 	 *
5636 	 * The minimum value is only important with signed
5637 	 * comparisons where we can't assume the floor of a
5638 	 * value is 0.  If we are using signed variables for our
5639 	 * index'es we need to make sure that whatever we use
5640 	 * will have a set floor within our range.
5641 	 */
5642 	if (reg->smin_value < 0 &&
5643 	    (reg->smin_value == S64_MIN ||
5644 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5645 	      reg->smin_value + off < 0)) {
5646 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5647 			regno);
5648 		return -EACCES;
5649 	}
5650 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5651 				 mem_size, zero_size_allowed);
5652 	if (err) {
5653 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5654 			regno);
5655 		return err;
5656 	}
5657 
5658 	/* If we haven't set a max value then we need to bail since we can't be
5659 	 * sure we won't do bad things.
5660 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5661 	 */
5662 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5663 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5664 			regno);
5665 		return -EACCES;
5666 	}
5667 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5668 				 mem_size, zero_size_allowed);
5669 	if (err) {
5670 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5671 			regno);
5672 		return err;
5673 	}
5674 
5675 	return 0;
5676 }
5677 
5678 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5679 			       const struct bpf_reg_state *reg, int regno,
5680 			       bool fixed_off_ok)
5681 {
5682 	/* Access to this pointer-typed register or passing it to a helper
5683 	 * is only allowed in its original, unmodified form.
5684 	 */
5685 
5686 	if (reg->off < 0) {
5687 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5688 			reg_type_str(env, reg->type), regno, reg->off);
5689 		return -EACCES;
5690 	}
5691 
5692 	if (!fixed_off_ok && reg->off) {
5693 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5694 			reg_type_str(env, reg->type), regno, reg->off);
5695 		return -EACCES;
5696 	}
5697 
5698 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5699 		char tn_buf[48];
5700 
5701 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5702 		verbose(env, "variable %s access var_off=%s disallowed\n",
5703 			reg_type_str(env, reg->type), tn_buf);
5704 		return -EACCES;
5705 	}
5706 
5707 	return 0;
5708 }
5709 
5710 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5711 		             const struct bpf_reg_state *reg, int regno)
5712 {
5713 	return __check_ptr_off_reg(env, reg, regno, false);
5714 }
5715 
5716 static int map_kptr_match_type(struct bpf_verifier_env *env,
5717 			       struct btf_field *kptr_field,
5718 			       struct bpf_reg_state *reg, u32 regno)
5719 {
5720 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5721 	int perm_flags;
5722 	const char *reg_name = "";
5723 
5724 	if (btf_is_kernel(reg->btf)) {
5725 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5726 
5727 		/* Only unreferenced case accepts untrusted pointers */
5728 		if (kptr_field->type == BPF_KPTR_UNREF)
5729 			perm_flags |= PTR_UNTRUSTED;
5730 	} else {
5731 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5732 		if (kptr_field->type == BPF_KPTR_PERCPU)
5733 			perm_flags |= MEM_PERCPU;
5734 	}
5735 
5736 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5737 		goto bad_type;
5738 
5739 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5740 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5741 
5742 	/* For ref_ptr case, release function check should ensure we get one
5743 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5744 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5745 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5746 	 * reg->off and reg->ref_obj_id are not needed here.
5747 	 */
5748 	if (__check_ptr_off_reg(env, reg, regno, true))
5749 		return -EACCES;
5750 
5751 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5752 	 * we also need to take into account the reg->off.
5753 	 *
5754 	 * We want to support cases like:
5755 	 *
5756 	 * struct foo {
5757 	 *         struct bar br;
5758 	 *         struct baz bz;
5759 	 * };
5760 	 *
5761 	 * struct foo *v;
5762 	 * v = func();	      // PTR_TO_BTF_ID
5763 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5764 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5765 	 *                    // first member type of struct after comparison fails
5766 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5767 	 *                    // to match type
5768 	 *
5769 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5770 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5771 	 * the struct to match type against first member of struct, i.e. reject
5772 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5773 	 * strict mode to true for type match.
5774 	 */
5775 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5776 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5777 				  kptr_field->type != BPF_KPTR_UNREF))
5778 		goto bad_type;
5779 	return 0;
5780 bad_type:
5781 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5782 		reg_type_str(env, reg->type), reg_name);
5783 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5784 	if (kptr_field->type == BPF_KPTR_UNREF)
5785 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5786 			targ_name);
5787 	else
5788 		verbose(env, "\n");
5789 	return -EINVAL;
5790 }
5791 
5792 static bool in_sleepable(struct bpf_verifier_env *env)
5793 {
5794 	return env->prog->sleepable ||
5795 	       (env->cur_state && env->cur_state->in_sleepable);
5796 }
5797 
5798 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5799  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5800  */
5801 static bool in_rcu_cs(struct bpf_verifier_env *env)
5802 {
5803 	return env->cur_state->active_rcu_lock ||
5804 	       env->cur_state->active_locks ||
5805 	       !in_sleepable(env);
5806 }
5807 
5808 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5809 BTF_SET_START(rcu_protected_types)
5810 #ifdef CONFIG_NET
5811 BTF_ID(struct, prog_test_ref_kfunc)
5812 #endif
5813 #ifdef CONFIG_CGROUPS
5814 BTF_ID(struct, cgroup)
5815 #endif
5816 #ifdef CONFIG_BPF_JIT
5817 BTF_ID(struct, bpf_cpumask)
5818 #endif
5819 BTF_ID(struct, task_struct)
5820 #ifdef CONFIG_CRYPTO
5821 BTF_ID(struct, bpf_crypto_ctx)
5822 #endif
5823 BTF_SET_END(rcu_protected_types)
5824 
5825 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5826 {
5827 	if (!btf_is_kernel(btf))
5828 		return true;
5829 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5830 }
5831 
5832 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5833 {
5834 	struct btf_struct_meta *meta;
5835 
5836 	if (btf_is_kernel(kptr_field->kptr.btf))
5837 		return NULL;
5838 
5839 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5840 				    kptr_field->kptr.btf_id);
5841 
5842 	return meta ? meta->record : NULL;
5843 }
5844 
5845 static bool rcu_safe_kptr(const struct btf_field *field)
5846 {
5847 	const struct btf_field_kptr *kptr = &field->kptr;
5848 
5849 	return field->type == BPF_KPTR_PERCPU ||
5850 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5851 }
5852 
5853 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5854 {
5855 	struct btf_record *rec;
5856 	u32 ret;
5857 
5858 	ret = PTR_MAYBE_NULL;
5859 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5860 		ret |= MEM_RCU;
5861 		if (kptr_field->type == BPF_KPTR_PERCPU)
5862 			ret |= MEM_PERCPU;
5863 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5864 			ret |= MEM_ALLOC;
5865 
5866 		rec = kptr_pointee_btf_record(kptr_field);
5867 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5868 			ret |= NON_OWN_REF;
5869 	} else {
5870 		ret |= PTR_UNTRUSTED;
5871 	}
5872 
5873 	return ret;
5874 }
5875 
5876 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
5877 			    struct btf_field *field)
5878 {
5879 	struct bpf_reg_state *reg;
5880 	const struct btf_type *t;
5881 
5882 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
5883 	mark_reg_known_zero(env, cur_regs(env), regno);
5884 	reg = reg_state(env, regno);
5885 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5886 	reg->mem_size = t->size;
5887 	reg->id = ++env->id_gen;
5888 
5889 	return 0;
5890 }
5891 
5892 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5893 				 int value_regno, int insn_idx,
5894 				 struct btf_field *kptr_field)
5895 {
5896 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5897 	int class = BPF_CLASS(insn->code);
5898 	struct bpf_reg_state *val_reg;
5899 
5900 	/* Things we already checked for in check_map_access and caller:
5901 	 *  - Reject cases where variable offset may touch kptr
5902 	 *  - size of access (must be BPF_DW)
5903 	 *  - tnum_is_const(reg->var_off)
5904 	 *  - kptr_field->offset == off + reg->var_off.value
5905 	 */
5906 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5907 	if (BPF_MODE(insn->code) != BPF_MEM) {
5908 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5909 		return -EACCES;
5910 	}
5911 
5912 	/* We only allow loading referenced kptr, since it will be marked as
5913 	 * untrusted, similar to unreferenced kptr.
5914 	 */
5915 	if (class != BPF_LDX &&
5916 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5917 		verbose(env, "store to referenced kptr disallowed\n");
5918 		return -EACCES;
5919 	}
5920 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
5921 		verbose(env, "store to uptr disallowed\n");
5922 		return -EACCES;
5923 	}
5924 
5925 	if (class == BPF_LDX) {
5926 		if (kptr_field->type == BPF_UPTR)
5927 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
5928 
5929 		/* We can simply mark the value_regno receiving the pointer
5930 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5931 		 */
5932 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5933 				kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5934 	} else if (class == BPF_STX) {
5935 		val_reg = reg_state(env, value_regno);
5936 		if (!register_is_null(val_reg) &&
5937 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5938 			return -EACCES;
5939 	} else if (class == BPF_ST) {
5940 		if (insn->imm) {
5941 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5942 				kptr_field->offset);
5943 			return -EACCES;
5944 		}
5945 	} else {
5946 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5947 		return -EACCES;
5948 	}
5949 	return 0;
5950 }
5951 
5952 /* check read/write into a map element with possible variable offset */
5953 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5954 			    int off, int size, bool zero_size_allowed,
5955 			    enum bpf_access_src src)
5956 {
5957 	struct bpf_verifier_state *vstate = env->cur_state;
5958 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5959 	struct bpf_reg_state *reg = &state->regs[regno];
5960 	struct bpf_map *map = reg->map_ptr;
5961 	struct btf_record *rec;
5962 	int err, i;
5963 
5964 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5965 				      zero_size_allowed);
5966 	if (err)
5967 		return err;
5968 
5969 	if (IS_ERR_OR_NULL(map->record))
5970 		return 0;
5971 	rec = map->record;
5972 	for (i = 0; i < rec->cnt; i++) {
5973 		struct btf_field *field = &rec->fields[i];
5974 		u32 p = field->offset;
5975 
5976 		/* If any part of a field  can be touched by load/store, reject
5977 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5978 		 * it is sufficient to check x1 < y2 && y1 < x2.
5979 		 */
5980 		if (reg->smin_value + off < p + field->size &&
5981 		    p < reg->umax_value + off + size) {
5982 			switch (field->type) {
5983 			case BPF_KPTR_UNREF:
5984 			case BPF_KPTR_REF:
5985 			case BPF_KPTR_PERCPU:
5986 			case BPF_UPTR:
5987 				if (src != ACCESS_DIRECT) {
5988 					verbose(env, "%s cannot be accessed indirectly by helper\n",
5989 						btf_field_type_name(field->type));
5990 					return -EACCES;
5991 				}
5992 				if (!tnum_is_const(reg->var_off)) {
5993 					verbose(env, "%s access cannot have variable offset\n",
5994 						btf_field_type_name(field->type));
5995 					return -EACCES;
5996 				}
5997 				if (p != off + reg->var_off.value) {
5998 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
5999 						btf_field_type_name(field->type),
6000 						p, off + reg->var_off.value);
6001 					return -EACCES;
6002 				}
6003 				if (size != bpf_size_to_bytes(BPF_DW)) {
6004 					verbose(env, "%s access size must be BPF_DW\n",
6005 						btf_field_type_name(field->type));
6006 					return -EACCES;
6007 				}
6008 				break;
6009 			default:
6010 				verbose(env, "%s cannot be accessed directly by load/store\n",
6011 					btf_field_type_name(field->type));
6012 				return -EACCES;
6013 			}
6014 		}
6015 	}
6016 	return 0;
6017 }
6018 
6019 #define MAX_PACKET_OFF 0xffff
6020 
6021 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
6022 				       const struct bpf_call_arg_meta *meta,
6023 				       enum bpf_access_type t)
6024 {
6025 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6026 
6027 	switch (prog_type) {
6028 	/* Program types only with direct read access go here! */
6029 	case BPF_PROG_TYPE_LWT_IN:
6030 	case BPF_PROG_TYPE_LWT_OUT:
6031 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
6032 	case BPF_PROG_TYPE_SK_REUSEPORT:
6033 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6034 	case BPF_PROG_TYPE_CGROUP_SKB:
6035 		if (t == BPF_WRITE)
6036 			return false;
6037 		fallthrough;
6038 
6039 	/* Program types with direct read + write access go here! */
6040 	case BPF_PROG_TYPE_SCHED_CLS:
6041 	case BPF_PROG_TYPE_SCHED_ACT:
6042 	case BPF_PROG_TYPE_XDP:
6043 	case BPF_PROG_TYPE_LWT_XMIT:
6044 	case BPF_PROG_TYPE_SK_SKB:
6045 	case BPF_PROG_TYPE_SK_MSG:
6046 		if (meta)
6047 			return meta->pkt_access;
6048 
6049 		env->seen_direct_write = true;
6050 		return true;
6051 
6052 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
6053 		if (t == BPF_WRITE)
6054 			env->seen_direct_write = true;
6055 
6056 		return true;
6057 
6058 	default:
6059 		return false;
6060 	}
6061 }
6062 
6063 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
6064 			       int size, bool zero_size_allowed)
6065 {
6066 	struct bpf_reg_state *regs = cur_regs(env);
6067 	struct bpf_reg_state *reg = &regs[regno];
6068 	int err;
6069 
6070 	/* We may have added a variable offset to the packet pointer; but any
6071 	 * reg->range we have comes after that.  We are only checking the fixed
6072 	 * offset.
6073 	 */
6074 
6075 	/* We don't allow negative numbers, because we aren't tracking enough
6076 	 * detail to prove they're safe.
6077 	 */
6078 	if (reg->smin_value < 0) {
6079 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6080 			regno);
6081 		return -EACCES;
6082 	}
6083 
6084 	err = reg->range < 0 ? -EINVAL :
6085 	      __check_mem_access(env, regno, off, size, reg->range,
6086 				 zero_size_allowed);
6087 	if (err) {
6088 		verbose(env, "R%d offset is outside of the packet\n", regno);
6089 		return err;
6090 	}
6091 
6092 	/* __check_mem_access has made sure "off + size - 1" is within u16.
6093 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
6094 	 * otherwise find_good_pkt_pointers would have refused to set range info
6095 	 * that __check_mem_access would have rejected this pkt access.
6096 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
6097 	 */
6098 	env->prog->aux->max_pkt_offset =
6099 		max_t(u32, env->prog->aux->max_pkt_offset,
6100 		      off + reg->umax_value + size - 1);
6101 
6102 	return err;
6103 }
6104 
6105 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
6106 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
6107 			    enum bpf_access_type t, struct bpf_insn_access_aux *info)
6108 {
6109 	if (env->ops->is_valid_access &&
6110 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
6111 		/* A non zero info.ctx_field_size indicates that this field is a
6112 		 * candidate for later verifier transformation to load the whole
6113 		 * field and then apply a mask when accessed with a narrower
6114 		 * access than actual ctx access size. A zero info.ctx_field_size
6115 		 * will only allow for whole field access and rejects any other
6116 		 * type of narrower access.
6117 		 */
6118 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
6119 			if (info->ref_obj_id &&
6120 			    !find_reference_state(env->cur_state, info->ref_obj_id)) {
6121 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
6122 					off);
6123 				return -EACCES;
6124 			}
6125 		} else {
6126 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
6127 		}
6128 		/* remember the offset of last byte accessed in ctx */
6129 		if (env->prog->aux->max_ctx_offset < off + size)
6130 			env->prog->aux->max_ctx_offset = off + size;
6131 		return 0;
6132 	}
6133 
6134 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
6135 	return -EACCES;
6136 }
6137 
6138 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
6139 				  int size)
6140 {
6141 	if (size < 0 || off < 0 ||
6142 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
6143 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
6144 			off, size);
6145 		return -EACCES;
6146 	}
6147 	return 0;
6148 }
6149 
6150 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
6151 			     u32 regno, int off, int size,
6152 			     enum bpf_access_type t)
6153 {
6154 	struct bpf_reg_state *regs = cur_regs(env);
6155 	struct bpf_reg_state *reg = &regs[regno];
6156 	struct bpf_insn_access_aux info = {};
6157 	bool valid;
6158 
6159 	if (reg->smin_value < 0) {
6160 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6161 			regno);
6162 		return -EACCES;
6163 	}
6164 
6165 	switch (reg->type) {
6166 	case PTR_TO_SOCK_COMMON:
6167 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
6168 		break;
6169 	case PTR_TO_SOCKET:
6170 		valid = bpf_sock_is_valid_access(off, size, t, &info);
6171 		break;
6172 	case PTR_TO_TCP_SOCK:
6173 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
6174 		break;
6175 	case PTR_TO_XDP_SOCK:
6176 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
6177 		break;
6178 	default:
6179 		valid = false;
6180 	}
6181 
6182 
6183 	if (valid) {
6184 		env->insn_aux_data[insn_idx].ctx_field_size =
6185 			info.ctx_field_size;
6186 		return 0;
6187 	}
6188 
6189 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
6190 		regno, reg_type_str(env, reg->type), off, size);
6191 
6192 	return -EACCES;
6193 }
6194 
6195 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
6196 {
6197 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
6198 }
6199 
6200 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
6201 {
6202 	const struct bpf_reg_state *reg = reg_state(env, regno);
6203 
6204 	return reg->type == PTR_TO_CTX;
6205 }
6206 
6207 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
6208 {
6209 	const struct bpf_reg_state *reg = reg_state(env, regno);
6210 
6211 	return type_is_sk_pointer(reg->type);
6212 }
6213 
6214 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
6215 {
6216 	const struct bpf_reg_state *reg = reg_state(env, regno);
6217 
6218 	return type_is_pkt_pointer(reg->type);
6219 }
6220 
6221 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
6222 {
6223 	const struct bpf_reg_state *reg = reg_state(env, regno);
6224 
6225 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
6226 	return reg->type == PTR_TO_FLOW_KEYS;
6227 }
6228 
6229 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
6230 {
6231 	const struct bpf_reg_state *reg = reg_state(env, regno);
6232 
6233 	return reg->type == PTR_TO_ARENA;
6234 }
6235 
6236 /* Return false if @regno contains a pointer whose type isn't supported for
6237  * atomic instruction @insn.
6238  */
6239 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
6240 			       struct bpf_insn *insn)
6241 {
6242 	if (is_ctx_reg(env, regno))
6243 		return false;
6244 	if (is_pkt_reg(env, regno))
6245 		return false;
6246 	if (is_flow_key_reg(env, regno))
6247 		return false;
6248 	if (is_sk_reg(env, regno))
6249 		return false;
6250 	if (is_arena_reg(env, regno))
6251 		return bpf_jit_supports_insn(insn, true);
6252 
6253 	return true;
6254 }
6255 
6256 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
6257 #ifdef CONFIG_NET
6258 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
6259 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6260 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
6261 #endif
6262 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
6263 };
6264 
6265 static bool is_trusted_reg(const struct bpf_reg_state *reg)
6266 {
6267 	/* A referenced register is always trusted. */
6268 	if (reg->ref_obj_id)
6269 		return true;
6270 
6271 	/* Types listed in the reg2btf_ids are always trusted */
6272 	if (reg2btf_ids[base_type(reg->type)] &&
6273 	    !bpf_type_has_unsafe_modifiers(reg->type))
6274 		return true;
6275 
6276 	/* If a register is not referenced, it is trusted if it has the
6277 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
6278 	 * other type modifiers may be safe, but we elect to take an opt-in
6279 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
6280 	 * not.
6281 	 *
6282 	 * Eventually, we should make PTR_TRUSTED the single source of truth
6283 	 * for whether a register is trusted.
6284 	 */
6285 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
6286 	       !bpf_type_has_unsafe_modifiers(reg->type);
6287 }
6288 
6289 static bool is_rcu_reg(const struct bpf_reg_state *reg)
6290 {
6291 	return reg->type & MEM_RCU;
6292 }
6293 
6294 static void clear_trusted_flags(enum bpf_type_flag *flag)
6295 {
6296 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
6297 }
6298 
6299 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
6300 				   const struct bpf_reg_state *reg,
6301 				   int off, int size, bool strict)
6302 {
6303 	struct tnum reg_off;
6304 	int ip_align;
6305 
6306 	/* Byte size accesses are always allowed. */
6307 	if (!strict || size == 1)
6308 		return 0;
6309 
6310 	/* For platforms that do not have a Kconfig enabling
6311 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
6312 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
6313 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
6314 	 * to this code only in strict mode where we want to emulate
6315 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
6316 	 * unconditional IP align value of '2'.
6317 	 */
6318 	ip_align = 2;
6319 
6320 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
6321 	if (!tnum_is_aligned(reg_off, size)) {
6322 		char tn_buf[48];
6323 
6324 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6325 		verbose(env,
6326 			"misaligned packet access off %d+%s+%d+%d size %d\n",
6327 			ip_align, tn_buf, reg->off, off, size);
6328 		return -EACCES;
6329 	}
6330 
6331 	return 0;
6332 }
6333 
6334 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
6335 				       const struct bpf_reg_state *reg,
6336 				       const char *pointer_desc,
6337 				       int off, int size, bool strict)
6338 {
6339 	struct tnum reg_off;
6340 
6341 	/* Byte size accesses are always allowed. */
6342 	if (!strict || size == 1)
6343 		return 0;
6344 
6345 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
6346 	if (!tnum_is_aligned(reg_off, size)) {
6347 		char tn_buf[48];
6348 
6349 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6350 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
6351 			pointer_desc, tn_buf, reg->off, off, size);
6352 		return -EACCES;
6353 	}
6354 
6355 	return 0;
6356 }
6357 
6358 static int check_ptr_alignment(struct bpf_verifier_env *env,
6359 			       const struct bpf_reg_state *reg, int off,
6360 			       int size, bool strict_alignment_once)
6361 {
6362 	bool strict = env->strict_alignment || strict_alignment_once;
6363 	const char *pointer_desc = "";
6364 
6365 	switch (reg->type) {
6366 	case PTR_TO_PACKET:
6367 	case PTR_TO_PACKET_META:
6368 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
6369 		 * right in front, treat it the very same way.
6370 		 */
6371 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
6372 	case PTR_TO_FLOW_KEYS:
6373 		pointer_desc = "flow keys ";
6374 		break;
6375 	case PTR_TO_MAP_KEY:
6376 		pointer_desc = "key ";
6377 		break;
6378 	case PTR_TO_MAP_VALUE:
6379 		pointer_desc = "value ";
6380 		break;
6381 	case PTR_TO_CTX:
6382 		pointer_desc = "context ";
6383 		break;
6384 	case PTR_TO_STACK:
6385 		pointer_desc = "stack ";
6386 		/* The stack spill tracking logic in check_stack_write_fixed_off()
6387 		 * and check_stack_read_fixed_off() relies on stack accesses being
6388 		 * aligned.
6389 		 */
6390 		strict = true;
6391 		break;
6392 	case PTR_TO_SOCKET:
6393 		pointer_desc = "sock ";
6394 		break;
6395 	case PTR_TO_SOCK_COMMON:
6396 		pointer_desc = "sock_common ";
6397 		break;
6398 	case PTR_TO_TCP_SOCK:
6399 		pointer_desc = "tcp_sock ";
6400 		break;
6401 	case PTR_TO_XDP_SOCK:
6402 		pointer_desc = "xdp_sock ";
6403 		break;
6404 	case PTR_TO_ARENA:
6405 		return 0;
6406 	default:
6407 		break;
6408 	}
6409 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
6410 					   strict);
6411 }
6412 
6413 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
6414 {
6415 	if (!bpf_jit_supports_private_stack())
6416 		return NO_PRIV_STACK;
6417 
6418 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
6419 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
6420 	 * explicitly.
6421 	 */
6422 	switch (prog->type) {
6423 	case BPF_PROG_TYPE_KPROBE:
6424 	case BPF_PROG_TYPE_TRACEPOINT:
6425 	case BPF_PROG_TYPE_PERF_EVENT:
6426 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6427 		return PRIV_STACK_ADAPTIVE;
6428 	case BPF_PROG_TYPE_TRACING:
6429 	case BPF_PROG_TYPE_LSM:
6430 	case BPF_PROG_TYPE_STRUCT_OPS:
6431 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
6432 			return PRIV_STACK_ADAPTIVE;
6433 		fallthrough;
6434 	default:
6435 		break;
6436 	}
6437 
6438 	return NO_PRIV_STACK;
6439 }
6440 
6441 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
6442 {
6443 	if (env->prog->jit_requested)
6444 		return round_up(stack_depth, 16);
6445 
6446 	/* round up to 32-bytes, since this is granularity
6447 	 * of interpreter stack size
6448 	 */
6449 	return round_up(max_t(u32, stack_depth, 1), 32);
6450 }
6451 
6452 /* starting from main bpf function walk all instructions of the function
6453  * and recursively walk all callees that given function can call.
6454  * Ignore jump and exit insns.
6455  * Since recursion is prevented by check_cfg() this algorithm
6456  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6457  */
6458 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
6459 					 bool priv_stack_supported)
6460 {
6461 	struct bpf_subprog_info *subprog = env->subprog_info;
6462 	struct bpf_insn *insn = env->prog->insnsi;
6463 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
6464 	bool tail_call_reachable = false;
6465 	int ret_insn[MAX_CALL_FRAMES];
6466 	int ret_prog[MAX_CALL_FRAMES];
6467 	int j;
6468 
6469 	i = subprog[idx].start;
6470 	if (!priv_stack_supported)
6471 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6472 process_func:
6473 	/* protect against potential stack overflow that might happen when
6474 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6475 	 * depth for such case down to 256 so that the worst case scenario
6476 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
6477 	 * 8k).
6478 	 *
6479 	 * To get the idea what might happen, see an example:
6480 	 * func1 -> sub rsp, 128
6481 	 *  subfunc1 -> sub rsp, 256
6482 	 *  tailcall1 -> add rsp, 256
6483 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6484 	 *   subfunc2 -> sub rsp, 64
6485 	 *   subfunc22 -> sub rsp, 128
6486 	 *   tailcall2 -> add rsp, 128
6487 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6488 	 *
6489 	 * tailcall will unwind the current stack frame but it will not get rid
6490 	 * of caller's stack as shown on the example above.
6491 	 */
6492 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
6493 		verbose(env,
6494 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6495 			depth);
6496 		return -EACCES;
6497 	}
6498 
6499 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
6500 	if (priv_stack_supported) {
6501 		/* Request private stack support only if the subprog stack
6502 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
6503 		 * avoid jit penalty if the stack usage is small.
6504 		 */
6505 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
6506 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
6507 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
6508 	}
6509 
6510 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6511 		if (subprog_depth > MAX_BPF_STACK) {
6512 			verbose(env, "stack size of subprog %d is %d. Too large\n",
6513 				idx, subprog_depth);
6514 			return -EACCES;
6515 		}
6516 	} else {
6517 		depth += subprog_depth;
6518 		if (depth > MAX_BPF_STACK) {
6519 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
6520 				frame + 1, depth);
6521 			return -EACCES;
6522 		}
6523 	}
6524 continue_func:
6525 	subprog_end = subprog[idx + 1].start;
6526 	for (; i < subprog_end; i++) {
6527 		int next_insn, sidx;
6528 
6529 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6530 			bool err = false;
6531 
6532 			if (!is_bpf_throw_kfunc(insn + i))
6533 				continue;
6534 			if (subprog[idx].is_cb)
6535 				err = true;
6536 			for (int c = 0; c < frame && !err; c++) {
6537 				if (subprog[ret_prog[c]].is_cb) {
6538 					err = true;
6539 					break;
6540 				}
6541 			}
6542 			if (!err)
6543 				continue;
6544 			verbose(env,
6545 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6546 				i, idx);
6547 			return -EINVAL;
6548 		}
6549 
6550 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6551 			continue;
6552 		/* remember insn and function to return to */
6553 		ret_insn[frame] = i + 1;
6554 		ret_prog[frame] = idx;
6555 
6556 		/* find the callee */
6557 		next_insn = i + insn[i].imm + 1;
6558 		sidx = find_subprog(env, next_insn);
6559 		if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
6560 			return -EFAULT;
6561 		if (subprog[sidx].is_async_cb) {
6562 			if (subprog[sidx].has_tail_call) {
6563 				verifier_bug(env, "subprog has tail_call and async cb");
6564 				return -EFAULT;
6565 			}
6566 			/* async callbacks don't increase bpf prog stack size unless called directly */
6567 			if (!bpf_pseudo_call(insn + i))
6568 				continue;
6569 			if (subprog[sidx].is_exception_cb) {
6570 				verbose(env, "insn %d cannot call exception cb directly", i);
6571 				return -EINVAL;
6572 			}
6573 		}
6574 		i = next_insn;
6575 		idx = sidx;
6576 		if (!priv_stack_supported)
6577 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6578 
6579 		if (subprog[idx].has_tail_call)
6580 			tail_call_reachable = true;
6581 
6582 		frame++;
6583 		if (frame >= MAX_CALL_FRAMES) {
6584 			verbose(env, "the call stack of %d frames is too deep !\n",
6585 				frame);
6586 			return -E2BIG;
6587 		}
6588 		goto process_func;
6589 	}
6590 	/* if tail call got detected across bpf2bpf calls then mark each of the
6591 	 * currently present subprog frames as tail call reachable subprogs;
6592 	 * this info will be utilized by JIT so that we will be preserving the
6593 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6594 	 */
6595 	if (tail_call_reachable)
6596 		for (j = 0; j < frame; j++) {
6597 			if (subprog[ret_prog[j]].is_exception_cb) {
6598 				verbose(env, "cannot tail call within exception cb\n");
6599 				return -EINVAL;
6600 			}
6601 			subprog[ret_prog[j]].tail_call_reachable = true;
6602 		}
6603 	if (subprog[0].tail_call_reachable)
6604 		env->prog->aux->tail_call_reachable = true;
6605 
6606 	/* end of for() loop means the last insn of the 'subprog'
6607 	 * was reached. Doesn't matter whether it was JA or EXIT
6608 	 */
6609 	if (frame == 0)
6610 		return 0;
6611 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6612 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6613 	frame--;
6614 	i = ret_insn[frame];
6615 	idx = ret_prog[frame];
6616 	goto continue_func;
6617 }
6618 
6619 static int check_max_stack_depth(struct bpf_verifier_env *env)
6620 {
6621 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6622 	struct bpf_subprog_info *si = env->subprog_info;
6623 	bool priv_stack_supported;
6624 	int ret;
6625 
6626 	for (int i = 0; i < env->subprog_cnt; i++) {
6627 		if (si[i].has_tail_call) {
6628 			priv_stack_mode = NO_PRIV_STACK;
6629 			break;
6630 		}
6631 	}
6632 
6633 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6634 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6635 
6636 	/* All async_cb subprogs use normal kernel stack. If a particular
6637 	 * subprog appears in both main prog and async_cb subtree, that
6638 	 * subprog will use normal kernel stack to avoid potential nesting.
6639 	 * The reverse subprog traversal ensures when main prog subtree is
6640 	 * checked, the subprogs appearing in async_cb subtrees are already
6641 	 * marked as using normal kernel stack, so stack size checking can
6642 	 * be done properly.
6643 	 */
6644 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6645 		if (!i || si[i].is_async_cb) {
6646 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6647 			ret = check_max_stack_depth_subprog(env, i, priv_stack_supported);
6648 			if (ret < 0)
6649 				return ret;
6650 		}
6651 	}
6652 
6653 	for (int i = 0; i < env->subprog_cnt; i++) {
6654 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6655 			env->prog->aux->jits_use_priv_stack = true;
6656 			break;
6657 		}
6658 	}
6659 
6660 	return 0;
6661 }
6662 
6663 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6664 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6665 				  const struct bpf_insn *insn, int idx)
6666 {
6667 	int start = idx + insn->imm + 1, subprog;
6668 
6669 	subprog = find_subprog(env, start);
6670 	if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start))
6671 		return -EFAULT;
6672 	return env->subprog_info[subprog].stack_depth;
6673 }
6674 #endif
6675 
6676 static int __check_buffer_access(struct bpf_verifier_env *env,
6677 				 const char *buf_info,
6678 				 const struct bpf_reg_state *reg,
6679 				 int regno, int off, int size)
6680 {
6681 	if (off < 0) {
6682 		verbose(env,
6683 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6684 			regno, buf_info, off, size);
6685 		return -EACCES;
6686 	}
6687 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6688 		char tn_buf[48];
6689 
6690 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6691 		verbose(env,
6692 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6693 			regno, off, tn_buf);
6694 		return -EACCES;
6695 	}
6696 
6697 	return 0;
6698 }
6699 
6700 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6701 				  const struct bpf_reg_state *reg,
6702 				  int regno, int off, int size)
6703 {
6704 	int err;
6705 
6706 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6707 	if (err)
6708 		return err;
6709 
6710 	if (off + size > env->prog->aux->max_tp_access)
6711 		env->prog->aux->max_tp_access = off + size;
6712 
6713 	return 0;
6714 }
6715 
6716 static int check_buffer_access(struct bpf_verifier_env *env,
6717 			       const struct bpf_reg_state *reg,
6718 			       int regno, int off, int size,
6719 			       bool zero_size_allowed,
6720 			       u32 *max_access)
6721 {
6722 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6723 	int err;
6724 
6725 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6726 	if (err)
6727 		return err;
6728 
6729 	if (off + size > *max_access)
6730 		*max_access = off + size;
6731 
6732 	return 0;
6733 }
6734 
6735 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6736 static void zext_32_to_64(struct bpf_reg_state *reg)
6737 {
6738 	reg->var_off = tnum_subreg(reg->var_off);
6739 	__reg_assign_32_into_64(reg);
6740 }
6741 
6742 /* truncate register to smaller size (in bytes)
6743  * must be called with size < BPF_REG_SIZE
6744  */
6745 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6746 {
6747 	u64 mask;
6748 
6749 	/* clear high bits in bit representation */
6750 	reg->var_off = tnum_cast(reg->var_off, size);
6751 
6752 	/* fix arithmetic bounds */
6753 	mask = ((u64)1 << (size * 8)) - 1;
6754 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6755 		reg->umin_value &= mask;
6756 		reg->umax_value &= mask;
6757 	} else {
6758 		reg->umin_value = 0;
6759 		reg->umax_value = mask;
6760 	}
6761 	reg->smin_value = reg->umin_value;
6762 	reg->smax_value = reg->umax_value;
6763 
6764 	/* If size is smaller than 32bit register the 32bit register
6765 	 * values are also truncated so we push 64-bit bounds into
6766 	 * 32-bit bounds. Above were truncated < 32-bits already.
6767 	 */
6768 	if (size < 4)
6769 		__mark_reg32_unbounded(reg);
6770 
6771 	reg_bounds_sync(reg);
6772 }
6773 
6774 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6775 {
6776 	if (size == 1) {
6777 		reg->smin_value = reg->s32_min_value = S8_MIN;
6778 		reg->smax_value = reg->s32_max_value = S8_MAX;
6779 	} else if (size == 2) {
6780 		reg->smin_value = reg->s32_min_value = S16_MIN;
6781 		reg->smax_value = reg->s32_max_value = S16_MAX;
6782 	} else {
6783 		/* size == 4 */
6784 		reg->smin_value = reg->s32_min_value = S32_MIN;
6785 		reg->smax_value = reg->s32_max_value = S32_MAX;
6786 	}
6787 	reg->umin_value = reg->u32_min_value = 0;
6788 	reg->umax_value = U64_MAX;
6789 	reg->u32_max_value = U32_MAX;
6790 	reg->var_off = tnum_unknown;
6791 }
6792 
6793 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6794 {
6795 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6796 	u64 top_smax_value, top_smin_value;
6797 	u64 num_bits = size * 8;
6798 
6799 	if (tnum_is_const(reg->var_off)) {
6800 		u64_cval = reg->var_off.value;
6801 		if (size == 1)
6802 			reg->var_off = tnum_const((s8)u64_cval);
6803 		else if (size == 2)
6804 			reg->var_off = tnum_const((s16)u64_cval);
6805 		else
6806 			/* size == 4 */
6807 			reg->var_off = tnum_const((s32)u64_cval);
6808 
6809 		u64_cval = reg->var_off.value;
6810 		reg->smax_value = reg->smin_value = u64_cval;
6811 		reg->umax_value = reg->umin_value = u64_cval;
6812 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6813 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6814 		return;
6815 	}
6816 
6817 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6818 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6819 
6820 	if (top_smax_value != top_smin_value)
6821 		goto out;
6822 
6823 	/* find the s64_min and s64_min after sign extension */
6824 	if (size == 1) {
6825 		init_s64_max = (s8)reg->smax_value;
6826 		init_s64_min = (s8)reg->smin_value;
6827 	} else if (size == 2) {
6828 		init_s64_max = (s16)reg->smax_value;
6829 		init_s64_min = (s16)reg->smin_value;
6830 	} else {
6831 		init_s64_max = (s32)reg->smax_value;
6832 		init_s64_min = (s32)reg->smin_value;
6833 	}
6834 
6835 	s64_max = max(init_s64_max, init_s64_min);
6836 	s64_min = min(init_s64_max, init_s64_min);
6837 
6838 	/* both of s64_max/s64_min positive or negative */
6839 	if ((s64_max >= 0) == (s64_min >= 0)) {
6840 		reg->s32_min_value = reg->smin_value = s64_min;
6841 		reg->s32_max_value = reg->smax_value = s64_max;
6842 		reg->u32_min_value = reg->umin_value = s64_min;
6843 		reg->u32_max_value = reg->umax_value = s64_max;
6844 		reg->var_off = tnum_range(s64_min, s64_max);
6845 		return;
6846 	}
6847 
6848 out:
6849 	set_sext64_default_val(reg, size);
6850 }
6851 
6852 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6853 {
6854 	if (size == 1) {
6855 		reg->s32_min_value = S8_MIN;
6856 		reg->s32_max_value = S8_MAX;
6857 	} else {
6858 		/* size == 2 */
6859 		reg->s32_min_value = S16_MIN;
6860 		reg->s32_max_value = S16_MAX;
6861 	}
6862 	reg->u32_min_value = 0;
6863 	reg->u32_max_value = U32_MAX;
6864 	reg->var_off = tnum_subreg(tnum_unknown);
6865 }
6866 
6867 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6868 {
6869 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6870 	u32 top_smax_value, top_smin_value;
6871 	u32 num_bits = size * 8;
6872 
6873 	if (tnum_is_const(reg->var_off)) {
6874 		u32_val = reg->var_off.value;
6875 		if (size == 1)
6876 			reg->var_off = tnum_const((s8)u32_val);
6877 		else
6878 			reg->var_off = tnum_const((s16)u32_val);
6879 
6880 		u32_val = reg->var_off.value;
6881 		reg->s32_min_value = reg->s32_max_value = u32_val;
6882 		reg->u32_min_value = reg->u32_max_value = u32_val;
6883 		return;
6884 	}
6885 
6886 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6887 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6888 
6889 	if (top_smax_value != top_smin_value)
6890 		goto out;
6891 
6892 	/* find the s32_min and s32_min after sign extension */
6893 	if (size == 1) {
6894 		init_s32_max = (s8)reg->s32_max_value;
6895 		init_s32_min = (s8)reg->s32_min_value;
6896 	} else {
6897 		/* size == 2 */
6898 		init_s32_max = (s16)reg->s32_max_value;
6899 		init_s32_min = (s16)reg->s32_min_value;
6900 	}
6901 	s32_max = max(init_s32_max, init_s32_min);
6902 	s32_min = min(init_s32_max, init_s32_min);
6903 
6904 	if ((s32_min >= 0) == (s32_max >= 0)) {
6905 		reg->s32_min_value = s32_min;
6906 		reg->s32_max_value = s32_max;
6907 		reg->u32_min_value = (u32)s32_min;
6908 		reg->u32_max_value = (u32)s32_max;
6909 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6910 		return;
6911 	}
6912 
6913 out:
6914 	set_sext32_default_val(reg, size);
6915 }
6916 
6917 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6918 {
6919 	/* A map is considered read-only if the following condition are true:
6920 	 *
6921 	 * 1) BPF program side cannot change any of the map content. The
6922 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6923 	 *    and was set at map creation time.
6924 	 * 2) The map value(s) have been initialized from user space by a
6925 	 *    loader and then "frozen", such that no new map update/delete
6926 	 *    operations from syscall side are possible for the rest of
6927 	 *    the map's lifetime from that point onwards.
6928 	 * 3) Any parallel/pending map update/delete operations from syscall
6929 	 *    side have been completed. Only after that point, it's safe to
6930 	 *    assume that map value(s) are immutable.
6931 	 */
6932 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6933 	       READ_ONCE(map->frozen) &&
6934 	       !bpf_map_write_active(map);
6935 }
6936 
6937 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6938 			       bool is_ldsx)
6939 {
6940 	void *ptr;
6941 	u64 addr;
6942 	int err;
6943 
6944 	err = map->ops->map_direct_value_addr(map, &addr, off);
6945 	if (err)
6946 		return err;
6947 	ptr = (void *)(long)addr + off;
6948 
6949 	switch (size) {
6950 	case sizeof(u8):
6951 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6952 		break;
6953 	case sizeof(u16):
6954 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6955 		break;
6956 	case sizeof(u32):
6957 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6958 		break;
6959 	case sizeof(u64):
6960 		*val = *(u64 *)ptr;
6961 		break;
6962 	default:
6963 		return -EINVAL;
6964 	}
6965 	return 0;
6966 }
6967 
6968 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6969 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6970 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6971 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6972 
6973 /*
6974  * Allow list few fields as RCU trusted or full trusted.
6975  * This logic doesn't allow mix tagging and will be removed once GCC supports
6976  * btf_type_tag.
6977  */
6978 
6979 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6980 BTF_TYPE_SAFE_RCU(struct task_struct) {
6981 	const cpumask_t *cpus_ptr;
6982 	struct css_set __rcu *cgroups;
6983 	struct task_struct __rcu *real_parent;
6984 	struct task_struct *group_leader;
6985 };
6986 
6987 BTF_TYPE_SAFE_RCU(struct cgroup) {
6988 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6989 	struct kernfs_node *kn;
6990 };
6991 
6992 BTF_TYPE_SAFE_RCU(struct css_set) {
6993 	struct cgroup *dfl_cgrp;
6994 };
6995 
6996 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
6997 	struct cgroup *cgroup;
6998 };
6999 
7000 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
7001 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
7002 	struct file __rcu *exe_file;
7003 };
7004 
7005 /* skb->sk, req->sk are not RCU protected, but we mark them as such
7006  * because bpf prog accessible sockets are SOCK_RCU_FREE.
7007  */
7008 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
7009 	struct sock *sk;
7010 };
7011 
7012 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
7013 	struct sock *sk;
7014 };
7015 
7016 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
7017 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
7018 	struct seq_file *seq;
7019 };
7020 
7021 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
7022 	struct bpf_iter_meta *meta;
7023 	struct task_struct *task;
7024 };
7025 
7026 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
7027 	struct file *file;
7028 };
7029 
7030 BTF_TYPE_SAFE_TRUSTED(struct file) {
7031 	struct inode *f_inode;
7032 };
7033 
7034 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
7035 	struct inode *d_inode;
7036 };
7037 
7038 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
7039 	struct sock *sk;
7040 };
7041 
7042 static bool type_is_rcu(struct bpf_verifier_env *env,
7043 			struct bpf_reg_state *reg,
7044 			const char *field_name, u32 btf_id)
7045 {
7046 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
7047 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
7048 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
7049 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
7050 
7051 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
7052 }
7053 
7054 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
7055 				struct bpf_reg_state *reg,
7056 				const char *field_name, u32 btf_id)
7057 {
7058 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
7059 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
7060 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
7061 
7062 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
7063 }
7064 
7065 static bool type_is_trusted(struct bpf_verifier_env *env,
7066 			    struct bpf_reg_state *reg,
7067 			    const char *field_name, u32 btf_id)
7068 {
7069 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
7070 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
7071 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
7072 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
7073 
7074 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
7075 }
7076 
7077 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
7078 				    struct bpf_reg_state *reg,
7079 				    const char *field_name, u32 btf_id)
7080 {
7081 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
7082 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
7083 
7084 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
7085 					  "__safe_trusted_or_null");
7086 }
7087 
7088 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
7089 				   struct bpf_reg_state *regs,
7090 				   int regno, int off, int size,
7091 				   enum bpf_access_type atype,
7092 				   int value_regno)
7093 {
7094 	struct bpf_reg_state *reg = regs + regno;
7095 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
7096 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
7097 	const char *field_name = NULL;
7098 	enum bpf_type_flag flag = 0;
7099 	u32 btf_id = 0;
7100 	int ret;
7101 
7102 	if (!env->allow_ptr_leaks) {
7103 		verbose(env,
7104 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7105 			tname);
7106 		return -EPERM;
7107 	}
7108 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
7109 		verbose(env,
7110 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
7111 			tname);
7112 		return -EINVAL;
7113 	}
7114 	if (off < 0) {
7115 		verbose(env,
7116 			"R%d is ptr_%s invalid negative access: off=%d\n",
7117 			regno, tname, off);
7118 		return -EACCES;
7119 	}
7120 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
7121 		char tn_buf[48];
7122 
7123 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7124 		verbose(env,
7125 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
7126 			regno, tname, off, tn_buf);
7127 		return -EACCES;
7128 	}
7129 
7130 	if (reg->type & MEM_USER) {
7131 		verbose(env,
7132 			"R%d is ptr_%s access user memory: off=%d\n",
7133 			regno, tname, off);
7134 		return -EACCES;
7135 	}
7136 
7137 	if (reg->type & MEM_PERCPU) {
7138 		verbose(env,
7139 			"R%d is ptr_%s access percpu memory: off=%d\n",
7140 			regno, tname, off);
7141 		return -EACCES;
7142 	}
7143 
7144 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
7145 		if (!btf_is_kernel(reg->btf)) {
7146 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
7147 			return -EFAULT;
7148 		}
7149 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
7150 	} else {
7151 		/* Writes are permitted with default btf_struct_access for
7152 		 * program allocated objects (which always have ref_obj_id > 0),
7153 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
7154 		 */
7155 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
7156 			verbose(env, "only read is supported\n");
7157 			return -EACCES;
7158 		}
7159 
7160 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
7161 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
7162 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
7163 			return -EFAULT;
7164 		}
7165 
7166 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
7167 	}
7168 
7169 	if (ret < 0)
7170 		return ret;
7171 
7172 	if (ret != PTR_TO_BTF_ID) {
7173 		/* just mark; */
7174 
7175 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
7176 		/* If this is an untrusted pointer, all pointers formed by walking it
7177 		 * also inherit the untrusted flag.
7178 		 */
7179 		flag = PTR_UNTRUSTED;
7180 
7181 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
7182 		/* By default any pointer obtained from walking a trusted pointer is no
7183 		 * longer trusted, unless the field being accessed has explicitly been
7184 		 * marked as inheriting its parent's state of trust (either full or RCU).
7185 		 * For example:
7186 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
7187 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
7188 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
7189 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
7190 		 *
7191 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
7192 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
7193 		 */
7194 		if (type_is_trusted(env, reg, field_name, btf_id)) {
7195 			flag |= PTR_TRUSTED;
7196 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
7197 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
7198 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
7199 			if (type_is_rcu(env, reg, field_name, btf_id)) {
7200 				/* ignore __rcu tag and mark it MEM_RCU */
7201 				flag |= MEM_RCU;
7202 			} else if (flag & MEM_RCU ||
7203 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
7204 				/* __rcu tagged pointers can be NULL */
7205 				flag |= MEM_RCU | PTR_MAYBE_NULL;
7206 
7207 				/* We always trust them */
7208 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
7209 				    flag & PTR_UNTRUSTED)
7210 					flag &= ~PTR_UNTRUSTED;
7211 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
7212 				/* keep as-is */
7213 			} else {
7214 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
7215 				clear_trusted_flags(&flag);
7216 			}
7217 		} else {
7218 			/*
7219 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
7220 			 * aggressively mark as untrusted otherwise such
7221 			 * pointers will be plain PTR_TO_BTF_ID without flags
7222 			 * and will be allowed to be passed into helpers for
7223 			 * compat reasons.
7224 			 */
7225 			flag = PTR_UNTRUSTED;
7226 		}
7227 	} else {
7228 		/* Old compat. Deprecated */
7229 		clear_trusted_flags(&flag);
7230 	}
7231 
7232 	if (atype == BPF_READ && value_regno >= 0)
7233 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
7234 
7235 	return 0;
7236 }
7237 
7238 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
7239 				   struct bpf_reg_state *regs,
7240 				   int regno, int off, int size,
7241 				   enum bpf_access_type atype,
7242 				   int value_regno)
7243 {
7244 	struct bpf_reg_state *reg = regs + regno;
7245 	struct bpf_map *map = reg->map_ptr;
7246 	struct bpf_reg_state map_reg;
7247 	enum bpf_type_flag flag = 0;
7248 	const struct btf_type *t;
7249 	const char *tname;
7250 	u32 btf_id;
7251 	int ret;
7252 
7253 	if (!btf_vmlinux) {
7254 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
7255 		return -ENOTSUPP;
7256 	}
7257 
7258 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
7259 		verbose(env, "map_ptr access not supported for map type %d\n",
7260 			map->map_type);
7261 		return -ENOTSUPP;
7262 	}
7263 
7264 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
7265 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
7266 
7267 	if (!env->allow_ptr_leaks) {
7268 		verbose(env,
7269 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7270 			tname);
7271 		return -EPERM;
7272 	}
7273 
7274 	if (off < 0) {
7275 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
7276 			regno, tname, off);
7277 		return -EACCES;
7278 	}
7279 
7280 	if (atype != BPF_READ) {
7281 		verbose(env, "only read from %s is supported\n", tname);
7282 		return -EACCES;
7283 	}
7284 
7285 	/* Simulate access to a PTR_TO_BTF_ID */
7286 	memset(&map_reg, 0, sizeof(map_reg));
7287 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
7288 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
7289 	if (ret < 0)
7290 		return ret;
7291 
7292 	if (value_regno >= 0)
7293 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
7294 
7295 	return 0;
7296 }
7297 
7298 /* Check that the stack access at the given offset is within bounds. The
7299  * maximum valid offset is -1.
7300  *
7301  * The minimum valid offset is -MAX_BPF_STACK for writes, and
7302  * -state->allocated_stack for reads.
7303  */
7304 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
7305                                           s64 off,
7306                                           struct bpf_func_state *state,
7307                                           enum bpf_access_type t)
7308 {
7309 	int min_valid_off;
7310 
7311 	if (t == BPF_WRITE || env->allow_uninit_stack)
7312 		min_valid_off = -MAX_BPF_STACK;
7313 	else
7314 		min_valid_off = -state->allocated_stack;
7315 
7316 	if (off < min_valid_off || off > -1)
7317 		return -EACCES;
7318 	return 0;
7319 }
7320 
7321 /* Check that the stack access at 'regno + off' falls within the maximum stack
7322  * bounds.
7323  *
7324  * 'off' includes `regno->offset`, but not its dynamic part (if any).
7325  */
7326 static int check_stack_access_within_bounds(
7327 		struct bpf_verifier_env *env,
7328 		int regno, int off, int access_size,
7329 		enum bpf_access_type type)
7330 {
7331 	struct bpf_reg_state *regs = cur_regs(env);
7332 	struct bpf_reg_state *reg = regs + regno;
7333 	struct bpf_func_state *state = func(env, reg);
7334 	s64 min_off, max_off;
7335 	int err;
7336 	char *err_extra;
7337 
7338 	if (type == BPF_READ)
7339 		err_extra = " read from";
7340 	else
7341 		err_extra = " write to";
7342 
7343 	if (tnum_is_const(reg->var_off)) {
7344 		min_off = (s64)reg->var_off.value + off;
7345 		max_off = min_off + access_size;
7346 	} else {
7347 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
7348 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
7349 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
7350 				err_extra, regno);
7351 			return -EACCES;
7352 		}
7353 		min_off = reg->smin_value + off;
7354 		max_off = reg->smax_value + off + access_size;
7355 	}
7356 
7357 	err = check_stack_slot_within_bounds(env, min_off, state, type);
7358 	if (!err && max_off > 0)
7359 		err = -EINVAL; /* out of stack access into non-negative offsets */
7360 	if (!err && access_size < 0)
7361 		/* access_size should not be negative (or overflow an int); others checks
7362 		 * along the way should have prevented such an access.
7363 		 */
7364 		err = -EFAULT; /* invalid negative access size; integer overflow? */
7365 
7366 	if (err) {
7367 		if (tnum_is_const(reg->var_off)) {
7368 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
7369 				err_extra, regno, off, access_size);
7370 		} else {
7371 			char tn_buf[48];
7372 
7373 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7374 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
7375 				err_extra, regno, tn_buf, off, access_size);
7376 		}
7377 		return err;
7378 	}
7379 
7380 	/* Note that there is no stack access with offset zero, so the needed stack
7381 	 * size is -min_off, not -min_off+1.
7382 	 */
7383 	return grow_stack_state(env, state, -min_off /* size */);
7384 }
7385 
7386 static bool get_func_retval_range(struct bpf_prog *prog,
7387 				  struct bpf_retval_range *range)
7388 {
7389 	if (prog->type == BPF_PROG_TYPE_LSM &&
7390 		prog->expected_attach_type == BPF_LSM_MAC &&
7391 		!bpf_lsm_get_retval_range(prog, range)) {
7392 		return true;
7393 	}
7394 	return false;
7395 }
7396 
7397 /* check whether memory at (regno + off) is accessible for t = (read | write)
7398  * if t==write, value_regno is a register which value is stored into memory
7399  * if t==read, value_regno is a register which will receive the value from memory
7400  * if t==write && value_regno==-1, some unknown value is stored into memory
7401  * if t==read && value_regno==-1, don't care what we read from memory
7402  */
7403 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
7404 			    int off, int bpf_size, enum bpf_access_type t,
7405 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7406 {
7407 	struct bpf_reg_state *regs = cur_regs(env);
7408 	struct bpf_reg_state *reg = regs + regno;
7409 	int size, err = 0;
7410 
7411 	size = bpf_size_to_bytes(bpf_size);
7412 	if (size < 0)
7413 		return size;
7414 
7415 	/* alignment checks will add in reg->off themselves */
7416 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7417 	if (err)
7418 		return err;
7419 
7420 	/* for access checks, reg->off is just part of off */
7421 	off += reg->off;
7422 
7423 	if (reg->type == PTR_TO_MAP_KEY) {
7424 		if (t == BPF_WRITE) {
7425 			verbose(env, "write to change key R%d not allowed\n", regno);
7426 			return -EACCES;
7427 		}
7428 
7429 		err = check_mem_region_access(env, regno, off, size,
7430 					      reg->map_ptr->key_size, false);
7431 		if (err)
7432 			return err;
7433 		if (value_regno >= 0)
7434 			mark_reg_unknown(env, regs, value_regno);
7435 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7436 		struct btf_field *kptr_field = NULL;
7437 
7438 		if (t == BPF_WRITE && value_regno >= 0 &&
7439 		    is_pointer_value(env, value_regno)) {
7440 			verbose(env, "R%d leaks addr into map\n", value_regno);
7441 			return -EACCES;
7442 		}
7443 		err = check_map_access_type(env, regno, off, size, t);
7444 		if (err)
7445 			return err;
7446 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
7447 		if (err)
7448 			return err;
7449 		if (tnum_is_const(reg->var_off))
7450 			kptr_field = btf_record_find(reg->map_ptr->record,
7451 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7452 		if (kptr_field) {
7453 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
7454 		} else if (t == BPF_READ && value_regno >= 0) {
7455 			struct bpf_map *map = reg->map_ptr;
7456 
7457 			/* if map is read-only, track its contents as scalars */
7458 			if (tnum_is_const(reg->var_off) &&
7459 			    bpf_map_is_rdonly(map) &&
7460 			    map->ops->map_direct_value_addr) {
7461 				int map_off = off + reg->var_off.value;
7462 				u64 val = 0;
7463 
7464 				err = bpf_map_direct_read(map, map_off, size,
7465 							  &val, is_ldsx);
7466 				if (err)
7467 					return err;
7468 
7469 				regs[value_regno].type = SCALAR_VALUE;
7470 				__mark_reg_known(&regs[value_regno], val);
7471 			} else {
7472 				mark_reg_unknown(env, regs, value_regno);
7473 			}
7474 		}
7475 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7476 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7477 
7478 		if (type_may_be_null(reg->type)) {
7479 			verbose(env, "R%d invalid mem access '%s'\n", regno,
7480 				reg_type_str(env, reg->type));
7481 			return -EACCES;
7482 		}
7483 
7484 		if (t == BPF_WRITE && rdonly_mem) {
7485 			verbose(env, "R%d cannot write into %s\n",
7486 				regno, reg_type_str(env, reg->type));
7487 			return -EACCES;
7488 		}
7489 
7490 		if (t == BPF_WRITE && value_regno >= 0 &&
7491 		    is_pointer_value(env, value_regno)) {
7492 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7493 			return -EACCES;
7494 		}
7495 
7496 		err = check_mem_region_access(env, regno, off, size,
7497 					      reg->mem_size, false);
7498 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7499 			mark_reg_unknown(env, regs, value_regno);
7500 	} else if (reg->type == PTR_TO_CTX) {
7501 		struct bpf_retval_range range;
7502 		struct bpf_insn_access_aux info = {
7503 			.reg_type = SCALAR_VALUE,
7504 			.is_ldsx = is_ldsx,
7505 			.log = &env->log,
7506 		};
7507 
7508 		if (t == BPF_WRITE && value_regno >= 0 &&
7509 		    is_pointer_value(env, value_regno)) {
7510 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7511 			return -EACCES;
7512 		}
7513 
7514 		err = check_ptr_off_reg(env, reg, regno);
7515 		if (err < 0)
7516 			return err;
7517 
7518 		err = check_ctx_access(env, insn_idx, off, size, t, &info);
7519 		if (err)
7520 			verbose_linfo(env, insn_idx, "; ");
7521 		if (!err && t == BPF_READ && value_regno >= 0) {
7522 			/* ctx access returns either a scalar, or a
7523 			 * PTR_TO_PACKET[_META,_END]. In the latter
7524 			 * case, we know the offset is zero.
7525 			 */
7526 			if (info.reg_type == SCALAR_VALUE) {
7527 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
7528 					err = __mark_reg_s32_range(env, regs, value_regno,
7529 								   range.minval, range.maxval);
7530 					if (err)
7531 						return err;
7532 				} else {
7533 					mark_reg_unknown(env, regs, value_regno);
7534 				}
7535 			} else {
7536 				mark_reg_known_zero(env, regs,
7537 						    value_regno);
7538 				if (type_may_be_null(info.reg_type))
7539 					regs[value_regno].id = ++env->id_gen;
7540 				/* A load of ctx field could have different
7541 				 * actual load size with the one encoded in the
7542 				 * insn. When the dst is PTR, it is for sure not
7543 				 * a sub-register.
7544 				 */
7545 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7546 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
7547 					regs[value_regno].btf = info.btf;
7548 					regs[value_regno].btf_id = info.btf_id;
7549 					regs[value_regno].ref_obj_id = info.ref_obj_id;
7550 				}
7551 			}
7552 			regs[value_regno].type = info.reg_type;
7553 		}
7554 
7555 	} else if (reg->type == PTR_TO_STACK) {
7556 		/* Basic bounds checks. */
7557 		err = check_stack_access_within_bounds(env, regno, off, size, t);
7558 		if (err)
7559 			return err;
7560 
7561 		if (t == BPF_READ)
7562 			err = check_stack_read(env, regno, off, size,
7563 					       value_regno);
7564 		else
7565 			err = check_stack_write(env, regno, off, size,
7566 						value_regno, insn_idx);
7567 	} else if (reg_is_pkt_pointer(reg)) {
7568 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7569 			verbose(env, "cannot write into packet\n");
7570 			return -EACCES;
7571 		}
7572 		if (t == BPF_WRITE && value_regno >= 0 &&
7573 		    is_pointer_value(env, value_regno)) {
7574 			verbose(env, "R%d leaks addr into packet\n",
7575 				value_regno);
7576 			return -EACCES;
7577 		}
7578 		err = check_packet_access(env, regno, off, size, false);
7579 		if (!err && t == BPF_READ && value_regno >= 0)
7580 			mark_reg_unknown(env, regs, value_regno);
7581 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7582 		if (t == BPF_WRITE && value_regno >= 0 &&
7583 		    is_pointer_value(env, value_regno)) {
7584 			verbose(env, "R%d leaks addr into flow keys\n",
7585 				value_regno);
7586 			return -EACCES;
7587 		}
7588 
7589 		err = check_flow_keys_access(env, off, size);
7590 		if (!err && t == BPF_READ && value_regno >= 0)
7591 			mark_reg_unknown(env, regs, value_regno);
7592 	} else if (type_is_sk_pointer(reg->type)) {
7593 		if (t == BPF_WRITE) {
7594 			verbose(env, "R%d cannot write into %s\n",
7595 				regno, reg_type_str(env, reg->type));
7596 			return -EACCES;
7597 		}
7598 		err = check_sock_access(env, insn_idx, regno, off, size, t);
7599 		if (!err && value_regno >= 0)
7600 			mark_reg_unknown(env, regs, value_regno);
7601 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7602 		err = check_tp_buffer_access(env, reg, regno, off, size);
7603 		if (!err && t == BPF_READ && value_regno >= 0)
7604 			mark_reg_unknown(env, regs, value_regno);
7605 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7606 		   !type_may_be_null(reg->type)) {
7607 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7608 					      value_regno);
7609 	} else if (reg->type == CONST_PTR_TO_MAP) {
7610 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7611 					      value_regno);
7612 	} else if (base_type(reg->type) == PTR_TO_BUF) {
7613 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7614 		u32 *max_access;
7615 
7616 		if (rdonly_mem) {
7617 			if (t == BPF_WRITE) {
7618 				verbose(env, "R%d cannot write into %s\n",
7619 					regno, reg_type_str(env, reg->type));
7620 				return -EACCES;
7621 			}
7622 			max_access = &env->prog->aux->max_rdonly_access;
7623 		} else {
7624 			max_access = &env->prog->aux->max_rdwr_access;
7625 		}
7626 
7627 		err = check_buffer_access(env, reg, regno, off, size, false,
7628 					  max_access);
7629 
7630 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7631 			mark_reg_unknown(env, regs, value_regno);
7632 	} else if (reg->type == PTR_TO_ARENA) {
7633 		if (t == BPF_READ && value_regno >= 0)
7634 			mark_reg_unknown(env, regs, value_regno);
7635 	} else {
7636 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7637 			reg_type_str(env, reg->type));
7638 		return -EACCES;
7639 	}
7640 
7641 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7642 	    regs[value_regno].type == SCALAR_VALUE) {
7643 		if (!is_ldsx)
7644 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7645 			coerce_reg_to_size(&regs[value_regno], size);
7646 		else
7647 			coerce_reg_to_size_sx(&regs[value_regno], size);
7648 	}
7649 	return err;
7650 }
7651 
7652 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7653 			     bool allow_trust_mismatch);
7654 
7655 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
7656 			  bool strict_alignment_once, bool is_ldsx,
7657 			  bool allow_trust_mismatch, const char *ctx)
7658 {
7659 	struct bpf_reg_state *regs = cur_regs(env);
7660 	enum bpf_reg_type src_reg_type;
7661 	int err;
7662 
7663 	/* check src operand */
7664 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7665 	if (err)
7666 		return err;
7667 
7668 	/* check dst operand */
7669 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7670 	if (err)
7671 		return err;
7672 
7673 	src_reg_type = regs[insn->src_reg].type;
7674 
7675 	/* Check if (src_reg + off) is readable. The state of dst_reg will be
7676 	 * updated by this call.
7677 	 */
7678 	err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off,
7679 			       BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
7680 			       strict_alignment_once, is_ldsx);
7681 	err = err ?: save_aux_ptr_type(env, src_reg_type,
7682 				       allow_trust_mismatch);
7683 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
7684 
7685 	return err;
7686 }
7687 
7688 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
7689 			   bool strict_alignment_once)
7690 {
7691 	struct bpf_reg_state *regs = cur_regs(env);
7692 	enum bpf_reg_type dst_reg_type;
7693 	int err;
7694 
7695 	/* check src1 operand */
7696 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7697 	if (err)
7698 		return err;
7699 
7700 	/* check src2 operand */
7701 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7702 	if (err)
7703 		return err;
7704 
7705 	dst_reg_type = regs[insn->dst_reg].type;
7706 
7707 	/* Check if (dst_reg + off) is writeable. */
7708 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7709 			       BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
7710 			       strict_alignment_once, false);
7711 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
7712 
7713 	return err;
7714 }
7715 
7716 static int check_atomic_rmw(struct bpf_verifier_env *env,
7717 			    struct bpf_insn *insn)
7718 {
7719 	int load_reg;
7720 	int err;
7721 
7722 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7723 		verbose(env, "invalid atomic operand size\n");
7724 		return -EINVAL;
7725 	}
7726 
7727 	/* check src1 operand */
7728 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7729 	if (err)
7730 		return err;
7731 
7732 	/* check src2 operand */
7733 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7734 	if (err)
7735 		return err;
7736 
7737 	if (insn->imm == BPF_CMPXCHG) {
7738 		/* Check comparison of R0 with memory location */
7739 		const u32 aux_reg = BPF_REG_0;
7740 
7741 		err = check_reg_arg(env, aux_reg, SRC_OP);
7742 		if (err)
7743 			return err;
7744 
7745 		if (is_pointer_value(env, aux_reg)) {
7746 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7747 			return -EACCES;
7748 		}
7749 	}
7750 
7751 	if (is_pointer_value(env, insn->src_reg)) {
7752 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7753 		return -EACCES;
7754 	}
7755 
7756 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7757 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7758 			insn->dst_reg,
7759 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7760 		return -EACCES;
7761 	}
7762 
7763 	if (insn->imm & BPF_FETCH) {
7764 		if (insn->imm == BPF_CMPXCHG)
7765 			load_reg = BPF_REG_0;
7766 		else
7767 			load_reg = insn->src_reg;
7768 
7769 		/* check and record load of old value */
7770 		err = check_reg_arg(env, load_reg, DST_OP);
7771 		if (err)
7772 			return err;
7773 	} else {
7774 		/* This instruction accesses a memory location but doesn't
7775 		 * actually load it into a register.
7776 		 */
7777 		load_reg = -1;
7778 	}
7779 
7780 	/* Check whether we can read the memory, with second call for fetch
7781 	 * case to simulate the register fill.
7782 	 */
7783 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7784 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7785 	if (!err && load_reg >= 0)
7786 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
7787 				       insn->off, BPF_SIZE(insn->code),
7788 				       BPF_READ, load_reg, true, false);
7789 	if (err)
7790 		return err;
7791 
7792 	if (is_arena_reg(env, insn->dst_reg)) {
7793 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7794 		if (err)
7795 			return err;
7796 	}
7797 	/* Check whether we can write into the same memory. */
7798 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7799 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7800 	if (err)
7801 		return err;
7802 	return 0;
7803 }
7804 
7805 static int check_atomic_load(struct bpf_verifier_env *env,
7806 			     struct bpf_insn *insn)
7807 {
7808 	int err;
7809 
7810 	err = check_load_mem(env, insn, true, false, false, "atomic_load");
7811 	if (err)
7812 		return err;
7813 
7814 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
7815 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
7816 			insn->src_reg,
7817 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
7818 		return -EACCES;
7819 	}
7820 
7821 	return 0;
7822 }
7823 
7824 static int check_atomic_store(struct bpf_verifier_env *env,
7825 			      struct bpf_insn *insn)
7826 {
7827 	int err;
7828 
7829 	err = check_store_reg(env, insn, true);
7830 	if (err)
7831 		return err;
7832 
7833 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7834 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7835 			insn->dst_reg,
7836 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7837 		return -EACCES;
7838 	}
7839 
7840 	return 0;
7841 }
7842 
7843 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
7844 {
7845 	switch (insn->imm) {
7846 	case BPF_ADD:
7847 	case BPF_ADD | BPF_FETCH:
7848 	case BPF_AND:
7849 	case BPF_AND | BPF_FETCH:
7850 	case BPF_OR:
7851 	case BPF_OR | BPF_FETCH:
7852 	case BPF_XOR:
7853 	case BPF_XOR | BPF_FETCH:
7854 	case BPF_XCHG:
7855 	case BPF_CMPXCHG:
7856 		return check_atomic_rmw(env, insn);
7857 	case BPF_LOAD_ACQ:
7858 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7859 			verbose(env,
7860 				"64-bit load-acquires are only supported on 64-bit arches\n");
7861 			return -EOPNOTSUPP;
7862 		}
7863 		return check_atomic_load(env, insn);
7864 	case BPF_STORE_REL:
7865 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7866 			verbose(env,
7867 				"64-bit store-releases are only supported on 64-bit arches\n");
7868 			return -EOPNOTSUPP;
7869 		}
7870 		return check_atomic_store(env, insn);
7871 	default:
7872 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
7873 			insn->imm);
7874 		return -EINVAL;
7875 	}
7876 }
7877 
7878 /* When register 'regno' is used to read the stack (either directly or through
7879  * a helper function) make sure that it's within stack boundary and, depending
7880  * on the access type and privileges, that all elements of the stack are
7881  * initialized.
7882  *
7883  * 'off' includes 'regno->off', but not its dynamic part (if any).
7884  *
7885  * All registers that have been spilled on the stack in the slots within the
7886  * read offsets are marked as read.
7887  */
7888 static int check_stack_range_initialized(
7889 		struct bpf_verifier_env *env, int regno, int off,
7890 		int access_size, bool zero_size_allowed,
7891 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
7892 {
7893 	struct bpf_reg_state *reg = reg_state(env, regno);
7894 	struct bpf_func_state *state = func(env, reg);
7895 	int err, min_off, max_off, i, j, slot, spi;
7896 	/* Some accesses can write anything into the stack, others are
7897 	 * read-only.
7898 	 */
7899 	bool clobber = false;
7900 
7901 	if (access_size == 0 && !zero_size_allowed) {
7902 		verbose(env, "invalid zero-sized read\n");
7903 		return -EACCES;
7904 	}
7905 
7906 	if (type == BPF_WRITE)
7907 		clobber = true;
7908 
7909 	err = check_stack_access_within_bounds(env, regno, off, access_size, type);
7910 	if (err)
7911 		return err;
7912 
7913 
7914 	if (tnum_is_const(reg->var_off)) {
7915 		min_off = max_off = reg->var_off.value + off;
7916 	} else {
7917 		/* Variable offset is prohibited for unprivileged mode for
7918 		 * simplicity since it requires corresponding support in
7919 		 * Spectre masking for stack ALU.
7920 		 * See also retrieve_ptr_limit().
7921 		 */
7922 		if (!env->bypass_spec_v1) {
7923 			char tn_buf[48];
7924 
7925 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7926 			verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
7927 				regno, tn_buf);
7928 			return -EACCES;
7929 		}
7930 		/* Only initialized buffer on stack is allowed to be accessed
7931 		 * with variable offset. With uninitialized buffer it's hard to
7932 		 * guarantee that whole memory is marked as initialized on
7933 		 * helper return since specific bounds are unknown what may
7934 		 * cause uninitialized stack leaking.
7935 		 */
7936 		if (meta && meta->raw_mode)
7937 			meta = NULL;
7938 
7939 		min_off = reg->smin_value + off;
7940 		max_off = reg->smax_value + off;
7941 	}
7942 
7943 	if (meta && meta->raw_mode) {
7944 		/* Ensure we won't be overwriting dynptrs when simulating byte
7945 		 * by byte access in check_helper_call using meta.access_size.
7946 		 * This would be a problem if we have a helper in the future
7947 		 * which takes:
7948 		 *
7949 		 *	helper(uninit_mem, len, dynptr)
7950 		 *
7951 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7952 		 * may end up writing to dynptr itself when touching memory from
7953 		 * arg 1. This can be relaxed on a case by case basis for known
7954 		 * safe cases, but reject due to the possibilitiy of aliasing by
7955 		 * default.
7956 		 */
7957 		for (i = min_off; i < max_off + access_size; i++) {
7958 			int stack_off = -i - 1;
7959 
7960 			spi = __get_spi(i);
7961 			/* raw_mode may write past allocated_stack */
7962 			if (state->allocated_stack <= stack_off)
7963 				continue;
7964 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7965 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7966 				return -EACCES;
7967 			}
7968 		}
7969 		meta->access_size = access_size;
7970 		meta->regno = regno;
7971 		return 0;
7972 	}
7973 
7974 	for (i = min_off; i < max_off + access_size; i++) {
7975 		u8 *stype;
7976 
7977 		slot = -i - 1;
7978 		spi = slot / BPF_REG_SIZE;
7979 		if (state->allocated_stack <= slot) {
7980 			verbose(env, "allocated_stack too small\n");
7981 			return -EFAULT;
7982 		}
7983 
7984 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7985 		if (*stype == STACK_MISC)
7986 			goto mark;
7987 		if ((*stype == STACK_ZERO) ||
7988 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7989 			if (clobber) {
7990 				/* helper can write anything into the stack */
7991 				*stype = STACK_MISC;
7992 			}
7993 			goto mark;
7994 		}
7995 
7996 		if (is_spilled_reg(&state->stack[spi]) &&
7997 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7998 		     env->allow_ptr_leaks)) {
7999 			if (clobber) {
8000 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
8001 				for (j = 0; j < BPF_REG_SIZE; j++)
8002 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
8003 			}
8004 			goto mark;
8005 		}
8006 
8007 		if (tnum_is_const(reg->var_off)) {
8008 			verbose(env, "invalid read from stack R%d off %d+%d size %d\n",
8009 				regno, min_off, i - min_off, access_size);
8010 		} else {
8011 			char tn_buf[48];
8012 
8013 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8014 			verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n",
8015 				regno, tn_buf, i - min_off, access_size);
8016 		}
8017 		return -EACCES;
8018 mark:
8019 		/* reading any byte out of 8-byte 'spill_slot' will cause
8020 		 * the whole slot to be marked as 'read'
8021 		 */
8022 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
8023 			      state->stack[spi].spilled_ptr.parent,
8024 			      REG_LIVE_READ64);
8025 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
8026 		 * be sure that whether stack slot is written to or not. Hence,
8027 		 * we must still conservatively propagate reads upwards even if
8028 		 * helper may write to the entire memory range.
8029 		 */
8030 	}
8031 	return 0;
8032 }
8033 
8034 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
8035 				   int access_size, enum bpf_access_type access_type,
8036 				   bool zero_size_allowed,
8037 				   struct bpf_call_arg_meta *meta)
8038 {
8039 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8040 	u32 *max_access;
8041 
8042 	switch (base_type(reg->type)) {
8043 	case PTR_TO_PACKET:
8044 	case PTR_TO_PACKET_META:
8045 		return check_packet_access(env, regno, reg->off, access_size,
8046 					   zero_size_allowed);
8047 	case PTR_TO_MAP_KEY:
8048 		if (access_type == BPF_WRITE) {
8049 			verbose(env, "R%d cannot write into %s\n", regno,
8050 				reg_type_str(env, reg->type));
8051 			return -EACCES;
8052 		}
8053 		return check_mem_region_access(env, regno, reg->off, access_size,
8054 					       reg->map_ptr->key_size, false);
8055 	case PTR_TO_MAP_VALUE:
8056 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
8057 			return -EACCES;
8058 		return check_map_access(env, regno, reg->off, access_size,
8059 					zero_size_allowed, ACCESS_HELPER);
8060 	case PTR_TO_MEM:
8061 		if (type_is_rdonly_mem(reg->type)) {
8062 			if (access_type == BPF_WRITE) {
8063 				verbose(env, "R%d cannot write into %s\n", regno,
8064 					reg_type_str(env, reg->type));
8065 				return -EACCES;
8066 			}
8067 		}
8068 		return check_mem_region_access(env, regno, reg->off,
8069 					       access_size, reg->mem_size,
8070 					       zero_size_allowed);
8071 	case PTR_TO_BUF:
8072 		if (type_is_rdonly_mem(reg->type)) {
8073 			if (access_type == BPF_WRITE) {
8074 				verbose(env, "R%d cannot write into %s\n", regno,
8075 					reg_type_str(env, reg->type));
8076 				return -EACCES;
8077 			}
8078 
8079 			max_access = &env->prog->aux->max_rdonly_access;
8080 		} else {
8081 			max_access = &env->prog->aux->max_rdwr_access;
8082 		}
8083 		return check_buffer_access(env, reg, regno, reg->off,
8084 					   access_size, zero_size_allowed,
8085 					   max_access);
8086 	case PTR_TO_STACK:
8087 		return check_stack_range_initialized(
8088 				env,
8089 				regno, reg->off, access_size,
8090 				zero_size_allowed, access_type, meta);
8091 	case PTR_TO_BTF_ID:
8092 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
8093 					       access_size, BPF_READ, -1);
8094 	case PTR_TO_CTX:
8095 		/* in case the function doesn't know how to access the context,
8096 		 * (because we are in a program of type SYSCALL for example), we
8097 		 * can not statically check its size.
8098 		 * Dynamically check it now.
8099 		 */
8100 		if (!env->ops->convert_ctx_access) {
8101 			int offset = access_size - 1;
8102 
8103 			/* Allow zero-byte read from PTR_TO_CTX */
8104 			if (access_size == 0)
8105 				return zero_size_allowed ? 0 : -EACCES;
8106 
8107 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
8108 						access_type, -1, false, false);
8109 		}
8110 
8111 		fallthrough;
8112 	default: /* scalar_value or invalid ptr */
8113 		/* Allow zero-byte read from NULL, regardless of pointer type */
8114 		if (zero_size_allowed && access_size == 0 &&
8115 		    register_is_null(reg))
8116 			return 0;
8117 
8118 		verbose(env, "R%d type=%s ", regno,
8119 			reg_type_str(env, reg->type));
8120 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
8121 		return -EACCES;
8122 	}
8123 }
8124 
8125 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
8126  * size.
8127  *
8128  * @regno is the register containing the access size. regno-1 is the register
8129  * containing the pointer.
8130  */
8131 static int check_mem_size_reg(struct bpf_verifier_env *env,
8132 			      struct bpf_reg_state *reg, u32 regno,
8133 			      enum bpf_access_type access_type,
8134 			      bool zero_size_allowed,
8135 			      struct bpf_call_arg_meta *meta)
8136 {
8137 	int err;
8138 
8139 	/* This is used to refine r0 return value bounds for helpers
8140 	 * that enforce this value as an upper bound on return values.
8141 	 * See do_refine_retval_range() for helpers that can refine
8142 	 * the return value. C type of helper is u32 so we pull register
8143 	 * bound from umax_value however, if negative verifier errors
8144 	 * out. Only upper bounds can be learned because retval is an
8145 	 * int type and negative retvals are allowed.
8146 	 */
8147 	meta->msize_max_value = reg->umax_value;
8148 
8149 	/* The register is SCALAR_VALUE; the access check happens using
8150 	 * its boundaries. For unprivileged variable accesses, disable
8151 	 * raw mode so that the program is required to initialize all
8152 	 * the memory that the helper could just partially fill up.
8153 	 */
8154 	if (!tnum_is_const(reg->var_off))
8155 		meta = NULL;
8156 
8157 	if (reg->smin_value < 0) {
8158 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
8159 			regno);
8160 		return -EACCES;
8161 	}
8162 
8163 	if (reg->umin_value == 0 && !zero_size_allowed) {
8164 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
8165 			regno, reg->umin_value, reg->umax_value);
8166 		return -EACCES;
8167 	}
8168 
8169 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
8170 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
8171 			regno);
8172 		return -EACCES;
8173 	}
8174 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
8175 				      access_type, zero_size_allowed, meta);
8176 	if (!err)
8177 		err = mark_chain_precision(env, regno);
8178 	return err;
8179 }
8180 
8181 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8182 			 u32 regno, u32 mem_size)
8183 {
8184 	bool may_be_null = type_may_be_null(reg->type);
8185 	struct bpf_reg_state saved_reg;
8186 	int err;
8187 
8188 	if (register_is_null(reg))
8189 		return 0;
8190 
8191 	/* Assuming that the register contains a value check if the memory
8192 	 * access is safe. Temporarily save and restore the register's state as
8193 	 * the conversion shouldn't be visible to a caller.
8194 	 */
8195 	if (may_be_null) {
8196 		saved_reg = *reg;
8197 		mark_ptr_not_null_reg(reg);
8198 	}
8199 
8200 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
8201 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
8202 
8203 	if (may_be_null)
8204 		*reg = saved_reg;
8205 
8206 	return err;
8207 }
8208 
8209 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8210 				    u32 regno)
8211 {
8212 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
8213 	bool may_be_null = type_may_be_null(mem_reg->type);
8214 	struct bpf_reg_state saved_reg;
8215 	struct bpf_call_arg_meta meta;
8216 	int err;
8217 
8218 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
8219 
8220 	memset(&meta, 0, sizeof(meta));
8221 
8222 	if (may_be_null) {
8223 		saved_reg = *mem_reg;
8224 		mark_ptr_not_null_reg(mem_reg);
8225 	}
8226 
8227 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
8228 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
8229 
8230 	if (may_be_null)
8231 		*mem_reg = saved_reg;
8232 
8233 	return err;
8234 }
8235 
8236 enum {
8237 	PROCESS_SPIN_LOCK = (1 << 0),
8238 	PROCESS_RES_LOCK  = (1 << 1),
8239 	PROCESS_LOCK_IRQ  = (1 << 2),
8240 };
8241 
8242 /* Implementation details:
8243  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
8244  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
8245  * Two bpf_map_lookups (even with the same key) will have different reg->id.
8246  * Two separate bpf_obj_new will also have different reg->id.
8247  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
8248  * clears reg->id after value_or_null->value transition, since the verifier only
8249  * cares about the range of access to valid map value pointer and doesn't care
8250  * about actual address of the map element.
8251  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
8252  * reg->id > 0 after value_or_null->value transition. By doing so
8253  * two bpf_map_lookups will be considered two different pointers that
8254  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
8255  * returned from bpf_obj_new.
8256  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8257  * dead-locks.
8258  * Since only one bpf_spin_lock is allowed the checks are simpler than
8259  * reg_is_refcounted() logic. The verifier needs to remember only
8260  * one spin_lock instead of array of acquired_refs.
8261  * env->cur_state->active_locks remembers which map value element or allocated
8262  * object got locked and clears it after bpf_spin_unlock.
8263  */
8264 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags)
8265 {
8266 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
8267 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
8268 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8269 	struct bpf_verifier_state *cur = env->cur_state;
8270 	bool is_const = tnum_is_const(reg->var_off);
8271 	bool is_irq = flags & PROCESS_LOCK_IRQ;
8272 	u64 val = reg->var_off.value;
8273 	struct bpf_map *map = NULL;
8274 	struct btf *btf = NULL;
8275 	struct btf_record *rec;
8276 	u32 spin_lock_off;
8277 	int err;
8278 
8279 	if (!is_const) {
8280 		verbose(env,
8281 			"R%d doesn't have constant offset. %s_lock has to be at the constant offset\n",
8282 			regno, lock_str);
8283 		return -EINVAL;
8284 	}
8285 	if (reg->type == PTR_TO_MAP_VALUE) {
8286 		map = reg->map_ptr;
8287 		if (!map->btf) {
8288 			verbose(env,
8289 				"map '%s' has to have BTF in order to use %s_lock\n",
8290 				map->name, lock_str);
8291 			return -EINVAL;
8292 		}
8293 	} else {
8294 		btf = reg->btf;
8295 	}
8296 
8297 	rec = reg_btf_record(reg);
8298 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
8299 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
8300 			map ? map->name : "kptr", lock_str);
8301 		return -EINVAL;
8302 	}
8303 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
8304 	if (spin_lock_off != val + reg->off) {
8305 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
8306 			val + reg->off, lock_str, spin_lock_off);
8307 		return -EINVAL;
8308 	}
8309 	if (is_lock) {
8310 		void *ptr;
8311 		int type;
8312 
8313 		if (map)
8314 			ptr = map;
8315 		else
8316 			ptr = btf;
8317 
8318 		if (!is_res_lock && cur->active_locks) {
8319 			if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) {
8320 				verbose(env,
8321 					"Locking two bpf_spin_locks are not allowed\n");
8322 				return -EINVAL;
8323 			}
8324 		} else if (is_res_lock && cur->active_locks) {
8325 			if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) {
8326 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
8327 				return -EINVAL;
8328 			}
8329 		}
8330 
8331 		if (is_res_lock && is_irq)
8332 			type = REF_TYPE_RES_LOCK_IRQ;
8333 		else if (is_res_lock)
8334 			type = REF_TYPE_RES_LOCK;
8335 		else
8336 			type = REF_TYPE_LOCK;
8337 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
8338 		if (err < 0) {
8339 			verbose(env, "Failed to acquire lock state\n");
8340 			return err;
8341 		}
8342 	} else {
8343 		void *ptr;
8344 		int type;
8345 
8346 		if (map)
8347 			ptr = map;
8348 		else
8349 			ptr = btf;
8350 
8351 		if (!cur->active_locks) {
8352 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
8353 			return -EINVAL;
8354 		}
8355 
8356 		if (is_res_lock && is_irq)
8357 			type = REF_TYPE_RES_LOCK_IRQ;
8358 		else if (is_res_lock)
8359 			type = REF_TYPE_RES_LOCK;
8360 		else
8361 			type = REF_TYPE_LOCK;
8362 		if (!find_lock_state(cur, type, reg->id, ptr)) {
8363 			verbose(env, "%s_unlock of different lock\n", lock_str);
8364 			return -EINVAL;
8365 		}
8366 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
8367 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
8368 			return -EINVAL;
8369 		}
8370 		if (release_lock_state(cur, type, reg->id, ptr)) {
8371 			verbose(env, "%s_unlock of different lock\n", lock_str);
8372 			return -EINVAL;
8373 		}
8374 
8375 		invalidate_non_owning_refs(env);
8376 	}
8377 	return 0;
8378 }
8379 
8380 static int process_timer_func(struct bpf_verifier_env *env, int regno,
8381 			      struct bpf_call_arg_meta *meta)
8382 {
8383 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8384 	bool is_const = tnum_is_const(reg->var_off);
8385 	struct bpf_map *map = reg->map_ptr;
8386 	u64 val = reg->var_off.value;
8387 
8388 	if (!is_const) {
8389 		verbose(env,
8390 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
8391 			regno);
8392 		return -EINVAL;
8393 	}
8394 	if (!map->btf) {
8395 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
8396 			map->name);
8397 		return -EINVAL;
8398 	}
8399 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
8400 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
8401 		return -EINVAL;
8402 	}
8403 	if (map->record->timer_off != val + reg->off) {
8404 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
8405 			val + reg->off, map->record->timer_off);
8406 		return -EINVAL;
8407 	}
8408 	if (meta->map_ptr) {
8409 		verifier_bug(env, "Two map pointers in a timer helper");
8410 		return -EFAULT;
8411 	}
8412 	meta->map_uid = reg->map_uid;
8413 	meta->map_ptr = map;
8414 	return 0;
8415 }
8416 
8417 static int process_wq_func(struct bpf_verifier_env *env, int regno,
8418 			   struct bpf_kfunc_call_arg_meta *meta)
8419 {
8420 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8421 	struct bpf_map *map = reg->map_ptr;
8422 	u64 val = reg->var_off.value;
8423 
8424 	if (map->record->wq_off != val + reg->off) {
8425 		verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
8426 			val + reg->off, map->record->wq_off);
8427 		return -EINVAL;
8428 	}
8429 	meta->map.uid = reg->map_uid;
8430 	meta->map.ptr = map;
8431 	return 0;
8432 }
8433 
8434 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8435 			     struct bpf_call_arg_meta *meta)
8436 {
8437 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8438 	struct btf_field *kptr_field;
8439 	struct bpf_map *map_ptr;
8440 	struct btf_record *rec;
8441 	u32 kptr_off;
8442 
8443 	if (type_is_ptr_alloc_obj(reg->type)) {
8444 		rec = reg_btf_record(reg);
8445 	} else { /* PTR_TO_MAP_VALUE */
8446 		map_ptr = reg->map_ptr;
8447 		if (!map_ptr->btf) {
8448 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8449 				map_ptr->name);
8450 			return -EINVAL;
8451 		}
8452 		rec = map_ptr->record;
8453 		meta->map_ptr = map_ptr;
8454 	}
8455 
8456 	if (!tnum_is_const(reg->var_off)) {
8457 		verbose(env,
8458 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8459 			regno);
8460 		return -EINVAL;
8461 	}
8462 
8463 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8464 		verbose(env, "R%d has no valid kptr\n", regno);
8465 		return -EINVAL;
8466 	}
8467 
8468 	kptr_off = reg->off + reg->var_off.value;
8469 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8470 	if (!kptr_field) {
8471 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8472 		return -EACCES;
8473 	}
8474 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8475 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8476 		return -EACCES;
8477 	}
8478 	meta->kptr_field = kptr_field;
8479 	return 0;
8480 }
8481 
8482 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8483  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8484  *
8485  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8486  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8487  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8488  *
8489  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
8490  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
8491  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
8492  * mutate the view of the dynptr and also possibly destroy it. In the latter
8493  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
8494  * memory that dynptr points to.
8495  *
8496  * The verifier will keep track both levels of mutation (bpf_dynptr's in
8497  * reg->type and the memory's in reg->dynptr.type), but there is no support for
8498  * readonly dynptr view yet, hence only the first case is tracked and checked.
8499  *
8500  * This is consistent with how C applies the const modifier to a struct object,
8501  * where the pointer itself inside bpf_dynptr becomes const but not what it
8502  * points to.
8503  *
8504  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
8505  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
8506  */
8507 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
8508 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
8509 {
8510 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8511 	int err;
8512 
8513 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
8514 		verbose(env,
8515 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
8516 			regno - 1);
8517 		return -EINVAL;
8518 	}
8519 
8520 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
8521 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
8522 	 */
8523 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
8524 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
8525 		return -EFAULT;
8526 	}
8527 
8528 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8529 	 *		 constructing a mutable bpf_dynptr object.
8530 	 *
8531 	 *		 Currently, this is only possible with PTR_TO_STACK
8532 	 *		 pointing to a region of at least 16 bytes which doesn't
8533 	 *		 contain an existing bpf_dynptr.
8534 	 *
8535 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
8536 	 *		 mutated or destroyed. However, the memory it points to
8537 	 *		 may be mutated.
8538 	 *
8539 	 *  None       - Points to a initialized dynptr that can be mutated and
8540 	 *		 destroyed, including mutation of the memory it points
8541 	 *		 to.
8542 	 */
8543 	if (arg_type & MEM_UNINIT) {
8544 		int i;
8545 
8546 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8547 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8548 			return -EINVAL;
8549 		}
8550 
8551 		/* we write BPF_DW bits (8 bytes) at a time */
8552 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8553 			err = check_mem_access(env, insn_idx, regno,
8554 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8555 			if (err)
8556 				return err;
8557 		}
8558 
8559 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
8560 	} else /* MEM_RDONLY and None case from above */ {
8561 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8562 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
8563 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
8564 			return -EINVAL;
8565 		}
8566 
8567 		if (!is_dynptr_reg_valid_init(env, reg)) {
8568 			verbose(env,
8569 				"Expected an initialized dynptr as arg #%d\n",
8570 				regno - 1);
8571 			return -EINVAL;
8572 		}
8573 
8574 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
8575 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
8576 			verbose(env,
8577 				"Expected a dynptr of type %s as arg #%d\n",
8578 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
8579 			return -EINVAL;
8580 		}
8581 
8582 		err = mark_dynptr_read(env, reg);
8583 	}
8584 	return err;
8585 }
8586 
8587 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
8588 {
8589 	struct bpf_func_state *state = func(env, reg);
8590 
8591 	return state->stack[spi].spilled_ptr.ref_obj_id;
8592 }
8593 
8594 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8595 {
8596 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8597 }
8598 
8599 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8600 {
8601 	return meta->kfunc_flags & KF_ITER_NEW;
8602 }
8603 
8604 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8605 {
8606 	return meta->kfunc_flags & KF_ITER_NEXT;
8607 }
8608 
8609 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8610 {
8611 	return meta->kfunc_flags & KF_ITER_DESTROY;
8612 }
8613 
8614 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
8615 			      const struct btf_param *arg)
8616 {
8617 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8618 	 * kfunc is iter state pointer
8619 	 */
8620 	if (is_iter_kfunc(meta))
8621 		return arg_idx == 0;
8622 
8623 	/* iter passed as an argument to a generic kfunc */
8624 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8625 }
8626 
8627 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
8628 			    struct bpf_kfunc_call_arg_meta *meta)
8629 {
8630 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8631 	const struct btf_type *t;
8632 	int spi, err, i, nr_slots, btf_id;
8633 
8634 	if (reg->type != PTR_TO_STACK) {
8635 		verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
8636 		return -EINVAL;
8637 	}
8638 
8639 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8640 	 * ensures struct convention, so we wouldn't need to do any BTF
8641 	 * validation here. But given iter state can be passed as a parameter
8642 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8643 	 * conservative here.
8644 	 */
8645 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8646 	if (btf_id < 0) {
8647 		verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
8648 		return -EINVAL;
8649 	}
8650 	t = btf_type_by_id(meta->btf, btf_id);
8651 	nr_slots = t->size / BPF_REG_SIZE;
8652 
8653 	if (is_iter_new_kfunc(meta)) {
8654 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8655 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8656 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8657 				iter_type_str(meta->btf, btf_id), regno - 1);
8658 			return -EINVAL;
8659 		}
8660 
8661 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8662 			err = check_mem_access(env, insn_idx, regno,
8663 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8664 			if (err)
8665 				return err;
8666 		}
8667 
8668 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8669 		if (err)
8670 			return err;
8671 	} else {
8672 		/* iter_next() or iter_destroy(), as well as any kfunc
8673 		 * accepting iter argument, expect initialized iter state
8674 		 */
8675 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8676 		switch (err) {
8677 		case 0:
8678 			break;
8679 		case -EINVAL:
8680 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
8681 				iter_type_str(meta->btf, btf_id), regno - 1);
8682 			return err;
8683 		case -EPROTO:
8684 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8685 			return err;
8686 		default:
8687 			return err;
8688 		}
8689 
8690 		spi = iter_get_spi(env, reg, nr_slots);
8691 		if (spi < 0)
8692 			return spi;
8693 
8694 		err = mark_iter_read(env, reg, spi, nr_slots);
8695 		if (err)
8696 			return err;
8697 
8698 		/* remember meta->iter info for process_iter_next_call() */
8699 		meta->iter.spi = spi;
8700 		meta->iter.frameno = reg->frameno;
8701 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8702 
8703 		if (is_iter_destroy_kfunc(meta)) {
8704 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8705 			if (err)
8706 				return err;
8707 		}
8708 	}
8709 
8710 	return 0;
8711 }
8712 
8713 /* Look for a previous loop entry at insn_idx: nearest parent state
8714  * stopped at insn_idx with callsites matching those in cur->frame.
8715  */
8716 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8717 						  struct bpf_verifier_state *cur,
8718 						  int insn_idx)
8719 {
8720 	struct bpf_verifier_state_list *sl;
8721 	struct bpf_verifier_state *st;
8722 	struct list_head *pos, *head;
8723 
8724 	/* Explored states are pushed in stack order, most recent states come first */
8725 	head = explored_state(env, insn_idx);
8726 	list_for_each(pos, head) {
8727 		sl = container_of(pos, struct bpf_verifier_state_list, node);
8728 		/* If st->branches != 0 state is a part of current DFS verification path,
8729 		 * hence cur & st for a loop.
8730 		 */
8731 		st = &sl->state;
8732 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8733 		    st->dfs_depth < cur->dfs_depth)
8734 			return st;
8735 	}
8736 
8737 	return NULL;
8738 }
8739 
8740 static void reset_idmap_scratch(struct bpf_verifier_env *env);
8741 static bool regs_exact(const struct bpf_reg_state *rold,
8742 		       const struct bpf_reg_state *rcur,
8743 		       struct bpf_idmap *idmap);
8744 
8745 static void maybe_widen_reg(struct bpf_verifier_env *env,
8746 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8747 			    struct bpf_idmap *idmap)
8748 {
8749 	if (rold->type != SCALAR_VALUE)
8750 		return;
8751 	if (rold->type != rcur->type)
8752 		return;
8753 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
8754 		return;
8755 	__mark_reg_unknown(env, rcur);
8756 }
8757 
8758 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8759 				   struct bpf_verifier_state *old,
8760 				   struct bpf_verifier_state *cur)
8761 {
8762 	struct bpf_func_state *fold, *fcur;
8763 	int i, fr;
8764 
8765 	reset_idmap_scratch(env);
8766 	for (fr = old->curframe; fr >= 0; fr--) {
8767 		fold = old->frame[fr];
8768 		fcur = cur->frame[fr];
8769 
8770 		for (i = 0; i < MAX_BPF_REG; i++)
8771 			maybe_widen_reg(env,
8772 					&fold->regs[i],
8773 					&fcur->regs[i],
8774 					&env->idmap_scratch);
8775 
8776 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
8777 			if (!is_spilled_reg(&fold->stack[i]) ||
8778 			    !is_spilled_reg(&fcur->stack[i]))
8779 				continue;
8780 
8781 			maybe_widen_reg(env,
8782 					&fold->stack[i].spilled_ptr,
8783 					&fcur->stack[i].spilled_ptr,
8784 					&env->idmap_scratch);
8785 		}
8786 	}
8787 	return 0;
8788 }
8789 
8790 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8791 						 struct bpf_kfunc_call_arg_meta *meta)
8792 {
8793 	int iter_frameno = meta->iter.frameno;
8794 	int iter_spi = meta->iter.spi;
8795 
8796 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8797 }
8798 
8799 /* process_iter_next_call() is called when verifier gets to iterator's next
8800  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8801  * to it as just "iter_next()" in comments below.
8802  *
8803  * BPF verifier relies on a crucial contract for any iter_next()
8804  * implementation: it should *eventually* return NULL, and once that happens
8805  * it should keep returning NULL. That is, once iterator exhausts elements to
8806  * iterate, it should never reset or spuriously return new elements.
8807  *
8808  * With the assumption of such contract, process_iter_next_call() simulates
8809  * a fork in the verifier state to validate loop logic correctness and safety
8810  * without having to simulate infinite amount of iterations.
8811  *
8812  * In current state, we first assume that iter_next() returned NULL and
8813  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8814  * conditions we should not form an infinite loop and should eventually reach
8815  * exit.
8816  *
8817  * Besides that, we also fork current state and enqueue it for later
8818  * verification. In a forked state we keep iterator state as ACTIVE
8819  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8820  * also bump iteration depth to prevent erroneous infinite loop detection
8821  * later on (see iter_active_depths_differ() comment for details). In this
8822  * state we assume that we'll eventually loop back to another iter_next()
8823  * calls (it could be in exactly same location or in some other instruction,
8824  * it doesn't matter, we don't make any unnecessary assumptions about this,
8825  * everything revolves around iterator state in a stack slot, not which
8826  * instruction is calling iter_next()). When that happens, we either will come
8827  * to iter_next() with equivalent state and can conclude that next iteration
8828  * will proceed in exactly the same way as we just verified, so it's safe to
8829  * assume that loop converges. If not, we'll go on another iteration
8830  * simulation with a different input state, until all possible starting states
8831  * are validated or we reach maximum number of instructions limit.
8832  *
8833  * This way, we will either exhaustively discover all possible input states
8834  * that iterator loop can start with and eventually will converge, or we'll
8835  * effectively regress into bounded loop simulation logic and either reach
8836  * maximum number of instructions if loop is not provably convergent, or there
8837  * is some statically known limit on number of iterations (e.g., if there is
8838  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8839  *
8840  * Iteration convergence logic in is_state_visited() relies on exact
8841  * states comparison, which ignores read and precision marks.
8842  * This is necessary because read and precision marks are not finalized
8843  * while in the loop. Exact comparison might preclude convergence for
8844  * simple programs like below:
8845  *
8846  *     i = 0;
8847  *     while(iter_next(&it))
8848  *       i++;
8849  *
8850  * At each iteration step i++ would produce a new distinct state and
8851  * eventually instruction processing limit would be reached.
8852  *
8853  * To avoid such behavior speculatively forget (widen) range for
8854  * imprecise scalar registers, if those registers were not precise at the
8855  * end of the previous iteration and do not match exactly.
8856  *
8857  * This is a conservative heuristic that allows to verify wide range of programs,
8858  * however it precludes verification of programs that conjure an
8859  * imprecise value on the first loop iteration and use it as precise on a second.
8860  * For example, the following safe program would fail to verify:
8861  *
8862  *     struct bpf_num_iter it;
8863  *     int arr[10];
8864  *     int i = 0, a = 0;
8865  *     bpf_iter_num_new(&it, 0, 10);
8866  *     while (bpf_iter_num_next(&it)) {
8867  *       if (a == 0) {
8868  *         a = 1;
8869  *         i = 7; // Because i changed verifier would forget
8870  *                // it's range on second loop entry.
8871  *       } else {
8872  *         arr[i] = 42; // This would fail to verify.
8873  *       }
8874  *     }
8875  *     bpf_iter_num_destroy(&it);
8876  */
8877 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8878 				  struct bpf_kfunc_call_arg_meta *meta)
8879 {
8880 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8881 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8882 	struct bpf_reg_state *cur_iter, *queued_iter;
8883 
8884 	BTF_TYPE_EMIT(struct bpf_iter);
8885 
8886 	cur_iter = get_iter_from_state(cur_st, meta);
8887 
8888 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8889 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8890 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
8891 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8892 		return -EFAULT;
8893 	}
8894 
8895 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8896 		/* Because iter_next() call is a checkpoint is_state_visitied()
8897 		 * should guarantee parent state with same call sites and insn_idx.
8898 		 */
8899 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8900 		    !same_callsites(cur_st->parent, cur_st)) {
8901 			verbose(env, "bug: bad parent state for iter next call");
8902 			return -EFAULT;
8903 		}
8904 		/* Note cur_st->parent in the call below, it is necessary to skip
8905 		 * checkpoint created for cur_st by is_state_visited()
8906 		 * right at this instruction.
8907 		 */
8908 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8909 		/* branch out active iter state */
8910 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8911 		if (!queued_st)
8912 			return -ENOMEM;
8913 
8914 		queued_iter = get_iter_from_state(queued_st, meta);
8915 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8916 		queued_iter->iter.depth++;
8917 		if (prev_st)
8918 			widen_imprecise_scalars(env, prev_st, queued_st);
8919 
8920 		queued_fr = queued_st->frame[queued_st->curframe];
8921 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8922 	}
8923 
8924 	/* switch to DRAINED state, but keep the depth unchanged */
8925 	/* mark current iter state as drained and assume returned NULL */
8926 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8927 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8928 
8929 	return 0;
8930 }
8931 
8932 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8933 {
8934 	return type == ARG_CONST_SIZE ||
8935 	       type == ARG_CONST_SIZE_OR_ZERO;
8936 }
8937 
8938 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
8939 {
8940 	return base_type(type) == ARG_PTR_TO_MEM &&
8941 	       type & MEM_UNINIT;
8942 }
8943 
8944 static bool arg_type_is_release(enum bpf_arg_type type)
8945 {
8946 	return type & OBJ_RELEASE;
8947 }
8948 
8949 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8950 {
8951 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8952 }
8953 
8954 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8955 				 const struct bpf_call_arg_meta *meta,
8956 				 enum bpf_arg_type *arg_type)
8957 {
8958 	if (!meta->map_ptr) {
8959 		/* kernel subsystem misconfigured verifier */
8960 		verbose(env, "invalid map_ptr to access map->type\n");
8961 		return -EACCES;
8962 	}
8963 
8964 	switch (meta->map_ptr->map_type) {
8965 	case BPF_MAP_TYPE_SOCKMAP:
8966 	case BPF_MAP_TYPE_SOCKHASH:
8967 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8968 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8969 		} else {
8970 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8971 			return -EINVAL;
8972 		}
8973 		break;
8974 	case BPF_MAP_TYPE_BLOOM_FILTER:
8975 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8976 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8977 		break;
8978 	default:
8979 		break;
8980 	}
8981 	return 0;
8982 }
8983 
8984 struct bpf_reg_types {
8985 	const enum bpf_reg_type types[10];
8986 	u32 *btf_id;
8987 };
8988 
8989 static const struct bpf_reg_types sock_types = {
8990 	.types = {
8991 		PTR_TO_SOCK_COMMON,
8992 		PTR_TO_SOCKET,
8993 		PTR_TO_TCP_SOCK,
8994 		PTR_TO_XDP_SOCK,
8995 	},
8996 };
8997 
8998 #ifdef CONFIG_NET
8999 static const struct bpf_reg_types btf_id_sock_common_types = {
9000 	.types = {
9001 		PTR_TO_SOCK_COMMON,
9002 		PTR_TO_SOCKET,
9003 		PTR_TO_TCP_SOCK,
9004 		PTR_TO_XDP_SOCK,
9005 		PTR_TO_BTF_ID,
9006 		PTR_TO_BTF_ID | PTR_TRUSTED,
9007 	},
9008 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9009 };
9010 #endif
9011 
9012 static const struct bpf_reg_types mem_types = {
9013 	.types = {
9014 		PTR_TO_STACK,
9015 		PTR_TO_PACKET,
9016 		PTR_TO_PACKET_META,
9017 		PTR_TO_MAP_KEY,
9018 		PTR_TO_MAP_VALUE,
9019 		PTR_TO_MEM,
9020 		PTR_TO_MEM | MEM_RINGBUF,
9021 		PTR_TO_BUF,
9022 		PTR_TO_BTF_ID | PTR_TRUSTED,
9023 	},
9024 };
9025 
9026 static const struct bpf_reg_types spin_lock_types = {
9027 	.types = {
9028 		PTR_TO_MAP_VALUE,
9029 		PTR_TO_BTF_ID | MEM_ALLOC,
9030 	}
9031 };
9032 
9033 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
9034 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
9035 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
9036 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
9037 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
9038 static const struct bpf_reg_types btf_ptr_types = {
9039 	.types = {
9040 		PTR_TO_BTF_ID,
9041 		PTR_TO_BTF_ID | PTR_TRUSTED,
9042 		PTR_TO_BTF_ID | MEM_RCU,
9043 	},
9044 };
9045 static const struct bpf_reg_types percpu_btf_ptr_types = {
9046 	.types = {
9047 		PTR_TO_BTF_ID | MEM_PERCPU,
9048 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
9049 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
9050 	}
9051 };
9052 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
9053 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
9054 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
9055 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
9056 static const struct bpf_reg_types kptr_xchg_dest_types = {
9057 	.types = {
9058 		PTR_TO_MAP_VALUE,
9059 		PTR_TO_BTF_ID | MEM_ALLOC
9060 	}
9061 };
9062 static const struct bpf_reg_types dynptr_types = {
9063 	.types = {
9064 		PTR_TO_STACK,
9065 		CONST_PTR_TO_DYNPTR,
9066 	}
9067 };
9068 
9069 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
9070 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
9071 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
9072 	[ARG_CONST_SIZE]		= &scalar_types,
9073 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
9074 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
9075 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
9076 	[ARG_PTR_TO_CTX]		= &context_types,
9077 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
9078 #ifdef CONFIG_NET
9079 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
9080 #endif
9081 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
9082 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
9083 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
9084 	[ARG_PTR_TO_MEM]		= &mem_types,
9085 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
9086 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
9087 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
9088 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
9089 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
9090 	[ARG_PTR_TO_TIMER]		= &timer_types,
9091 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
9092 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
9093 };
9094 
9095 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
9096 			  enum bpf_arg_type arg_type,
9097 			  const u32 *arg_btf_id,
9098 			  struct bpf_call_arg_meta *meta)
9099 {
9100 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9101 	enum bpf_reg_type expected, type = reg->type;
9102 	const struct bpf_reg_types *compatible;
9103 	int i, j;
9104 
9105 	compatible = compatible_reg_types[base_type(arg_type)];
9106 	if (!compatible) {
9107 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
9108 		return -EFAULT;
9109 	}
9110 
9111 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
9112 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
9113 	 *
9114 	 * Same for MAYBE_NULL:
9115 	 *
9116 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
9117 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
9118 	 *
9119 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
9120 	 *
9121 	 * Therefore we fold these flags depending on the arg_type before comparison.
9122 	 */
9123 	if (arg_type & MEM_RDONLY)
9124 		type &= ~MEM_RDONLY;
9125 	if (arg_type & PTR_MAYBE_NULL)
9126 		type &= ~PTR_MAYBE_NULL;
9127 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
9128 		type &= ~DYNPTR_TYPE_FLAG_MASK;
9129 
9130 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
9131 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
9132 		type &= ~MEM_ALLOC;
9133 		type &= ~MEM_PERCPU;
9134 	}
9135 
9136 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
9137 		expected = compatible->types[i];
9138 		if (expected == NOT_INIT)
9139 			break;
9140 
9141 		if (type == expected)
9142 			goto found;
9143 	}
9144 
9145 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
9146 	for (j = 0; j + 1 < i; j++)
9147 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
9148 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
9149 	return -EACCES;
9150 
9151 found:
9152 	if (base_type(reg->type) != PTR_TO_BTF_ID)
9153 		return 0;
9154 
9155 	if (compatible == &mem_types) {
9156 		if (!(arg_type & MEM_RDONLY)) {
9157 			verbose(env,
9158 				"%s() may write into memory pointed by R%d type=%s\n",
9159 				func_id_name(meta->func_id),
9160 				regno, reg_type_str(env, reg->type));
9161 			return -EACCES;
9162 		}
9163 		return 0;
9164 	}
9165 
9166 	switch ((int)reg->type) {
9167 	case PTR_TO_BTF_ID:
9168 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9169 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
9170 	case PTR_TO_BTF_ID | MEM_RCU:
9171 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
9172 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
9173 	{
9174 		/* For bpf_sk_release, it needs to match against first member
9175 		 * 'struct sock_common', hence make an exception for it. This
9176 		 * allows bpf_sk_release to work for multiple socket types.
9177 		 */
9178 		bool strict_type_match = arg_type_is_release(arg_type) &&
9179 					 meta->func_id != BPF_FUNC_sk_release;
9180 
9181 		if (type_may_be_null(reg->type) &&
9182 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
9183 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
9184 			return -EACCES;
9185 		}
9186 
9187 		if (!arg_btf_id) {
9188 			if (!compatible->btf_id) {
9189 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
9190 				return -EFAULT;
9191 			}
9192 			arg_btf_id = compatible->btf_id;
9193 		}
9194 
9195 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
9196 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9197 				return -EACCES;
9198 		} else {
9199 			if (arg_btf_id == BPF_PTR_POISON) {
9200 				verbose(env, "verifier internal error:");
9201 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
9202 					regno);
9203 				return -EACCES;
9204 			}
9205 
9206 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
9207 						  btf_vmlinux, *arg_btf_id,
9208 						  strict_type_match)) {
9209 				verbose(env, "R%d is of type %s but %s is expected\n",
9210 					regno, btf_type_name(reg->btf, reg->btf_id),
9211 					btf_type_name(btf_vmlinux, *arg_btf_id));
9212 				return -EACCES;
9213 			}
9214 		}
9215 		break;
9216 	}
9217 	case PTR_TO_BTF_ID | MEM_ALLOC:
9218 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
9219 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
9220 		    meta->func_id != BPF_FUNC_kptr_xchg) {
9221 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
9222 			return -EFAULT;
9223 		}
9224 		/* Check if local kptr in src arg matches kptr in dst arg */
9225 		if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
9226 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9227 				return -EACCES;
9228 		}
9229 		break;
9230 	case PTR_TO_BTF_ID | MEM_PERCPU:
9231 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
9232 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
9233 		/* Handled by helper specific checks */
9234 		break;
9235 	default:
9236 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
9237 		return -EFAULT;
9238 	}
9239 	return 0;
9240 }
9241 
9242 static struct btf_field *
9243 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
9244 {
9245 	struct btf_field *field;
9246 	struct btf_record *rec;
9247 
9248 	rec = reg_btf_record(reg);
9249 	if (!rec)
9250 		return NULL;
9251 
9252 	field = btf_record_find(rec, off, fields);
9253 	if (!field)
9254 		return NULL;
9255 
9256 	return field;
9257 }
9258 
9259 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
9260 				  const struct bpf_reg_state *reg, int regno,
9261 				  enum bpf_arg_type arg_type)
9262 {
9263 	u32 type = reg->type;
9264 
9265 	/* When referenced register is passed to release function, its fixed
9266 	 * offset must be 0.
9267 	 *
9268 	 * We will check arg_type_is_release reg has ref_obj_id when storing
9269 	 * meta->release_regno.
9270 	 */
9271 	if (arg_type_is_release(arg_type)) {
9272 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
9273 		 * may not directly point to the object being released, but to
9274 		 * dynptr pointing to such object, which might be at some offset
9275 		 * on the stack. In that case, we simply to fallback to the
9276 		 * default handling.
9277 		 */
9278 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
9279 			return 0;
9280 
9281 		/* Doing check_ptr_off_reg check for the offset will catch this
9282 		 * because fixed_off_ok is false, but checking here allows us
9283 		 * to give the user a better error message.
9284 		 */
9285 		if (reg->off) {
9286 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
9287 				regno);
9288 			return -EINVAL;
9289 		}
9290 		return __check_ptr_off_reg(env, reg, regno, false);
9291 	}
9292 
9293 	switch (type) {
9294 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9295 	case PTR_TO_STACK:
9296 	case PTR_TO_PACKET:
9297 	case PTR_TO_PACKET_META:
9298 	case PTR_TO_MAP_KEY:
9299 	case PTR_TO_MAP_VALUE:
9300 	case PTR_TO_MEM:
9301 	case PTR_TO_MEM | MEM_RDONLY:
9302 	case PTR_TO_MEM | MEM_RINGBUF:
9303 	case PTR_TO_BUF:
9304 	case PTR_TO_BUF | MEM_RDONLY:
9305 	case PTR_TO_ARENA:
9306 	case SCALAR_VALUE:
9307 		return 0;
9308 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9309 	 * fixed offset.
9310 	 */
9311 	case PTR_TO_BTF_ID:
9312 	case PTR_TO_BTF_ID | MEM_ALLOC:
9313 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9314 	case PTR_TO_BTF_ID | MEM_RCU:
9315 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9316 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9317 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9318 		 * its fixed offset must be 0. In the other cases, fixed offset
9319 		 * can be non-zero. This was already checked above. So pass
9320 		 * fixed_off_ok as true to allow fixed offset for all other
9321 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
9322 		 * still need to do checks instead of returning.
9323 		 */
9324 		return __check_ptr_off_reg(env, reg, regno, true);
9325 	default:
9326 		return __check_ptr_off_reg(env, reg, regno, false);
9327 	}
9328 }
9329 
9330 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
9331 						const struct bpf_func_proto *fn,
9332 						struct bpf_reg_state *regs)
9333 {
9334 	struct bpf_reg_state *state = NULL;
9335 	int i;
9336 
9337 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
9338 		if (arg_type_is_dynptr(fn->arg_type[i])) {
9339 			if (state) {
9340 				verbose(env, "verifier internal error: multiple dynptr args\n");
9341 				return NULL;
9342 			}
9343 			state = &regs[BPF_REG_1 + i];
9344 		}
9345 
9346 	if (!state)
9347 		verbose(env, "verifier internal error: no dynptr arg found\n");
9348 
9349 	return state;
9350 }
9351 
9352 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9353 {
9354 	struct bpf_func_state *state = func(env, reg);
9355 	int spi;
9356 
9357 	if (reg->type == CONST_PTR_TO_DYNPTR)
9358 		return reg->id;
9359 	spi = dynptr_get_spi(env, reg);
9360 	if (spi < 0)
9361 		return spi;
9362 	return state->stack[spi].spilled_ptr.id;
9363 }
9364 
9365 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9366 {
9367 	struct bpf_func_state *state = func(env, reg);
9368 	int spi;
9369 
9370 	if (reg->type == CONST_PTR_TO_DYNPTR)
9371 		return reg->ref_obj_id;
9372 	spi = dynptr_get_spi(env, reg);
9373 	if (spi < 0)
9374 		return spi;
9375 	return state->stack[spi].spilled_ptr.ref_obj_id;
9376 }
9377 
9378 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
9379 					    struct bpf_reg_state *reg)
9380 {
9381 	struct bpf_func_state *state = func(env, reg);
9382 	int spi;
9383 
9384 	if (reg->type == CONST_PTR_TO_DYNPTR)
9385 		return reg->dynptr.type;
9386 
9387 	spi = __get_spi(reg->off);
9388 	if (spi < 0) {
9389 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
9390 		return BPF_DYNPTR_TYPE_INVALID;
9391 	}
9392 
9393 	return state->stack[spi].spilled_ptr.dynptr.type;
9394 }
9395 
9396 static int check_reg_const_str(struct bpf_verifier_env *env,
9397 			       struct bpf_reg_state *reg, u32 regno)
9398 {
9399 	struct bpf_map *map = reg->map_ptr;
9400 	int err;
9401 	int map_off;
9402 	u64 map_addr;
9403 	char *str_ptr;
9404 
9405 	if (reg->type != PTR_TO_MAP_VALUE)
9406 		return -EINVAL;
9407 
9408 	if (!bpf_map_is_rdonly(map)) {
9409 		verbose(env, "R%d does not point to a readonly map'\n", regno);
9410 		return -EACCES;
9411 	}
9412 
9413 	if (!tnum_is_const(reg->var_off)) {
9414 		verbose(env, "R%d is not a constant address'\n", regno);
9415 		return -EACCES;
9416 	}
9417 
9418 	if (!map->ops->map_direct_value_addr) {
9419 		verbose(env, "no direct value access support for this map type\n");
9420 		return -EACCES;
9421 	}
9422 
9423 	err = check_map_access(env, regno, reg->off,
9424 			       map->value_size - reg->off, false,
9425 			       ACCESS_HELPER);
9426 	if (err)
9427 		return err;
9428 
9429 	map_off = reg->off + reg->var_off.value;
9430 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9431 	if (err) {
9432 		verbose(env, "direct value access on string failed\n");
9433 		return err;
9434 	}
9435 
9436 	str_ptr = (char *)(long)(map_addr);
9437 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9438 		verbose(env, "string is not zero-terminated\n");
9439 		return -EINVAL;
9440 	}
9441 	return 0;
9442 }
9443 
9444 /* Returns constant key value in `value` if possible, else negative error */
9445 static int get_constant_map_key(struct bpf_verifier_env *env,
9446 				struct bpf_reg_state *key,
9447 				u32 key_size,
9448 				s64 *value)
9449 {
9450 	struct bpf_func_state *state = func(env, key);
9451 	struct bpf_reg_state *reg;
9452 	int slot, spi, off;
9453 	int spill_size = 0;
9454 	int zero_size = 0;
9455 	int stack_off;
9456 	int i, err;
9457 	u8 *stype;
9458 
9459 	if (!env->bpf_capable)
9460 		return -EOPNOTSUPP;
9461 	if (key->type != PTR_TO_STACK)
9462 		return -EOPNOTSUPP;
9463 	if (!tnum_is_const(key->var_off))
9464 		return -EOPNOTSUPP;
9465 
9466 	stack_off = key->off + key->var_off.value;
9467 	slot = -stack_off - 1;
9468 	spi = slot / BPF_REG_SIZE;
9469 	off = slot % BPF_REG_SIZE;
9470 	stype = state->stack[spi].slot_type;
9471 
9472 	/* First handle precisely tracked STACK_ZERO */
9473 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9474 		zero_size++;
9475 	if (zero_size >= key_size) {
9476 		*value = 0;
9477 		return 0;
9478 	}
9479 
9480 	/* Check that stack contains a scalar spill of expected size */
9481 	if (!is_spilled_scalar_reg(&state->stack[spi]))
9482 		return -EOPNOTSUPP;
9483 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9484 		spill_size++;
9485 	if (spill_size != key_size)
9486 		return -EOPNOTSUPP;
9487 
9488 	reg = &state->stack[spi].spilled_ptr;
9489 	if (!tnum_is_const(reg->var_off))
9490 		/* Stack value not statically known */
9491 		return -EOPNOTSUPP;
9492 
9493 	/* We are relying on a constant value. So mark as precise
9494 	 * to prevent pruning on it.
9495 	 */
9496 	bt_set_frame_slot(&env->bt, key->frameno, spi);
9497 	err = mark_chain_precision_batch(env);
9498 	if (err < 0)
9499 		return err;
9500 
9501 	*value = reg->var_off.value;
9502 	return 0;
9503 }
9504 
9505 static bool can_elide_value_nullness(enum bpf_map_type type);
9506 
9507 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9508 			  struct bpf_call_arg_meta *meta,
9509 			  const struct bpf_func_proto *fn,
9510 			  int insn_idx)
9511 {
9512 	u32 regno = BPF_REG_1 + arg;
9513 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9514 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9515 	enum bpf_reg_type type = reg->type;
9516 	u32 *arg_btf_id = NULL;
9517 	u32 key_size;
9518 	int err = 0;
9519 
9520 	if (arg_type == ARG_DONTCARE)
9521 		return 0;
9522 
9523 	err = check_reg_arg(env, regno, SRC_OP);
9524 	if (err)
9525 		return err;
9526 
9527 	if (arg_type == ARG_ANYTHING) {
9528 		if (is_pointer_value(env, regno)) {
9529 			verbose(env, "R%d leaks addr into helper function\n",
9530 				regno);
9531 			return -EACCES;
9532 		}
9533 		return 0;
9534 	}
9535 
9536 	if (type_is_pkt_pointer(type) &&
9537 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9538 		verbose(env, "helper access to the packet is not allowed\n");
9539 		return -EACCES;
9540 	}
9541 
9542 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9543 		err = resolve_map_arg_type(env, meta, &arg_type);
9544 		if (err)
9545 			return err;
9546 	}
9547 
9548 	if (register_is_null(reg) && type_may_be_null(arg_type))
9549 		/* A NULL register has a SCALAR_VALUE type, so skip
9550 		 * type checking.
9551 		 */
9552 		goto skip_type_check;
9553 
9554 	/* arg_btf_id and arg_size are in a union. */
9555 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9556 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9557 		arg_btf_id = fn->arg_btf_id[arg];
9558 
9559 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9560 	if (err)
9561 		return err;
9562 
9563 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
9564 	if (err)
9565 		return err;
9566 
9567 skip_type_check:
9568 	if (arg_type_is_release(arg_type)) {
9569 		if (arg_type_is_dynptr(arg_type)) {
9570 			struct bpf_func_state *state = func(env, reg);
9571 			int spi;
9572 
9573 			/* Only dynptr created on stack can be released, thus
9574 			 * the get_spi and stack state checks for spilled_ptr
9575 			 * should only be done before process_dynptr_func for
9576 			 * PTR_TO_STACK.
9577 			 */
9578 			if (reg->type == PTR_TO_STACK) {
9579 				spi = dynptr_get_spi(env, reg);
9580 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9581 					verbose(env, "arg %d is an unacquired reference\n", regno);
9582 					return -EINVAL;
9583 				}
9584 			} else {
9585 				verbose(env, "cannot release unowned const bpf_dynptr\n");
9586 				return -EINVAL;
9587 			}
9588 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
9589 			verbose(env, "R%d must be referenced when passed to release function\n",
9590 				regno);
9591 			return -EINVAL;
9592 		}
9593 		if (meta->release_regno) {
9594 			verbose(env, "verifier internal error: more than one release argument\n");
9595 			return -EFAULT;
9596 		}
9597 		meta->release_regno = regno;
9598 	}
9599 
9600 	if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9601 		if (meta->ref_obj_id) {
9602 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
9603 				regno, reg->ref_obj_id,
9604 				meta->ref_obj_id);
9605 			return -EFAULT;
9606 		}
9607 		meta->ref_obj_id = reg->ref_obj_id;
9608 	}
9609 
9610 	switch (base_type(arg_type)) {
9611 	case ARG_CONST_MAP_PTR:
9612 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9613 		if (meta->map_ptr) {
9614 			/* Use map_uid (which is unique id of inner map) to reject:
9615 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9616 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9617 			 * if (inner_map1 && inner_map2) {
9618 			 *     timer = bpf_map_lookup_elem(inner_map1);
9619 			 *     if (timer)
9620 			 *         // mismatch would have been allowed
9621 			 *         bpf_timer_init(timer, inner_map2);
9622 			 * }
9623 			 *
9624 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
9625 			 */
9626 			if (meta->map_ptr != reg->map_ptr ||
9627 			    meta->map_uid != reg->map_uid) {
9628 				verbose(env,
9629 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9630 					meta->map_uid, reg->map_uid);
9631 				return -EINVAL;
9632 			}
9633 		}
9634 		meta->map_ptr = reg->map_ptr;
9635 		meta->map_uid = reg->map_uid;
9636 		break;
9637 	case ARG_PTR_TO_MAP_KEY:
9638 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9639 		 * check that [key, key + map->key_size) are within
9640 		 * stack limits and initialized
9641 		 */
9642 		if (!meta->map_ptr) {
9643 			/* in function declaration map_ptr must come before
9644 			 * map_key, so that it's verified and known before
9645 			 * we have to check map_key here. Otherwise it means
9646 			 * that kernel subsystem misconfigured verifier
9647 			 */
9648 			verbose(env, "invalid map_ptr to access map->key\n");
9649 			return -EACCES;
9650 		}
9651 		key_size = meta->map_ptr->key_size;
9652 		err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL);
9653 		if (err)
9654 			return err;
9655 		if (can_elide_value_nullness(meta->map_ptr->map_type)) {
9656 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9657 			if (err < 0) {
9658 				meta->const_map_key = -1;
9659 				if (err == -EOPNOTSUPP)
9660 					err = 0;
9661 				else
9662 					return err;
9663 			}
9664 		}
9665 		break;
9666 	case ARG_PTR_TO_MAP_VALUE:
9667 		if (type_may_be_null(arg_type) && register_is_null(reg))
9668 			return 0;
9669 
9670 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9671 		 * check [value, value + map->value_size) validity
9672 		 */
9673 		if (!meta->map_ptr) {
9674 			/* kernel subsystem misconfigured verifier */
9675 			verbose(env, "invalid map_ptr to access map->value\n");
9676 			return -EACCES;
9677 		}
9678 		meta->raw_mode = arg_type & MEM_UNINIT;
9679 		err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
9680 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9681 					      false, meta);
9682 		break;
9683 	case ARG_PTR_TO_PERCPU_BTF_ID:
9684 		if (!reg->btf_id) {
9685 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9686 			return -EACCES;
9687 		}
9688 		meta->ret_btf = reg->btf;
9689 		meta->ret_btf_id = reg->btf_id;
9690 		break;
9691 	case ARG_PTR_TO_SPIN_LOCK:
9692 		if (in_rbtree_lock_required_cb(env)) {
9693 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9694 			return -EACCES;
9695 		}
9696 		if (meta->func_id == BPF_FUNC_spin_lock) {
9697 			err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK);
9698 			if (err)
9699 				return err;
9700 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
9701 			err = process_spin_lock(env, regno, 0);
9702 			if (err)
9703 				return err;
9704 		} else {
9705 			verbose(env, "verifier internal error\n");
9706 			return -EFAULT;
9707 		}
9708 		break;
9709 	case ARG_PTR_TO_TIMER:
9710 		err = process_timer_func(env, regno, meta);
9711 		if (err)
9712 			return err;
9713 		break;
9714 	case ARG_PTR_TO_FUNC:
9715 		meta->subprogno = reg->subprogno;
9716 		break;
9717 	case ARG_PTR_TO_MEM:
9718 		/* The access to this pointer is only checked when we hit the
9719 		 * next is_mem_size argument below.
9720 		 */
9721 		meta->raw_mode = arg_type & MEM_UNINIT;
9722 		if (arg_type & MEM_FIXED_SIZE) {
9723 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
9724 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9725 						      false, meta);
9726 			if (err)
9727 				return err;
9728 			if (arg_type & MEM_ALIGNED)
9729 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9730 		}
9731 		break;
9732 	case ARG_CONST_SIZE:
9733 		err = check_mem_size_reg(env, reg, regno,
9734 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9735 					 BPF_WRITE : BPF_READ,
9736 					 false, meta);
9737 		break;
9738 	case ARG_CONST_SIZE_OR_ZERO:
9739 		err = check_mem_size_reg(env, reg, regno,
9740 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9741 					 BPF_WRITE : BPF_READ,
9742 					 true, meta);
9743 		break;
9744 	case ARG_PTR_TO_DYNPTR:
9745 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9746 		if (err)
9747 			return err;
9748 		break;
9749 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9750 		if (!tnum_is_const(reg->var_off)) {
9751 			verbose(env, "R%d is not a known constant'\n",
9752 				regno);
9753 			return -EACCES;
9754 		}
9755 		meta->mem_size = reg->var_off.value;
9756 		err = mark_chain_precision(env, regno);
9757 		if (err)
9758 			return err;
9759 		break;
9760 	case ARG_PTR_TO_CONST_STR:
9761 	{
9762 		err = check_reg_const_str(env, reg, regno);
9763 		if (err)
9764 			return err;
9765 		break;
9766 	}
9767 	case ARG_KPTR_XCHG_DEST:
9768 		err = process_kptr_func(env, regno, meta);
9769 		if (err)
9770 			return err;
9771 		break;
9772 	}
9773 
9774 	return err;
9775 }
9776 
9777 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9778 {
9779 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
9780 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9781 
9782 	if (func_id != BPF_FUNC_map_update_elem &&
9783 	    func_id != BPF_FUNC_map_delete_elem)
9784 		return false;
9785 
9786 	/* It's not possible to get access to a locked struct sock in these
9787 	 * contexts, so updating is safe.
9788 	 */
9789 	switch (type) {
9790 	case BPF_PROG_TYPE_TRACING:
9791 		if (eatype == BPF_TRACE_ITER)
9792 			return true;
9793 		break;
9794 	case BPF_PROG_TYPE_SOCK_OPS:
9795 		/* map_update allowed only via dedicated helpers with event type checks */
9796 		if (func_id == BPF_FUNC_map_delete_elem)
9797 			return true;
9798 		break;
9799 	case BPF_PROG_TYPE_SOCKET_FILTER:
9800 	case BPF_PROG_TYPE_SCHED_CLS:
9801 	case BPF_PROG_TYPE_SCHED_ACT:
9802 	case BPF_PROG_TYPE_XDP:
9803 	case BPF_PROG_TYPE_SK_REUSEPORT:
9804 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
9805 	case BPF_PROG_TYPE_SK_LOOKUP:
9806 		return true;
9807 	default:
9808 		break;
9809 	}
9810 
9811 	verbose(env, "cannot update sockmap in this context\n");
9812 	return false;
9813 }
9814 
9815 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
9816 {
9817 	return env->prog->jit_requested &&
9818 	       bpf_jit_supports_subprog_tailcalls();
9819 }
9820 
9821 static int check_map_func_compatibility(struct bpf_verifier_env *env,
9822 					struct bpf_map *map, int func_id)
9823 {
9824 	if (!map)
9825 		return 0;
9826 
9827 	/* We need a two way check, first is from map perspective ... */
9828 	switch (map->map_type) {
9829 	case BPF_MAP_TYPE_PROG_ARRAY:
9830 		if (func_id != BPF_FUNC_tail_call)
9831 			goto error;
9832 		break;
9833 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
9834 		if (func_id != BPF_FUNC_perf_event_read &&
9835 		    func_id != BPF_FUNC_perf_event_output &&
9836 		    func_id != BPF_FUNC_skb_output &&
9837 		    func_id != BPF_FUNC_perf_event_read_value &&
9838 		    func_id != BPF_FUNC_xdp_output)
9839 			goto error;
9840 		break;
9841 	case BPF_MAP_TYPE_RINGBUF:
9842 		if (func_id != BPF_FUNC_ringbuf_output &&
9843 		    func_id != BPF_FUNC_ringbuf_reserve &&
9844 		    func_id != BPF_FUNC_ringbuf_query &&
9845 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
9846 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
9847 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
9848 			goto error;
9849 		break;
9850 	case BPF_MAP_TYPE_USER_RINGBUF:
9851 		if (func_id != BPF_FUNC_user_ringbuf_drain)
9852 			goto error;
9853 		break;
9854 	case BPF_MAP_TYPE_STACK_TRACE:
9855 		if (func_id != BPF_FUNC_get_stackid)
9856 			goto error;
9857 		break;
9858 	case BPF_MAP_TYPE_CGROUP_ARRAY:
9859 		if (func_id != BPF_FUNC_skb_under_cgroup &&
9860 		    func_id != BPF_FUNC_current_task_under_cgroup)
9861 			goto error;
9862 		break;
9863 	case BPF_MAP_TYPE_CGROUP_STORAGE:
9864 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
9865 		if (func_id != BPF_FUNC_get_local_storage)
9866 			goto error;
9867 		break;
9868 	case BPF_MAP_TYPE_DEVMAP:
9869 	case BPF_MAP_TYPE_DEVMAP_HASH:
9870 		if (func_id != BPF_FUNC_redirect_map &&
9871 		    func_id != BPF_FUNC_map_lookup_elem)
9872 			goto error;
9873 		break;
9874 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
9875 	 * appear.
9876 	 */
9877 	case BPF_MAP_TYPE_CPUMAP:
9878 		if (func_id != BPF_FUNC_redirect_map)
9879 			goto error;
9880 		break;
9881 	case BPF_MAP_TYPE_XSKMAP:
9882 		if (func_id != BPF_FUNC_redirect_map &&
9883 		    func_id != BPF_FUNC_map_lookup_elem)
9884 			goto error;
9885 		break;
9886 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
9887 	case BPF_MAP_TYPE_HASH_OF_MAPS:
9888 		if (func_id != BPF_FUNC_map_lookup_elem)
9889 			goto error;
9890 		break;
9891 	case BPF_MAP_TYPE_SOCKMAP:
9892 		if (func_id != BPF_FUNC_sk_redirect_map &&
9893 		    func_id != BPF_FUNC_sock_map_update &&
9894 		    func_id != BPF_FUNC_msg_redirect_map &&
9895 		    func_id != BPF_FUNC_sk_select_reuseport &&
9896 		    func_id != BPF_FUNC_map_lookup_elem &&
9897 		    !may_update_sockmap(env, func_id))
9898 			goto error;
9899 		break;
9900 	case BPF_MAP_TYPE_SOCKHASH:
9901 		if (func_id != BPF_FUNC_sk_redirect_hash &&
9902 		    func_id != BPF_FUNC_sock_hash_update &&
9903 		    func_id != BPF_FUNC_msg_redirect_hash &&
9904 		    func_id != BPF_FUNC_sk_select_reuseport &&
9905 		    func_id != BPF_FUNC_map_lookup_elem &&
9906 		    !may_update_sockmap(env, func_id))
9907 			goto error;
9908 		break;
9909 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
9910 		if (func_id != BPF_FUNC_sk_select_reuseport)
9911 			goto error;
9912 		break;
9913 	case BPF_MAP_TYPE_QUEUE:
9914 	case BPF_MAP_TYPE_STACK:
9915 		if (func_id != BPF_FUNC_map_peek_elem &&
9916 		    func_id != BPF_FUNC_map_pop_elem &&
9917 		    func_id != BPF_FUNC_map_push_elem)
9918 			goto error;
9919 		break;
9920 	case BPF_MAP_TYPE_SK_STORAGE:
9921 		if (func_id != BPF_FUNC_sk_storage_get &&
9922 		    func_id != BPF_FUNC_sk_storage_delete &&
9923 		    func_id != BPF_FUNC_kptr_xchg)
9924 			goto error;
9925 		break;
9926 	case BPF_MAP_TYPE_INODE_STORAGE:
9927 		if (func_id != BPF_FUNC_inode_storage_get &&
9928 		    func_id != BPF_FUNC_inode_storage_delete &&
9929 		    func_id != BPF_FUNC_kptr_xchg)
9930 			goto error;
9931 		break;
9932 	case BPF_MAP_TYPE_TASK_STORAGE:
9933 		if (func_id != BPF_FUNC_task_storage_get &&
9934 		    func_id != BPF_FUNC_task_storage_delete &&
9935 		    func_id != BPF_FUNC_kptr_xchg)
9936 			goto error;
9937 		break;
9938 	case BPF_MAP_TYPE_CGRP_STORAGE:
9939 		if (func_id != BPF_FUNC_cgrp_storage_get &&
9940 		    func_id != BPF_FUNC_cgrp_storage_delete &&
9941 		    func_id != BPF_FUNC_kptr_xchg)
9942 			goto error;
9943 		break;
9944 	case BPF_MAP_TYPE_BLOOM_FILTER:
9945 		if (func_id != BPF_FUNC_map_peek_elem &&
9946 		    func_id != BPF_FUNC_map_push_elem)
9947 			goto error;
9948 		break;
9949 	default:
9950 		break;
9951 	}
9952 
9953 	/* ... and second from the function itself. */
9954 	switch (func_id) {
9955 	case BPF_FUNC_tail_call:
9956 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
9957 			goto error;
9958 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
9959 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
9960 			return -EINVAL;
9961 		}
9962 		break;
9963 	case BPF_FUNC_perf_event_read:
9964 	case BPF_FUNC_perf_event_output:
9965 	case BPF_FUNC_perf_event_read_value:
9966 	case BPF_FUNC_skb_output:
9967 	case BPF_FUNC_xdp_output:
9968 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9969 			goto error;
9970 		break;
9971 	case BPF_FUNC_ringbuf_output:
9972 	case BPF_FUNC_ringbuf_reserve:
9973 	case BPF_FUNC_ringbuf_query:
9974 	case BPF_FUNC_ringbuf_reserve_dynptr:
9975 	case BPF_FUNC_ringbuf_submit_dynptr:
9976 	case BPF_FUNC_ringbuf_discard_dynptr:
9977 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9978 			goto error;
9979 		break;
9980 	case BPF_FUNC_user_ringbuf_drain:
9981 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9982 			goto error;
9983 		break;
9984 	case BPF_FUNC_get_stackid:
9985 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9986 			goto error;
9987 		break;
9988 	case BPF_FUNC_current_task_under_cgroup:
9989 	case BPF_FUNC_skb_under_cgroup:
9990 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9991 			goto error;
9992 		break;
9993 	case BPF_FUNC_redirect_map:
9994 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9995 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9996 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
9997 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
9998 			goto error;
9999 		break;
10000 	case BPF_FUNC_sk_redirect_map:
10001 	case BPF_FUNC_msg_redirect_map:
10002 	case BPF_FUNC_sock_map_update:
10003 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10004 			goto error;
10005 		break;
10006 	case BPF_FUNC_sk_redirect_hash:
10007 	case BPF_FUNC_msg_redirect_hash:
10008 	case BPF_FUNC_sock_hash_update:
10009 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10010 			goto error;
10011 		break;
10012 	case BPF_FUNC_get_local_storage:
10013 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10014 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10015 			goto error;
10016 		break;
10017 	case BPF_FUNC_sk_select_reuseport:
10018 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10019 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10020 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
10021 			goto error;
10022 		break;
10023 	case BPF_FUNC_map_pop_elem:
10024 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10025 		    map->map_type != BPF_MAP_TYPE_STACK)
10026 			goto error;
10027 		break;
10028 	case BPF_FUNC_map_peek_elem:
10029 	case BPF_FUNC_map_push_elem:
10030 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10031 		    map->map_type != BPF_MAP_TYPE_STACK &&
10032 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10033 			goto error;
10034 		break;
10035 	case BPF_FUNC_map_lookup_percpu_elem:
10036 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10037 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10038 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10039 			goto error;
10040 		break;
10041 	case BPF_FUNC_sk_storage_get:
10042 	case BPF_FUNC_sk_storage_delete:
10043 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10044 			goto error;
10045 		break;
10046 	case BPF_FUNC_inode_storage_get:
10047 	case BPF_FUNC_inode_storage_delete:
10048 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10049 			goto error;
10050 		break;
10051 	case BPF_FUNC_task_storage_get:
10052 	case BPF_FUNC_task_storage_delete:
10053 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10054 			goto error;
10055 		break;
10056 	case BPF_FUNC_cgrp_storage_get:
10057 	case BPF_FUNC_cgrp_storage_delete:
10058 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10059 			goto error;
10060 		break;
10061 	default:
10062 		break;
10063 	}
10064 
10065 	return 0;
10066 error:
10067 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
10068 		map->map_type, func_id_name(func_id), func_id);
10069 	return -EINVAL;
10070 }
10071 
10072 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
10073 {
10074 	int count = 0;
10075 
10076 	if (arg_type_is_raw_mem(fn->arg1_type))
10077 		count++;
10078 	if (arg_type_is_raw_mem(fn->arg2_type))
10079 		count++;
10080 	if (arg_type_is_raw_mem(fn->arg3_type))
10081 		count++;
10082 	if (arg_type_is_raw_mem(fn->arg4_type))
10083 		count++;
10084 	if (arg_type_is_raw_mem(fn->arg5_type))
10085 		count++;
10086 
10087 	/* We only support one arg being in raw mode at the moment,
10088 	 * which is sufficient for the helper functions we have
10089 	 * right now.
10090 	 */
10091 	return count <= 1;
10092 }
10093 
10094 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10095 {
10096 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10097 	bool has_size = fn->arg_size[arg] != 0;
10098 	bool is_next_size = false;
10099 
10100 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10101 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10102 
10103 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10104 		return is_next_size;
10105 
10106 	return has_size == is_next_size || is_next_size == is_fixed;
10107 }
10108 
10109 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10110 {
10111 	/* bpf_xxx(..., buf, len) call will access 'len'
10112 	 * bytes from memory 'buf'. Both arg types need
10113 	 * to be paired, so make sure there's no buggy
10114 	 * helper function specification.
10115 	 */
10116 	if (arg_type_is_mem_size(fn->arg1_type) ||
10117 	    check_args_pair_invalid(fn, 0) ||
10118 	    check_args_pair_invalid(fn, 1) ||
10119 	    check_args_pair_invalid(fn, 2) ||
10120 	    check_args_pair_invalid(fn, 3) ||
10121 	    check_args_pair_invalid(fn, 4))
10122 		return false;
10123 
10124 	return true;
10125 }
10126 
10127 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10128 {
10129 	int i;
10130 
10131 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10132 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10133 			return !!fn->arg_btf_id[i];
10134 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10135 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
10136 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10137 		    /* arg_btf_id and arg_size are in a union. */
10138 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10139 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10140 			return false;
10141 	}
10142 
10143 	return true;
10144 }
10145 
10146 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
10147 {
10148 	return check_raw_mode_ok(fn) &&
10149 	       check_arg_pair_ok(fn) &&
10150 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
10151 }
10152 
10153 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
10154  * are now invalid, so turn them into unknown SCALAR_VALUE.
10155  *
10156  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
10157  * since these slices point to packet data.
10158  */
10159 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
10160 {
10161 	struct bpf_func_state *state;
10162 	struct bpf_reg_state *reg;
10163 
10164 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10165 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
10166 			mark_reg_invalid(env, reg);
10167 	}));
10168 }
10169 
10170 enum {
10171 	AT_PKT_END = -1,
10172 	BEYOND_PKT_END = -2,
10173 };
10174 
10175 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
10176 {
10177 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10178 	struct bpf_reg_state *reg = &state->regs[regn];
10179 
10180 	if (reg->type != PTR_TO_PACKET)
10181 		/* PTR_TO_PACKET_META is not supported yet */
10182 		return;
10183 
10184 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
10185 	 * How far beyond pkt_end it goes is unknown.
10186 	 * if (!range_open) it's the case of pkt >= pkt_end
10187 	 * if (range_open) it's the case of pkt > pkt_end
10188 	 * hence this pointer is at least 1 byte bigger than pkt_end
10189 	 */
10190 	if (range_open)
10191 		reg->range = BEYOND_PKT_END;
10192 	else
10193 		reg->range = AT_PKT_END;
10194 }
10195 
10196 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id)
10197 {
10198 	int i;
10199 
10200 	for (i = 0; i < state->acquired_refs; i++) {
10201 		if (state->refs[i].type != REF_TYPE_PTR)
10202 			continue;
10203 		if (state->refs[i].id == ref_obj_id) {
10204 			release_reference_state(state, i);
10205 			return 0;
10206 		}
10207 	}
10208 	return -EINVAL;
10209 }
10210 
10211 /* The pointer with the specified id has released its reference to kernel
10212  * resources. Identify all copies of the same pointer and clear the reference.
10213  *
10214  * This is the release function corresponding to acquire_reference(). Idempotent.
10215  */
10216 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id)
10217 {
10218 	struct bpf_verifier_state *vstate = env->cur_state;
10219 	struct bpf_func_state *state;
10220 	struct bpf_reg_state *reg;
10221 	int err;
10222 
10223 	err = release_reference_nomark(vstate, ref_obj_id);
10224 	if (err)
10225 		return err;
10226 
10227 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10228 		if (reg->ref_obj_id == ref_obj_id)
10229 			mark_reg_invalid(env, reg);
10230 	}));
10231 
10232 	return 0;
10233 }
10234 
10235 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
10236 {
10237 	struct bpf_func_state *unused;
10238 	struct bpf_reg_state *reg;
10239 
10240 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10241 		if (type_is_non_owning_ref(reg->type))
10242 			mark_reg_invalid(env, reg);
10243 	}));
10244 }
10245 
10246 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
10247 				    struct bpf_reg_state *regs)
10248 {
10249 	int i;
10250 
10251 	/* after the call registers r0 - r5 were scratched */
10252 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10253 		mark_reg_not_init(env, regs, caller_saved[i]);
10254 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
10255 	}
10256 }
10257 
10258 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
10259 				   struct bpf_func_state *caller,
10260 				   struct bpf_func_state *callee,
10261 				   int insn_idx);
10262 
10263 static int set_callee_state(struct bpf_verifier_env *env,
10264 			    struct bpf_func_state *caller,
10265 			    struct bpf_func_state *callee, int insn_idx);
10266 
10267 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
10268 			    set_callee_state_fn set_callee_state_cb,
10269 			    struct bpf_verifier_state *state)
10270 {
10271 	struct bpf_func_state *caller, *callee;
10272 	int err;
10273 
10274 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
10275 		verbose(env, "the call stack of %d frames is too deep\n",
10276 			state->curframe + 2);
10277 		return -E2BIG;
10278 	}
10279 
10280 	if (state->frame[state->curframe + 1]) {
10281 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
10282 		return -EFAULT;
10283 	}
10284 
10285 	caller = state->frame[state->curframe];
10286 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
10287 	if (!callee)
10288 		return -ENOMEM;
10289 	state->frame[state->curframe + 1] = callee;
10290 
10291 	/* callee cannot access r0, r6 - r9 for reading and has to write
10292 	 * into its own stack before reading from it.
10293 	 * callee can read/write into caller's stack
10294 	 */
10295 	init_func_state(env, callee,
10296 			/* remember the callsite, it will be used by bpf_exit */
10297 			callsite,
10298 			state->curframe + 1 /* frameno within this callchain */,
10299 			subprog /* subprog number within this prog */);
10300 	err = set_callee_state_cb(env, caller, callee, callsite);
10301 	if (err)
10302 		goto err_out;
10303 
10304 	/* only increment it after check_reg_arg() finished */
10305 	state->curframe++;
10306 
10307 	return 0;
10308 
10309 err_out:
10310 	free_func_state(callee);
10311 	state->frame[state->curframe + 1] = NULL;
10312 	return err;
10313 }
10314 
10315 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
10316 				    const struct btf *btf,
10317 				    struct bpf_reg_state *regs)
10318 {
10319 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
10320 	struct bpf_verifier_log *log = &env->log;
10321 	u32 i;
10322 	int ret;
10323 
10324 	ret = btf_prepare_func_args(env, subprog);
10325 	if (ret)
10326 		return ret;
10327 
10328 	/* check that BTF function arguments match actual types that the
10329 	 * verifier sees.
10330 	 */
10331 	for (i = 0; i < sub->arg_cnt; i++) {
10332 		u32 regno = i + 1;
10333 		struct bpf_reg_state *reg = &regs[regno];
10334 		struct bpf_subprog_arg_info *arg = &sub->args[i];
10335 
10336 		if (arg->arg_type == ARG_ANYTHING) {
10337 			if (reg->type != SCALAR_VALUE) {
10338 				bpf_log(log, "R%d is not a scalar\n", regno);
10339 				return -EINVAL;
10340 			}
10341 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
10342 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10343 			if (ret < 0)
10344 				return ret;
10345 			/* If function expects ctx type in BTF check that caller
10346 			 * is passing PTR_TO_CTX.
10347 			 */
10348 			if (reg->type != PTR_TO_CTX) {
10349 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
10350 				return -EINVAL;
10351 			}
10352 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
10353 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10354 			if (ret < 0)
10355 				return ret;
10356 			if (check_mem_reg(env, reg, regno, arg->mem_size))
10357 				return -EINVAL;
10358 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
10359 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
10360 				return -EINVAL;
10361 			}
10362 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
10363 			/*
10364 			 * Can pass any value and the kernel won't crash, but
10365 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
10366 			 * else is a bug in the bpf program. Point it out to
10367 			 * the user at the verification time instead of
10368 			 * run-time debug nightmare.
10369 			 */
10370 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
10371 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
10372 				return -EINVAL;
10373 			}
10374 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
10375 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
10376 			if (ret)
10377 				return ret;
10378 
10379 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
10380 			if (ret)
10381 				return ret;
10382 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
10383 			struct bpf_call_arg_meta meta;
10384 			int err;
10385 
10386 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
10387 				continue;
10388 
10389 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
10390 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
10391 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
10392 			if (err)
10393 				return err;
10394 		} else {
10395 			verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type);
10396 			return -EFAULT;
10397 		}
10398 	}
10399 
10400 	return 0;
10401 }
10402 
10403 /* Compare BTF of a function call with given bpf_reg_state.
10404  * Returns:
10405  * EFAULT - there is a verifier bug. Abort verification.
10406  * EINVAL - there is a type mismatch or BTF is not available.
10407  * 0 - BTF matches with what bpf_reg_state expects.
10408  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
10409  */
10410 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
10411 				  struct bpf_reg_state *regs)
10412 {
10413 	struct bpf_prog *prog = env->prog;
10414 	struct btf *btf = prog->aux->btf;
10415 	u32 btf_id;
10416 	int err;
10417 
10418 	if (!prog->aux->func_info)
10419 		return -EINVAL;
10420 
10421 	btf_id = prog->aux->func_info[subprog].type_id;
10422 	if (!btf_id)
10423 		return -EFAULT;
10424 
10425 	if (prog->aux->func_info_aux[subprog].unreliable)
10426 		return -EINVAL;
10427 
10428 	err = btf_check_func_arg_match(env, subprog, btf, regs);
10429 	/* Compiler optimizations can remove arguments from static functions
10430 	 * or mismatched type can be passed into a global function.
10431 	 * In such cases mark the function as unreliable from BTF point of view.
10432 	 */
10433 	if (err)
10434 		prog->aux->func_info_aux[subprog].unreliable = true;
10435 	return err;
10436 }
10437 
10438 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10439 			      int insn_idx, int subprog,
10440 			      set_callee_state_fn set_callee_state_cb)
10441 {
10442 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
10443 	struct bpf_func_state *caller, *callee;
10444 	int err;
10445 
10446 	caller = state->frame[state->curframe];
10447 	err = btf_check_subprog_call(env, subprog, caller->regs);
10448 	if (err == -EFAULT)
10449 		return err;
10450 
10451 	/* set_callee_state is used for direct subprog calls, but we are
10452 	 * interested in validating only BPF helpers that can call subprogs as
10453 	 * callbacks
10454 	 */
10455 	env->subprog_info[subprog].is_cb = true;
10456 	if (bpf_pseudo_kfunc_call(insn) &&
10457 	    !is_callback_calling_kfunc(insn->imm)) {
10458 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
10459 			     func_id_name(insn->imm), insn->imm);
10460 		return -EFAULT;
10461 	} else if (!bpf_pseudo_kfunc_call(insn) &&
10462 		   !is_callback_calling_function(insn->imm)) { /* helper */
10463 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
10464 			     func_id_name(insn->imm), insn->imm);
10465 		return -EFAULT;
10466 	}
10467 
10468 	if (is_async_callback_calling_insn(insn)) {
10469 		struct bpf_verifier_state *async_cb;
10470 
10471 		/* there is no real recursion here. timer and workqueue callbacks are async */
10472 		env->subprog_info[subprog].is_async_cb = true;
10473 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
10474 					 insn_idx, subprog,
10475 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm));
10476 		if (!async_cb)
10477 			return -EFAULT;
10478 		callee = async_cb->frame[0];
10479 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
10480 
10481 		/* Convert bpf_timer_set_callback() args into timer callback args */
10482 		err = set_callee_state_cb(env, caller, callee, insn_idx);
10483 		if (err)
10484 			return err;
10485 
10486 		return 0;
10487 	}
10488 
10489 	/* for callback functions enqueue entry to callback and
10490 	 * proceed with next instruction within current frame.
10491 	 */
10492 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
10493 	if (!callback_state)
10494 		return -ENOMEM;
10495 
10496 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
10497 			       callback_state);
10498 	if (err)
10499 		return err;
10500 
10501 	callback_state->callback_unroll_depth++;
10502 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
10503 	caller->callback_depth = 0;
10504 	return 0;
10505 }
10506 
10507 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10508 			   int *insn_idx)
10509 {
10510 	struct bpf_verifier_state *state = env->cur_state;
10511 	struct bpf_func_state *caller;
10512 	int err, subprog, target_insn;
10513 
10514 	target_insn = *insn_idx + insn->imm + 1;
10515 	subprog = find_subprog(env, target_insn);
10516 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
10517 			    target_insn))
10518 		return -EFAULT;
10519 
10520 	caller = state->frame[state->curframe];
10521 	err = btf_check_subprog_call(env, subprog, caller->regs);
10522 	if (err == -EFAULT)
10523 		return err;
10524 	if (subprog_is_global(env, subprog)) {
10525 		const char *sub_name = subprog_name(env, subprog);
10526 
10527 		if (env->cur_state->active_locks) {
10528 			verbose(env, "global function calls are not allowed while holding a lock,\n"
10529 				     "use static function instead\n");
10530 			return -EINVAL;
10531 		}
10532 
10533 		if (env->subprog_info[subprog].might_sleep &&
10534 		    (env->cur_state->active_rcu_lock || env->cur_state->active_preempt_locks ||
10535 		     env->cur_state->active_irq_id || !in_sleepable(env))) {
10536 			verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n"
10537 				     "i.e., in a RCU/IRQ/preempt-disabled section, or in\n"
10538 				     "a non-sleepable BPF program context\n");
10539 			return -EINVAL;
10540 		}
10541 
10542 		if (err) {
10543 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10544 				subprog, sub_name);
10545 			return err;
10546 		}
10547 
10548 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10549 			subprog, sub_name);
10550 		if (env->subprog_info[subprog].changes_pkt_data)
10551 			clear_all_pkt_pointers(env);
10552 		/* mark global subprog for verifying after main prog */
10553 		subprog_aux(env, subprog)->called = true;
10554 		clear_caller_saved_regs(env, caller->regs);
10555 
10556 		/* All global functions return a 64-bit SCALAR_VALUE */
10557 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
10558 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10559 
10560 		/* continue with next insn after call */
10561 		return 0;
10562 	}
10563 
10564 	/* for regular function entry setup new frame and continue
10565 	 * from that frame.
10566 	 */
10567 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10568 	if (err)
10569 		return err;
10570 
10571 	clear_caller_saved_regs(env, caller->regs);
10572 
10573 	/* and go analyze first insn of the callee */
10574 	*insn_idx = env->subprog_info[subprog].start - 1;
10575 
10576 	if (env->log.level & BPF_LOG_LEVEL) {
10577 		verbose(env, "caller:\n");
10578 		print_verifier_state(env, state, caller->frameno, true);
10579 		verbose(env, "callee:\n");
10580 		print_verifier_state(env, state, state->curframe, true);
10581 	}
10582 
10583 	return 0;
10584 }
10585 
10586 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10587 				   struct bpf_func_state *caller,
10588 				   struct bpf_func_state *callee)
10589 {
10590 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10591 	 *      void *callback_ctx, u64 flags);
10592 	 * callback_fn(struct bpf_map *map, void *key, void *value,
10593 	 *      void *callback_ctx);
10594 	 */
10595 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10596 
10597 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10598 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10599 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10600 
10601 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10602 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10603 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10604 
10605 	/* pointer to stack or null */
10606 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10607 
10608 	/* unused */
10609 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10610 	return 0;
10611 }
10612 
10613 static int set_callee_state(struct bpf_verifier_env *env,
10614 			    struct bpf_func_state *caller,
10615 			    struct bpf_func_state *callee, int insn_idx)
10616 {
10617 	int i;
10618 
10619 	/* copy r1 - r5 args that callee can access.  The copy includes parent
10620 	 * pointers, which connects us up to the liveness chain
10621 	 */
10622 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10623 		callee->regs[i] = caller->regs[i];
10624 	return 0;
10625 }
10626 
10627 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10628 				       struct bpf_func_state *caller,
10629 				       struct bpf_func_state *callee,
10630 				       int insn_idx)
10631 {
10632 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10633 	struct bpf_map *map;
10634 	int err;
10635 
10636 	/* valid map_ptr and poison value does not matter */
10637 	map = insn_aux->map_ptr_state.map_ptr;
10638 	if (!map->ops->map_set_for_each_callback_args ||
10639 	    !map->ops->map_for_each_callback) {
10640 		verbose(env, "callback function not allowed for map\n");
10641 		return -ENOTSUPP;
10642 	}
10643 
10644 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10645 	if (err)
10646 		return err;
10647 
10648 	callee->in_callback_fn = true;
10649 	callee->callback_ret_range = retval_range(0, 1);
10650 	return 0;
10651 }
10652 
10653 static int set_loop_callback_state(struct bpf_verifier_env *env,
10654 				   struct bpf_func_state *caller,
10655 				   struct bpf_func_state *callee,
10656 				   int insn_idx)
10657 {
10658 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10659 	 *	    u64 flags);
10660 	 * callback_fn(u64 index, void *callback_ctx);
10661 	 */
10662 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10663 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10664 
10665 	/* unused */
10666 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10667 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10668 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10669 
10670 	callee->in_callback_fn = true;
10671 	callee->callback_ret_range = retval_range(0, 1);
10672 	return 0;
10673 }
10674 
10675 static int set_timer_callback_state(struct bpf_verifier_env *env,
10676 				    struct bpf_func_state *caller,
10677 				    struct bpf_func_state *callee,
10678 				    int insn_idx)
10679 {
10680 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10681 
10682 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10683 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10684 	 */
10685 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10686 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10687 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10688 
10689 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10690 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10691 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10692 
10693 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10694 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10695 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10696 
10697 	/* unused */
10698 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10699 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10700 	callee->in_async_callback_fn = true;
10701 	callee->callback_ret_range = retval_range(0, 1);
10702 	return 0;
10703 }
10704 
10705 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
10706 				       struct bpf_func_state *caller,
10707 				       struct bpf_func_state *callee,
10708 				       int insn_idx)
10709 {
10710 	/* bpf_find_vma(struct task_struct *task, u64 addr,
10711 	 *               void *callback_fn, void *callback_ctx, u64 flags)
10712 	 * (callback_fn)(struct task_struct *task,
10713 	 *               struct vm_area_struct *vma, void *callback_ctx);
10714 	 */
10715 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10716 
10717 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
10718 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10719 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
10720 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
10721 
10722 	/* pointer to stack or null */
10723 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
10724 
10725 	/* unused */
10726 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10727 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10728 	callee->in_callback_fn = true;
10729 	callee->callback_ret_range = retval_range(0, 1);
10730 	return 0;
10731 }
10732 
10733 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10734 					   struct bpf_func_state *caller,
10735 					   struct bpf_func_state *callee,
10736 					   int insn_idx)
10737 {
10738 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10739 	 *			  callback_ctx, u64 flags);
10740 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10741 	 */
10742 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10743 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10744 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10745 
10746 	/* unused */
10747 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10748 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10749 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10750 
10751 	callee->in_callback_fn = true;
10752 	callee->callback_ret_range = retval_range(0, 1);
10753 	return 0;
10754 }
10755 
10756 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10757 					 struct bpf_func_state *caller,
10758 					 struct bpf_func_state *callee,
10759 					 int insn_idx)
10760 {
10761 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10762 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10763 	 *
10764 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10765 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10766 	 * by this point, so look at 'root'
10767 	 */
10768 	struct btf_field *field;
10769 
10770 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10771 				      BPF_RB_ROOT);
10772 	if (!field || !field->graph_root.value_btf_id)
10773 		return -EFAULT;
10774 
10775 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10776 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10777 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10778 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10779 
10780 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10781 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10782 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10783 	callee->in_callback_fn = true;
10784 	callee->callback_ret_range = retval_range(0, 1);
10785 	return 0;
10786 }
10787 
10788 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
10789 
10790 /* Are we currently verifying the callback for a rbtree helper that must
10791  * be called with lock held? If so, no need to complain about unreleased
10792  * lock
10793  */
10794 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
10795 {
10796 	struct bpf_verifier_state *state = env->cur_state;
10797 	struct bpf_insn *insn = env->prog->insnsi;
10798 	struct bpf_func_state *callee;
10799 	int kfunc_btf_id;
10800 
10801 	if (!state->curframe)
10802 		return false;
10803 
10804 	callee = state->frame[state->curframe];
10805 
10806 	if (!callee->in_callback_fn)
10807 		return false;
10808 
10809 	kfunc_btf_id = insn[callee->callsite].imm;
10810 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
10811 }
10812 
10813 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
10814 				bool return_32bit)
10815 {
10816 	if (return_32bit)
10817 		return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
10818 	else
10819 		return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
10820 }
10821 
10822 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
10823 {
10824 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
10825 	struct bpf_func_state *caller, *callee;
10826 	struct bpf_reg_state *r0;
10827 	bool in_callback_fn;
10828 	int err;
10829 
10830 	callee = state->frame[state->curframe];
10831 	r0 = &callee->regs[BPF_REG_0];
10832 	if (r0->type == PTR_TO_STACK) {
10833 		/* technically it's ok to return caller's stack pointer
10834 		 * (or caller's caller's pointer) back to the caller,
10835 		 * since these pointers are valid. Only current stack
10836 		 * pointer will be invalid as soon as function exits,
10837 		 * but let's be conservative
10838 		 */
10839 		verbose(env, "cannot return stack pointer to the caller\n");
10840 		return -EINVAL;
10841 	}
10842 
10843 	caller = state->frame[state->curframe - 1];
10844 	if (callee->in_callback_fn) {
10845 		if (r0->type != SCALAR_VALUE) {
10846 			verbose(env, "R0 not a scalar value\n");
10847 			return -EACCES;
10848 		}
10849 
10850 		/* we are going to rely on register's precise value */
10851 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
10852 		err = err ?: mark_chain_precision(env, BPF_REG_0);
10853 		if (err)
10854 			return err;
10855 
10856 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
10857 		if (!retval_range_within(callee->callback_ret_range, r0, false)) {
10858 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
10859 					       "At callback return", "R0");
10860 			return -EINVAL;
10861 		}
10862 		if (!calls_callback(env, callee->callsite)) {
10863 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
10864 				*insn_idx, callee->callsite);
10865 			return -EFAULT;
10866 		}
10867 	} else {
10868 		/* return to the caller whatever r0 had in the callee */
10869 		caller->regs[BPF_REG_0] = *r0;
10870 	}
10871 
10872 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
10873 	 * there function call logic would reschedule callback visit. If iteration
10874 	 * converges is_state_visited() would prune that visit eventually.
10875 	 */
10876 	in_callback_fn = callee->in_callback_fn;
10877 	if (in_callback_fn)
10878 		*insn_idx = callee->callsite;
10879 	else
10880 		*insn_idx = callee->callsite + 1;
10881 
10882 	if (env->log.level & BPF_LOG_LEVEL) {
10883 		verbose(env, "returning from callee:\n");
10884 		print_verifier_state(env, state, callee->frameno, true);
10885 		verbose(env, "to caller at %d:\n", *insn_idx);
10886 		print_verifier_state(env, state, caller->frameno, true);
10887 	}
10888 	/* clear everything in the callee. In case of exceptional exits using
10889 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
10890 	free_func_state(callee);
10891 	state->frame[state->curframe--] = NULL;
10892 
10893 	/* for callbacks widen imprecise scalars to make programs like below verify:
10894 	 *
10895 	 *   struct ctx { int i; }
10896 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
10897 	 *   ...
10898 	 *   struct ctx = { .i = 0; }
10899 	 *   bpf_loop(100, cb, &ctx, 0);
10900 	 *
10901 	 * This is similar to what is done in process_iter_next_call() for open
10902 	 * coded iterators.
10903 	 */
10904 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
10905 	if (prev_st) {
10906 		err = widen_imprecise_scalars(env, prev_st, state);
10907 		if (err)
10908 			return err;
10909 	}
10910 	return 0;
10911 }
10912 
10913 static int do_refine_retval_range(struct bpf_verifier_env *env,
10914 				  struct bpf_reg_state *regs, int ret_type,
10915 				  int func_id,
10916 				  struct bpf_call_arg_meta *meta)
10917 {
10918 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
10919 
10920 	if (ret_type != RET_INTEGER)
10921 		return 0;
10922 
10923 	switch (func_id) {
10924 	case BPF_FUNC_get_stack:
10925 	case BPF_FUNC_get_task_stack:
10926 	case BPF_FUNC_probe_read_str:
10927 	case BPF_FUNC_probe_read_kernel_str:
10928 	case BPF_FUNC_probe_read_user_str:
10929 		ret_reg->smax_value = meta->msize_max_value;
10930 		ret_reg->s32_max_value = meta->msize_max_value;
10931 		ret_reg->smin_value = -MAX_ERRNO;
10932 		ret_reg->s32_min_value = -MAX_ERRNO;
10933 		reg_bounds_sync(ret_reg);
10934 		break;
10935 	case BPF_FUNC_get_smp_processor_id:
10936 		ret_reg->umax_value = nr_cpu_ids - 1;
10937 		ret_reg->u32_max_value = nr_cpu_ids - 1;
10938 		ret_reg->smax_value = nr_cpu_ids - 1;
10939 		ret_reg->s32_max_value = nr_cpu_ids - 1;
10940 		ret_reg->umin_value = 0;
10941 		ret_reg->u32_min_value = 0;
10942 		ret_reg->smin_value = 0;
10943 		ret_reg->s32_min_value = 0;
10944 		reg_bounds_sync(ret_reg);
10945 		break;
10946 	}
10947 
10948 	return reg_bounds_sanity_check(env, ret_reg, "retval");
10949 }
10950 
10951 static int
10952 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10953 		int func_id, int insn_idx)
10954 {
10955 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10956 	struct bpf_map *map = meta->map_ptr;
10957 
10958 	if (func_id != BPF_FUNC_tail_call &&
10959 	    func_id != BPF_FUNC_map_lookup_elem &&
10960 	    func_id != BPF_FUNC_map_update_elem &&
10961 	    func_id != BPF_FUNC_map_delete_elem &&
10962 	    func_id != BPF_FUNC_map_push_elem &&
10963 	    func_id != BPF_FUNC_map_pop_elem &&
10964 	    func_id != BPF_FUNC_map_peek_elem &&
10965 	    func_id != BPF_FUNC_for_each_map_elem &&
10966 	    func_id != BPF_FUNC_redirect_map &&
10967 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
10968 		return 0;
10969 
10970 	if (map == NULL) {
10971 		verbose(env, "kernel subsystem misconfigured verifier\n");
10972 		return -EINVAL;
10973 	}
10974 
10975 	/* In case of read-only, some additional restrictions
10976 	 * need to be applied in order to prevent altering the
10977 	 * state of the map from program side.
10978 	 */
10979 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
10980 	    (func_id == BPF_FUNC_map_delete_elem ||
10981 	     func_id == BPF_FUNC_map_update_elem ||
10982 	     func_id == BPF_FUNC_map_push_elem ||
10983 	     func_id == BPF_FUNC_map_pop_elem)) {
10984 		verbose(env, "write into map forbidden\n");
10985 		return -EACCES;
10986 	}
10987 
10988 	if (!aux->map_ptr_state.map_ptr)
10989 		bpf_map_ptr_store(aux, meta->map_ptr,
10990 				  !meta->map_ptr->bypass_spec_v1, false);
10991 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
10992 		bpf_map_ptr_store(aux, meta->map_ptr,
10993 				  !meta->map_ptr->bypass_spec_v1, true);
10994 	return 0;
10995 }
10996 
10997 static int
10998 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10999 		int func_id, int insn_idx)
11000 {
11001 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11002 	struct bpf_reg_state *regs = cur_regs(env), *reg;
11003 	struct bpf_map *map = meta->map_ptr;
11004 	u64 val, max;
11005 	int err;
11006 
11007 	if (func_id != BPF_FUNC_tail_call)
11008 		return 0;
11009 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
11010 		verbose(env, "kernel subsystem misconfigured verifier\n");
11011 		return -EINVAL;
11012 	}
11013 
11014 	reg = &regs[BPF_REG_3];
11015 	val = reg->var_off.value;
11016 	max = map->max_entries;
11017 
11018 	if (!(is_reg_const(reg, false) && val < max)) {
11019 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11020 		return 0;
11021 	}
11022 
11023 	err = mark_chain_precision(env, BPF_REG_3);
11024 	if (err)
11025 		return err;
11026 	if (bpf_map_key_unseen(aux))
11027 		bpf_map_key_store(aux, val);
11028 	else if (!bpf_map_key_poisoned(aux) &&
11029 		  bpf_map_key_immediate(aux) != val)
11030 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11031 	return 0;
11032 }
11033 
11034 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
11035 {
11036 	struct bpf_verifier_state *state = env->cur_state;
11037 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11038 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
11039 	bool refs_lingering = false;
11040 	int i;
11041 
11042 	if (!exception_exit && cur_func(env)->frameno)
11043 		return 0;
11044 
11045 	for (i = 0; i < state->acquired_refs; i++) {
11046 		if (state->refs[i].type != REF_TYPE_PTR)
11047 			continue;
11048 		/* Allow struct_ops programs to return a referenced kptr back to
11049 		 * kernel. Type checks are performed later in check_return_code.
11050 		 */
11051 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
11052 		    reg->ref_obj_id == state->refs[i].id)
11053 			continue;
11054 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
11055 			state->refs[i].id, state->refs[i].insn_idx);
11056 		refs_lingering = true;
11057 	}
11058 	return refs_lingering ? -EINVAL : 0;
11059 }
11060 
11061 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
11062 {
11063 	int err;
11064 
11065 	if (check_lock && env->cur_state->active_locks) {
11066 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
11067 		return -EINVAL;
11068 	}
11069 
11070 	err = check_reference_leak(env, exception_exit);
11071 	if (err) {
11072 		verbose(env, "%s would lead to reference leak\n", prefix);
11073 		return err;
11074 	}
11075 
11076 	if (check_lock && env->cur_state->active_irq_id) {
11077 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
11078 		return -EINVAL;
11079 	}
11080 
11081 	if (check_lock && env->cur_state->active_rcu_lock) {
11082 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
11083 		return -EINVAL;
11084 	}
11085 
11086 	if (check_lock && env->cur_state->active_preempt_locks) {
11087 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
11088 		return -EINVAL;
11089 	}
11090 
11091 	return 0;
11092 }
11093 
11094 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
11095 				   struct bpf_reg_state *regs)
11096 {
11097 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
11098 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
11099 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
11100 	struct bpf_bprintf_data data = {};
11101 	int err, fmt_map_off, num_args;
11102 	u64 fmt_addr;
11103 	char *fmt;
11104 
11105 	/* data must be an array of u64 */
11106 	if (data_len_reg->var_off.value % 8)
11107 		return -EINVAL;
11108 	num_args = data_len_reg->var_off.value / 8;
11109 
11110 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
11111 	 * and map_direct_value_addr is set.
11112 	 */
11113 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
11114 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
11115 						  fmt_map_off);
11116 	if (err) {
11117 		verbose(env, "failed to retrieve map value address\n");
11118 		return -EFAULT;
11119 	}
11120 	fmt = (char *)(long)fmt_addr + fmt_map_off;
11121 
11122 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
11123 	 * can focus on validating the format specifiers.
11124 	 */
11125 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
11126 	if (err < 0)
11127 		verbose(env, "Invalid format string\n");
11128 
11129 	return err;
11130 }
11131 
11132 static int check_get_func_ip(struct bpf_verifier_env *env)
11133 {
11134 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11135 	int func_id = BPF_FUNC_get_func_ip;
11136 
11137 	if (type == BPF_PROG_TYPE_TRACING) {
11138 		if (!bpf_prog_has_trampoline(env->prog)) {
11139 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
11140 				func_id_name(func_id), func_id);
11141 			return -ENOTSUPP;
11142 		}
11143 		return 0;
11144 	} else if (type == BPF_PROG_TYPE_KPROBE) {
11145 		return 0;
11146 	}
11147 
11148 	verbose(env, "func %s#%d not supported for program type %d\n",
11149 		func_id_name(func_id), func_id, type);
11150 	return -ENOTSUPP;
11151 }
11152 
11153 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
11154 {
11155 	return &env->insn_aux_data[env->insn_idx];
11156 }
11157 
11158 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
11159 {
11160 	struct bpf_reg_state *regs = cur_regs(env);
11161 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
11162 	bool reg_is_null = register_is_null(reg);
11163 
11164 	if (reg_is_null)
11165 		mark_chain_precision(env, BPF_REG_4);
11166 
11167 	return reg_is_null;
11168 }
11169 
11170 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
11171 {
11172 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
11173 
11174 	if (!state->initialized) {
11175 		state->initialized = 1;
11176 		state->fit_for_inline = loop_flag_is_zero(env);
11177 		state->callback_subprogno = subprogno;
11178 		return;
11179 	}
11180 
11181 	if (!state->fit_for_inline)
11182 		return;
11183 
11184 	state->fit_for_inline = (loop_flag_is_zero(env) &&
11185 				 state->callback_subprogno == subprogno);
11186 }
11187 
11188 /* Returns whether or not the given map type can potentially elide
11189  * lookup return value nullness check. This is possible if the key
11190  * is statically known.
11191  */
11192 static bool can_elide_value_nullness(enum bpf_map_type type)
11193 {
11194 	switch (type) {
11195 	case BPF_MAP_TYPE_ARRAY:
11196 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11197 		return true;
11198 	default:
11199 		return false;
11200 	}
11201 }
11202 
11203 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
11204 			    const struct bpf_func_proto **ptr)
11205 {
11206 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
11207 		return -ERANGE;
11208 
11209 	if (!env->ops->get_func_proto)
11210 		return -EINVAL;
11211 
11212 	*ptr = env->ops->get_func_proto(func_id, env->prog);
11213 	return *ptr ? 0 : -EINVAL;
11214 }
11215 
11216 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11217 			     int *insn_idx_p)
11218 {
11219 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11220 	bool returns_cpu_specific_alloc_ptr = false;
11221 	const struct bpf_func_proto *fn = NULL;
11222 	enum bpf_return_type ret_type;
11223 	enum bpf_type_flag ret_flag;
11224 	struct bpf_reg_state *regs;
11225 	struct bpf_call_arg_meta meta;
11226 	int insn_idx = *insn_idx_p;
11227 	bool changes_data;
11228 	int i, err, func_id;
11229 
11230 	/* find function prototype */
11231 	func_id = insn->imm;
11232 	err = get_helper_proto(env, insn->imm, &fn);
11233 	if (err == -ERANGE) {
11234 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
11235 		return -EINVAL;
11236 	}
11237 
11238 	if (err) {
11239 		verbose(env, "program of this type cannot use helper %s#%d\n",
11240 			func_id_name(func_id), func_id);
11241 		return err;
11242 	}
11243 
11244 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
11245 	if (!env->prog->gpl_compatible && fn->gpl_only) {
11246 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
11247 		return -EINVAL;
11248 	}
11249 
11250 	if (fn->allowed && !fn->allowed(env->prog)) {
11251 		verbose(env, "helper call is not allowed in probe\n");
11252 		return -EINVAL;
11253 	}
11254 
11255 	if (!in_sleepable(env) && fn->might_sleep) {
11256 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
11257 		return -EINVAL;
11258 	}
11259 
11260 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
11261 	changes_data = bpf_helper_changes_pkt_data(func_id);
11262 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
11263 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
11264 			func_id_name(func_id), func_id);
11265 		return -EINVAL;
11266 	}
11267 
11268 	memset(&meta, 0, sizeof(meta));
11269 	meta.pkt_access = fn->pkt_access;
11270 
11271 	err = check_func_proto(fn, func_id);
11272 	if (err) {
11273 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
11274 			func_id_name(func_id), func_id);
11275 		return err;
11276 	}
11277 
11278 	if (env->cur_state->active_rcu_lock) {
11279 		if (fn->might_sleep) {
11280 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
11281 				func_id_name(func_id), func_id);
11282 			return -EINVAL;
11283 		}
11284 
11285 		if (in_sleepable(env) && is_storage_get_function(func_id))
11286 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11287 	}
11288 
11289 	if (env->cur_state->active_preempt_locks) {
11290 		if (fn->might_sleep) {
11291 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
11292 				func_id_name(func_id), func_id);
11293 			return -EINVAL;
11294 		}
11295 
11296 		if (in_sleepable(env) && is_storage_get_function(func_id))
11297 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11298 	}
11299 
11300 	if (env->cur_state->active_irq_id) {
11301 		if (fn->might_sleep) {
11302 			verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n",
11303 				func_id_name(func_id), func_id);
11304 			return -EINVAL;
11305 		}
11306 
11307 		if (in_sleepable(env) && is_storage_get_function(func_id))
11308 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11309 	}
11310 
11311 	meta.func_id = func_id;
11312 	/* check args */
11313 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
11314 		err = check_func_arg(env, i, &meta, fn, insn_idx);
11315 		if (err)
11316 			return err;
11317 	}
11318 
11319 	err = record_func_map(env, &meta, func_id, insn_idx);
11320 	if (err)
11321 		return err;
11322 
11323 	err = record_func_key(env, &meta, func_id, insn_idx);
11324 	if (err)
11325 		return err;
11326 
11327 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
11328 	 * is inferred from register state.
11329 	 */
11330 	for (i = 0; i < meta.access_size; i++) {
11331 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
11332 				       BPF_WRITE, -1, false, false);
11333 		if (err)
11334 			return err;
11335 	}
11336 
11337 	regs = cur_regs(env);
11338 
11339 	if (meta.release_regno) {
11340 		err = -EINVAL;
11341 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
11342 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
11343 		 * is safe to do directly.
11344 		 */
11345 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
11346 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
11347 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
11348 				return -EFAULT;
11349 			}
11350 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
11351 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
11352 			u32 ref_obj_id = meta.ref_obj_id;
11353 			bool in_rcu = in_rcu_cs(env);
11354 			struct bpf_func_state *state;
11355 			struct bpf_reg_state *reg;
11356 
11357 			err = release_reference_nomark(env->cur_state, ref_obj_id);
11358 			if (!err) {
11359 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11360 					if (reg->ref_obj_id == ref_obj_id) {
11361 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11362 							reg->ref_obj_id = 0;
11363 							reg->type &= ~MEM_ALLOC;
11364 							reg->type |= MEM_RCU;
11365 						} else {
11366 							mark_reg_invalid(env, reg);
11367 						}
11368 					}
11369 				}));
11370 			}
11371 		} else if (meta.ref_obj_id) {
11372 			err = release_reference(env, meta.ref_obj_id);
11373 		} else if (register_is_null(&regs[meta.release_regno])) {
11374 			/* meta.ref_obj_id can only be 0 if register that is meant to be
11375 			 * released is NULL, which must be > R0.
11376 			 */
11377 			err = 0;
11378 		}
11379 		if (err) {
11380 			verbose(env, "func %s#%d reference has not been acquired before\n",
11381 				func_id_name(func_id), func_id);
11382 			return err;
11383 		}
11384 	}
11385 
11386 	switch (func_id) {
11387 	case BPF_FUNC_tail_call:
11388 		err = check_resource_leak(env, false, true, "tail_call");
11389 		if (err)
11390 			return err;
11391 		break;
11392 	case BPF_FUNC_get_local_storage:
11393 		/* check that flags argument in get_local_storage(map, flags) is 0,
11394 		 * this is required because get_local_storage() can't return an error.
11395 		 */
11396 		if (!register_is_null(&regs[BPF_REG_2])) {
11397 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
11398 			return -EINVAL;
11399 		}
11400 		break;
11401 	case BPF_FUNC_for_each_map_elem:
11402 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11403 					 set_map_elem_callback_state);
11404 		break;
11405 	case BPF_FUNC_timer_set_callback:
11406 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11407 					 set_timer_callback_state);
11408 		break;
11409 	case BPF_FUNC_find_vma:
11410 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11411 					 set_find_vma_callback_state);
11412 		break;
11413 	case BPF_FUNC_snprintf:
11414 		err = check_bpf_snprintf_call(env, regs);
11415 		break;
11416 	case BPF_FUNC_loop:
11417 		update_loop_inline_state(env, meta.subprogno);
11418 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
11419 		 * is finished, thus mark it precise.
11420 		 */
11421 		err = mark_chain_precision(env, BPF_REG_1);
11422 		if (err)
11423 			return err;
11424 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
11425 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11426 						 set_loop_callback_state);
11427 		} else {
11428 			cur_func(env)->callback_depth = 0;
11429 			if (env->log.level & BPF_LOG_LEVEL2)
11430 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
11431 					env->cur_state->curframe);
11432 		}
11433 		break;
11434 	case BPF_FUNC_dynptr_from_mem:
11435 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
11436 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
11437 				reg_type_str(env, regs[BPF_REG_1].type));
11438 			return -EACCES;
11439 		}
11440 		break;
11441 	case BPF_FUNC_set_retval:
11442 		if (prog_type == BPF_PROG_TYPE_LSM &&
11443 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11444 			if (!env->prog->aux->attach_func_proto->type) {
11445 				/* Make sure programs that attach to void
11446 				 * hooks don't try to modify return value.
11447 				 */
11448 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11449 				return -EINVAL;
11450 			}
11451 		}
11452 		break;
11453 	case BPF_FUNC_dynptr_data:
11454 	{
11455 		struct bpf_reg_state *reg;
11456 		int id, ref_obj_id;
11457 
11458 		reg = get_dynptr_arg_reg(env, fn, regs);
11459 		if (!reg)
11460 			return -EFAULT;
11461 
11462 
11463 		if (meta.dynptr_id) {
11464 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
11465 			return -EFAULT;
11466 		}
11467 		if (meta.ref_obj_id) {
11468 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
11469 			return -EFAULT;
11470 		}
11471 
11472 		id = dynptr_id(env, reg);
11473 		if (id < 0) {
11474 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11475 			return id;
11476 		}
11477 
11478 		ref_obj_id = dynptr_ref_obj_id(env, reg);
11479 		if (ref_obj_id < 0) {
11480 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
11481 			return ref_obj_id;
11482 		}
11483 
11484 		meta.dynptr_id = id;
11485 		meta.ref_obj_id = ref_obj_id;
11486 
11487 		break;
11488 	}
11489 	case BPF_FUNC_dynptr_write:
11490 	{
11491 		enum bpf_dynptr_type dynptr_type;
11492 		struct bpf_reg_state *reg;
11493 
11494 		reg = get_dynptr_arg_reg(env, fn, regs);
11495 		if (!reg)
11496 			return -EFAULT;
11497 
11498 		dynptr_type = dynptr_get_type(env, reg);
11499 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11500 			return -EFAULT;
11501 
11502 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
11503 			/* this will trigger clear_all_pkt_pointers(), which will
11504 			 * invalidate all dynptr slices associated with the skb
11505 			 */
11506 			changes_data = true;
11507 
11508 		break;
11509 	}
11510 	case BPF_FUNC_per_cpu_ptr:
11511 	case BPF_FUNC_this_cpu_ptr:
11512 	{
11513 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
11514 		const struct btf_type *type;
11515 
11516 		if (reg->type & MEM_RCU) {
11517 			type = btf_type_by_id(reg->btf, reg->btf_id);
11518 			if (!type || !btf_type_is_struct(type)) {
11519 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
11520 				return -EFAULT;
11521 			}
11522 			returns_cpu_specific_alloc_ptr = true;
11523 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11524 		}
11525 		break;
11526 	}
11527 	case BPF_FUNC_user_ringbuf_drain:
11528 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11529 					 set_user_ringbuf_callback_state);
11530 		break;
11531 	}
11532 
11533 	if (err)
11534 		return err;
11535 
11536 	/* reset caller saved regs */
11537 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11538 		mark_reg_not_init(env, regs, caller_saved[i]);
11539 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11540 	}
11541 
11542 	/* helper call returns 64-bit value. */
11543 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
11544 
11545 	/* update return register (already marked as written above) */
11546 	ret_type = fn->ret_type;
11547 	ret_flag = type_flag(ret_type);
11548 
11549 	switch (base_type(ret_type)) {
11550 	case RET_INTEGER:
11551 		/* sets type to SCALAR_VALUE */
11552 		mark_reg_unknown(env, regs, BPF_REG_0);
11553 		break;
11554 	case RET_VOID:
11555 		regs[BPF_REG_0].type = NOT_INIT;
11556 		break;
11557 	case RET_PTR_TO_MAP_VALUE:
11558 		/* There is no offset yet applied, variable or fixed */
11559 		mark_reg_known_zero(env, regs, BPF_REG_0);
11560 		/* remember map_ptr, so that check_map_access()
11561 		 * can check 'value_size' boundary of memory access
11562 		 * to map element returned from bpf_map_lookup_elem()
11563 		 */
11564 		if (meta.map_ptr == NULL) {
11565 			verbose(env,
11566 				"kernel subsystem misconfigured verifier\n");
11567 			return -EINVAL;
11568 		}
11569 
11570 		if (func_id == BPF_FUNC_map_lookup_elem &&
11571 		    can_elide_value_nullness(meta.map_ptr->map_type) &&
11572 		    meta.const_map_key >= 0 &&
11573 		    meta.const_map_key < meta.map_ptr->max_entries)
11574 			ret_flag &= ~PTR_MAYBE_NULL;
11575 
11576 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
11577 		regs[BPF_REG_0].map_uid = meta.map_uid;
11578 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11579 		if (!type_may_be_null(ret_flag) &&
11580 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
11581 			regs[BPF_REG_0].id = ++env->id_gen;
11582 		}
11583 		break;
11584 	case RET_PTR_TO_SOCKET:
11585 		mark_reg_known_zero(env, regs, BPF_REG_0);
11586 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11587 		break;
11588 	case RET_PTR_TO_SOCK_COMMON:
11589 		mark_reg_known_zero(env, regs, BPF_REG_0);
11590 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11591 		break;
11592 	case RET_PTR_TO_TCP_SOCK:
11593 		mark_reg_known_zero(env, regs, BPF_REG_0);
11594 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11595 		break;
11596 	case RET_PTR_TO_MEM:
11597 		mark_reg_known_zero(env, regs, BPF_REG_0);
11598 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11599 		regs[BPF_REG_0].mem_size = meta.mem_size;
11600 		break;
11601 	case RET_PTR_TO_MEM_OR_BTF_ID:
11602 	{
11603 		const struct btf_type *t;
11604 
11605 		mark_reg_known_zero(env, regs, BPF_REG_0);
11606 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11607 		if (!btf_type_is_struct(t)) {
11608 			u32 tsize;
11609 			const struct btf_type *ret;
11610 			const char *tname;
11611 
11612 			/* resolve the type size of ksym. */
11613 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11614 			if (IS_ERR(ret)) {
11615 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11616 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
11617 					tname, PTR_ERR(ret));
11618 				return -EINVAL;
11619 			}
11620 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11621 			regs[BPF_REG_0].mem_size = tsize;
11622 		} else {
11623 			if (returns_cpu_specific_alloc_ptr) {
11624 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11625 			} else {
11626 				/* MEM_RDONLY may be carried from ret_flag, but it
11627 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11628 				 * it will confuse the check of PTR_TO_BTF_ID in
11629 				 * check_mem_access().
11630 				 */
11631 				ret_flag &= ~MEM_RDONLY;
11632 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11633 			}
11634 
11635 			regs[BPF_REG_0].btf = meta.ret_btf;
11636 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11637 		}
11638 		break;
11639 	}
11640 	case RET_PTR_TO_BTF_ID:
11641 	{
11642 		struct btf *ret_btf;
11643 		int ret_btf_id;
11644 
11645 		mark_reg_known_zero(env, regs, BPF_REG_0);
11646 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11647 		if (func_id == BPF_FUNC_kptr_xchg) {
11648 			ret_btf = meta.kptr_field->kptr.btf;
11649 			ret_btf_id = meta.kptr_field->kptr.btf_id;
11650 			if (!btf_is_kernel(ret_btf)) {
11651 				regs[BPF_REG_0].type |= MEM_ALLOC;
11652 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11653 					regs[BPF_REG_0].type |= MEM_PERCPU;
11654 			}
11655 		} else {
11656 			if (fn->ret_btf_id == BPF_PTR_POISON) {
11657 				verbose(env, "verifier internal error:");
11658 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
11659 					func_id_name(func_id));
11660 				return -EINVAL;
11661 			}
11662 			ret_btf = btf_vmlinux;
11663 			ret_btf_id = *fn->ret_btf_id;
11664 		}
11665 		if (ret_btf_id == 0) {
11666 			verbose(env, "invalid return type %u of func %s#%d\n",
11667 				base_type(ret_type), func_id_name(func_id),
11668 				func_id);
11669 			return -EINVAL;
11670 		}
11671 		regs[BPF_REG_0].btf = ret_btf;
11672 		regs[BPF_REG_0].btf_id = ret_btf_id;
11673 		break;
11674 	}
11675 	default:
11676 		verbose(env, "unknown return type %u of func %s#%d\n",
11677 			base_type(ret_type), func_id_name(func_id), func_id);
11678 		return -EINVAL;
11679 	}
11680 
11681 	if (type_may_be_null(regs[BPF_REG_0].type))
11682 		regs[BPF_REG_0].id = ++env->id_gen;
11683 
11684 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
11685 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
11686 			func_id_name(func_id), func_id);
11687 		return -EFAULT;
11688 	}
11689 
11690 	if (is_dynptr_ref_function(func_id))
11691 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
11692 
11693 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
11694 		/* For release_reference() */
11695 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11696 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
11697 		int id = acquire_reference(env, insn_idx);
11698 
11699 		if (id < 0)
11700 			return id;
11701 		/* For mark_ptr_or_null_reg() */
11702 		regs[BPF_REG_0].id = id;
11703 		/* For release_reference() */
11704 		regs[BPF_REG_0].ref_obj_id = id;
11705 	}
11706 
11707 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
11708 	if (err)
11709 		return err;
11710 
11711 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
11712 	if (err)
11713 		return err;
11714 
11715 	if ((func_id == BPF_FUNC_get_stack ||
11716 	     func_id == BPF_FUNC_get_task_stack) &&
11717 	    !env->prog->has_callchain_buf) {
11718 		const char *err_str;
11719 
11720 #ifdef CONFIG_PERF_EVENTS
11721 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
11722 		err_str = "cannot get callchain buffer for func %s#%d\n";
11723 #else
11724 		err = -ENOTSUPP;
11725 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
11726 #endif
11727 		if (err) {
11728 			verbose(env, err_str, func_id_name(func_id), func_id);
11729 			return err;
11730 		}
11731 
11732 		env->prog->has_callchain_buf = true;
11733 	}
11734 
11735 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
11736 		env->prog->call_get_stack = true;
11737 
11738 	if (func_id == BPF_FUNC_get_func_ip) {
11739 		if (check_get_func_ip(env))
11740 			return -ENOTSUPP;
11741 		env->prog->call_get_func_ip = true;
11742 	}
11743 
11744 	if (changes_data)
11745 		clear_all_pkt_pointers(env);
11746 	return 0;
11747 }
11748 
11749 /* mark_btf_func_reg_size() is used when the reg size is determined by
11750  * the BTF func_proto's return value size and argument.
11751  */
11752 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
11753 				     u32 regno, size_t reg_size)
11754 {
11755 	struct bpf_reg_state *reg = &regs[regno];
11756 
11757 	if (regno == BPF_REG_0) {
11758 		/* Function return value */
11759 		reg->live |= REG_LIVE_WRITTEN;
11760 		reg->subreg_def = reg_size == sizeof(u64) ?
11761 			DEF_NOT_SUBREG : env->insn_idx + 1;
11762 	} else {
11763 		/* Function argument */
11764 		if (reg_size == sizeof(u64)) {
11765 			mark_insn_zext(env, reg);
11766 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
11767 		} else {
11768 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
11769 		}
11770 	}
11771 }
11772 
11773 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
11774 				   size_t reg_size)
11775 {
11776 	return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size);
11777 }
11778 
11779 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
11780 {
11781 	return meta->kfunc_flags & KF_ACQUIRE;
11782 }
11783 
11784 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
11785 {
11786 	return meta->kfunc_flags & KF_RELEASE;
11787 }
11788 
11789 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
11790 {
11791 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
11792 }
11793 
11794 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
11795 {
11796 	return meta->kfunc_flags & KF_SLEEPABLE;
11797 }
11798 
11799 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
11800 {
11801 	return meta->kfunc_flags & KF_DESTRUCTIVE;
11802 }
11803 
11804 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
11805 {
11806 	return meta->kfunc_flags & KF_RCU;
11807 }
11808 
11809 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
11810 {
11811 	return meta->kfunc_flags & KF_RCU_PROTECTED;
11812 }
11813 
11814 static bool is_kfunc_arg_mem_size(const struct btf *btf,
11815 				  const struct btf_param *arg,
11816 				  const struct bpf_reg_state *reg)
11817 {
11818 	const struct btf_type *t;
11819 
11820 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11821 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11822 		return false;
11823 
11824 	return btf_param_match_suffix(btf, arg, "__sz");
11825 }
11826 
11827 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
11828 					const struct btf_param *arg,
11829 					const struct bpf_reg_state *reg)
11830 {
11831 	const struct btf_type *t;
11832 
11833 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11834 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11835 		return false;
11836 
11837 	return btf_param_match_suffix(btf, arg, "__szk");
11838 }
11839 
11840 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
11841 {
11842 	return btf_param_match_suffix(btf, arg, "__opt");
11843 }
11844 
11845 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
11846 {
11847 	return btf_param_match_suffix(btf, arg, "__k");
11848 }
11849 
11850 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
11851 {
11852 	return btf_param_match_suffix(btf, arg, "__ign");
11853 }
11854 
11855 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
11856 {
11857 	return btf_param_match_suffix(btf, arg, "__map");
11858 }
11859 
11860 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
11861 {
11862 	return btf_param_match_suffix(btf, arg, "__alloc");
11863 }
11864 
11865 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
11866 {
11867 	return btf_param_match_suffix(btf, arg, "__uninit");
11868 }
11869 
11870 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
11871 {
11872 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
11873 }
11874 
11875 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
11876 {
11877 	return btf_param_match_suffix(btf, arg, "__nullable");
11878 }
11879 
11880 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
11881 {
11882 	return btf_param_match_suffix(btf, arg, "__str");
11883 }
11884 
11885 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
11886 {
11887 	return btf_param_match_suffix(btf, arg, "__irq_flag");
11888 }
11889 
11890 static bool is_kfunc_arg_prog(const struct btf *btf, const struct btf_param *arg)
11891 {
11892 	return btf_param_match_suffix(btf, arg, "__prog");
11893 }
11894 
11895 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
11896 					  const struct btf_param *arg,
11897 					  const char *name)
11898 {
11899 	int len, target_len = strlen(name);
11900 	const char *param_name;
11901 
11902 	param_name = btf_name_by_offset(btf, arg->name_off);
11903 	if (str_is_empty(param_name))
11904 		return false;
11905 	len = strlen(param_name);
11906 	if (len != target_len)
11907 		return false;
11908 	if (strcmp(param_name, name))
11909 		return false;
11910 
11911 	return true;
11912 }
11913 
11914 enum {
11915 	KF_ARG_DYNPTR_ID,
11916 	KF_ARG_LIST_HEAD_ID,
11917 	KF_ARG_LIST_NODE_ID,
11918 	KF_ARG_RB_ROOT_ID,
11919 	KF_ARG_RB_NODE_ID,
11920 	KF_ARG_WORKQUEUE_ID,
11921 	KF_ARG_RES_SPIN_LOCK_ID,
11922 };
11923 
11924 BTF_ID_LIST(kf_arg_btf_ids)
11925 BTF_ID(struct, bpf_dynptr)
11926 BTF_ID(struct, bpf_list_head)
11927 BTF_ID(struct, bpf_list_node)
11928 BTF_ID(struct, bpf_rb_root)
11929 BTF_ID(struct, bpf_rb_node)
11930 BTF_ID(struct, bpf_wq)
11931 BTF_ID(struct, bpf_res_spin_lock)
11932 
11933 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
11934 				    const struct btf_param *arg, int type)
11935 {
11936 	const struct btf_type *t;
11937 	u32 res_id;
11938 
11939 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11940 	if (!t)
11941 		return false;
11942 	if (!btf_type_is_ptr(t))
11943 		return false;
11944 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
11945 	if (!t)
11946 		return false;
11947 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
11948 }
11949 
11950 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
11951 {
11952 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
11953 }
11954 
11955 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
11956 {
11957 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
11958 }
11959 
11960 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
11961 {
11962 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
11963 }
11964 
11965 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
11966 {
11967 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
11968 }
11969 
11970 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
11971 {
11972 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
11973 }
11974 
11975 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
11976 {
11977 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
11978 }
11979 
11980 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
11981 {
11982 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
11983 }
11984 
11985 static bool is_rbtree_node_type(const struct btf_type *t)
11986 {
11987 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
11988 }
11989 
11990 static bool is_list_node_type(const struct btf_type *t)
11991 {
11992 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
11993 }
11994 
11995 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
11996 				  const struct btf_param *arg)
11997 {
11998 	const struct btf_type *t;
11999 
12000 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
12001 	if (!t)
12002 		return false;
12003 
12004 	return true;
12005 }
12006 
12007 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
12008 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
12009 					const struct btf *btf,
12010 					const struct btf_type *t, int rec)
12011 {
12012 	const struct btf_type *member_type;
12013 	const struct btf_member *member;
12014 	u32 i;
12015 
12016 	if (!btf_type_is_struct(t))
12017 		return false;
12018 
12019 	for_each_member(i, t, member) {
12020 		const struct btf_array *array;
12021 
12022 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
12023 		if (btf_type_is_struct(member_type)) {
12024 			if (rec >= 3) {
12025 				verbose(env, "max struct nesting depth exceeded\n");
12026 				return false;
12027 			}
12028 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
12029 				return false;
12030 			continue;
12031 		}
12032 		if (btf_type_is_array(member_type)) {
12033 			array = btf_array(member_type);
12034 			if (!array->nelems)
12035 				return false;
12036 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
12037 			if (!btf_type_is_scalar(member_type))
12038 				return false;
12039 			continue;
12040 		}
12041 		if (!btf_type_is_scalar(member_type))
12042 			return false;
12043 	}
12044 	return true;
12045 }
12046 
12047 enum kfunc_ptr_arg_type {
12048 	KF_ARG_PTR_TO_CTX,
12049 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
12050 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
12051 	KF_ARG_PTR_TO_DYNPTR,
12052 	KF_ARG_PTR_TO_ITER,
12053 	KF_ARG_PTR_TO_LIST_HEAD,
12054 	KF_ARG_PTR_TO_LIST_NODE,
12055 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
12056 	KF_ARG_PTR_TO_MEM,
12057 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
12058 	KF_ARG_PTR_TO_CALLBACK,
12059 	KF_ARG_PTR_TO_RB_ROOT,
12060 	KF_ARG_PTR_TO_RB_NODE,
12061 	KF_ARG_PTR_TO_NULL,
12062 	KF_ARG_PTR_TO_CONST_STR,
12063 	KF_ARG_PTR_TO_MAP,
12064 	KF_ARG_PTR_TO_WORKQUEUE,
12065 	KF_ARG_PTR_TO_IRQ_FLAG,
12066 	KF_ARG_PTR_TO_RES_SPIN_LOCK,
12067 };
12068 
12069 enum special_kfunc_type {
12070 	KF_bpf_obj_new_impl,
12071 	KF_bpf_obj_drop_impl,
12072 	KF_bpf_refcount_acquire_impl,
12073 	KF_bpf_list_push_front_impl,
12074 	KF_bpf_list_push_back_impl,
12075 	KF_bpf_list_pop_front,
12076 	KF_bpf_list_pop_back,
12077 	KF_bpf_list_front,
12078 	KF_bpf_list_back,
12079 	KF_bpf_cast_to_kern_ctx,
12080 	KF_bpf_rdonly_cast,
12081 	KF_bpf_rcu_read_lock,
12082 	KF_bpf_rcu_read_unlock,
12083 	KF_bpf_rbtree_remove,
12084 	KF_bpf_rbtree_add_impl,
12085 	KF_bpf_rbtree_first,
12086 	KF_bpf_rbtree_root,
12087 	KF_bpf_rbtree_left,
12088 	KF_bpf_rbtree_right,
12089 	KF_bpf_dynptr_from_skb,
12090 	KF_bpf_dynptr_from_xdp,
12091 	KF_bpf_dynptr_slice,
12092 	KF_bpf_dynptr_slice_rdwr,
12093 	KF_bpf_dynptr_clone,
12094 	KF_bpf_percpu_obj_new_impl,
12095 	KF_bpf_percpu_obj_drop_impl,
12096 	KF_bpf_throw,
12097 	KF_bpf_wq_set_callback_impl,
12098 	KF_bpf_preempt_disable,
12099 	KF_bpf_preempt_enable,
12100 	KF_bpf_iter_css_task_new,
12101 	KF_bpf_session_cookie,
12102 	KF_bpf_get_kmem_cache,
12103 	KF_bpf_local_irq_save,
12104 	KF_bpf_local_irq_restore,
12105 	KF_bpf_iter_num_new,
12106 	KF_bpf_iter_num_next,
12107 	KF_bpf_iter_num_destroy,
12108 	KF_bpf_set_dentry_xattr,
12109 	KF_bpf_remove_dentry_xattr,
12110 	KF_bpf_res_spin_lock,
12111 	KF_bpf_res_spin_unlock,
12112 	KF_bpf_res_spin_lock_irqsave,
12113 	KF_bpf_res_spin_unlock_irqrestore,
12114 	KF___bpf_trap,
12115 };
12116 
12117 BTF_ID_LIST(special_kfunc_list)
12118 BTF_ID(func, bpf_obj_new_impl)
12119 BTF_ID(func, bpf_obj_drop_impl)
12120 BTF_ID(func, bpf_refcount_acquire_impl)
12121 BTF_ID(func, bpf_list_push_front_impl)
12122 BTF_ID(func, bpf_list_push_back_impl)
12123 BTF_ID(func, bpf_list_pop_front)
12124 BTF_ID(func, bpf_list_pop_back)
12125 BTF_ID(func, bpf_list_front)
12126 BTF_ID(func, bpf_list_back)
12127 BTF_ID(func, bpf_cast_to_kern_ctx)
12128 BTF_ID(func, bpf_rdonly_cast)
12129 BTF_ID(func, bpf_rcu_read_lock)
12130 BTF_ID(func, bpf_rcu_read_unlock)
12131 BTF_ID(func, bpf_rbtree_remove)
12132 BTF_ID(func, bpf_rbtree_add_impl)
12133 BTF_ID(func, bpf_rbtree_first)
12134 BTF_ID(func, bpf_rbtree_root)
12135 BTF_ID(func, bpf_rbtree_left)
12136 BTF_ID(func, bpf_rbtree_right)
12137 #ifdef CONFIG_NET
12138 BTF_ID(func, bpf_dynptr_from_skb)
12139 BTF_ID(func, bpf_dynptr_from_xdp)
12140 #else
12141 BTF_ID_UNUSED
12142 BTF_ID_UNUSED
12143 #endif
12144 BTF_ID(func, bpf_dynptr_slice)
12145 BTF_ID(func, bpf_dynptr_slice_rdwr)
12146 BTF_ID(func, bpf_dynptr_clone)
12147 BTF_ID(func, bpf_percpu_obj_new_impl)
12148 BTF_ID(func, bpf_percpu_obj_drop_impl)
12149 BTF_ID(func, bpf_throw)
12150 BTF_ID(func, bpf_wq_set_callback_impl)
12151 BTF_ID(func, bpf_preempt_disable)
12152 BTF_ID(func, bpf_preempt_enable)
12153 #ifdef CONFIG_CGROUPS
12154 BTF_ID(func, bpf_iter_css_task_new)
12155 #else
12156 BTF_ID_UNUSED
12157 #endif
12158 #ifdef CONFIG_BPF_EVENTS
12159 BTF_ID(func, bpf_session_cookie)
12160 #else
12161 BTF_ID_UNUSED
12162 #endif
12163 BTF_ID(func, bpf_get_kmem_cache)
12164 BTF_ID(func, bpf_local_irq_save)
12165 BTF_ID(func, bpf_local_irq_restore)
12166 BTF_ID(func, bpf_iter_num_new)
12167 BTF_ID(func, bpf_iter_num_next)
12168 BTF_ID(func, bpf_iter_num_destroy)
12169 #ifdef CONFIG_BPF_LSM
12170 BTF_ID(func, bpf_set_dentry_xattr)
12171 BTF_ID(func, bpf_remove_dentry_xattr)
12172 #else
12173 BTF_ID_UNUSED
12174 BTF_ID_UNUSED
12175 #endif
12176 BTF_ID(func, bpf_res_spin_lock)
12177 BTF_ID(func, bpf_res_spin_unlock)
12178 BTF_ID(func, bpf_res_spin_lock_irqsave)
12179 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
12180 BTF_ID(func, __bpf_trap)
12181 
12182 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
12183 {
12184 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
12185 	    meta->arg_owning_ref) {
12186 		return false;
12187 	}
12188 
12189 	return meta->kfunc_flags & KF_RET_NULL;
12190 }
12191 
12192 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
12193 {
12194 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
12195 }
12196 
12197 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
12198 {
12199 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
12200 }
12201 
12202 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
12203 {
12204 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
12205 }
12206 
12207 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
12208 {
12209 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
12210 }
12211 
12212 static enum kfunc_ptr_arg_type
12213 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
12214 		       struct bpf_kfunc_call_arg_meta *meta,
12215 		       const struct btf_type *t, const struct btf_type *ref_t,
12216 		       const char *ref_tname, const struct btf_param *args,
12217 		       int argno, int nargs)
12218 {
12219 	u32 regno = argno + 1;
12220 	struct bpf_reg_state *regs = cur_regs(env);
12221 	struct bpf_reg_state *reg = &regs[regno];
12222 	bool arg_mem_size = false;
12223 
12224 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
12225 		return KF_ARG_PTR_TO_CTX;
12226 
12227 	/* In this function, we verify the kfunc's BTF as per the argument type,
12228 	 * leaving the rest of the verification with respect to the register
12229 	 * type to our caller. When a set of conditions hold in the BTF type of
12230 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
12231 	 */
12232 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
12233 		return KF_ARG_PTR_TO_CTX;
12234 
12235 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
12236 		return KF_ARG_PTR_TO_NULL;
12237 
12238 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
12239 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
12240 
12241 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
12242 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
12243 
12244 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
12245 		return KF_ARG_PTR_TO_DYNPTR;
12246 
12247 	if (is_kfunc_arg_iter(meta, argno, &args[argno]))
12248 		return KF_ARG_PTR_TO_ITER;
12249 
12250 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
12251 		return KF_ARG_PTR_TO_LIST_HEAD;
12252 
12253 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
12254 		return KF_ARG_PTR_TO_LIST_NODE;
12255 
12256 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
12257 		return KF_ARG_PTR_TO_RB_ROOT;
12258 
12259 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
12260 		return KF_ARG_PTR_TO_RB_NODE;
12261 
12262 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
12263 		return KF_ARG_PTR_TO_CONST_STR;
12264 
12265 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
12266 		return KF_ARG_PTR_TO_MAP;
12267 
12268 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
12269 		return KF_ARG_PTR_TO_WORKQUEUE;
12270 
12271 	if (is_kfunc_arg_irq_flag(meta->btf, &args[argno]))
12272 		return KF_ARG_PTR_TO_IRQ_FLAG;
12273 
12274 	if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno]))
12275 		return KF_ARG_PTR_TO_RES_SPIN_LOCK;
12276 
12277 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
12278 		if (!btf_type_is_struct(ref_t)) {
12279 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
12280 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
12281 			return -EINVAL;
12282 		}
12283 		return KF_ARG_PTR_TO_BTF_ID;
12284 	}
12285 
12286 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
12287 		return KF_ARG_PTR_TO_CALLBACK;
12288 
12289 	if (argno + 1 < nargs &&
12290 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
12291 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
12292 		arg_mem_size = true;
12293 
12294 	/* This is the catch all argument type of register types supported by
12295 	 * check_helper_mem_access. However, we only allow when argument type is
12296 	 * pointer to scalar, or struct composed (recursively) of scalars. When
12297 	 * arg_mem_size is true, the pointer can be void *.
12298 	 */
12299 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
12300 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
12301 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
12302 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
12303 		return -EINVAL;
12304 	}
12305 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
12306 }
12307 
12308 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
12309 					struct bpf_reg_state *reg,
12310 					const struct btf_type *ref_t,
12311 					const char *ref_tname, u32 ref_id,
12312 					struct bpf_kfunc_call_arg_meta *meta,
12313 					int argno)
12314 {
12315 	const struct btf_type *reg_ref_t;
12316 	bool strict_type_match = false;
12317 	const struct btf *reg_btf;
12318 	const char *reg_ref_tname;
12319 	bool taking_projection;
12320 	bool struct_same;
12321 	u32 reg_ref_id;
12322 
12323 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
12324 		reg_btf = reg->btf;
12325 		reg_ref_id = reg->btf_id;
12326 	} else {
12327 		reg_btf = btf_vmlinux;
12328 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
12329 	}
12330 
12331 	/* Enforce strict type matching for calls to kfuncs that are acquiring
12332 	 * or releasing a reference, or are no-cast aliases. We do _not_
12333 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
12334 	 * as we want to enable BPF programs to pass types that are bitwise
12335 	 * equivalent without forcing them to explicitly cast with something
12336 	 * like bpf_cast_to_kern_ctx().
12337 	 *
12338 	 * For example, say we had a type like the following:
12339 	 *
12340 	 * struct bpf_cpumask {
12341 	 *	cpumask_t cpumask;
12342 	 *	refcount_t usage;
12343 	 * };
12344 	 *
12345 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
12346 	 * to a struct cpumask, so it would be safe to pass a struct
12347 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
12348 	 *
12349 	 * The philosophy here is similar to how we allow scalars of different
12350 	 * types to be passed to kfuncs as long as the size is the same. The
12351 	 * only difference here is that we're simply allowing
12352 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
12353 	 * resolve types.
12354 	 */
12355 	if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
12356 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
12357 		strict_type_match = true;
12358 
12359 	WARN_ON_ONCE(is_kfunc_release(meta) &&
12360 		     (reg->off || !tnum_is_const(reg->var_off) ||
12361 		      reg->var_off.value));
12362 
12363 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
12364 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
12365 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
12366 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
12367 	 * actually use it -- it must cast to the underlying type. So we allow
12368 	 * caller to pass in the underlying type.
12369 	 */
12370 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
12371 	if (!taking_projection && !struct_same) {
12372 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
12373 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
12374 			btf_type_str(reg_ref_t), reg_ref_tname);
12375 		return -EINVAL;
12376 	}
12377 	return 0;
12378 }
12379 
12380 static int process_irq_flag(struct bpf_verifier_env *env, int regno,
12381 			     struct bpf_kfunc_call_arg_meta *meta)
12382 {
12383 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
12384 	int err, kfunc_class = IRQ_NATIVE_KFUNC;
12385 	bool irq_save;
12386 
12387 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
12388 	    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
12389 		irq_save = true;
12390 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12391 			kfunc_class = IRQ_LOCK_KFUNC;
12392 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
12393 		   meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
12394 		irq_save = false;
12395 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12396 			kfunc_class = IRQ_LOCK_KFUNC;
12397 	} else {
12398 		verbose(env, "verifier internal error: unknown irq flags kfunc\n");
12399 		return -EFAULT;
12400 	}
12401 
12402 	if (irq_save) {
12403 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
12404 			verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1);
12405 			return -EINVAL;
12406 		}
12407 
12408 		err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false);
12409 		if (err)
12410 			return err;
12411 
12412 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
12413 		if (err)
12414 			return err;
12415 	} else {
12416 		err = is_irq_flag_reg_valid_init(env, reg);
12417 		if (err) {
12418 			verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1);
12419 			return err;
12420 		}
12421 
12422 		err = mark_irq_flag_read(env, reg);
12423 		if (err)
12424 			return err;
12425 
12426 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
12427 		if (err)
12428 			return err;
12429 	}
12430 	return 0;
12431 }
12432 
12433 
12434 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12435 {
12436 	struct btf_record *rec = reg_btf_record(reg);
12437 
12438 	if (!env->cur_state->active_locks) {
12439 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
12440 		return -EFAULT;
12441 	}
12442 
12443 	if (type_flag(reg->type) & NON_OWN_REF) {
12444 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
12445 		return -EFAULT;
12446 	}
12447 
12448 	reg->type |= NON_OWN_REF;
12449 	if (rec->refcount_off >= 0)
12450 		reg->type |= MEM_RCU;
12451 
12452 	return 0;
12453 }
12454 
12455 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
12456 {
12457 	struct bpf_verifier_state *state = env->cur_state;
12458 	struct bpf_func_state *unused;
12459 	struct bpf_reg_state *reg;
12460 	int i;
12461 
12462 	if (!ref_obj_id) {
12463 		verbose(env, "verifier internal error: ref_obj_id is zero for "
12464 			     "owning -> non-owning conversion\n");
12465 		return -EFAULT;
12466 	}
12467 
12468 	for (i = 0; i < state->acquired_refs; i++) {
12469 		if (state->refs[i].id != ref_obj_id)
12470 			continue;
12471 
12472 		/* Clear ref_obj_id here so release_reference doesn't clobber
12473 		 * the whole reg
12474 		 */
12475 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12476 			if (reg->ref_obj_id == ref_obj_id) {
12477 				reg->ref_obj_id = 0;
12478 				ref_set_non_owning(env, reg);
12479 			}
12480 		}));
12481 		return 0;
12482 	}
12483 
12484 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
12485 	return -EFAULT;
12486 }
12487 
12488 /* Implementation details:
12489  *
12490  * Each register points to some region of memory, which we define as an
12491  * allocation. Each allocation may embed a bpf_spin_lock which protects any
12492  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12493  * allocation. The lock and the data it protects are colocated in the same
12494  * memory region.
12495  *
12496  * Hence, everytime a register holds a pointer value pointing to such
12497  * allocation, the verifier preserves a unique reg->id for it.
12498  *
12499  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12500  * bpf_spin_lock is called.
12501  *
12502  * To enable this, lock state in the verifier captures two values:
12503  *	active_lock.ptr = Register's type specific pointer
12504  *	active_lock.id  = A unique ID for each register pointer value
12505  *
12506  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12507  * supported register types.
12508  *
12509  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12510  * allocated objects is the reg->btf pointer.
12511  *
12512  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12513  * can establish the provenance of the map value statically for each distinct
12514  * lookup into such maps. They always contain a single map value hence unique
12515  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12516  *
12517  * So, in case of global variables, they use array maps with max_entries = 1,
12518  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12519  * into the same map value as max_entries is 1, as described above).
12520  *
12521  * In case of inner map lookups, the inner map pointer has same map_ptr as the
12522  * outer map pointer (in verifier context), but each lookup into an inner map
12523  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12524  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12525  * will get different reg->id assigned to each lookup, hence different
12526  * active_lock.id.
12527  *
12528  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12529  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12530  * returned from bpf_obj_new. Each allocation receives a new reg->id.
12531  */
12532 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12533 {
12534 	struct bpf_reference_state *s;
12535 	void *ptr;
12536 	u32 id;
12537 
12538 	switch ((int)reg->type) {
12539 	case PTR_TO_MAP_VALUE:
12540 		ptr = reg->map_ptr;
12541 		break;
12542 	case PTR_TO_BTF_ID | MEM_ALLOC:
12543 		ptr = reg->btf;
12544 		break;
12545 	default:
12546 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
12547 		return -EFAULT;
12548 	}
12549 	id = reg->id;
12550 
12551 	if (!env->cur_state->active_locks)
12552 		return -EINVAL;
12553 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
12554 	if (!s) {
12555 		verbose(env, "held lock and object are not in the same allocation\n");
12556 		return -EINVAL;
12557 	}
12558 	return 0;
12559 }
12560 
12561 static bool is_bpf_list_api_kfunc(u32 btf_id)
12562 {
12563 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12564 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12565 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12566 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
12567 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
12568 	       btf_id == special_kfunc_list[KF_bpf_list_back];
12569 }
12570 
12571 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
12572 {
12573 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12574 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12575 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
12576 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
12577 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12578 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
12579 }
12580 
12581 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
12582 {
12583 	return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
12584 	       btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
12585 	       btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
12586 }
12587 
12588 static bool is_bpf_graph_api_kfunc(u32 btf_id)
12589 {
12590 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
12591 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
12592 }
12593 
12594 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
12595 {
12596 	return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
12597 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
12598 	       btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
12599 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
12600 }
12601 
12602 static bool kfunc_spin_allowed(u32 btf_id)
12603 {
12604 	return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) ||
12605 	       is_bpf_res_spin_lock_kfunc(btf_id);
12606 }
12607 
12608 static bool is_sync_callback_calling_kfunc(u32 btf_id)
12609 {
12610 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
12611 }
12612 
12613 static bool is_async_callback_calling_kfunc(u32 btf_id)
12614 {
12615 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12616 }
12617 
12618 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
12619 {
12620 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
12621 	       insn->imm == special_kfunc_list[KF_bpf_throw];
12622 }
12623 
12624 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
12625 {
12626 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12627 }
12628 
12629 static bool is_callback_calling_kfunc(u32 btf_id)
12630 {
12631 	return is_sync_callback_calling_kfunc(btf_id) ||
12632 	       is_async_callback_calling_kfunc(btf_id);
12633 }
12634 
12635 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
12636 {
12637 	return is_bpf_rbtree_api_kfunc(btf_id);
12638 }
12639 
12640 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
12641 					  enum btf_field_type head_field_type,
12642 					  u32 kfunc_btf_id)
12643 {
12644 	bool ret;
12645 
12646 	switch (head_field_type) {
12647 	case BPF_LIST_HEAD:
12648 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
12649 		break;
12650 	case BPF_RB_ROOT:
12651 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
12652 		break;
12653 	default:
12654 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
12655 			btf_field_type_name(head_field_type));
12656 		return false;
12657 	}
12658 
12659 	if (!ret)
12660 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
12661 			btf_field_type_name(head_field_type));
12662 	return ret;
12663 }
12664 
12665 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
12666 					  enum btf_field_type node_field_type,
12667 					  u32 kfunc_btf_id)
12668 {
12669 	bool ret;
12670 
12671 	switch (node_field_type) {
12672 	case BPF_LIST_NODE:
12673 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12674 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
12675 		break;
12676 	case BPF_RB_NODE:
12677 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12678 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12679 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12680 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
12681 		break;
12682 	default:
12683 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
12684 			btf_field_type_name(node_field_type));
12685 		return false;
12686 	}
12687 
12688 	if (!ret)
12689 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
12690 			btf_field_type_name(node_field_type));
12691 	return ret;
12692 }
12693 
12694 static int
12695 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
12696 				   struct bpf_reg_state *reg, u32 regno,
12697 				   struct bpf_kfunc_call_arg_meta *meta,
12698 				   enum btf_field_type head_field_type,
12699 				   struct btf_field **head_field)
12700 {
12701 	const char *head_type_name;
12702 	struct btf_field *field;
12703 	struct btf_record *rec;
12704 	u32 head_off;
12705 
12706 	if (meta->btf != btf_vmlinux) {
12707 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
12708 		return -EFAULT;
12709 	}
12710 
12711 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
12712 		return -EFAULT;
12713 
12714 	head_type_name = btf_field_type_name(head_field_type);
12715 	if (!tnum_is_const(reg->var_off)) {
12716 		verbose(env,
12717 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12718 			regno, head_type_name);
12719 		return -EINVAL;
12720 	}
12721 
12722 	rec = reg_btf_record(reg);
12723 	head_off = reg->off + reg->var_off.value;
12724 	field = btf_record_find(rec, head_off, head_field_type);
12725 	if (!field) {
12726 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
12727 		return -EINVAL;
12728 	}
12729 
12730 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
12731 	if (check_reg_allocation_locked(env, reg)) {
12732 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
12733 			rec->spin_lock_off, head_type_name);
12734 		return -EINVAL;
12735 	}
12736 
12737 	if (*head_field) {
12738 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
12739 		return -EFAULT;
12740 	}
12741 	*head_field = field;
12742 	return 0;
12743 }
12744 
12745 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
12746 					   struct bpf_reg_state *reg, u32 regno,
12747 					   struct bpf_kfunc_call_arg_meta *meta)
12748 {
12749 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
12750 							  &meta->arg_list_head.field);
12751 }
12752 
12753 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
12754 					     struct bpf_reg_state *reg, u32 regno,
12755 					     struct bpf_kfunc_call_arg_meta *meta)
12756 {
12757 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
12758 							  &meta->arg_rbtree_root.field);
12759 }
12760 
12761 static int
12762 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
12763 				   struct bpf_reg_state *reg, u32 regno,
12764 				   struct bpf_kfunc_call_arg_meta *meta,
12765 				   enum btf_field_type head_field_type,
12766 				   enum btf_field_type node_field_type,
12767 				   struct btf_field **node_field)
12768 {
12769 	const char *node_type_name;
12770 	const struct btf_type *et, *t;
12771 	struct btf_field *field;
12772 	u32 node_off;
12773 
12774 	if (meta->btf != btf_vmlinux) {
12775 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
12776 		return -EFAULT;
12777 	}
12778 
12779 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
12780 		return -EFAULT;
12781 
12782 	node_type_name = btf_field_type_name(node_field_type);
12783 	if (!tnum_is_const(reg->var_off)) {
12784 		verbose(env,
12785 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12786 			regno, node_type_name);
12787 		return -EINVAL;
12788 	}
12789 
12790 	node_off = reg->off + reg->var_off.value;
12791 	field = reg_find_field_offset(reg, node_off, node_field_type);
12792 	if (!field) {
12793 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
12794 		return -EINVAL;
12795 	}
12796 
12797 	field = *node_field;
12798 
12799 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
12800 	t = btf_type_by_id(reg->btf, reg->btf_id);
12801 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
12802 				  field->graph_root.value_btf_id, true)) {
12803 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
12804 			"in struct %s, but arg is at offset=%d in struct %s\n",
12805 			btf_field_type_name(head_field_type),
12806 			btf_field_type_name(node_field_type),
12807 			field->graph_root.node_offset,
12808 			btf_name_by_offset(field->graph_root.btf, et->name_off),
12809 			node_off, btf_name_by_offset(reg->btf, t->name_off));
12810 		return -EINVAL;
12811 	}
12812 	meta->arg_btf = reg->btf;
12813 	meta->arg_btf_id = reg->btf_id;
12814 
12815 	if (node_off != field->graph_root.node_offset) {
12816 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
12817 			node_off, btf_field_type_name(node_field_type),
12818 			field->graph_root.node_offset,
12819 			btf_name_by_offset(field->graph_root.btf, et->name_off));
12820 		return -EINVAL;
12821 	}
12822 
12823 	return 0;
12824 }
12825 
12826 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
12827 					   struct bpf_reg_state *reg, u32 regno,
12828 					   struct bpf_kfunc_call_arg_meta *meta)
12829 {
12830 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
12831 						  BPF_LIST_HEAD, BPF_LIST_NODE,
12832 						  &meta->arg_list_head.field);
12833 }
12834 
12835 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
12836 					     struct bpf_reg_state *reg, u32 regno,
12837 					     struct bpf_kfunc_call_arg_meta *meta)
12838 {
12839 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
12840 						  BPF_RB_ROOT, BPF_RB_NODE,
12841 						  &meta->arg_rbtree_root.field);
12842 }
12843 
12844 /*
12845  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
12846  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
12847  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
12848  * them can only be attached to some specific hook points.
12849  */
12850 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
12851 {
12852 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12853 
12854 	switch (prog_type) {
12855 	case BPF_PROG_TYPE_LSM:
12856 		return true;
12857 	case BPF_PROG_TYPE_TRACING:
12858 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
12859 			return true;
12860 		fallthrough;
12861 	default:
12862 		return in_sleepable(env);
12863 	}
12864 }
12865 
12866 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
12867 			    int insn_idx)
12868 {
12869 	const char *func_name = meta->func_name, *ref_tname;
12870 	const struct btf *btf = meta->btf;
12871 	const struct btf_param *args;
12872 	struct btf_record *rec;
12873 	u32 i, nargs;
12874 	int ret;
12875 
12876 	args = (const struct btf_param *)(meta->func_proto + 1);
12877 	nargs = btf_type_vlen(meta->func_proto);
12878 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
12879 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
12880 			MAX_BPF_FUNC_REG_ARGS);
12881 		return -EINVAL;
12882 	}
12883 
12884 	/* Check that BTF function arguments match actual types that the
12885 	 * verifier sees.
12886 	 */
12887 	for (i = 0; i < nargs; i++) {
12888 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
12889 		const struct btf_type *t, *ref_t, *resolve_ret;
12890 		enum bpf_arg_type arg_type = ARG_DONTCARE;
12891 		u32 regno = i + 1, ref_id, type_size;
12892 		bool is_ret_buf_sz = false;
12893 		int kf_arg_type;
12894 
12895 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
12896 
12897 		if (is_kfunc_arg_ignore(btf, &args[i]))
12898 			continue;
12899 
12900 		if (is_kfunc_arg_prog(btf, &args[i])) {
12901 			/* Used to reject repeated use of __prog. */
12902 			if (meta->arg_prog) {
12903 				verbose(env, "Only 1 prog->aux argument supported per-kfunc\n");
12904 				return -EFAULT;
12905 			}
12906 			meta->arg_prog = true;
12907 			cur_aux(env)->arg_prog = regno;
12908 			continue;
12909 		}
12910 
12911 		if (btf_type_is_scalar(t)) {
12912 			if (reg->type != SCALAR_VALUE) {
12913 				verbose(env, "R%d is not a scalar\n", regno);
12914 				return -EINVAL;
12915 			}
12916 
12917 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
12918 				if (meta->arg_constant.found) {
12919 					verbose(env, "verifier internal error: only one constant argument permitted\n");
12920 					return -EFAULT;
12921 				}
12922 				if (!tnum_is_const(reg->var_off)) {
12923 					verbose(env, "R%d must be a known constant\n", regno);
12924 					return -EINVAL;
12925 				}
12926 				ret = mark_chain_precision(env, regno);
12927 				if (ret < 0)
12928 					return ret;
12929 				meta->arg_constant.found = true;
12930 				meta->arg_constant.value = reg->var_off.value;
12931 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
12932 				meta->r0_rdonly = true;
12933 				is_ret_buf_sz = true;
12934 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
12935 				is_ret_buf_sz = true;
12936 			}
12937 
12938 			if (is_ret_buf_sz) {
12939 				if (meta->r0_size) {
12940 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
12941 					return -EINVAL;
12942 				}
12943 
12944 				if (!tnum_is_const(reg->var_off)) {
12945 					verbose(env, "R%d is not a const\n", regno);
12946 					return -EINVAL;
12947 				}
12948 
12949 				meta->r0_size = reg->var_off.value;
12950 				ret = mark_chain_precision(env, regno);
12951 				if (ret)
12952 					return ret;
12953 			}
12954 			continue;
12955 		}
12956 
12957 		if (!btf_type_is_ptr(t)) {
12958 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
12959 			return -EINVAL;
12960 		}
12961 
12962 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
12963 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
12964 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
12965 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
12966 			return -EACCES;
12967 		}
12968 
12969 		if (reg->ref_obj_id) {
12970 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
12971 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
12972 					regno, reg->ref_obj_id,
12973 					meta->ref_obj_id);
12974 				return -EFAULT;
12975 			}
12976 			meta->ref_obj_id = reg->ref_obj_id;
12977 			if (is_kfunc_release(meta))
12978 				meta->release_regno = regno;
12979 		}
12980 
12981 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
12982 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12983 
12984 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
12985 		if (kf_arg_type < 0)
12986 			return kf_arg_type;
12987 
12988 		switch (kf_arg_type) {
12989 		case KF_ARG_PTR_TO_NULL:
12990 			continue;
12991 		case KF_ARG_PTR_TO_MAP:
12992 			if (!reg->map_ptr) {
12993 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
12994 				return -EINVAL;
12995 			}
12996 			if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) {
12997 				/* Use map_uid (which is unique id of inner map) to reject:
12998 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
12999 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
13000 				 * if (inner_map1 && inner_map2) {
13001 				 *     wq = bpf_map_lookup_elem(inner_map1);
13002 				 *     if (wq)
13003 				 *         // mismatch would have been allowed
13004 				 *         bpf_wq_init(wq, inner_map2);
13005 				 * }
13006 				 *
13007 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
13008 				 */
13009 				if (meta->map.ptr != reg->map_ptr ||
13010 				    meta->map.uid != reg->map_uid) {
13011 					verbose(env,
13012 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
13013 						meta->map.uid, reg->map_uid);
13014 					return -EINVAL;
13015 				}
13016 			}
13017 			meta->map.ptr = reg->map_ptr;
13018 			meta->map.uid = reg->map_uid;
13019 			fallthrough;
13020 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13021 		case KF_ARG_PTR_TO_BTF_ID:
13022 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
13023 				break;
13024 
13025 			if (!is_trusted_reg(reg)) {
13026 				if (!is_kfunc_rcu(meta)) {
13027 					verbose(env, "R%d must be referenced or trusted\n", regno);
13028 					return -EINVAL;
13029 				}
13030 				if (!is_rcu_reg(reg)) {
13031 					verbose(env, "R%d must be a rcu pointer\n", regno);
13032 					return -EINVAL;
13033 				}
13034 			}
13035 			fallthrough;
13036 		case KF_ARG_PTR_TO_CTX:
13037 		case KF_ARG_PTR_TO_DYNPTR:
13038 		case KF_ARG_PTR_TO_ITER:
13039 		case KF_ARG_PTR_TO_LIST_HEAD:
13040 		case KF_ARG_PTR_TO_LIST_NODE:
13041 		case KF_ARG_PTR_TO_RB_ROOT:
13042 		case KF_ARG_PTR_TO_RB_NODE:
13043 		case KF_ARG_PTR_TO_MEM:
13044 		case KF_ARG_PTR_TO_MEM_SIZE:
13045 		case KF_ARG_PTR_TO_CALLBACK:
13046 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13047 		case KF_ARG_PTR_TO_CONST_STR:
13048 		case KF_ARG_PTR_TO_WORKQUEUE:
13049 		case KF_ARG_PTR_TO_IRQ_FLAG:
13050 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13051 			break;
13052 		default:
13053 			WARN_ON_ONCE(1);
13054 			return -EFAULT;
13055 		}
13056 
13057 		if (is_kfunc_release(meta) && reg->ref_obj_id)
13058 			arg_type |= OBJ_RELEASE;
13059 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
13060 		if (ret < 0)
13061 			return ret;
13062 
13063 		switch (kf_arg_type) {
13064 		case KF_ARG_PTR_TO_CTX:
13065 			if (reg->type != PTR_TO_CTX) {
13066 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
13067 					i, reg_type_str(env, reg->type));
13068 				return -EINVAL;
13069 			}
13070 
13071 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13072 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
13073 				if (ret < 0)
13074 					return -EINVAL;
13075 				meta->ret_btf_id  = ret;
13076 			}
13077 			break;
13078 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13079 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
13080 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
13081 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
13082 					return -EINVAL;
13083 				}
13084 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
13085 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13086 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
13087 					return -EINVAL;
13088 				}
13089 			} else {
13090 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13091 				return -EINVAL;
13092 			}
13093 			if (!reg->ref_obj_id) {
13094 				verbose(env, "allocated object must be referenced\n");
13095 				return -EINVAL;
13096 			}
13097 			if (meta->btf == btf_vmlinux) {
13098 				meta->arg_btf = reg->btf;
13099 				meta->arg_btf_id = reg->btf_id;
13100 			}
13101 			break;
13102 		case KF_ARG_PTR_TO_DYNPTR:
13103 		{
13104 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
13105 			int clone_ref_obj_id = 0;
13106 
13107 			if (reg->type == CONST_PTR_TO_DYNPTR)
13108 				dynptr_arg_type |= MEM_RDONLY;
13109 
13110 			if (is_kfunc_arg_uninit(btf, &args[i]))
13111 				dynptr_arg_type |= MEM_UNINIT;
13112 
13113 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
13114 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
13115 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
13116 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
13117 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
13118 				   (dynptr_arg_type & MEM_UNINIT)) {
13119 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
13120 
13121 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
13122 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
13123 					return -EFAULT;
13124 				}
13125 
13126 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
13127 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
13128 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
13129 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
13130 					return -EFAULT;
13131 				}
13132 			}
13133 
13134 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
13135 			if (ret < 0)
13136 				return ret;
13137 
13138 			if (!(dynptr_arg_type & MEM_UNINIT)) {
13139 				int id = dynptr_id(env, reg);
13140 
13141 				if (id < 0) {
13142 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
13143 					return id;
13144 				}
13145 				meta->initialized_dynptr.id = id;
13146 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
13147 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
13148 			}
13149 
13150 			break;
13151 		}
13152 		case KF_ARG_PTR_TO_ITER:
13153 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
13154 				if (!check_css_task_iter_allowlist(env)) {
13155 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
13156 					return -EINVAL;
13157 				}
13158 			}
13159 			ret = process_iter_arg(env, regno, insn_idx, meta);
13160 			if (ret < 0)
13161 				return ret;
13162 			break;
13163 		case KF_ARG_PTR_TO_LIST_HEAD:
13164 			if (reg->type != PTR_TO_MAP_VALUE &&
13165 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13166 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13167 				return -EINVAL;
13168 			}
13169 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13170 				verbose(env, "allocated object must be referenced\n");
13171 				return -EINVAL;
13172 			}
13173 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
13174 			if (ret < 0)
13175 				return ret;
13176 			break;
13177 		case KF_ARG_PTR_TO_RB_ROOT:
13178 			if (reg->type != PTR_TO_MAP_VALUE &&
13179 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13180 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13181 				return -EINVAL;
13182 			}
13183 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13184 				verbose(env, "allocated object must be referenced\n");
13185 				return -EINVAL;
13186 			}
13187 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
13188 			if (ret < 0)
13189 				return ret;
13190 			break;
13191 		case KF_ARG_PTR_TO_LIST_NODE:
13192 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13193 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13194 				return -EINVAL;
13195 			}
13196 			if (!reg->ref_obj_id) {
13197 				verbose(env, "allocated object must be referenced\n");
13198 				return -EINVAL;
13199 			}
13200 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
13201 			if (ret < 0)
13202 				return ret;
13203 			break;
13204 		case KF_ARG_PTR_TO_RB_NODE:
13205 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13206 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13207 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
13208 					return -EINVAL;
13209 				}
13210 				if (!reg->ref_obj_id) {
13211 					verbose(env, "allocated object must be referenced\n");
13212 					return -EINVAL;
13213 				}
13214 			} else {
13215 				if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) {
13216 					verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
13217 					return -EINVAL;
13218 				}
13219 				if (in_rbtree_lock_required_cb(env)) {
13220 					verbose(env, "%s not allowed in rbtree cb\n", func_name);
13221 					return -EINVAL;
13222 				}
13223 			}
13224 
13225 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
13226 			if (ret < 0)
13227 				return ret;
13228 			break;
13229 		case KF_ARG_PTR_TO_MAP:
13230 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
13231 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
13232 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
13233 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13234 			fallthrough;
13235 		case KF_ARG_PTR_TO_BTF_ID:
13236 			/* Only base_type is checked, further checks are done here */
13237 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
13238 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
13239 			    !reg2btf_ids[base_type(reg->type)]) {
13240 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
13241 				verbose(env, "expected %s or socket\n",
13242 					reg_type_str(env, base_type(reg->type) |
13243 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
13244 				return -EINVAL;
13245 			}
13246 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
13247 			if (ret < 0)
13248 				return ret;
13249 			break;
13250 		case KF_ARG_PTR_TO_MEM:
13251 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
13252 			if (IS_ERR(resolve_ret)) {
13253 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
13254 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
13255 				return -EINVAL;
13256 			}
13257 			ret = check_mem_reg(env, reg, regno, type_size);
13258 			if (ret < 0)
13259 				return ret;
13260 			break;
13261 		case KF_ARG_PTR_TO_MEM_SIZE:
13262 		{
13263 			struct bpf_reg_state *buff_reg = &regs[regno];
13264 			const struct btf_param *buff_arg = &args[i];
13265 			struct bpf_reg_state *size_reg = &regs[regno + 1];
13266 			const struct btf_param *size_arg = &args[i + 1];
13267 
13268 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
13269 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
13270 				if (ret < 0) {
13271 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
13272 					return ret;
13273 				}
13274 			}
13275 
13276 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
13277 				if (meta->arg_constant.found) {
13278 					verbose(env, "verifier internal error: only one constant argument permitted\n");
13279 					return -EFAULT;
13280 				}
13281 				if (!tnum_is_const(size_reg->var_off)) {
13282 					verbose(env, "R%d must be a known constant\n", regno + 1);
13283 					return -EINVAL;
13284 				}
13285 				meta->arg_constant.found = true;
13286 				meta->arg_constant.value = size_reg->var_off.value;
13287 			}
13288 
13289 			/* Skip next '__sz' or '__szk' argument */
13290 			i++;
13291 			break;
13292 		}
13293 		case KF_ARG_PTR_TO_CALLBACK:
13294 			if (reg->type != PTR_TO_FUNC) {
13295 				verbose(env, "arg%d expected pointer to func\n", i);
13296 				return -EINVAL;
13297 			}
13298 			meta->subprogno = reg->subprogno;
13299 			break;
13300 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13301 			if (!type_is_ptr_alloc_obj(reg->type)) {
13302 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
13303 				return -EINVAL;
13304 			}
13305 			if (!type_is_non_owning_ref(reg->type))
13306 				meta->arg_owning_ref = true;
13307 
13308 			rec = reg_btf_record(reg);
13309 			if (!rec) {
13310 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
13311 				return -EFAULT;
13312 			}
13313 
13314 			if (rec->refcount_off < 0) {
13315 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
13316 				return -EINVAL;
13317 			}
13318 
13319 			meta->arg_btf = reg->btf;
13320 			meta->arg_btf_id = reg->btf_id;
13321 			break;
13322 		case KF_ARG_PTR_TO_CONST_STR:
13323 			if (reg->type != PTR_TO_MAP_VALUE) {
13324 				verbose(env, "arg#%d doesn't point to a const string\n", i);
13325 				return -EINVAL;
13326 			}
13327 			ret = check_reg_const_str(env, reg, regno);
13328 			if (ret)
13329 				return ret;
13330 			break;
13331 		case KF_ARG_PTR_TO_WORKQUEUE:
13332 			if (reg->type != PTR_TO_MAP_VALUE) {
13333 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13334 				return -EINVAL;
13335 			}
13336 			ret = process_wq_func(env, regno, meta);
13337 			if (ret < 0)
13338 				return ret;
13339 			break;
13340 		case KF_ARG_PTR_TO_IRQ_FLAG:
13341 			if (reg->type != PTR_TO_STACK) {
13342 				verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i);
13343 				return -EINVAL;
13344 			}
13345 			ret = process_irq_flag(env, regno, meta);
13346 			if (ret < 0)
13347 				return ret;
13348 			break;
13349 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13350 		{
13351 			int flags = PROCESS_RES_LOCK;
13352 
13353 			if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13354 				verbose(env, "arg#%d doesn't point to map value or allocated object\n", i);
13355 				return -EINVAL;
13356 			}
13357 
13358 			if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
13359 				return -EFAULT;
13360 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13361 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
13362 				flags |= PROCESS_SPIN_LOCK;
13363 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
13364 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
13365 				flags |= PROCESS_LOCK_IRQ;
13366 			ret = process_spin_lock(env, regno, flags);
13367 			if (ret < 0)
13368 				return ret;
13369 			break;
13370 		}
13371 		}
13372 	}
13373 
13374 	if (is_kfunc_release(meta) && !meta->release_regno) {
13375 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
13376 			func_name);
13377 		return -EINVAL;
13378 	}
13379 
13380 	return 0;
13381 }
13382 
13383 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
13384 			    struct bpf_insn *insn,
13385 			    struct bpf_kfunc_call_arg_meta *meta,
13386 			    const char **kfunc_name)
13387 {
13388 	const struct btf_type *func, *func_proto;
13389 	u32 func_id, *kfunc_flags;
13390 	const char *func_name;
13391 	struct btf *desc_btf;
13392 
13393 	if (kfunc_name)
13394 		*kfunc_name = NULL;
13395 
13396 	if (!insn->imm)
13397 		return -EINVAL;
13398 
13399 	desc_btf = find_kfunc_desc_btf(env, insn->off);
13400 	if (IS_ERR(desc_btf))
13401 		return PTR_ERR(desc_btf);
13402 
13403 	func_id = insn->imm;
13404 	func = btf_type_by_id(desc_btf, func_id);
13405 	func_name = btf_name_by_offset(desc_btf, func->name_off);
13406 	if (kfunc_name)
13407 		*kfunc_name = func_name;
13408 	func_proto = btf_type_by_id(desc_btf, func->type);
13409 
13410 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
13411 	if (!kfunc_flags) {
13412 		return -EACCES;
13413 	}
13414 
13415 	memset(meta, 0, sizeof(*meta));
13416 	meta->btf = desc_btf;
13417 	meta->func_id = func_id;
13418 	meta->kfunc_flags = *kfunc_flags;
13419 	meta->func_proto = func_proto;
13420 	meta->func_name = func_name;
13421 
13422 	return 0;
13423 }
13424 
13425 /* check special kfuncs and return:
13426  *  1  - not fall-through to 'else' branch, continue verification
13427  *  0  - fall-through to 'else' branch
13428  * < 0 - not fall-through to 'else' branch, return error
13429  */
13430 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13431 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
13432 			       const struct btf_type *ptr_type, struct btf *desc_btf)
13433 {
13434 	const struct btf_type *ret_t;
13435 	int err = 0;
13436 
13437 	if (meta->btf != btf_vmlinux)
13438 		return 0;
13439 
13440 	if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
13441 	    meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13442 		struct btf_struct_meta *struct_meta;
13443 		struct btf *ret_btf;
13444 		u32 ret_btf_id;
13445 
13446 		if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
13447 			return -ENOMEM;
13448 
13449 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
13450 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13451 			return -EINVAL;
13452 		}
13453 
13454 		ret_btf = env->prog->aux->btf;
13455 		ret_btf_id = meta->arg_constant.value;
13456 
13457 		/* This may be NULL due to user not supplying a BTF */
13458 		if (!ret_btf) {
13459 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13460 			return -EINVAL;
13461 		}
13462 
13463 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13464 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
13465 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13466 			return -EINVAL;
13467 		}
13468 
13469 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13470 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13471 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13472 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13473 				return -EINVAL;
13474 			}
13475 
13476 			if (!bpf_global_percpu_ma_set) {
13477 				mutex_lock(&bpf_percpu_ma_lock);
13478 				if (!bpf_global_percpu_ma_set) {
13479 					/* Charge memory allocated with bpf_global_percpu_ma to
13480 					 * root memcg. The obj_cgroup for root memcg is NULL.
13481 					 */
13482 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13483 					if (!err)
13484 						bpf_global_percpu_ma_set = true;
13485 				}
13486 				mutex_unlock(&bpf_percpu_ma_lock);
13487 				if (err)
13488 					return err;
13489 			}
13490 
13491 			mutex_lock(&bpf_percpu_ma_lock);
13492 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13493 			mutex_unlock(&bpf_percpu_ma_lock);
13494 			if (err)
13495 				return err;
13496 		}
13497 
13498 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13499 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13500 			if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13501 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13502 				return -EINVAL;
13503 			}
13504 
13505 			if (struct_meta) {
13506 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13507 				return -EINVAL;
13508 			}
13509 		}
13510 
13511 		mark_reg_known_zero(env, regs, BPF_REG_0);
13512 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13513 		regs[BPF_REG_0].btf = ret_btf;
13514 		regs[BPF_REG_0].btf_id = ret_btf_id;
13515 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
13516 			regs[BPF_REG_0].type |= MEM_PERCPU;
13517 
13518 		insn_aux->obj_new_size = ret_t->size;
13519 		insn_aux->kptr_struct_meta = struct_meta;
13520 	} else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
13521 		mark_reg_known_zero(env, regs, BPF_REG_0);
13522 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13523 		regs[BPF_REG_0].btf = meta->arg_btf;
13524 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
13525 
13526 		insn_aux->kptr_struct_meta =
13527 			btf_find_struct_meta(meta->arg_btf,
13528 					     meta->arg_btf_id);
13529 	} else if (is_list_node_type(ptr_type)) {
13530 		struct btf_field *field = meta->arg_list_head.field;
13531 
13532 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13533 	} else if (is_rbtree_node_type(ptr_type)) {
13534 		struct btf_field *field = meta->arg_rbtree_root.field;
13535 
13536 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13537 	} else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13538 		mark_reg_known_zero(env, regs, BPF_REG_0);
13539 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13540 		regs[BPF_REG_0].btf = desc_btf;
13541 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
13542 	} else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
13543 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
13544 		if (!ret_t || !btf_type_is_struct(ret_t)) {
13545 			verbose(env,
13546 				"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
13547 			return -EINVAL;
13548 		}
13549 
13550 		mark_reg_known_zero(env, regs, BPF_REG_0);
13551 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13552 		regs[BPF_REG_0].btf = desc_btf;
13553 		regs[BPF_REG_0].btf_id = meta->arg_constant.value;
13554 	} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13555 		   meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13556 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type);
13557 
13558 		mark_reg_known_zero(env, regs, BPF_REG_0);
13559 
13560 		if (!meta->arg_constant.found) {
13561 			verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
13562 			return -EFAULT;
13563 		}
13564 
13565 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
13566 
13567 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
13568 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
13569 
13570 		if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
13571 			regs[BPF_REG_0].type |= MEM_RDONLY;
13572 		} else {
13573 			/* this will set env->seen_direct_write to true */
13574 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
13575 				verbose(env, "the prog does not allow writes to packet data\n");
13576 				return -EINVAL;
13577 			}
13578 		}
13579 
13580 		if (!meta->initialized_dynptr.id) {
13581 			verbose(env, "verifier internal error: no dynptr id\n");
13582 			return -EFAULT;
13583 		}
13584 		regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id;
13585 
13586 		/* we don't need to set BPF_REG_0's ref obj id
13587 		 * because packet slices are not refcounted (see
13588 		 * dynptr_type_refcounted)
13589 		 */
13590 	} else {
13591 		return 0;
13592 	}
13593 
13594 	return 1;
13595 }
13596 
13597 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
13598 
13599 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
13600 			    int *insn_idx_p)
13601 {
13602 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
13603 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
13604 	struct bpf_reg_state *regs = cur_regs(env);
13605 	const char *func_name, *ptr_type_name;
13606 	const struct btf_type *t, *ptr_type;
13607 	struct bpf_kfunc_call_arg_meta meta;
13608 	struct bpf_insn_aux_data *insn_aux;
13609 	int err, insn_idx = *insn_idx_p;
13610 	const struct btf_param *args;
13611 	struct btf *desc_btf;
13612 
13613 	/* skip for now, but return error when we find this in fixup_kfunc_call */
13614 	if (!insn->imm)
13615 		return 0;
13616 
13617 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
13618 	if (err == -EACCES && func_name)
13619 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
13620 	if (err)
13621 		return err;
13622 	desc_btf = meta.btf;
13623 	insn_aux = &env->insn_aux_data[insn_idx];
13624 
13625 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
13626 
13627 	if (!insn->off &&
13628 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
13629 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
13630 		struct bpf_verifier_state *branch;
13631 		struct bpf_reg_state *regs;
13632 
13633 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13634 		if (!branch) {
13635 			verbose(env, "failed to push state for failed lock acquisition\n");
13636 			return -ENOMEM;
13637 		}
13638 
13639 		regs = branch->frame[branch->curframe]->regs;
13640 
13641 		/* Clear r0-r5 registers in forked state */
13642 		for (i = 0; i < CALLER_SAVED_REGS; i++)
13643 			mark_reg_not_init(env, regs, caller_saved[i]);
13644 
13645 		mark_reg_unknown(env, regs, BPF_REG_0);
13646 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
13647 		if (err) {
13648 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
13649 			return err;
13650 		}
13651 		__mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32));
13652 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
13653 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
13654 		return -EFAULT;
13655 	}
13656 
13657 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
13658 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
13659 		return -EACCES;
13660 	}
13661 
13662 	sleepable = is_kfunc_sleepable(&meta);
13663 	if (sleepable && !in_sleepable(env)) {
13664 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
13665 		return -EACCES;
13666 	}
13667 
13668 	/* Check the arguments */
13669 	err = check_kfunc_args(env, &meta, insn_idx);
13670 	if (err < 0)
13671 		return err;
13672 
13673 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13674 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13675 					 set_rbtree_add_callback_state);
13676 		if (err) {
13677 			verbose(env, "kfunc %s#%d failed callback verification\n",
13678 				func_name, meta.func_id);
13679 			return err;
13680 		}
13681 	}
13682 
13683 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
13684 		meta.r0_size = sizeof(u64);
13685 		meta.r0_rdonly = false;
13686 	}
13687 
13688 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
13689 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13690 					 set_timer_callback_state);
13691 		if (err) {
13692 			verbose(env, "kfunc %s#%d failed callback verification\n",
13693 				func_name, meta.func_id);
13694 			return err;
13695 		}
13696 	}
13697 
13698 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
13699 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
13700 
13701 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
13702 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
13703 
13704 	if (env->cur_state->active_rcu_lock) {
13705 		struct bpf_func_state *state;
13706 		struct bpf_reg_state *reg;
13707 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
13708 
13709 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
13710 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
13711 			return -EACCES;
13712 		}
13713 
13714 		if (rcu_lock) {
13715 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
13716 			return -EINVAL;
13717 		} else if (rcu_unlock) {
13718 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
13719 				if (reg->type & MEM_RCU) {
13720 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
13721 					reg->type |= PTR_UNTRUSTED;
13722 				}
13723 			}));
13724 			env->cur_state->active_rcu_lock = false;
13725 		} else if (sleepable) {
13726 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
13727 			return -EACCES;
13728 		}
13729 	} else if (rcu_lock) {
13730 		env->cur_state->active_rcu_lock = true;
13731 	} else if (rcu_unlock) {
13732 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
13733 		return -EINVAL;
13734 	}
13735 
13736 	if (env->cur_state->active_preempt_locks) {
13737 		if (preempt_disable) {
13738 			env->cur_state->active_preempt_locks++;
13739 		} else if (preempt_enable) {
13740 			env->cur_state->active_preempt_locks--;
13741 		} else if (sleepable) {
13742 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
13743 			return -EACCES;
13744 		}
13745 	} else if (preempt_disable) {
13746 		env->cur_state->active_preempt_locks++;
13747 	} else if (preempt_enable) {
13748 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
13749 		return -EINVAL;
13750 	}
13751 
13752 	if (env->cur_state->active_irq_id && sleepable) {
13753 		verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name);
13754 		return -EACCES;
13755 	}
13756 
13757 	/* In case of release function, we get register number of refcounted
13758 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
13759 	 */
13760 	if (meta.release_regno) {
13761 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
13762 		if (err) {
13763 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13764 				func_name, meta.func_id);
13765 			return err;
13766 		}
13767 	}
13768 
13769 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
13770 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
13771 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13772 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
13773 		insn_aux->insert_off = regs[BPF_REG_2].off;
13774 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
13775 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
13776 		if (err) {
13777 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
13778 				func_name, meta.func_id);
13779 			return err;
13780 		}
13781 
13782 		err = release_reference(env, release_ref_obj_id);
13783 		if (err) {
13784 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13785 				func_name, meta.func_id);
13786 			return err;
13787 		}
13788 	}
13789 
13790 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
13791 		if (!bpf_jit_supports_exceptions()) {
13792 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
13793 				func_name, meta.func_id);
13794 			return -ENOTSUPP;
13795 		}
13796 		env->seen_exception = true;
13797 
13798 		/* In the case of the default callback, the cookie value passed
13799 		 * to bpf_throw becomes the return value of the program.
13800 		 */
13801 		if (!env->exception_callback_subprog) {
13802 			err = check_return_code(env, BPF_REG_1, "R1");
13803 			if (err < 0)
13804 				return err;
13805 		}
13806 	}
13807 
13808 	for (i = 0; i < CALLER_SAVED_REGS; i++)
13809 		mark_reg_not_init(env, regs, caller_saved[i]);
13810 
13811 	/* Check return type */
13812 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
13813 
13814 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
13815 		/* Only exception is bpf_obj_new_impl */
13816 		if (meta.btf != btf_vmlinux ||
13817 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
13818 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
13819 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
13820 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
13821 			return -EINVAL;
13822 		}
13823 	}
13824 
13825 	if (btf_type_is_scalar(t)) {
13826 		mark_reg_unknown(env, regs, BPF_REG_0);
13827 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13828 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
13829 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
13830 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
13831 	} else if (btf_type_is_ptr(t)) {
13832 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
13833 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
13834 		if (err) {
13835 			if (err < 0)
13836 				return err;
13837 		} else if (btf_type_is_void(ptr_type)) {
13838 			/* kfunc returning 'void *' is equivalent to returning scalar */
13839 			mark_reg_unknown(env, regs, BPF_REG_0);
13840 		} else if (!__btf_type_is_struct(ptr_type)) {
13841 			if (!meta.r0_size) {
13842 				__u32 sz;
13843 
13844 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
13845 					meta.r0_size = sz;
13846 					meta.r0_rdonly = true;
13847 				}
13848 			}
13849 			if (!meta.r0_size) {
13850 				ptr_type_name = btf_name_by_offset(desc_btf,
13851 								   ptr_type->name_off);
13852 				verbose(env,
13853 					"kernel function %s returns pointer type %s %s is not supported\n",
13854 					func_name,
13855 					btf_type_str(ptr_type),
13856 					ptr_type_name);
13857 				return -EINVAL;
13858 			}
13859 
13860 			mark_reg_known_zero(env, regs, BPF_REG_0);
13861 			regs[BPF_REG_0].type = PTR_TO_MEM;
13862 			regs[BPF_REG_0].mem_size = meta.r0_size;
13863 
13864 			if (meta.r0_rdonly)
13865 				regs[BPF_REG_0].type |= MEM_RDONLY;
13866 
13867 			/* Ensures we don't access the memory after a release_reference() */
13868 			if (meta.ref_obj_id)
13869 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
13870 		} else {
13871 			mark_reg_known_zero(env, regs, BPF_REG_0);
13872 			regs[BPF_REG_0].btf = desc_btf;
13873 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
13874 			regs[BPF_REG_0].btf_id = ptr_type_id;
13875 
13876 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
13877 				regs[BPF_REG_0].type |= PTR_UNTRUSTED;
13878 
13879 			if (is_iter_next_kfunc(&meta)) {
13880 				struct bpf_reg_state *cur_iter;
13881 
13882 				cur_iter = get_iter_from_state(env->cur_state, &meta);
13883 
13884 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
13885 					regs[BPF_REG_0].type |= MEM_RCU;
13886 				else
13887 					regs[BPF_REG_0].type |= PTR_TRUSTED;
13888 			}
13889 		}
13890 
13891 		if (is_kfunc_ret_null(&meta)) {
13892 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
13893 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
13894 			regs[BPF_REG_0].id = ++env->id_gen;
13895 		}
13896 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
13897 		if (is_kfunc_acquire(&meta)) {
13898 			int id = acquire_reference(env, insn_idx);
13899 
13900 			if (id < 0)
13901 				return id;
13902 			if (is_kfunc_ret_null(&meta))
13903 				regs[BPF_REG_0].id = id;
13904 			regs[BPF_REG_0].ref_obj_id = id;
13905 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
13906 			ref_set_non_owning(env, &regs[BPF_REG_0]);
13907 		}
13908 
13909 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
13910 			regs[BPF_REG_0].id = ++env->id_gen;
13911 	} else if (btf_type_is_void(t)) {
13912 		if (meta.btf == btf_vmlinux) {
13913 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
13914 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13915 				insn_aux->kptr_struct_meta =
13916 					btf_find_struct_meta(meta.arg_btf,
13917 							     meta.arg_btf_id);
13918 			}
13919 		}
13920 	}
13921 
13922 	nargs = btf_type_vlen(meta.func_proto);
13923 	args = (const struct btf_param *)(meta.func_proto + 1);
13924 	for (i = 0; i < nargs; i++) {
13925 		u32 regno = i + 1;
13926 
13927 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
13928 		if (btf_type_is_ptr(t))
13929 			mark_btf_func_reg_size(env, regno, sizeof(void *));
13930 		else
13931 			/* scalar. ensured by btf_check_kfunc_arg_match() */
13932 			mark_btf_func_reg_size(env, regno, t->size);
13933 	}
13934 
13935 	if (is_iter_next_kfunc(&meta)) {
13936 		err = process_iter_next_call(env, insn_idx, &meta);
13937 		if (err)
13938 			return err;
13939 	}
13940 
13941 	return 0;
13942 }
13943 
13944 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
13945 				  const struct bpf_reg_state *reg,
13946 				  enum bpf_reg_type type)
13947 {
13948 	bool known = tnum_is_const(reg->var_off);
13949 	s64 val = reg->var_off.value;
13950 	s64 smin = reg->smin_value;
13951 
13952 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
13953 		verbose(env, "math between %s pointer and %lld is not allowed\n",
13954 			reg_type_str(env, type), val);
13955 		return false;
13956 	}
13957 
13958 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
13959 		verbose(env, "%s pointer offset %d is not allowed\n",
13960 			reg_type_str(env, type), reg->off);
13961 		return false;
13962 	}
13963 
13964 	if (smin == S64_MIN) {
13965 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
13966 			reg_type_str(env, type));
13967 		return false;
13968 	}
13969 
13970 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
13971 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
13972 			smin, reg_type_str(env, type));
13973 		return false;
13974 	}
13975 
13976 	return true;
13977 }
13978 
13979 enum {
13980 	REASON_BOUNDS	= -1,
13981 	REASON_TYPE	= -2,
13982 	REASON_PATHS	= -3,
13983 	REASON_LIMIT	= -4,
13984 	REASON_STACK	= -5,
13985 };
13986 
13987 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
13988 			      u32 *alu_limit, bool mask_to_left)
13989 {
13990 	u32 max = 0, ptr_limit = 0;
13991 
13992 	switch (ptr_reg->type) {
13993 	case PTR_TO_STACK:
13994 		/* Offset 0 is out-of-bounds, but acceptable start for the
13995 		 * left direction, see BPF_REG_FP. Also, unknown scalar
13996 		 * offset where we would need to deal with min/max bounds is
13997 		 * currently prohibited for unprivileged.
13998 		 */
13999 		max = MAX_BPF_STACK + mask_to_left;
14000 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
14001 		break;
14002 	case PTR_TO_MAP_VALUE:
14003 		max = ptr_reg->map_ptr->value_size;
14004 		ptr_limit = (mask_to_left ?
14005 			     ptr_reg->smin_value :
14006 			     ptr_reg->umax_value) + ptr_reg->off;
14007 		break;
14008 	default:
14009 		return REASON_TYPE;
14010 	}
14011 
14012 	if (ptr_limit >= max)
14013 		return REASON_LIMIT;
14014 	*alu_limit = ptr_limit;
14015 	return 0;
14016 }
14017 
14018 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
14019 				    const struct bpf_insn *insn)
14020 {
14021 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
14022 }
14023 
14024 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
14025 				       u32 alu_state, u32 alu_limit)
14026 {
14027 	/* If we arrived here from different branches with different
14028 	 * state or limits to sanitize, then this won't work.
14029 	 */
14030 	if (aux->alu_state &&
14031 	    (aux->alu_state != alu_state ||
14032 	     aux->alu_limit != alu_limit))
14033 		return REASON_PATHS;
14034 
14035 	/* Corresponding fixup done in do_misc_fixups(). */
14036 	aux->alu_state = alu_state;
14037 	aux->alu_limit = alu_limit;
14038 	return 0;
14039 }
14040 
14041 static int sanitize_val_alu(struct bpf_verifier_env *env,
14042 			    struct bpf_insn *insn)
14043 {
14044 	struct bpf_insn_aux_data *aux = cur_aux(env);
14045 
14046 	if (can_skip_alu_sanitation(env, insn))
14047 		return 0;
14048 
14049 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
14050 }
14051 
14052 static bool sanitize_needed(u8 opcode)
14053 {
14054 	return opcode == BPF_ADD || opcode == BPF_SUB;
14055 }
14056 
14057 struct bpf_sanitize_info {
14058 	struct bpf_insn_aux_data aux;
14059 	bool mask_to_left;
14060 };
14061 
14062 static struct bpf_verifier_state *
14063 sanitize_speculative_path(struct bpf_verifier_env *env,
14064 			  const struct bpf_insn *insn,
14065 			  u32 next_idx, u32 curr_idx)
14066 {
14067 	struct bpf_verifier_state *branch;
14068 	struct bpf_reg_state *regs;
14069 
14070 	branch = push_stack(env, next_idx, curr_idx, true);
14071 	if (branch && insn) {
14072 		regs = branch->frame[branch->curframe]->regs;
14073 		if (BPF_SRC(insn->code) == BPF_K) {
14074 			mark_reg_unknown(env, regs, insn->dst_reg);
14075 		} else if (BPF_SRC(insn->code) == BPF_X) {
14076 			mark_reg_unknown(env, regs, insn->dst_reg);
14077 			mark_reg_unknown(env, regs, insn->src_reg);
14078 		}
14079 	}
14080 	return branch;
14081 }
14082 
14083 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
14084 			    struct bpf_insn *insn,
14085 			    const struct bpf_reg_state *ptr_reg,
14086 			    const struct bpf_reg_state *off_reg,
14087 			    struct bpf_reg_state *dst_reg,
14088 			    struct bpf_sanitize_info *info,
14089 			    const bool commit_window)
14090 {
14091 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
14092 	struct bpf_verifier_state *vstate = env->cur_state;
14093 	bool off_is_imm = tnum_is_const(off_reg->var_off);
14094 	bool off_is_neg = off_reg->smin_value < 0;
14095 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
14096 	u8 opcode = BPF_OP(insn->code);
14097 	u32 alu_state, alu_limit;
14098 	struct bpf_reg_state tmp;
14099 	bool ret;
14100 	int err;
14101 
14102 	if (can_skip_alu_sanitation(env, insn))
14103 		return 0;
14104 
14105 	/* We already marked aux for masking from non-speculative
14106 	 * paths, thus we got here in the first place. We only care
14107 	 * to explore bad access from here.
14108 	 */
14109 	if (vstate->speculative)
14110 		goto do_sim;
14111 
14112 	if (!commit_window) {
14113 		if (!tnum_is_const(off_reg->var_off) &&
14114 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
14115 			return REASON_BOUNDS;
14116 
14117 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
14118 				     (opcode == BPF_SUB && !off_is_neg);
14119 	}
14120 
14121 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
14122 	if (err < 0)
14123 		return err;
14124 
14125 	if (commit_window) {
14126 		/* In commit phase we narrow the masking window based on
14127 		 * the observed pointer move after the simulated operation.
14128 		 */
14129 		alu_state = info->aux.alu_state;
14130 		alu_limit = abs(info->aux.alu_limit - alu_limit);
14131 	} else {
14132 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
14133 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
14134 		alu_state |= ptr_is_dst_reg ?
14135 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
14136 
14137 		/* Limit pruning on unknown scalars to enable deep search for
14138 		 * potential masking differences from other program paths.
14139 		 */
14140 		if (!off_is_imm)
14141 			env->explore_alu_limits = true;
14142 	}
14143 
14144 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
14145 	if (err < 0)
14146 		return err;
14147 do_sim:
14148 	/* If we're in commit phase, we're done here given we already
14149 	 * pushed the truncated dst_reg into the speculative verification
14150 	 * stack.
14151 	 *
14152 	 * Also, when register is a known constant, we rewrite register-based
14153 	 * operation to immediate-based, and thus do not need masking (and as
14154 	 * a consequence, do not need to simulate the zero-truncation either).
14155 	 */
14156 	if (commit_window || off_is_imm)
14157 		return 0;
14158 
14159 	/* Simulate and find potential out-of-bounds access under
14160 	 * speculative execution from truncation as a result of
14161 	 * masking when off was not within expected range. If off
14162 	 * sits in dst, then we temporarily need to move ptr there
14163 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
14164 	 * for cases where we use K-based arithmetic in one direction
14165 	 * and truncated reg-based in the other in order to explore
14166 	 * bad access.
14167 	 */
14168 	if (!ptr_is_dst_reg) {
14169 		tmp = *dst_reg;
14170 		copy_register_state(dst_reg, ptr_reg);
14171 	}
14172 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
14173 					env->insn_idx);
14174 	if (!ptr_is_dst_reg && ret)
14175 		*dst_reg = tmp;
14176 	return !ret ? REASON_STACK : 0;
14177 }
14178 
14179 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
14180 {
14181 	struct bpf_verifier_state *vstate = env->cur_state;
14182 
14183 	/* If we simulate paths under speculation, we don't update the
14184 	 * insn as 'seen' such that when we verify unreachable paths in
14185 	 * the non-speculative domain, sanitize_dead_code() can still
14186 	 * rewrite/sanitize them.
14187 	 */
14188 	if (!vstate->speculative)
14189 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
14190 }
14191 
14192 static int sanitize_err(struct bpf_verifier_env *env,
14193 			const struct bpf_insn *insn, int reason,
14194 			const struct bpf_reg_state *off_reg,
14195 			const struct bpf_reg_state *dst_reg)
14196 {
14197 	static const char *err = "pointer arithmetic with it prohibited for !root";
14198 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
14199 	u32 dst = insn->dst_reg, src = insn->src_reg;
14200 
14201 	switch (reason) {
14202 	case REASON_BOUNDS:
14203 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
14204 			off_reg == dst_reg ? dst : src, err);
14205 		break;
14206 	case REASON_TYPE:
14207 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
14208 			off_reg == dst_reg ? src : dst, err);
14209 		break;
14210 	case REASON_PATHS:
14211 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
14212 			dst, op, err);
14213 		break;
14214 	case REASON_LIMIT:
14215 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
14216 			dst, op, err);
14217 		break;
14218 	case REASON_STACK:
14219 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
14220 			dst, err);
14221 		break;
14222 	default:
14223 		verbose(env, "verifier internal error: unknown reason (%d)\n",
14224 			reason);
14225 		break;
14226 	}
14227 
14228 	return -EACCES;
14229 }
14230 
14231 /* check that stack access falls within stack limits and that 'reg' doesn't
14232  * have a variable offset.
14233  *
14234  * Variable offset is prohibited for unprivileged mode for simplicity since it
14235  * requires corresponding support in Spectre masking for stack ALU.  See also
14236  * retrieve_ptr_limit().
14237  *
14238  *
14239  * 'off' includes 'reg->off'.
14240  */
14241 static int check_stack_access_for_ptr_arithmetic(
14242 				struct bpf_verifier_env *env,
14243 				int regno,
14244 				const struct bpf_reg_state *reg,
14245 				int off)
14246 {
14247 	if (!tnum_is_const(reg->var_off)) {
14248 		char tn_buf[48];
14249 
14250 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
14251 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
14252 			regno, tn_buf, off);
14253 		return -EACCES;
14254 	}
14255 
14256 	if (off >= 0 || off < -MAX_BPF_STACK) {
14257 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
14258 			"prohibited for !root; off=%d\n", regno, off);
14259 		return -EACCES;
14260 	}
14261 
14262 	return 0;
14263 }
14264 
14265 static int sanitize_check_bounds(struct bpf_verifier_env *env,
14266 				 const struct bpf_insn *insn,
14267 				 const struct bpf_reg_state *dst_reg)
14268 {
14269 	u32 dst = insn->dst_reg;
14270 
14271 	/* For unprivileged we require that resulting offset must be in bounds
14272 	 * in order to be able to sanitize access later on.
14273 	 */
14274 	if (env->bypass_spec_v1)
14275 		return 0;
14276 
14277 	switch (dst_reg->type) {
14278 	case PTR_TO_STACK:
14279 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
14280 					dst_reg->off + dst_reg->var_off.value))
14281 			return -EACCES;
14282 		break;
14283 	case PTR_TO_MAP_VALUE:
14284 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
14285 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
14286 				"prohibited for !root\n", dst);
14287 			return -EACCES;
14288 		}
14289 		break;
14290 	default:
14291 		break;
14292 	}
14293 
14294 	return 0;
14295 }
14296 
14297 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
14298  * Caller should also handle BPF_MOV case separately.
14299  * If we return -EACCES, caller may want to try again treating pointer as a
14300  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
14301  */
14302 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
14303 				   struct bpf_insn *insn,
14304 				   const struct bpf_reg_state *ptr_reg,
14305 				   const struct bpf_reg_state *off_reg)
14306 {
14307 	struct bpf_verifier_state *vstate = env->cur_state;
14308 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14309 	struct bpf_reg_state *regs = state->regs, *dst_reg;
14310 	bool known = tnum_is_const(off_reg->var_off);
14311 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
14312 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
14313 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
14314 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
14315 	struct bpf_sanitize_info info = {};
14316 	u8 opcode = BPF_OP(insn->code);
14317 	u32 dst = insn->dst_reg;
14318 	int ret;
14319 
14320 	dst_reg = &regs[dst];
14321 
14322 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
14323 	    smin_val > smax_val || umin_val > umax_val) {
14324 		/* Taint dst register if offset had invalid bounds derived from
14325 		 * e.g. dead branches.
14326 		 */
14327 		__mark_reg_unknown(env, dst_reg);
14328 		return 0;
14329 	}
14330 
14331 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
14332 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
14333 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14334 			__mark_reg_unknown(env, dst_reg);
14335 			return 0;
14336 		}
14337 
14338 		verbose(env,
14339 			"R%d 32-bit pointer arithmetic prohibited\n",
14340 			dst);
14341 		return -EACCES;
14342 	}
14343 
14344 	if (ptr_reg->type & PTR_MAYBE_NULL) {
14345 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
14346 			dst, reg_type_str(env, ptr_reg->type));
14347 		return -EACCES;
14348 	}
14349 
14350 	switch (base_type(ptr_reg->type)) {
14351 	case PTR_TO_CTX:
14352 	case PTR_TO_MAP_VALUE:
14353 	case PTR_TO_MAP_KEY:
14354 	case PTR_TO_STACK:
14355 	case PTR_TO_PACKET_META:
14356 	case PTR_TO_PACKET:
14357 	case PTR_TO_TP_BUFFER:
14358 	case PTR_TO_BTF_ID:
14359 	case PTR_TO_MEM:
14360 	case PTR_TO_BUF:
14361 	case PTR_TO_FUNC:
14362 	case CONST_PTR_TO_DYNPTR:
14363 		break;
14364 	case PTR_TO_FLOW_KEYS:
14365 		if (known)
14366 			break;
14367 		fallthrough;
14368 	case CONST_PTR_TO_MAP:
14369 		/* smin_val represents the known value */
14370 		if (known && smin_val == 0 && opcode == BPF_ADD)
14371 			break;
14372 		fallthrough;
14373 	default:
14374 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
14375 			dst, reg_type_str(env, ptr_reg->type));
14376 		return -EACCES;
14377 	}
14378 
14379 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
14380 	 * The id may be overwritten later if we create a new variable offset.
14381 	 */
14382 	dst_reg->type = ptr_reg->type;
14383 	dst_reg->id = ptr_reg->id;
14384 
14385 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
14386 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
14387 		return -EINVAL;
14388 
14389 	/* pointer types do not carry 32-bit bounds at the moment. */
14390 	__mark_reg32_unbounded(dst_reg);
14391 
14392 	if (sanitize_needed(opcode)) {
14393 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
14394 				       &info, false);
14395 		if (ret < 0)
14396 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14397 	}
14398 
14399 	switch (opcode) {
14400 	case BPF_ADD:
14401 		/* We can take a fixed offset as long as it doesn't overflow
14402 		 * the s32 'off' field
14403 		 */
14404 		if (known && (ptr_reg->off + smin_val ==
14405 			      (s64)(s32)(ptr_reg->off + smin_val))) {
14406 			/* pointer += K.  Accumulate it into fixed offset */
14407 			dst_reg->smin_value = smin_ptr;
14408 			dst_reg->smax_value = smax_ptr;
14409 			dst_reg->umin_value = umin_ptr;
14410 			dst_reg->umax_value = umax_ptr;
14411 			dst_reg->var_off = ptr_reg->var_off;
14412 			dst_reg->off = ptr_reg->off + smin_val;
14413 			dst_reg->raw = ptr_reg->raw;
14414 			break;
14415 		}
14416 		/* A new variable offset is created.  Note that off_reg->off
14417 		 * == 0, since it's a scalar.
14418 		 * dst_reg gets the pointer type and since some positive
14419 		 * integer value was added to the pointer, give it a new 'id'
14420 		 * if it's a PTR_TO_PACKET.
14421 		 * this creates a new 'base' pointer, off_reg (variable) gets
14422 		 * added into the variable offset, and we copy the fixed offset
14423 		 * from ptr_reg.
14424 		 */
14425 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
14426 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
14427 			dst_reg->smin_value = S64_MIN;
14428 			dst_reg->smax_value = S64_MAX;
14429 		}
14430 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
14431 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
14432 			dst_reg->umin_value = 0;
14433 			dst_reg->umax_value = U64_MAX;
14434 		}
14435 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
14436 		dst_reg->off = ptr_reg->off;
14437 		dst_reg->raw = ptr_reg->raw;
14438 		if (reg_is_pkt_pointer(ptr_reg)) {
14439 			dst_reg->id = ++env->id_gen;
14440 			/* something was added to pkt_ptr, set range to zero */
14441 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14442 		}
14443 		break;
14444 	case BPF_SUB:
14445 		if (dst_reg == off_reg) {
14446 			/* scalar -= pointer.  Creates an unknown scalar */
14447 			verbose(env, "R%d tried to subtract pointer from scalar\n",
14448 				dst);
14449 			return -EACCES;
14450 		}
14451 		/* We don't allow subtraction from FP, because (according to
14452 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
14453 		 * be able to deal with it.
14454 		 */
14455 		if (ptr_reg->type == PTR_TO_STACK) {
14456 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
14457 				dst);
14458 			return -EACCES;
14459 		}
14460 		if (known && (ptr_reg->off - smin_val ==
14461 			      (s64)(s32)(ptr_reg->off - smin_val))) {
14462 			/* pointer -= K.  Subtract it from fixed offset */
14463 			dst_reg->smin_value = smin_ptr;
14464 			dst_reg->smax_value = smax_ptr;
14465 			dst_reg->umin_value = umin_ptr;
14466 			dst_reg->umax_value = umax_ptr;
14467 			dst_reg->var_off = ptr_reg->var_off;
14468 			dst_reg->id = ptr_reg->id;
14469 			dst_reg->off = ptr_reg->off - smin_val;
14470 			dst_reg->raw = ptr_reg->raw;
14471 			break;
14472 		}
14473 		/* A new variable offset is created.  If the subtrahend is known
14474 		 * nonnegative, then any reg->range we had before is still good.
14475 		 */
14476 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
14477 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
14478 			/* Overflow possible, we know nothing */
14479 			dst_reg->smin_value = S64_MIN;
14480 			dst_reg->smax_value = S64_MAX;
14481 		}
14482 		if (umin_ptr < umax_val) {
14483 			/* Overflow possible, we know nothing */
14484 			dst_reg->umin_value = 0;
14485 			dst_reg->umax_value = U64_MAX;
14486 		} else {
14487 			/* Cannot overflow (as long as bounds are consistent) */
14488 			dst_reg->umin_value = umin_ptr - umax_val;
14489 			dst_reg->umax_value = umax_ptr - umin_val;
14490 		}
14491 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
14492 		dst_reg->off = ptr_reg->off;
14493 		dst_reg->raw = ptr_reg->raw;
14494 		if (reg_is_pkt_pointer(ptr_reg)) {
14495 			dst_reg->id = ++env->id_gen;
14496 			/* something was added to pkt_ptr, set range to zero */
14497 			if (smin_val < 0)
14498 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14499 		}
14500 		break;
14501 	case BPF_AND:
14502 	case BPF_OR:
14503 	case BPF_XOR:
14504 		/* bitwise ops on pointers are troublesome, prohibit. */
14505 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
14506 			dst, bpf_alu_string[opcode >> 4]);
14507 		return -EACCES;
14508 	default:
14509 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
14510 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
14511 			dst, bpf_alu_string[opcode >> 4]);
14512 		return -EACCES;
14513 	}
14514 
14515 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
14516 		return -EINVAL;
14517 	reg_bounds_sync(dst_reg);
14518 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
14519 		return -EACCES;
14520 	if (sanitize_needed(opcode)) {
14521 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
14522 				       &info, true);
14523 		if (ret < 0)
14524 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14525 	}
14526 
14527 	return 0;
14528 }
14529 
14530 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
14531 				 struct bpf_reg_state *src_reg)
14532 {
14533 	s32 *dst_smin = &dst_reg->s32_min_value;
14534 	s32 *dst_smax = &dst_reg->s32_max_value;
14535 	u32 *dst_umin = &dst_reg->u32_min_value;
14536 	u32 *dst_umax = &dst_reg->u32_max_value;
14537 
14538 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
14539 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
14540 		*dst_smin = S32_MIN;
14541 		*dst_smax = S32_MAX;
14542 	}
14543 	if (check_add_overflow(*dst_umin, src_reg->u32_min_value, dst_umin) ||
14544 	    check_add_overflow(*dst_umax, src_reg->u32_max_value, dst_umax)) {
14545 		*dst_umin = 0;
14546 		*dst_umax = U32_MAX;
14547 	}
14548 }
14549 
14550 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
14551 			       struct bpf_reg_state *src_reg)
14552 {
14553 	s64 *dst_smin = &dst_reg->smin_value;
14554 	s64 *dst_smax = &dst_reg->smax_value;
14555 	u64 *dst_umin = &dst_reg->umin_value;
14556 	u64 *dst_umax = &dst_reg->umax_value;
14557 
14558 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
14559 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
14560 		*dst_smin = S64_MIN;
14561 		*dst_smax = S64_MAX;
14562 	}
14563 	if (check_add_overflow(*dst_umin, src_reg->umin_value, dst_umin) ||
14564 	    check_add_overflow(*dst_umax, src_reg->umax_value, dst_umax)) {
14565 		*dst_umin = 0;
14566 		*dst_umax = U64_MAX;
14567 	}
14568 }
14569 
14570 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
14571 				 struct bpf_reg_state *src_reg)
14572 {
14573 	s32 *dst_smin = &dst_reg->s32_min_value;
14574 	s32 *dst_smax = &dst_reg->s32_max_value;
14575 	u32 umin_val = src_reg->u32_min_value;
14576 	u32 umax_val = src_reg->u32_max_value;
14577 
14578 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
14579 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
14580 		/* Overflow possible, we know nothing */
14581 		*dst_smin = S32_MIN;
14582 		*dst_smax = S32_MAX;
14583 	}
14584 	if (dst_reg->u32_min_value < umax_val) {
14585 		/* Overflow possible, we know nothing */
14586 		dst_reg->u32_min_value = 0;
14587 		dst_reg->u32_max_value = U32_MAX;
14588 	} else {
14589 		/* Cannot overflow (as long as bounds are consistent) */
14590 		dst_reg->u32_min_value -= umax_val;
14591 		dst_reg->u32_max_value -= umin_val;
14592 	}
14593 }
14594 
14595 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
14596 			       struct bpf_reg_state *src_reg)
14597 {
14598 	s64 *dst_smin = &dst_reg->smin_value;
14599 	s64 *dst_smax = &dst_reg->smax_value;
14600 	u64 umin_val = src_reg->umin_value;
14601 	u64 umax_val = src_reg->umax_value;
14602 
14603 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
14604 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
14605 		/* Overflow possible, we know nothing */
14606 		*dst_smin = S64_MIN;
14607 		*dst_smax = S64_MAX;
14608 	}
14609 	if (dst_reg->umin_value < umax_val) {
14610 		/* Overflow possible, we know nothing */
14611 		dst_reg->umin_value = 0;
14612 		dst_reg->umax_value = U64_MAX;
14613 	} else {
14614 		/* Cannot overflow (as long as bounds are consistent) */
14615 		dst_reg->umin_value -= umax_val;
14616 		dst_reg->umax_value -= umin_val;
14617 	}
14618 }
14619 
14620 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
14621 				 struct bpf_reg_state *src_reg)
14622 {
14623 	s32 *dst_smin = &dst_reg->s32_min_value;
14624 	s32 *dst_smax = &dst_reg->s32_max_value;
14625 	u32 *dst_umin = &dst_reg->u32_min_value;
14626 	u32 *dst_umax = &dst_reg->u32_max_value;
14627 	s32 tmp_prod[4];
14628 
14629 	if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) ||
14630 	    check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) {
14631 		/* Overflow possible, we know nothing */
14632 		*dst_umin = 0;
14633 		*dst_umax = U32_MAX;
14634 	}
14635 	if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) ||
14636 	    check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) ||
14637 	    check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) ||
14638 	    check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) {
14639 		/* Overflow possible, we know nothing */
14640 		*dst_smin = S32_MIN;
14641 		*dst_smax = S32_MAX;
14642 	} else {
14643 		*dst_smin = min_array(tmp_prod, 4);
14644 		*dst_smax = max_array(tmp_prod, 4);
14645 	}
14646 }
14647 
14648 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
14649 			       struct bpf_reg_state *src_reg)
14650 {
14651 	s64 *dst_smin = &dst_reg->smin_value;
14652 	s64 *dst_smax = &dst_reg->smax_value;
14653 	u64 *dst_umin = &dst_reg->umin_value;
14654 	u64 *dst_umax = &dst_reg->umax_value;
14655 	s64 tmp_prod[4];
14656 
14657 	if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) ||
14658 	    check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) {
14659 		/* Overflow possible, we know nothing */
14660 		*dst_umin = 0;
14661 		*dst_umax = U64_MAX;
14662 	}
14663 	if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) ||
14664 	    check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) ||
14665 	    check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) ||
14666 	    check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) {
14667 		/* Overflow possible, we know nothing */
14668 		*dst_smin = S64_MIN;
14669 		*dst_smax = S64_MAX;
14670 	} else {
14671 		*dst_smin = min_array(tmp_prod, 4);
14672 		*dst_smax = max_array(tmp_prod, 4);
14673 	}
14674 }
14675 
14676 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
14677 				 struct bpf_reg_state *src_reg)
14678 {
14679 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14680 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14681 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14682 	u32 umax_val = src_reg->u32_max_value;
14683 
14684 	if (src_known && dst_known) {
14685 		__mark_reg32_known(dst_reg, var32_off.value);
14686 		return;
14687 	}
14688 
14689 	/* We get our minimum from the var_off, since that's inherently
14690 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14691 	 */
14692 	dst_reg->u32_min_value = var32_off.value;
14693 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
14694 
14695 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14696 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14697 	 */
14698 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14699 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14700 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14701 	} else {
14702 		dst_reg->s32_min_value = S32_MIN;
14703 		dst_reg->s32_max_value = S32_MAX;
14704 	}
14705 }
14706 
14707 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
14708 			       struct bpf_reg_state *src_reg)
14709 {
14710 	bool src_known = tnum_is_const(src_reg->var_off);
14711 	bool dst_known = tnum_is_const(dst_reg->var_off);
14712 	u64 umax_val = src_reg->umax_value;
14713 
14714 	if (src_known && dst_known) {
14715 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14716 		return;
14717 	}
14718 
14719 	/* We get our minimum from the var_off, since that's inherently
14720 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14721 	 */
14722 	dst_reg->umin_value = dst_reg->var_off.value;
14723 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
14724 
14725 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14726 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14727 	 */
14728 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
14729 		dst_reg->smin_value = dst_reg->umin_value;
14730 		dst_reg->smax_value = dst_reg->umax_value;
14731 	} else {
14732 		dst_reg->smin_value = S64_MIN;
14733 		dst_reg->smax_value = S64_MAX;
14734 	}
14735 	/* We may learn something more from the var_off */
14736 	__update_reg_bounds(dst_reg);
14737 }
14738 
14739 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
14740 				struct bpf_reg_state *src_reg)
14741 {
14742 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14743 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14744 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14745 	u32 umin_val = src_reg->u32_min_value;
14746 
14747 	if (src_known && dst_known) {
14748 		__mark_reg32_known(dst_reg, var32_off.value);
14749 		return;
14750 	}
14751 
14752 	/* We get our maximum from the var_off, and our minimum is the
14753 	 * maximum of the operands' minima
14754 	 */
14755 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
14756 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
14757 
14758 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14759 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14760 	 */
14761 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14762 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14763 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14764 	} else {
14765 		dst_reg->s32_min_value = S32_MIN;
14766 		dst_reg->s32_max_value = S32_MAX;
14767 	}
14768 }
14769 
14770 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
14771 			      struct bpf_reg_state *src_reg)
14772 {
14773 	bool src_known = tnum_is_const(src_reg->var_off);
14774 	bool dst_known = tnum_is_const(dst_reg->var_off);
14775 	u64 umin_val = src_reg->umin_value;
14776 
14777 	if (src_known && dst_known) {
14778 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14779 		return;
14780 	}
14781 
14782 	/* We get our maximum from the var_off, and our minimum is the
14783 	 * maximum of the operands' minima
14784 	 */
14785 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
14786 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
14787 
14788 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14789 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14790 	 */
14791 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
14792 		dst_reg->smin_value = dst_reg->umin_value;
14793 		dst_reg->smax_value = dst_reg->umax_value;
14794 	} else {
14795 		dst_reg->smin_value = S64_MIN;
14796 		dst_reg->smax_value = S64_MAX;
14797 	}
14798 	/* We may learn something more from the var_off */
14799 	__update_reg_bounds(dst_reg);
14800 }
14801 
14802 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
14803 				 struct bpf_reg_state *src_reg)
14804 {
14805 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14806 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14807 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14808 
14809 	if (src_known && dst_known) {
14810 		__mark_reg32_known(dst_reg, var32_off.value);
14811 		return;
14812 	}
14813 
14814 	/* We get both minimum and maximum from the var32_off. */
14815 	dst_reg->u32_min_value = var32_off.value;
14816 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
14817 
14818 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14819 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14820 	 */
14821 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14822 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14823 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14824 	} else {
14825 		dst_reg->s32_min_value = S32_MIN;
14826 		dst_reg->s32_max_value = S32_MAX;
14827 	}
14828 }
14829 
14830 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
14831 			       struct bpf_reg_state *src_reg)
14832 {
14833 	bool src_known = tnum_is_const(src_reg->var_off);
14834 	bool dst_known = tnum_is_const(dst_reg->var_off);
14835 
14836 	if (src_known && dst_known) {
14837 		/* dst_reg->var_off.value has been updated earlier */
14838 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14839 		return;
14840 	}
14841 
14842 	/* We get both minimum and maximum from the var_off. */
14843 	dst_reg->umin_value = dst_reg->var_off.value;
14844 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
14845 
14846 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14847 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14848 	 */
14849 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
14850 		dst_reg->smin_value = dst_reg->umin_value;
14851 		dst_reg->smax_value = dst_reg->umax_value;
14852 	} else {
14853 		dst_reg->smin_value = S64_MIN;
14854 		dst_reg->smax_value = S64_MAX;
14855 	}
14856 
14857 	__update_reg_bounds(dst_reg);
14858 }
14859 
14860 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
14861 				   u64 umin_val, u64 umax_val)
14862 {
14863 	/* We lose all sign bit information (except what we can pick
14864 	 * up from var_off)
14865 	 */
14866 	dst_reg->s32_min_value = S32_MIN;
14867 	dst_reg->s32_max_value = S32_MAX;
14868 	/* If we might shift our top bit out, then we know nothing */
14869 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
14870 		dst_reg->u32_min_value = 0;
14871 		dst_reg->u32_max_value = U32_MAX;
14872 	} else {
14873 		dst_reg->u32_min_value <<= umin_val;
14874 		dst_reg->u32_max_value <<= umax_val;
14875 	}
14876 }
14877 
14878 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
14879 				 struct bpf_reg_state *src_reg)
14880 {
14881 	u32 umax_val = src_reg->u32_max_value;
14882 	u32 umin_val = src_reg->u32_min_value;
14883 	/* u32 alu operation will zext upper bits */
14884 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
14885 
14886 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
14887 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
14888 	/* Not required but being careful mark reg64 bounds as unknown so
14889 	 * that we are forced to pick them up from tnum and zext later and
14890 	 * if some path skips this step we are still safe.
14891 	 */
14892 	__mark_reg64_unbounded(dst_reg);
14893 	__update_reg32_bounds(dst_reg);
14894 }
14895 
14896 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
14897 				   u64 umin_val, u64 umax_val)
14898 {
14899 	/* Special case <<32 because it is a common compiler pattern to sign
14900 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
14901 	 * positive we know this shift will also be positive so we can track
14902 	 * bounds correctly. Otherwise we lose all sign bit information except
14903 	 * what we can pick up from var_off. Perhaps we can generalize this
14904 	 * later to shifts of any length.
14905 	 */
14906 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
14907 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
14908 	else
14909 		dst_reg->smax_value = S64_MAX;
14910 
14911 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
14912 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
14913 	else
14914 		dst_reg->smin_value = S64_MIN;
14915 
14916 	/* If we might shift our top bit out, then we know nothing */
14917 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
14918 		dst_reg->umin_value = 0;
14919 		dst_reg->umax_value = U64_MAX;
14920 	} else {
14921 		dst_reg->umin_value <<= umin_val;
14922 		dst_reg->umax_value <<= umax_val;
14923 	}
14924 }
14925 
14926 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
14927 			       struct bpf_reg_state *src_reg)
14928 {
14929 	u64 umax_val = src_reg->umax_value;
14930 	u64 umin_val = src_reg->umin_value;
14931 
14932 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
14933 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
14934 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
14935 
14936 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
14937 	/* We may learn something more from the var_off */
14938 	__update_reg_bounds(dst_reg);
14939 }
14940 
14941 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
14942 				 struct bpf_reg_state *src_reg)
14943 {
14944 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
14945 	u32 umax_val = src_reg->u32_max_value;
14946 	u32 umin_val = src_reg->u32_min_value;
14947 
14948 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
14949 	 * be negative, then either:
14950 	 * 1) src_reg might be zero, so the sign bit of the result is
14951 	 *    unknown, so we lose our signed bounds
14952 	 * 2) it's known negative, thus the unsigned bounds capture the
14953 	 *    signed bounds
14954 	 * 3) the signed bounds cross zero, so they tell us nothing
14955 	 *    about the result
14956 	 * If the value in dst_reg is known nonnegative, then again the
14957 	 * unsigned bounds capture the signed bounds.
14958 	 * Thus, in all cases it suffices to blow away our signed bounds
14959 	 * and rely on inferring new ones from the unsigned bounds and
14960 	 * var_off of the result.
14961 	 */
14962 	dst_reg->s32_min_value = S32_MIN;
14963 	dst_reg->s32_max_value = S32_MAX;
14964 
14965 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
14966 	dst_reg->u32_min_value >>= umax_val;
14967 	dst_reg->u32_max_value >>= umin_val;
14968 
14969 	__mark_reg64_unbounded(dst_reg);
14970 	__update_reg32_bounds(dst_reg);
14971 }
14972 
14973 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
14974 			       struct bpf_reg_state *src_reg)
14975 {
14976 	u64 umax_val = src_reg->umax_value;
14977 	u64 umin_val = src_reg->umin_value;
14978 
14979 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
14980 	 * be negative, then either:
14981 	 * 1) src_reg might be zero, so the sign bit of the result is
14982 	 *    unknown, so we lose our signed bounds
14983 	 * 2) it's known negative, thus the unsigned bounds capture the
14984 	 *    signed bounds
14985 	 * 3) the signed bounds cross zero, so they tell us nothing
14986 	 *    about the result
14987 	 * If the value in dst_reg is known nonnegative, then again the
14988 	 * unsigned bounds capture the signed bounds.
14989 	 * Thus, in all cases it suffices to blow away our signed bounds
14990 	 * and rely on inferring new ones from the unsigned bounds and
14991 	 * var_off of the result.
14992 	 */
14993 	dst_reg->smin_value = S64_MIN;
14994 	dst_reg->smax_value = S64_MAX;
14995 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
14996 	dst_reg->umin_value >>= umax_val;
14997 	dst_reg->umax_value >>= umin_val;
14998 
14999 	/* Its not easy to operate on alu32 bounds here because it depends
15000 	 * on bits being shifted in. Take easy way out and mark unbounded
15001 	 * so we can recalculate later from tnum.
15002 	 */
15003 	__mark_reg32_unbounded(dst_reg);
15004 	__update_reg_bounds(dst_reg);
15005 }
15006 
15007 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
15008 				  struct bpf_reg_state *src_reg)
15009 {
15010 	u64 umin_val = src_reg->u32_min_value;
15011 
15012 	/* Upon reaching here, src_known is true and
15013 	 * umax_val is equal to umin_val.
15014 	 */
15015 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
15016 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
15017 
15018 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
15019 
15020 	/* blow away the dst_reg umin_value/umax_value and rely on
15021 	 * dst_reg var_off to refine the result.
15022 	 */
15023 	dst_reg->u32_min_value = 0;
15024 	dst_reg->u32_max_value = U32_MAX;
15025 
15026 	__mark_reg64_unbounded(dst_reg);
15027 	__update_reg32_bounds(dst_reg);
15028 }
15029 
15030 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
15031 				struct bpf_reg_state *src_reg)
15032 {
15033 	u64 umin_val = src_reg->umin_value;
15034 
15035 	/* Upon reaching here, src_known is true and umax_val is equal
15036 	 * to umin_val.
15037 	 */
15038 	dst_reg->smin_value >>= umin_val;
15039 	dst_reg->smax_value >>= umin_val;
15040 
15041 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
15042 
15043 	/* blow away the dst_reg umin_value/umax_value and rely on
15044 	 * dst_reg var_off to refine the result.
15045 	 */
15046 	dst_reg->umin_value = 0;
15047 	dst_reg->umax_value = U64_MAX;
15048 
15049 	/* Its not easy to operate on alu32 bounds here because it depends
15050 	 * on bits being shifted in from upper 32-bits. Take easy way out
15051 	 * and mark unbounded so we can recalculate later from tnum.
15052 	 */
15053 	__mark_reg32_unbounded(dst_reg);
15054 	__update_reg_bounds(dst_reg);
15055 }
15056 
15057 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
15058 					     const struct bpf_reg_state *src_reg)
15059 {
15060 	bool src_is_const = false;
15061 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
15062 
15063 	if (insn_bitness == 32) {
15064 		if (tnum_subreg_is_const(src_reg->var_off)
15065 		    && src_reg->s32_min_value == src_reg->s32_max_value
15066 		    && src_reg->u32_min_value == src_reg->u32_max_value)
15067 			src_is_const = true;
15068 	} else {
15069 		if (tnum_is_const(src_reg->var_off)
15070 		    && src_reg->smin_value == src_reg->smax_value
15071 		    && src_reg->umin_value == src_reg->umax_value)
15072 			src_is_const = true;
15073 	}
15074 
15075 	switch (BPF_OP(insn->code)) {
15076 	case BPF_ADD:
15077 	case BPF_SUB:
15078 	case BPF_AND:
15079 	case BPF_XOR:
15080 	case BPF_OR:
15081 	case BPF_MUL:
15082 		return true;
15083 
15084 	/* Shift operators range is only computable if shift dimension operand
15085 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
15086 	 * includes shifts by a negative number.
15087 	 */
15088 	case BPF_LSH:
15089 	case BPF_RSH:
15090 	case BPF_ARSH:
15091 		return (src_is_const && src_reg->umax_value < insn_bitness);
15092 	default:
15093 		return false;
15094 	}
15095 }
15096 
15097 /* WARNING: This function does calculations on 64-bit values, but the actual
15098  * execution may occur on 32-bit values. Therefore, things like bitshifts
15099  * need extra checks in the 32-bit case.
15100  */
15101 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
15102 				      struct bpf_insn *insn,
15103 				      struct bpf_reg_state *dst_reg,
15104 				      struct bpf_reg_state src_reg)
15105 {
15106 	u8 opcode = BPF_OP(insn->code);
15107 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15108 	int ret;
15109 
15110 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
15111 		__mark_reg_unknown(env, dst_reg);
15112 		return 0;
15113 	}
15114 
15115 	if (sanitize_needed(opcode)) {
15116 		ret = sanitize_val_alu(env, insn);
15117 		if (ret < 0)
15118 			return sanitize_err(env, insn, ret, NULL, NULL);
15119 	}
15120 
15121 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
15122 	 * There are two classes of instructions: The first class we track both
15123 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
15124 	 * greatest amount of precision when alu operations are mixed with jmp32
15125 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
15126 	 * and BPF_OR. This is possible because these ops have fairly easy to
15127 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
15128 	 * See alu32 verifier tests for examples. The second class of
15129 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
15130 	 * with regards to tracking sign/unsigned bounds because the bits may
15131 	 * cross subreg boundaries in the alu64 case. When this happens we mark
15132 	 * the reg unbounded in the subreg bound space and use the resulting
15133 	 * tnum to calculate an approximation of the sign/unsigned bounds.
15134 	 */
15135 	switch (opcode) {
15136 	case BPF_ADD:
15137 		scalar32_min_max_add(dst_reg, &src_reg);
15138 		scalar_min_max_add(dst_reg, &src_reg);
15139 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
15140 		break;
15141 	case BPF_SUB:
15142 		scalar32_min_max_sub(dst_reg, &src_reg);
15143 		scalar_min_max_sub(dst_reg, &src_reg);
15144 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
15145 		break;
15146 	case BPF_MUL:
15147 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
15148 		scalar32_min_max_mul(dst_reg, &src_reg);
15149 		scalar_min_max_mul(dst_reg, &src_reg);
15150 		break;
15151 	case BPF_AND:
15152 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
15153 		scalar32_min_max_and(dst_reg, &src_reg);
15154 		scalar_min_max_and(dst_reg, &src_reg);
15155 		break;
15156 	case BPF_OR:
15157 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
15158 		scalar32_min_max_or(dst_reg, &src_reg);
15159 		scalar_min_max_or(dst_reg, &src_reg);
15160 		break;
15161 	case BPF_XOR:
15162 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
15163 		scalar32_min_max_xor(dst_reg, &src_reg);
15164 		scalar_min_max_xor(dst_reg, &src_reg);
15165 		break;
15166 	case BPF_LSH:
15167 		if (alu32)
15168 			scalar32_min_max_lsh(dst_reg, &src_reg);
15169 		else
15170 			scalar_min_max_lsh(dst_reg, &src_reg);
15171 		break;
15172 	case BPF_RSH:
15173 		if (alu32)
15174 			scalar32_min_max_rsh(dst_reg, &src_reg);
15175 		else
15176 			scalar_min_max_rsh(dst_reg, &src_reg);
15177 		break;
15178 	case BPF_ARSH:
15179 		if (alu32)
15180 			scalar32_min_max_arsh(dst_reg, &src_reg);
15181 		else
15182 			scalar_min_max_arsh(dst_reg, &src_reg);
15183 		break;
15184 	default:
15185 		break;
15186 	}
15187 
15188 	/* ALU32 ops are zero extended into 64bit register */
15189 	if (alu32)
15190 		zext_32_to_64(dst_reg);
15191 	reg_bounds_sync(dst_reg);
15192 	return 0;
15193 }
15194 
15195 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
15196  * and var_off.
15197  */
15198 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
15199 				   struct bpf_insn *insn)
15200 {
15201 	struct bpf_verifier_state *vstate = env->cur_state;
15202 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15203 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
15204 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
15205 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15206 	u8 opcode = BPF_OP(insn->code);
15207 	int err;
15208 
15209 	dst_reg = &regs[insn->dst_reg];
15210 	src_reg = NULL;
15211 
15212 	if (dst_reg->type == PTR_TO_ARENA) {
15213 		struct bpf_insn_aux_data *aux = cur_aux(env);
15214 
15215 		if (BPF_CLASS(insn->code) == BPF_ALU64)
15216 			/*
15217 			 * 32-bit operations zero upper bits automatically.
15218 			 * 64-bit operations need to be converted to 32.
15219 			 */
15220 			aux->needs_zext = true;
15221 
15222 		/* Any arithmetic operations are allowed on arena pointers */
15223 		return 0;
15224 	}
15225 
15226 	if (dst_reg->type != SCALAR_VALUE)
15227 		ptr_reg = dst_reg;
15228 
15229 	if (BPF_SRC(insn->code) == BPF_X) {
15230 		src_reg = &regs[insn->src_reg];
15231 		if (src_reg->type != SCALAR_VALUE) {
15232 			if (dst_reg->type != SCALAR_VALUE) {
15233 				/* Combining two pointers by any ALU op yields
15234 				 * an arbitrary scalar. Disallow all math except
15235 				 * pointer subtraction
15236 				 */
15237 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
15238 					mark_reg_unknown(env, regs, insn->dst_reg);
15239 					return 0;
15240 				}
15241 				verbose(env, "R%d pointer %s pointer prohibited\n",
15242 					insn->dst_reg,
15243 					bpf_alu_string[opcode >> 4]);
15244 				return -EACCES;
15245 			} else {
15246 				/* scalar += pointer
15247 				 * This is legal, but we have to reverse our
15248 				 * src/dest handling in computing the range
15249 				 */
15250 				err = mark_chain_precision(env, insn->dst_reg);
15251 				if (err)
15252 					return err;
15253 				return adjust_ptr_min_max_vals(env, insn,
15254 							       src_reg, dst_reg);
15255 			}
15256 		} else if (ptr_reg) {
15257 			/* pointer += scalar */
15258 			err = mark_chain_precision(env, insn->src_reg);
15259 			if (err)
15260 				return err;
15261 			return adjust_ptr_min_max_vals(env, insn,
15262 						       dst_reg, src_reg);
15263 		} else if (dst_reg->precise) {
15264 			/* if dst_reg is precise, src_reg should be precise as well */
15265 			err = mark_chain_precision(env, insn->src_reg);
15266 			if (err)
15267 				return err;
15268 		}
15269 	} else {
15270 		/* Pretend the src is a reg with a known value, since we only
15271 		 * need to be able to read from this state.
15272 		 */
15273 		off_reg.type = SCALAR_VALUE;
15274 		__mark_reg_known(&off_reg, insn->imm);
15275 		src_reg = &off_reg;
15276 		if (ptr_reg) /* pointer += K */
15277 			return adjust_ptr_min_max_vals(env, insn,
15278 						       ptr_reg, src_reg);
15279 	}
15280 
15281 	/* Got here implies adding two SCALAR_VALUEs */
15282 	if (WARN_ON_ONCE(ptr_reg)) {
15283 		print_verifier_state(env, vstate, vstate->curframe, true);
15284 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
15285 		return -EINVAL;
15286 	}
15287 	if (WARN_ON(!src_reg)) {
15288 		print_verifier_state(env, vstate, vstate->curframe, true);
15289 		verbose(env, "verifier internal error: no src_reg\n");
15290 		return -EINVAL;
15291 	}
15292 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
15293 	if (err)
15294 		return err;
15295 	/*
15296 	 * Compilers can generate the code
15297 	 * r1 = r2
15298 	 * r1 += 0x1
15299 	 * if r2 < 1000 goto ...
15300 	 * use r1 in memory access
15301 	 * So for 64-bit alu remember constant delta between r2 and r1 and
15302 	 * update r1 after 'if' condition.
15303 	 */
15304 	if (env->bpf_capable &&
15305 	    BPF_OP(insn->code) == BPF_ADD && !alu32 &&
15306 	    dst_reg->id && is_reg_const(src_reg, false)) {
15307 		u64 val = reg_const_value(src_reg, false);
15308 
15309 		if ((dst_reg->id & BPF_ADD_CONST) ||
15310 		    /* prevent overflow in sync_linked_regs() later */
15311 		    val > (u32)S32_MAX) {
15312 			/*
15313 			 * If the register already went through rX += val
15314 			 * we cannot accumulate another val into rx->off.
15315 			 */
15316 			dst_reg->off = 0;
15317 			dst_reg->id = 0;
15318 		} else {
15319 			dst_reg->id |= BPF_ADD_CONST;
15320 			dst_reg->off = val;
15321 		}
15322 	} else {
15323 		/*
15324 		 * Make sure ID is cleared otherwise dst_reg min/max could be
15325 		 * incorrectly propagated into other registers by sync_linked_regs()
15326 		 */
15327 		dst_reg->id = 0;
15328 	}
15329 	return 0;
15330 }
15331 
15332 /* check validity of 32-bit and 64-bit arithmetic operations */
15333 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
15334 {
15335 	struct bpf_reg_state *regs = cur_regs(env);
15336 	u8 opcode = BPF_OP(insn->code);
15337 	int err;
15338 
15339 	if (opcode == BPF_END || opcode == BPF_NEG) {
15340 		if (opcode == BPF_NEG) {
15341 			if (BPF_SRC(insn->code) != BPF_K ||
15342 			    insn->src_reg != BPF_REG_0 ||
15343 			    insn->off != 0 || insn->imm != 0) {
15344 				verbose(env, "BPF_NEG uses reserved fields\n");
15345 				return -EINVAL;
15346 			}
15347 		} else {
15348 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
15349 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
15350 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
15351 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
15352 				verbose(env, "BPF_END uses reserved fields\n");
15353 				return -EINVAL;
15354 			}
15355 		}
15356 
15357 		/* check src operand */
15358 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15359 		if (err)
15360 			return err;
15361 
15362 		if (is_pointer_value(env, insn->dst_reg)) {
15363 			verbose(env, "R%d pointer arithmetic prohibited\n",
15364 				insn->dst_reg);
15365 			return -EACCES;
15366 		}
15367 
15368 		/* check dest operand */
15369 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
15370 		if (err)
15371 			return err;
15372 
15373 	} else if (opcode == BPF_MOV) {
15374 
15375 		if (BPF_SRC(insn->code) == BPF_X) {
15376 			if (BPF_CLASS(insn->code) == BPF_ALU) {
15377 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
15378 				    insn->imm) {
15379 					verbose(env, "BPF_MOV uses reserved fields\n");
15380 					return -EINVAL;
15381 				}
15382 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
15383 				if (insn->imm != 1 && insn->imm != 1u << 16) {
15384 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
15385 					return -EINVAL;
15386 				}
15387 				if (!env->prog->aux->arena) {
15388 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
15389 					return -EINVAL;
15390 				}
15391 			} else {
15392 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
15393 				     insn->off != 32) || insn->imm) {
15394 					verbose(env, "BPF_MOV uses reserved fields\n");
15395 					return -EINVAL;
15396 				}
15397 			}
15398 
15399 			/* check src operand */
15400 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15401 			if (err)
15402 				return err;
15403 		} else {
15404 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
15405 				verbose(env, "BPF_MOV uses reserved fields\n");
15406 				return -EINVAL;
15407 			}
15408 		}
15409 
15410 		/* check dest operand, mark as required later */
15411 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15412 		if (err)
15413 			return err;
15414 
15415 		if (BPF_SRC(insn->code) == BPF_X) {
15416 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
15417 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
15418 
15419 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15420 				if (insn->imm) {
15421 					/* off == BPF_ADDR_SPACE_CAST */
15422 					mark_reg_unknown(env, regs, insn->dst_reg);
15423 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
15424 						dst_reg->type = PTR_TO_ARENA;
15425 						/* PTR_TO_ARENA is 32-bit */
15426 						dst_reg->subreg_def = env->insn_idx + 1;
15427 					}
15428 				} else if (insn->off == 0) {
15429 					/* case: R1 = R2
15430 					 * copy register state to dest reg
15431 					 */
15432 					assign_scalar_id_before_mov(env, src_reg);
15433 					copy_register_state(dst_reg, src_reg);
15434 					dst_reg->live |= REG_LIVE_WRITTEN;
15435 					dst_reg->subreg_def = DEF_NOT_SUBREG;
15436 				} else {
15437 					/* case: R1 = (s8, s16 s32)R2 */
15438 					if (is_pointer_value(env, insn->src_reg)) {
15439 						verbose(env,
15440 							"R%d sign-extension part of pointer\n",
15441 							insn->src_reg);
15442 						return -EACCES;
15443 					} else if (src_reg->type == SCALAR_VALUE) {
15444 						bool no_sext;
15445 
15446 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15447 						if (no_sext)
15448 							assign_scalar_id_before_mov(env, src_reg);
15449 						copy_register_state(dst_reg, src_reg);
15450 						if (!no_sext)
15451 							dst_reg->id = 0;
15452 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
15453 						dst_reg->live |= REG_LIVE_WRITTEN;
15454 						dst_reg->subreg_def = DEF_NOT_SUBREG;
15455 					} else {
15456 						mark_reg_unknown(env, regs, insn->dst_reg);
15457 					}
15458 				}
15459 			} else {
15460 				/* R1 = (u32) R2 */
15461 				if (is_pointer_value(env, insn->src_reg)) {
15462 					verbose(env,
15463 						"R%d partial copy of pointer\n",
15464 						insn->src_reg);
15465 					return -EACCES;
15466 				} else if (src_reg->type == SCALAR_VALUE) {
15467 					if (insn->off == 0) {
15468 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
15469 
15470 						if (is_src_reg_u32)
15471 							assign_scalar_id_before_mov(env, src_reg);
15472 						copy_register_state(dst_reg, src_reg);
15473 						/* Make sure ID is cleared if src_reg is not in u32
15474 						 * range otherwise dst_reg min/max could be incorrectly
15475 						 * propagated into src_reg by sync_linked_regs()
15476 						 */
15477 						if (!is_src_reg_u32)
15478 							dst_reg->id = 0;
15479 						dst_reg->live |= REG_LIVE_WRITTEN;
15480 						dst_reg->subreg_def = env->insn_idx + 1;
15481 					} else {
15482 						/* case: W1 = (s8, s16)W2 */
15483 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15484 
15485 						if (no_sext)
15486 							assign_scalar_id_before_mov(env, src_reg);
15487 						copy_register_state(dst_reg, src_reg);
15488 						if (!no_sext)
15489 							dst_reg->id = 0;
15490 						dst_reg->live |= REG_LIVE_WRITTEN;
15491 						dst_reg->subreg_def = env->insn_idx + 1;
15492 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
15493 					}
15494 				} else {
15495 					mark_reg_unknown(env, regs,
15496 							 insn->dst_reg);
15497 				}
15498 				zext_32_to_64(dst_reg);
15499 				reg_bounds_sync(dst_reg);
15500 			}
15501 		} else {
15502 			/* case: R = imm
15503 			 * remember the value we stored into this reg
15504 			 */
15505 			/* clear any state __mark_reg_known doesn't set */
15506 			mark_reg_unknown(env, regs, insn->dst_reg);
15507 			regs[insn->dst_reg].type = SCALAR_VALUE;
15508 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15509 				__mark_reg_known(regs + insn->dst_reg,
15510 						 insn->imm);
15511 			} else {
15512 				__mark_reg_known(regs + insn->dst_reg,
15513 						 (u32)insn->imm);
15514 			}
15515 		}
15516 
15517 	} else if (opcode > BPF_END) {
15518 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
15519 		return -EINVAL;
15520 
15521 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
15522 
15523 		if (BPF_SRC(insn->code) == BPF_X) {
15524 			if (insn->imm != 0 || insn->off > 1 ||
15525 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15526 				verbose(env, "BPF_ALU uses reserved fields\n");
15527 				return -EINVAL;
15528 			}
15529 			/* check src1 operand */
15530 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15531 			if (err)
15532 				return err;
15533 		} else {
15534 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
15535 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15536 				verbose(env, "BPF_ALU uses reserved fields\n");
15537 				return -EINVAL;
15538 			}
15539 		}
15540 
15541 		/* check src2 operand */
15542 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15543 		if (err)
15544 			return err;
15545 
15546 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
15547 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
15548 			verbose(env, "div by zero\n");
15549 			return -EINVAL;
15550 		}
15551 
15552 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
15553 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
15554 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
15555 
15556 			if (insn->imm < 0 || insn->imm >= size) {
15557 				verbose(env, "invalid shift %d\n", insn->imm);
15558 				return -EINVAL;
15559 			}
15560 		}
15561 
15562 		/* check dest operand */
15563 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15564 		err = err ?: adjust_reg_min_max_vals(env, insn);
15565 		if (err)
15566 			return err;
15567 	}
15568 
15569 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
15570 }
15571 
15572 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
15573 				   struct bpf_reg_state *dst_reg,
15574 				   enum bpf_reg_type type,
15575 				   bool range_right_open)
15576 {
15577 	struct bpf_func_state *state;
15578 	struct bpf_reg_state *reg;
15579 	int new_range;
15580 
15581 	if (dst_reg->off < 0 ||
15582 	    (dst_reg->off == 0 && range_right_open))
15583 		/* This doesn't give us any range */
15584 		return;
15585 
15586 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
15587 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
15588 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
15589 		 * than pkt_end, but that's because it's also less than pkt.
15590 		 */
15591 		return;
15592 
15593 	new_range = dst_reg->off;
15594 	if (range_right_open)
15595 		new_range++;
15596 
15597 	/* Examples for register markings:
15598 	 *
15599 	 * pkt_data in dst register:
15600 	 *
15601 	 *   r2 = r3;
15602 	 *   r2 += 8;
15603 	 *   if (r2 > pkt_end) goto <handle exception>
15604 	 *   <access okay>
15605 	 *
15606 	 *   r2 = r3;
15607 	 *   r2 += 8;
15608 	 *   if (r2 < pkt_end) goto <access okay>
15609 	 *   <handle exception>
15610 	 *
15611 	 *   Where:
15612 	 *     r2 == dst_reg, pkt_end == src_reg
15613 	 *     r2=pkt(id=n,off=8,r=0)
15614 	 *     r3=pkt(id=n,off=0,r=0)
15615 	 *
15616 	 * pkt_data in src register:
15617 	 *
15618 	 *   r2 = r3;
15619 	 *   r2 += 8;
15620 	 *   if (pkt_end >= r2) goto <access okay>
15621 	 *   <handle exception>
15622 	 *
15623 	 *   r2 = r3;
15624 	 *   r2 += 8;
15625 	 *   if (pkt_end <= r2) goto <handle exception>
15626 	 *   <access okay>
15627 	 *
15628 	 *   Where:
15629 	 *     pkt_end == dst_reg, r2 == src_reg
15630 	 *     r2=pkt(id=n,off=8,r=0)
15631 	 *     r3=pkt(id=n,off=0,r=0)
15632 	 *
15633 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
15634 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
15635 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
15636 	 * the check.
15637 	 */
15638 
15639 	/* If our ids match, then we must have the same max_value.  And we
15640 	 * don't care about the other reg's fixed offset, since if it's too big
15641 	 * the range won't allow anything.
15642 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
15643 	 */
15644 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15645 		if (reg->type == type && reg->id == dst_reg->id)
15646 			/* keep the maximum range already checked */
15647 			reg->range = max(reg->range, new_range);
15648 	}));
15649 }
15650 
15651 /*
15652  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
15653  */
15654 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15655 				  u8 opcode, bool is_jmp32)
15656 {
15657 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
15658 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
15659 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
15660 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
15661 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
15662 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
15663 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
15664 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
15665 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
15666 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
15667 
15668 	switch (opcode) {
15669 	case BPF_JEQ:
15670 		/* constants, umin/umax and smin/smax checks would be
15671 		 * redundant in this case because they all should match
15672 		 */
15673 		if (tnum_is_const(t1) && tnum_is_const(t2))
15674 			return t1.value == t2.value;
15675 		/* non-overlapping ranges */
15676 		if (umin1 > umax2 || umax1 < umin2)
15677 			return 0;
15678 		if (smin1 > smax2 || smax1 < smin2)
15679 			return 0;
15680 		if (!is_jmp32) {
15681 			/* if 64-bit ranges are inconclusive, see if we can
15682 			 * utilize 32-bit subrange knowledge to eliminate
15683 			 * branches that can't be taken a priori
15684 			 */
15685 			if (reg1->u32_min_value > reg2->u32_max_value ||
15686 			    reg1->u32_max_value < reg2->u32_min_value)
15687 				return 0;
15688 			if (reg1->s32_min_value > reg2->s32_max_value ||
15689 			    reg1->s32_max_value < reg2->s32_min_value)
15690 				return 0;
15691 		}
15692 		break;
15693 	case BPF_JNE:
15694 		/* constants, umin/umax and smin/smax checks would be
15695 		 * redundant in this case because they all should match
15696 		 */
15697 		if (tnum_is_const(t1) && tnum_is_const(t2))
15698 			return t1.value != t2.value;
15699 		/* non-overlapping ranges */
15700 		if (umin1 > umax2 || umax1 < umin2)
15701 			return 1;
15702 		if (smin1 > smax2 || smax1 < smin2)
15703 			return 1;
15704 		if (!is_jmp32) {
15705 			/* if 64-bit ranges are inconclusive, see if we can
15706 			 * utilize 32-bit subrange knowledge to eliminate
15707 			 * branches that can't be taken a priori
15708 			 */
15709 			if (reg1->u32_min_value > reg2->u32_max_value ||
15710 			    reg1->u32_max_value < reg2->u32_min_value)
15711 				return 1;
15712 			if (reg1->s32_min_value > reg2->s32_max_value ||
15713 			    reg1->s32_max_value < reg2->s32_min_value)
15714 				return 1;
15715 		}
15716 		break;
15717 	case BPF_JSET:
15718 		if (!is_reg_const(reg2, is_jmp32)) {
15719 			swap(reg1, reg2);
15720 			swap(t1, t2);
15721 		}
15722 		if (!is_reg_const(reg2, is_jmp32))
15723 			return -1;
15724 		if ((~t1.mask & t1.value) & t2.value)
15725 			return 1;
15726 		if (!((t1.mask | t1.value) & t2.value))
15727 			return 0;
15728 		break;
15729 	case BPF_JGT:
15730 		if (umin1 > umax2)
15731 			return 1;
15732 		else if (umax1 <= umin2)
15733 			return 0;
15734 		break;
15735 	case BPF_JSGT:
15736 		if (smin1 > smax2)
15737 			return 1;
15738 		else if (smax1 <= smin2)
15739 			return 0;
15740 		break;
15741 	case BPF_JLT:
15742 		if (umax1 < umin2)
15743 			return 1;
15744 		else if (umin1 >= umax2)
15745 			return 0;
15746 		break;
15747 	case BPF_JSLT:
15748 		if (smax1 < smin2)
15749 			return 1;
15750 		else if (smin1 >= smax2)
15751 			return 0;
15752 		break;
15753 	case BPF_JGE:
15754 		if (umin1 >= umax2)
15755 			return 1;
15756 		else if (umax1 < umin2)
15757 			return 0;
15758 		break;
15759 	case BPF_JSGE:
15760 		if (smin1 >= smax2)
15761 			return 1;
15762 		else if (smax1 < smin2)
15763 			return 0;
15764 		break;
15765 	case BPF_JLE:
15766 		if (umax1 <= umin2)
15767 			return 1;
15768 		else if (umin1 > umax2)
15769 			return 0;
15770 		break;
15771 	case BPF_JSLE:
15772 		if (smax1 <= smin2)
15773 			return 1;
15774 		else if (smin1 > smax2)
15775 			return 0;
15776 		break;
15777 	}
15778 
15779 	return -1;
15780 }
15781 
15782 static int flip_opcode(u32 opcode)
15783 {
15784 	/* How can we transform "a <op> b" into "b <op> a"? */
15785 	static const u8 opcode_flip[16] = {
15786 		/* these stay the same */
15787 		[BPF_JEQ  >> 4] = BPF_JEQ,
15788 		[BPF_JNE  >> 4] = BPF_JNE,
15789 		[BPF_JSET >> 4] = BPF_JSET,
15790 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
15791 		[BPF_JGE  >> 4] = BPF_JLE,
15792 		[BPF_JGT  >> 4] = BPF_JLT,
15793 		[BPF_JLE  >> 4] = BPF_JGE,
15794 		[BPF_JLT  >> 4] = BPF_JGT,
15795 		[BPF_JSGE >> 4] = BPF_JSLE,
15796 		[BPF_JSGT >> 4] = BPF_JSLT,
15797 		[BPF_JSLE >> 4] = BPF_JSGE,
15798 		[BPF_JSLT >> 4] = BPF_JSGT
15799 	};
15800 	return opcode_flip[opcode >> 4];
15801 }
15802 
15803 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
15804 				   struct bpf_reg_state *src_reg,
15805 				   u8 opcode)
15806 {
15807 	struct bpf_reg_state *pkt;
15808 
15809 	if (src_reg->type == PTR_TO_PACKET_END) {
15810 		pkt = dst_reg;
15811 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
15812 		pkt = src_reg;
15813 		opcode = flip_opcode(opcode);
15814 	} else {
15815 		return -1;
15816 	}
15817 
15818 	if (pkt->range >= 0)
15819 		return -1;
15820 
15821 	switch (opcode) {
15822 	case BPF_JLE:
15823 		/* pkt <= pkt_end */
15824 		fallthrough;
15825 	case BPF_JGT:
15826 		/* pkt > pkt_end */
15827 		if (pkt->range == BEYOND_PKT_END)
15828 			/* pkt has at last one extra byte beyond pkt_end */
15829 			return opcode == BPF_JGT;
15830 		break;
15831 	case BPF_JLT:
15832 		/* pkt < pkt_end */
15833 		fallthrough;
15834 	case BPF_JGE:
15835 		/* pkt >= pkt_end */
15836 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
15837 			return opcode == BPF_JGE;
15838 		break;
15839 	}
15840 	return -1;
15841 }
15842 
15843 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
15844  * and return:
15845  *  1 - branch will be taken and "goto target" will be executed
15846  *  0 - branch will not be taken and fall-through to next insn
15847  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
15848  *      range [0,10]
15849  */
15850 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15851 			   u8 opcode, bool is_jmp32)
15852 {
15853 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
15854 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
15855 
15856 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
15857 		u64 val;
15858 
15859 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
15860 		if (!is_reg_const(reg2, is_jmp32)) {
15861 			opcode = flip_opcode(opcode);
15862 			swap(reg1, reg2);
15863 		}
15864 		/* and ensure that reg2 is a constant */
15865 		if (!is_reg_const(reg2, is_jmp32))
15866 			return -1;
15867 
15868 		if (!reg_not_null(reg1))
15869 			return -1;
15870 
15871 		/* If pointer is valid tests against zero will fail so we can
15872 		 * use this to direct branch taken.
15873 		 */
15874 		val = reg_const_value(reg2, is_jmp32);
15875 		if (val != 0)
15876 			return -1;
15877 
15878 		switch (opcode) {
15879 		case BPF_JEQ:
15880 			return 0;
15881 		case BPF_JNE:
15882 			return 1;
15883 		default:
15884 			return -1;
15885 		}
15886 	}
15887 
15888 	/* now deal with two scalars, but not necessarily constants */
15889 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
15890 }
15891 
15892 /* Opcode that corresponds to a *false* branch condition.
15893  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
15894  */
15895 static u8 rev_opcode(u8 opcode)
15896 {
15897 	switch (opcode) {
15898 	case BPF_JEQ:		return BPF_JNE;
15899 	case BPF_JNE:		return BPF_JEQ;
15900 	/* JSET doesn't have it's reverse opcode in BPF, so add
15901 	 * BPF_X flag to denote the reverse of that operation
15902 	 */
15903 	case BPF_JSET:		return BPF_JSET | BPF_X;
15904 	case BPF_JSET | BPF_X:	return BPF_JSET;
15905 	case BPF_JGE:		return BPF_JLT;
15906 	case BPF_JGT:		return BPF_JLE;
15907 	case BPF_JLE:		return BPF_JGT;
15908 	case BPF_JLT:		return BPF_JGE;
15909 	case BPF_JSGE:		return BPF_JSLT;
15910 	case BPF_JSGT:		return BPF_JSLE;
15911 	case BPF_JSLE:		return BPF_JSGT;
15912 	case BPF_JSLT:		return BPF_JSGE;
15913 	default:		return 0;
15914 	}
15915 }
15916 
15917 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
15918 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15919 				u8 opcode, bool is_jmp32)
15920 {
15921 	struct tnum t;
15922 	u64 val;
15923 
15924 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
15925 	switch (opcode) {
15926 	case BPF_JGE:
15927 	case BPF_JGT:
15928 	case BPF_JSGE:
15929 	case BPF_JSGT:
15930 		opcode = flip_opcode(opcode);
15931 		swap(reg1, reg2);
15932 		break;
15933 	default:
15934 		break;
15935 	}
15936 
15937 	switch (opcode) {
15938 	case BPF_JEQ:
15939 		if (is_jmp32) {
15940 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
15941 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
15942 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
15943 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
15944 			reg2->u32_min_value = reg1->u32_min_value;
15945 			reg2->u32_max_value = reg1->u32_max_value;
15946 			reg2->s32_min_value = reg1->s32_min_value;
15947 			reg2->s32_max_value = reg1->s32_max_value;
15948 
15949 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
15950 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15951 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
15952 		} else {
15953 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
15954 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
15955 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
15956 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
15957 			reg2->umin_value = reg1->umin_value;
15958 			reg2->umax_value = reg1->umax_value;
15959 			reg2->smin_value = reg1->smin_value;
15960 			reg2->smax_value = reg1->smax_value;
15961 
15962 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
15963 			reg2->var_off = reg1->var_off;
15964 		}
15965 		break;
15966 	case BPF_JNE:
15967 		if (!is_reg_const(reg2, is_jmp32))
15968 			swap(reg1, reg2);
15969 		if (!is_reg_const(reg2, is_jmp32))
15970 			break;
15971 
15972 		/* try to recompute the bound of reg1 if reg2 is a const and
15973 		 * is exactly the edge of reg1.
15974 		 */
15975 		val = reg_const_value(reg2, is_jmp32);
15976 		if (is_jmp32) {
15977 			/* u32_min_value is not equal to 0xffffffff at this point,
15978 			 * because otherwise u32_max_value is 0xffffffff as well,
15979 			 * in such a case both reg1 and reg2 would be constants,
15980 			 * jump would be predicted and reg_set_min_max() won't
15981 			 * be called.
15982 			 *
15983 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
15984 			 * below.
15985 			 */
15986 			if (reg1->u32_min_value == (u32)val)
15987 				reg1->u32_min_value++;
15988 			if (reg1->u32_max_value == (u32)val)
15989 				reg1->u32_max_value--;
15990 			if (reg1->s32_min_value == (s32)val)
15991 				reg1->s32_min_value++;
15992 			if (reg1->s32_max_value == (s32)val)
15993 				reg1->s32_max_value--;
15994 		} else {
15995 			if (reg1->umin_value == (u64)val)
15996 				reg1->umin_value++;
15997 			if (reg1->umax_value == (u64)val)
15998 				reg1->umax_value--;
15999 			if (reg1->smin_value == (s64)val)
16000 				reg1->smin_value++;
16001 			if (reg1->smax_value == (s64)val)
16002 				reg1->smax_value--;
16003 		}
16004 		break;
16005 	case BPF_JSET:
16006 		if (!is_reg_const(reg2, is_jmp32))
16007 			swap(reg1, reg2);
16008 		if (!is_reg_const(reg2, is_jmp32))
16009 			break;
16010 		val = reg_const_value(reg2, is_jmp32);
16011 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
16012 		 * requires single bit to learn something useful. E.g., if we
16013 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
16014 		 * are actually set? We can learn something definite only if
16015 		 * it's a single-bit value to begin with.
16016 		 *
16017 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
16018 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
16019 		 * bit 1 is set, which we can readily use in adjustments.
16020 		 */
16021 		if (!is_power_of_2(val))
16022 			break;
16023 		if (is_jmp32) {
16024 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
16025 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16026 		} else {
16027 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
16028 		}
16029 		break;
16030 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
16031 		if (!is_reg_const(reg2, is_jmp32))
16032 			swap(reg1, reg2);
16033 		if (!is_reg_const(reg2, is_jmp32))
16034 			break;
16035 		val = reg_const_value(reg2, is_jmp32);
16036 		if (is_jmp32) {
16037 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
16038 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16039 		} else {
16040 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
16041 		}
16042 		break;
16043 	case BPF_JLE:
16044 		if (is_jmp32) {
16045 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16046 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16047 		} else {
16048 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16049 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
16050 		}
16051 		break;
16052 	case BPF_JLT:
16053 		if (is_jmp32) {
16054 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
16055 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
16056 		} else {
16057 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
16058 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
16059 		}
16060 		break;
16061 	case BPF_JSLE:
16062 		if (is_jmp32) {
16063 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16064 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16065 		} else {
16066 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16067 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
16068 		}
16069 		break;
16070 	case BPF_JSLT:
16071 		if (is_jmp32) {
16072 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
16073 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
16074 		} else {
16075 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
16076 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
16077 		}
16078 		break;
16079 	default:
16080 		return;
16081 	}
16082 }
16083 
16084 /* Adjusts the register min/max values in the case that the dst_reg and
16085  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
16086  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
16087  * Technically we can do similar adjustments for pointers to the same object,
16088  * but we don't support that right now.
16089  */
16090 static int reg_set_min_max(struct bpf_verifier_env *env,
16091 			   struct bpf_reg_state *true_reg1,
16092 			   struct bpf_reg_state *true_reg2,
16093 			   struct bpf_reg_state *false_reg1,
16094 			   struct bpf_reg_state *false_reg2,
16095 			   u8 opcode, bool is_jmp32)
16096 {
16097 	int err;
16098 
16099 	/* If either register is a pointer, we can't learn anything about its
16100 	 * variable offset from the compare (unless they were a pointer into
16101 	 * the same object, but we don't bother with that).
16102 	 */
16103 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
16104 		return 0;
16105 
16106 	/* fallthrough (FALSE) branch */
16107 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
16108 	reg_bounds_sync(false_reg1);
16109 	reg_bounds_sync(false_reg2);
16110 
16111 	/* jump (TRUE) branch */
16112 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
16113 	reg_bounds_sync(true_reg1);
16114 	reg_bounds_sync(true_reg2);
16115 
16116 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
16117 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
16118 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
16119 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
16120 	return err;
16121 }
16122 
16123 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
16124 				 struct bpf_reg_state *reg, u32 id,
16125 				 bool is_null)
16126 {
16127 	if (type_may_be_null(reg->type) && reg->id == id &&
16128 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
16129 		/* Old offset (both fixed and variable parts) should have been
16130 		 * known-zero, because we don't allow pointer arithmetic on
16131 		 * pointers that might be NULL. If we see this happening, don't
16132 		 * convert the register.
16133 		 *
16134 		 * But in some cases, some helpers that return local kptrs
16135 		 * advance offset for the returned pointer. In those cases, it
16136 		 * is fine to expect to see reg->off.
16137 		 */
16138 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
16139 			return;
16140 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
16141 		    WARN_ON_ONCE(reg->off))
16142 			return;
16143 
16144 		if (is_null) {
16145 			reg->type = SCALAR_VALUE;
16146 			/* We don't need id and ref_obj_id from this point
16147 			 * onwards anymore, thus we should better reset it,
16148 			 * so that state pruning has chances to take effect.
16149 			 */
16150 			reg->id = 0;
16151 			reg->ref_obj_id = 0;
16152 
16153 			return;
16154 		}
16155 
16156 		mark_ptr_not_null_reg(reg);
16157 
16158 		if (!reg_may_point_to_spin_lock(reg)) {
16159 			/* For not-NULL ptr, reg->ref_obj_id will be reset
16160 			 * in release_reference().
16161 			 *
16162 			 * reg->id is still used by spin_lock ptr. Other
16163 			 * than spin_lock ptr type, reg->id can be reset.
16164 			 */
16165 			reg->id = 0;
16166 		}
16167 	}
16168 }
16169 
16170 /* The logic is similar to find_good_pkt_pointers(), both could eventually
16171  * be folded together at some point.
16172  */
16173 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
16174 				  bool is_null)
16175 {
16176 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
16177 	struct bpf_reg_state *regs = state->regs, *reg;
16178 	u32 ref_obj_id = regs[regno].ref_obj_id;
16179 	u32 id = regs[regno].id;
16180 
16181 	if (ref_obj_id && ref_obj_id == id && is_null)
16182 		/* regs[regno] is in the " == NULL" branch.
16183 		 * No one could have freed the reference state before
16184 		 * doing the NULL check.
16185 		 */
16186 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
16187 
16188 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16189 		mark_ptr_or_null_reg(state, reg, id, is_null);
16190 	}));
16191 }
16192 
16193 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
16194 				   struct bpf_reg_state *dst_reg,
16195 				   struct bpf_reg_state *src_reg,
16196 				   struct bpf_verifier_state *this_branch,
16197 				   struct bpf_verifier_state *other_branch)
16198 {
16199 	if (BPF_SRC(insn->code) != BPF_X)
16200 		return false;
16201 
16202 	/* Pointers are always 64-bit. */
16203 	if (BPF_CLASS(insn->code) == BPF_JMP32)
16204 		return false;
16205 
16206 	switch (BPF_OP(insn->code)) {
16207 	case BPF_JGT:
16208 		if ((dst_reg->type == PTR_TO_PACKET &&
16209 		     src_reg->type == PTR_TO_PACKET_END) ||
16210 		    (dst_reg->type == PTR_TO_PACKET_META &&
16211 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16212 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
16213 			find_good_pkt_pointers(this_branch, dst_reg,
16214 					       dst_reg->type, false);
16215 			mark_pkt_end(other_branch, insn->dst_reg, true);
16216 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16217 			    src_reg->type == PTR_TO_PACKET) ||
16218 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16219 			    src_reg->type == PTR_TO_PACKET_META)) {
16220 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
16221 			find_good_pkt_pointers(other_branch, src_reg,
16222 					       src_reg->type, true);
16223 			mark_pkt_end(this_branch, insn->src_reg, false);
16224 		} else {
16225 			return false;
16226 		}
16227 		break;
16228 	case BPF_JLT:
16229 		if ((dst_reg->type == PTR_TO_PACKET &&
16230 		     src_reg->type == PTR_TO_PACKET_END) ||
16231 		    (dst_reg->type == PTR_TO_PACKET_META &&
16232 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16233 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
16234 			find_good_pkt_pointers(other_branch, dst_reg,
16235 					       dst_reg->type, true);
16236 			mark_pkt_end(this_branch, insn->dst_reg, false);
16237 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16238 			    src_reg->type == PTR_TO_PACKET) ||
16239 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16240 			    src_reg->type == PTR_TO_PACKET_META)) {
16241 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
16242 			find_good_pkt_pointers(this_branch, src_reg,
16243 					       src_reg->type, false);
16244 			mark_pkt_end(other_branch, insn->src_reg, true);
16245 		} else {
16246 			return false;
16247 		}
16248 		break;
16249 	case BPF_JGE:
16250 		if ((dst_reg->type == PTR_TO_PACKET &&
16251 		     src_reg->type == PTR_TO_PACKET_END) ||
16252 		    (dst_reg->type == PTR_TO_PACKET_META &&
16253 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16254 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
16255 			find_good_pkt_pointers(this_branch, dst_reg,
16256 					       dst_reg->type, true);
16257 			mark_pkt_end(other_branch, insn->dst_reg, false);
16258 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16259 			    src_reg->type == PTR_TO_PACKET) ||
16260 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16261 			    src_reg->type == PTR_TO_PACKET_META)) {
16262 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
16263 			find_good_pkt_pointers(other_branch, src_reg,
16264 					       src_reg->type, false);
16265 			mark_pkt_end(this_branch, insn->src_reg, true);
16266 		} else {
16267 			return false;
16268 		}
16269 		break;
16270 	case BPF_JLE:
16271 		if ((dst_reg->type == PTR_TO_PACKET &&
16272 		     src_reg->type == PTR_TO_PACKET_END) ||
16273 		    (dst_reg->type == PTR_TO_PACKET_META &&
16274 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16275 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
16276 			find_good_pkt_pointers(other_branch, dst_reg,
16277 					       dst_reg->type, false);
16278 			mark_pkt_end(this_branch, insn->dst_reg, true);
16279 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16280 			    src_reg->type == PTR_TO_PACKET) ||
16281 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16282 			    src_reg->type == PTR_TO_PACKET_META)) {
16283 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
16284 			find_good_pkt_pointers(this_branch, src_reg,
16285 					       src_reg->type, true);
16286 			mark_pkt_end(other_branch, insn->src_reg, false);
16287 		} else {
16288 			return false;
16289 		}
16290 		break;
16291 	default:
16292 		return false;
16293 	}
16294 
16295 	return true;
16296 }
16297 
16298 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
16299 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
16300 {
16301 	struct linked_reg *e;
16302 
16303 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
16304 		return;
16305 
16306 	e = linked_regs_push(reg_set);
16307 	if (e) {
16308 		e->frameno = frameno;
16309 		e->is_reg = is_reg;
16310 		e->regno = spi_or_reg;
16311 	} else {
16312 		reg->id = 0;
16313 	}
16314 }
16315 
16316 /* For all R being scalar registers or spilled scalar registers
16317  * in verifier state, save R in linked_regs if R->id == id.
16318  * If there are too many Rs sharing same id, reset id for leftover Rs.
16319  */
16320 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
16321 				struct linked_regs *linked_regs)
16322 {
16323 	struct bpf_func_state *func;
16324 	struct bpf_reg_state *reg;
16325 	int i, j;
16326 
16327 	id = id & ~BPF_ADD_CONST;
16328 	for (i = vstate->curframe; i >= 0; i--) {
16329 		func = vstate->frame[i];
16330 		for (j = 0; j < BPF_REG_FP; j++) {
16331 			reg = &func->regs[j];
16332 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
16333 		}
16334 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
16335 			if (!is_spilled_reg(&func->stack[j]))
16336 				continue;
16337 			reg = &func->stack[j].spilled_ptr;
16338 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
16339 		}
16340 	}
16341 }
16342 
16343 /* For all R in linked_regs, copy known_reg range into R
16344  * if R->id == known_reg->id.
16345  */
16346 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
16347 			     struct linked_regs *linked_regs)
16348 {
16349 	struct bpf_reg_state fake_reg;
16350 	struct bpf_reg_state *reg;
16351 	struct linked_reg *e;
16352 	int i;
16353 
16354 	for (i = 0; i < linked_regs->cnt; ++i) {
16355 		e = &linked_regs->entries[i];
16356 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
16357 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
16358 		if (reg->type != SCALAR_VALUE || reg == known_reg)
16359 			continue;
16360 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
16361 			continue;
16362 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
16363 		    reg->off == known_reg->off) {
16364 			s32 saved_subreg_def = reg->subreg_def;
16365 
16366 			copy_register_state(reg, known_reg);
16367 			reg->subreg_def = saved_subreg_def;
16368 		} else {
16369 			s32 saved_subreg_def = reg->subreg_def;
16370 			s32 saved_off = reg->off;
16371 
16372 			fake_reg.type = SCALAR_VALUE;
16373 			__mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
16374 
16375 			/* reg = known_reg; reg += delta */
16376 			copy_register_state(reg, known_reg);
16377 			/*
16378 			 * Must preserve off, id and add_const flag,
16379 			 * otherwise another sync_linked_regs() will be incorrect.
16380 			 */
16381 			reg->off = saved_off;
16382 			reg->subreg_def = saved_subreg_def;
16383 
16384 			scalar32_min_max_add(reg, &fake_reg);
16385 			scalar_min_max_add(reg, &fake_reg);
16386 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
16387 		}
16388 	}
16389 }
16390 
16391 static int check_cond_jmp_op(struct bpf_verifier_env *env,
16392 			     struct bpf_insn *insn, int *insn_idx)
16393 {
16394 	struct bpf_verifier_state *this_branch = env->cur_state;
16395 	struct bpf_verifier_state *other_branch;
16396 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
16397 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
16398 	struct bpf_reg_state *eq_branch_regs;
16399 	struct linked_regs linked_regs = {};
16400 	u8 opcode = BPF_OP(insn->code);
16401 	int insn_flags = 0;
16402 	bool is_jmp32;
16403 	int pred = -1;
16404 	int err;
16405 
16406 	/* Only conditional jumps are expected to reach here. */
16407 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
16408 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
16409 		return -EINVAL;
16410 	}
16411 
16412 	if (opcode == BPF_JCOND) {
16413 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
16414 		int idx = *insn_idx;
16415 
16416 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
16417 		    insn->src_reg != BPF_MAY_GOTO ||
16418 		    insn->dst_reg || insn->imm) {
16419 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
16420 			return -EINVAL;
16421 		}
16422 		prev_st = find_prev_entry(env, cur_st->parent, idx);
16423 
16424 		/* branch out 'fallthrough' insn as a new state to explore */
16425 		queued_st = push_stack(env, idx + 1, idx, false);
16426 		if (!queued_st)
16427 			return -ENOMEM;
16428 
16429 		queued_st->may_goto_depth++;
16430 		if (prev_st)
16431 			widen_imprecise_scalars(env, prev_st, queued_st);
16432 		*insn_idx += insn->off;
16433 		return 0;
16434 	}
16435 
16436 	/* check src2 operand */
16437 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16438 	if (err)
16439 		return err;
16440 
16441 	dst_reg = &regs[insn->dst_reg];
16442 	if (BPF_SRC(insn->code) == BPF_X) {
16443 		if (insn->imm != 0) {
16444 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16445 			return -EINVAL;
16446 		}
16447 
16448 		/* check src1 operand */
16449 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16450 		if (err)
16451 			return err;
16452 
16453 		src_reg = &regs[insn->src_reg];
16454 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
16455 		    is_pointer_value(env, insn->src_reg)) {
16456 			verbose(env, "R%d pointer comparison prohibited\n",
16457 				insn->src_reg);
16458 			return -EACCES;
16459 		}
16460 
16461 		if (src_reg->type == PTR_TO_STACK)
16462 			insn_flags |= INSN_F_SRC_REG_STACK;
16463 		if (dst_reg->type == PTR_TO_STACK)
16464 			insn_flags |= INSN_F_DST_REG_STACK;
16465 	} else {
16466 		if (insn->src_reg != BPF_REG_0) {
16467 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16468 			return -EINVAL;
16469 		}
16470 		src_reg = &env->fake_reg[0];
16471 		memset(src_reg, 0, sizeof(*src_reg));
16472 		src_reg->type = SCALAR_VALUE;
16473 		__mark_reg_known(src_reg, insn->imm);
16474 
16475 		if (dst_reg->type == PTR_TO_STACK)
16476 			insn_flags |= INSN_F_DST_REG_STACK;
16477 	}
16478 
16479 	if (insn_flags) {
16480 		err = push_insn_history(env, this_branch, insn_flags, 0);
16481 		if (err)
16482 			return err;
16483 	}
16484 
16485 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
16486 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
16487 	if (pred >= 0) {
16488 		/* If we get here with a dst_reg pointer type it is because
16489 		 * above is_branch_taken() special cased the 0 comparison.
16490 		 */
16491 		if (!__is_pointer_value(false, dst_reg))
16492 			err = mark_chain_precision(env, insn->dst_reg);
16493 		if (BPF_SRC(insn->code) == BPF_X && !err &&
16494 		    !__is_pointer_value(false, src_reg))
16495 			err = mark_chain_precision(env, insn->src_reg);
16496 		if (err)
16497 			return err;
16498 	}
16499 
16500 	if (pred == 1) {
16501 		/* Only follow the goto, ignore fall-through. If needed, push
16502 		 * the fall-through branch for simulation under speculative
16503 		 * execution.
16504 		 */
16505 		if (!env->bypass_spec_v1 &&
16506 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
16507 					       *insn_idx))
16508 			return -EFAULT;
16509 		if (env->log.level & BPF_LOG_LEVEL)
16510 			print_insn_state(env, this_branch, this_branch->curframe);
16511 		*insn_idx += insn->off;
16512 		return 0;
16513 	} else if (pred == 0) {
16514 		/* Only follow the fall-through branch, since that's where the
16515 		 * program will go. If needed, push the goto branch for
16516 		 * simulation under speculative execution.
16517 		 */
16518 		if (!env->bypass_spec_v1 &&
16519 		    !sanitize_speculative_path(env, insn,
16520 					       *insn_idx + insn->off + 1,
16521 					       *insn_idx))
16522 			return -EFAULT;
16523 		if (env->log.level & BPF_LOG_LEVEL)
16524 			print_insn_state(env, this_branch, this_branch->curframe);
16525 		return 0;
16526 	}
16527 
16528 	/* Push scalar registers sharing same ID to jump history,
16529 	 * do this before creating 'other_branch', so that both
16530 	 * 'this_branch' and 'other_branch' share this history
16531 	 * if parent state is created.
16532 	 */
16533 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
16534 		collect_linked_regs(this_branch, src_reg->id, &linked_regs);
16535 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
16536 		collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
16537 	if (linked_regs.cnt > 1) {
16538 		err = push_insn_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
16539 		if (err)
16540 			return err;
16541 	}
16542 
16543 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
16544 				  false);
16545 	if (!other_branch)
16546 		return -EFAULT;
16547 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
16548 
16549 	if (BPF_SRC(insn->code) == BPF_X) {
16550 		err = reg_set_min_max(env,
16551 				      &other_branch_regs[insn->dst_reg],
16552 				      &other_branch_regs[insn->src_reg],
16553 				      dst_reg, src_reg, opcode, is_jmp32);
16554 	} else /* BPF_SRC(insn->code) == BPF_K */ {
16555 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
16556 		 * so that these are two different memory locations. The
16557 		 * src_reg is not used beyond here in context of K.
16558 		 */
16559 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
16560 		       sizeof(env->fake_reg[0]));
16561 		err = reg_set_min_max(env,
16562 				      &other_branch_regs[insn->dst_reg],
16563 				      &env->fake_reg[0],
16564 				      dst_reg, &env->fake_reg[1],
16565 				      opcode, is_jmp32);
16566 	}
16567 	if (err)
16568 		return err;
16569 
16570 	if (BPF_SRC(insn->code) == BPF_X &&
16571 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
16572 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
16573 		sync_linked_regs(this_branch, src_reg, &linked_regs);
16574 		sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
16575 	}
16576 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
16577 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
16578 		sync_linked_regs(this_branch, dst_reg, &linked_regs);
16579 		sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
16580 	}
16581 
16582 	/* if one pointer register is compared to another pointer
16583 	 * register check if PTR_MAYBE_NULL could be lifted.
16584 	 * E.g. register A - maybe null
16585 	 *      register B - not null
16586 	 * for JNE A, B, ... - A is not null in the false branch;
16587 	 * for JEQ A, B, ... - A is not null in the true branch.
16588 	 *
16589 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
16590 	 * not need to be null checked by the BPF program, i.e.,
16591 	 * could be null even without PTR_MAYBE_NULL marking, so
16592 	 * only propagate nullness when neither reg is that type.
16593 	 */
16594 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
16595 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
16596 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
16597 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
16598 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
16599 		eq_branch_regs = NULL;
16600 		switch (opcode) {
16601 		case BPF_JEQ:
16602 			eq_branch_regs = other_branch_regs;
16603 			break;
16604 		case BPF_JNE:
16605 			eq_branch_regs = regs;
16606 			break;
16607 		default:
16608 			/* do nothing */
16609 			break;
16610 		}
16611 		if (eq_branch_regs) {
16612 			if (type_may_be_null(src_reg->type))
16613 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
16614 			else
16615 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
16616 		}
16617 	}
16618 
16619 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
16620 	 * NOTE: these optimizations below are related with pointer comparison
16621 	 *       which will never be JMP32.
16622 	 */
16623 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
16624 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
16625 	    type_may_be_null(dst_reg->type)) {
16626 		/* Mark all identical registers in each branch as either
16627 		 * safe or unknown depending R == 0 or R != 0 conditional.
16628 		 */
16629 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
16630 				      opcode == BPF_JNE);
16631 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
16632 				      opcode == BPF_JEQ);
16633 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
16634 					   this_branch, other_branch) &&
16635 		   is_pointer_value(env, insn->dst_reg)) {
16636 		verbose(env, "R%d pointer comparison prohibited\n",
16637 			insn->dst_reg);
16638 		return -EACCES;
16639 	}
16640 	if (env->log.level & BPF_LOG_LEVEL)
16641 		print_insn_state(env, this_branch, this_branch->curframe);
16642 	return 0;
16643 }
16644 
16645 /* verify BPF_LD_IMM64 instruction */
16646 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
16647 {
16648 	struct bpf_insn_aux_data *aux = cur_aux(env);
16649 	struct bpf_reg_state *regs = cur_regs(env);
16650 	struct bpf_reg_state *dst_reg;
16651 	struct bpf_map *map;
16652 	int err;
16653 
16654 	if (BPF_SIZE(insn->code) != BPF_DW) {
16655 		verbose(env, "invalid BPF_LD_IMM insn\n");
16656 		return -EINVAL;
16657 	}
16658 	if (insn->off != 0) {
16659 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
16660 		return -EINVAL;
16661 	}
16662 
16663 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
16664 	if (err)
16665 		return err;
16666 
16667 	dst_reg = &regs[insn->dst_reg];
16668 	if (insn->src_reg == 0) {
16669 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
16670 
16671 		dst_reg->type = SCALAR_VALUE;
16672 		__mark_reg_known(&regs[insn->dst_reg], imm);
16673 		return 0;
16674 	}
16675 
16676 	/* All special src_reg cases are listed below. From this point onwards
16677 	 * we either succeed and assign a corresponding dst_reg->type after
16678 	 * zeroing the offset, or fail and reject the program.
16679 	 */
16680 	mark_reg_known_zero(env, regs, insn->dst_reg);
16681 
16682 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
16683 		dst_reg->type = aux->btf_var.reg_type;
16684 		switch (base_type(dst_reg->type)) {
16685 		case PTR_TO_MEM:
16686 			dst_reg->mem_size = aux->btf_var.mem_size;
16687 			break;
16688 		case PTR_TO_BTF_ID:
16689 			dst_reg->btf = aux->btf_var.btf;
16690 			dst_reg->btf_id = aux->btf_var.btf_id;
16691 			break;
16692 		default:
16693 			verbose(env, "bpf verifier is misconfigured\n");
16694 			return -EFAULT;
16695 		}
16696 		return 0;
16697 	}
16698 
16699 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
16700 		struct bpf_prog_aux *aux = env->prog->aux;
16701 		u32 subprogno = find_subprog(env,
16702 					     env->insn_idx + insn->imm + 1);
16703 
16704 		if (!aux->func_info) {
16705 			verbose(env, "missing btf func_info\n");
16706 			return -EINVAL;
16707 		}
16708 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
16709 			verbose(env, "callback function not static\n");
16710 			return -EINVAL;
16711 		}
16712 
16713 		dst_reg->type = PTR_TO_FUNC;
16714 		dst_reg->subprogno = subprogno;
16715 		return 0;
16716 	}
16717 
16718 	map = env->used_maps[aux->map_index];
16719 	dst_reg->map_ptr = map;
16720 
16721 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
16722 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
16723 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
16724 			__mark_reg_unknown(env, dst_reg);
16725 			return 0;
16726 		}
16727 		dst_reg->type = PTR_TO_MAP_VALUE;
16728 		dst_reg->off = aux->map_off;
16729 		WARN_ON_ONCE(map->max_entries != 1);
16730 		/* We want reg->id to be same (0) as map_value is not distinct */
16731 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
16732 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
16733 		dst_reg->type = CONST_PTR_TO_MAP;
16734 	} else {
16735 		verbose(env, "bpf verifier is misconfigured\n");
16736 		return -EINVAL;
16737 	}
16738 
16739 	return 0;
16740 }
16741 
16742 static bool may_access_skb(enum bpf_prog_type type)
16743 {
16744 	switch (type) {
16745 	case BPF_PROG_TYPE_SOCKET_FILTER:
16746 	case BPF_PROG_TYPE_SCHED_CLS:
16747 	case BPF_PROG_TYPE_SCHED_ACT:
16748 		return true;
16749 	default:
16750 		return false;
16751 	}
16752 }
16753 
16754 /* verify safety of LD_ABS|LD_IND instructions:
16755  * - they can only appear in the programs where ctx == skb
16756  * - since they are wrappers of function calls, they scratch R1-R5 registers,
16757  *   preserve R6-R9, and store return value into R0
16758  *
16759  * Implicit input:
16760  *   ctx == skb == R6 == CTX
16761  *
16762  * Explicit input:
16763  *   SRC == any register
16764  *   IMM == 32-bit immediate
16765  *
16766  * Output:
16767  *   R0 - 8/16/32-bit skb data converted to cpu endianness
16768  */
16769 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
16770 {
16771 	struct bpf_reg_state *regs = cur_regs(env);
16772 	static const int ctx_reg = BPF_REG_6;
16773 	u8 mode = BPF_MODE(insn->code);
16774 	int i, err;
16775 
16776 	if (!may_access_skb(resolve_prog_type(env->prog))) {
16777 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
16778 		return -EINVAL;
16779 	}
16780 
16781 	if (!env->ops->gen_ld_abs) {
16782 		verbose(env, "bpf verifier is misconfigured\n");
16783 		return -EINVAL;
16784 	}
16785 
16786 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
16787 	    BPF_SIZE(insn->code) == BPF_DW ||
16788 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
16789 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
16790 		return -EINVAL;
16791 	}
16792 
16793 	/* check whether implicit source operand (register R6) is readable */
16794 	err = check_reg_arg(env, ctx_reg, SRC_OP);
16795 	if (err)
16796 		return err;
16797 
16798 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
16799 	 * gen_ld_abs() may terminate the program at runtime, leading to
16800 	 * reference leak.
16801 	 */
16802 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
16803 	if (err)
16804 		return err;
16805 
16806 	if (regs[ctx_reg].type != PTR_TO_CTX) {
16807 		verbose(env,
16808 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
16809 		return -EINVAL;
16810 	}
16811 
16812 	if (mode == BPF_IND) {
16813 		/* check explicit source operand */
16814 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16815 		if (err)
16816 			return err;
16817 	}
16818 
16819 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
16820 	if (err < 0)
16821 		return err;
16822 
16823 	/* reset caller saved regs to unreadable */
16824 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
16825 		mark_reg_not_init(env, regs, caller_saved[i]);
16826 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
16827 	}
16828 
16829 	/* mark destination R0 register as readable, since it contains
16830 	 * the value fetched from the packet.
16831 	 * Already marked as written above.
16832 	 */
16833 	mark_reg_unknown(env, regs, BPF_REG_0);
16834 	/* ld_abs load up to 32-bit skb data. */
16835 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
16836 	return 0;
16837 }
16838 
16839 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
16840 {
16841 	const char *exit_ctx = "At program exit";
16842 	struct tnum enforce_attach_type_range = tnum_unknown;
16843 	const struct bpf_prog *prog = env->prog;
16844 	struct bpf_reg_state *reg = reg_state(env, regno);
16845 	struct bpf_retval_range range = retval_range(0, 1);
16846 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
16847 	int err;
16848 	struct bpf_func_state *frame = env->cur_state->frame[0];
16849 	const bool is_subprog = frame->subprogno;
16850 	bool return_32bit = false;
16851 	const struct btf_type *reg_type, *ret_type = NULL;
16852 
16853 	/* LSM and struct_ops func-ptr's return type could be "void" */
16854 	if (!is_subprog || frame->in_exception_callback_fn) {
16855 		switch (prog_type) {
16856 		case BPF_PROG_TYPE_LSM:
16857 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
16858 				/* See below, can be 0 or 0-1 depending on hook. */
16859 				break;
16860 			if (!prog->aux->attach_func_proto->type)
16861 				return 0;
16862 			break;
16863 		case BPF_PROG_TYPE_STRUCT_OPS:
16864 			if (!prog->aux->attach_func_proto->type)
16865 				return 0;
16866 
16867 			if (frame->in_exception_callback_fn)
16868 				break;
16869 
16870 			/* Allow a struct_ops program to return a referenced kptr if it
16871 			 * matches the operator's return type and is in its unmodified
16872 			 * form. A scalar zero (i.e., a null pointer) is also allowed.
16873 			 */
16874 			reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
16875 			ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
16876 							prog->aux->attach_func_proto->type,
16877 							NULL);
16878 			if (ret_type && ret_type == reg_type && reg->ref_obj_id)
16879 				return __check_ptr_off_reg(env, reg, regno, false);
16880 			break;
16881 		default:
16882 			break;
16883 		}
16884 	}
16885 
16886 	/* eBPF calling convention is such that R0 is used
16887 	 * to return the value from eBPF program.
16888 	 * Make sure that it's readable at this time
16889 	 * of bpf_exit, which means that program wrote
16890 	 * something into it earlier
16891 	 */
16892 	err = check_reg_arg(env, regno, SRC_OP);
16893 	if (err)
16894 		return err;
16895 
16896 	if (is_pointer_value(env, regno)) {
16897 		verbose(env, "R%d leaks addr as return value\n", regno);
16898 		return -EACCES;
16899 	}
16900 
16901 	if (frame->in_async_callback_fn) {
16902 		/* enforce return zero from async callbacks like timer */
16903 		exit_ctx = "At async callback return";
16904 		range = retval_range(0, 0);
16905 		goto enforce_retval;
16906 	}
16907 
16908 	if (is_subprog && !frame->in_exception_callback_fn) {
16909 		if (reg->type != SCALAR_VALUE) {
16910 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
16911 				regno, reg_type_str(env, reg->type));
16912 			return -EINVAL;
16913 		}
16914 		return 0;
16915 	}
16916 
16917 	switch (prog_type) {
16918 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
16919 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
16920 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
16921 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
16922 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
16923 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
16924 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
16925 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
16926 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
16927 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
16928 			range = retval_range(1, 1);
16929 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
16930 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
16931 			range = retval_range(0, 3);
16932 		break;
16933 	case BPF_PROG_TYPE_CGROUP_SKB:
16934 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
16935 			range = retval_range(0, 3);
16936 			enforce_attach_type_range = tnum_range(2, 3);
16937 		}
16938 		break;
16939 	case BPF_PROG_TYPE_CGROUP_SOCK:
16940 	case BPF_PROG_TYPE_SOCK_OPS:
16941 	case BPF_PROG_TYPE_CGROUP_DEVICE:
16942 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
16943 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
16944 		break;
16945 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
16946 		if (!env->prog->aux->attach_btf_id)
16947 			return 0;
16948 		range = retval_range(0, 0);
16949 		break;
16950 	case BPF_PROG_TYPE_TRACING:
16951 		switch (env->prog->expected_attach_type) {
16952 		case BPF_TRACE_FENTRY:
16953 		case BPF_TRACE_FEXIT:
16954 			range = retval_range(0, 0);
16955 			break;
16956 		case BPF_TRACE_RAW_TP:
16957 		case BPF_MODIFY_RETURN:
16958 			return 0;
16959 		case BPF_TRACE_ITER:
16960 			break;
16961 		default:
16962 			return -ENOTSUPP;
16963 		}
16964 		break;
16965 	case BPF_PROG_TYPE_KPROBE:
16966 		switch (env->prog->expected_attach_type) {
16967 		case BPF_TRACE_KPROBE_SESSION:
16968 		case BPF_TRACE_UPROBE_SESSION:
16969 			range = retval_range(0, 1);
16970 			break;
16971 		default:
16972 			return 0;
16973 		}
16974 		break;
16975 	case BPF_PROG_TYPE_SK_LOOKUP:
16976 		range = retval_range(SK_DROP, SK_PASS);
16977 		break;
16978 
16979 	case BPF_PROG_TYPE_LSM:
16980 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
16981 			/* no range found, any return value is allowed */
16982 			if (!get_func_retval_range(env->prog, &range))
16983 				return 0;
16984 			/* no restricted range, any return value is allowed */
16985 			if (range.minval == S32_MIN && range.maxval == S32_MAX)
16986 				return 0;
16987 			return_32bit = true;
16988 		} else if (!env->prog->aux->attach_func_proto->type) {
16989 			/* Make sure programs that attach to void
16990 			 * hooks don't try to modify return value.
16991 			 */
16992 			range = retval_range(1, 1);
16993 		}
16994 		break;
16995 
16996 	case BPF_PROG_TYPE_NETFILTER:
16997 		range = retval_range(NF_DROP, NF_ACCEPT);
16998 		break;
16999 	case BPF_PROG_TYPE_STRUCT_OPS:
17000 		if (!ret_type)
17001 			return 0;
17002 		range = retval_range(0, 0);
17003 		break;
17004 	case BPF_PROG_TYPE_EXT:
17005 		/* freplace program can return anything as its return value
17006 		 * depends on the to-be-replaced kernel func or bpf program.
17007 		 */
17008 	default:
17009 		return 0;
17010 	}
17011 
17012 enforce_retval:
17013 	if (reg->type != SCALAR_VALUE) {
17014 		verbose(env, "%s the register R%d is not a known value (%s)\n",
17015 			exit_ctx, regno, reg_type_str(env, reg->type));
17016 		return -EINVAL;
17017 	}
17018 
17019 	err = mark_chain_precision(env, regno);
17020 	if (err)
17021 		return err;
17022 
17023 	if (!retval_range_within(range, reg, return_32bit)) {
17024 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
17025 		if (!is_subprog &&
17026 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
17027 		    prog_type == BPF_PROG_TYPE_LSM &&
17028 		    !prog->aux->attach_func_proto->type)
17029 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
17030 		return -EINVAL;
17031 	}
17032 
17033 	if (!tnum_is_unknown(enforce_attach_type_range) &&
17034 	    tnum_in(enforce_attach_type_range, reg->var_off))
17035 		env->prog->enforce_expected_attach_type = 1;
17036 	return 0;
17037 }
17038 
17039 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
17040 {
17041 	struct bpf_subprog_info *subprog;
17042 
17043 	subprog = find_containing_subprog(env, off);
17044 	subprog->changes_pkt_data = true;
17045 }
17046 
17047 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off)
17048 {
17049 	struct bpf_subprog_info *subprog;
17050 
17051 	subprog = find_containing_subprog(env, off);
17052 	subprog->might_sleep = true;
17053 }
17054 
17055 /* 't' is an index of a call-site.
17056  * 'w' is a callee entry point.
17057  * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
17058  * Rely on DFS traversal order and absence of recursive calls to guarantee that
17059  * callee's change_pkt_data marks would be correct at that moment.
17060  */
17061 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
17062 {
17063 	struct bpf_subprog_info *caller, *callee;
17064 
17065 	caller = find_containing_subprog(env, t);
17066 	callee = find_containing_subprog(env, w);
17067 	caller->changes_pkt_data |= callee->changes_pkt_data;
17068 	caller->might_sleep |= callee->might_sleep;
17069 }
17070 
17071 /* non-recursive DFS pseudo code
17072  * 1  procedure DFS-iterative(G,v):
17073  * 2      label v as discovered
17074  * 3      let S be a stack
17075  * 4      S.push(v)
17076  * 5      while S is not empty
17077  * 6            t <- S.peek()
17078  * 7            if t is what we're looking for:
17079  * 8                return t
17080  * 9            for all edges e in G.adjacentEdges(t) do
17081  * 10               if edge e is already labelled
17082  * 11                   continue with the next edge
17083  * 12               w <- G.adjacentVertex(t,e)
17084  * 13               if vertex w is not discovered and not explored
17085  * 14                   label e as tree-edge
17086  * 15                   label w as discovered
17087  * 16                   S.push(w)
17088  * 17                   continue at 5
17089  * 18               else if vertex w is discovered
17090  * 19                   label e as back-edge
17091  * 20               else
17092  * 21                   // vertex w is explored
17093  * 22                   label e as forward- or cross-edge
17094  * 23           label t as explored
17095  * 24           S.pop()
17096  *
17097  * convention:
17098  * 0x10 - discovered
17099  * 0x11 - discovered and fall-through edge labelled
17100  * 0x12 - discovered and fall-through and branch edges labelled
17101  * 0x20 - explored
17102  */
17103 
17104 enum {
17105 	DISCOVERED = 0x10,
17106 	EXPLORED = 0x20,
17107 	FALLTHROUGH = 1,
17108 	BRANCH = 2,
17109 };
17110 
17111 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
17112 {
17113 	env->insn_aux_data[idx].prune_point = true;
17114 }
17115 
17116 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
17117 {
17118 	return env->insn_aux_data[insn_idx].prune_point;
17119 }
17120 
17121 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
17122 {
17123 	env->insn_aux_data[idx].force_checkpoint = true;
17124 }
17125 
17126 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
17127 {
17128 	return env->insn_aux_data[insn_idx].force_checkpoint;
17129 }
17130 
17131 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
17132 {
17133 	env->insn_aux_data[idx].calls_callback = true;
17134 }
17135 
17136 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
17137 {
17138 	return env->insn_aux_data[insn_idx].calls_callback;
17139 }
17140 
17141 enum {
17142 	DONE_EXPLORING = 0,
17143 	KEEP_EXPLORING = 1,
17144 };
17145 
17146 /* t, w, e - match pseudo-code above:
17147  * t - index of current instruction
17148  * w - next instruction
17149  * e - edge
17150  */
17151 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
17152 {
17153 	int *insn_stack = env->cfg.insn_stack;
17154 	int *insn_state = env->cfg.insn_state;
17155 
17156 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
17157 		return DONE_EXPLORING;
17158 
17159 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
17160 		return DONE_EXPLORING;
17161 
17162 	if (w < 0 || w >= env->prog->len) {
17163 		verbose_linfo(env, t, "%d: ", t);
17164 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
17165 		return -EINVAL;
17166 	}
17167 
17168 	if (e == BRANCH) {
17169 		/* mark branch target for state pruning */
17170 		mark_prune_point(env, w);
17171 		mark_jmp_point(env, w);
17172 	}
17173 
17174 	if (insn_state[w] == 0) {
17175 		/* tree-edge */
17176 		insn_state[t] = DISCOVERED | e;
17177 		insn_state[w] = DISCOVERED;
17178 		if (env->cfg.cur_stack >= env->prog->len)
17179 			return -E2BIG;
17180 		insn_stack[env->cfg.cur_stack++] = w;
17181 		return KEEP_EXPLORING;
17182 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
17183 		if (env->bpf_capable)
17184 			return DONE_EXPLORING;
17185 		verbose_linfo(env, t, "%d: ", t);
17186 		verbose_linfo(env, w, "%d: ", w);
17187 		verbose(env, "back-edge from insn %d to %d\n", t, w);
17188 		return -EINVAL;
17189 	} else if (insn_state[w] == EXPLORED) {
17190 		/* forward- or cross-edge */
17191 		insn_state[t] = DISCOVERED | e;
17192 	} else {
17193 		verbose(env, "insn state internal bug\n");
17194 		return -EFAULT;
17195 	}
17196 	return DONE_EXPLORING;
17197 }
17198 
17199 static int visit_func_call_insn(int t, struct bpf_insn *insns,
17200 				struct bpf_verifier_env *env,
17201 				bool visit_callee)
17202 {
17203 	int ret, insn_sz;
17204 	int w;
17205 
17206 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
17207 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
17208 	if (ret)
17209 		return ret;
17210 
17211 	mark_prune_point(env, t + insn_sz);
17212 	/* when we exit from subprog, we need to record non-linear history */
17213 	mark_jmp_point(env, t + insn_sz);
17214 
17215 	if (visit_callee) {
17216 		w = t + insns[t].imm + 1;
17217 		mark_prune_point(env, t);
17218 		merge_callee_effects(env, t, w);
17219 		ret = push_insn(t, w, BRANCH, env);
17220 	}
17221 	return ret;
17222 }
17223 
17224 /* Bitmask with 1s for all caller saved registers */
17225 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
17226 
17227 /* True if do_misc_fixups() replaces calls to helper number 'imm',
17228  * replacement patch is presumed to follow bpf_fastcall contract
17229  * (see mark_fastcall_pattern_for_call() below).
17230  */
17231 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
17232 {
17233 	switch (imm) {
17234 #ifdef CONFIG_X86_64
17235 	case BPF_FUNC_get_smp_processor_id:
17236 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
17237 #endif
17238 	default:
17239 		return false;
17240 	}
17241 }
17242 
17243 struct call_summary {
17244 	u8 num_params;
17245 	bool is_void;
17246 	bool fastcall;
17247 };
17248 
17249 /* If @call is a kfunc or helper call, fills @cs and returns true,
17250  * otherwise returns false.
17251  */
17252 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
17253 			     struct call_summary *cs)
17254 {
17255 	struct bpf_kfunc_call_arg_meta meta;
17256 	const struct bpf_func_proto *fn;
17257 	int i;
17258 
17259 	if (bpf_helper_call(call)) {
17260 
17261 		if (get_helper_proto(env, call->imm, &fn) < 0)
17262 			/* error would be reported later */
17263 			return false;
17264 		cs->fastcall = fn->allow_fastcall &&
17265 			       (verifier_inlines_helper_call(env, call->imm) ||
17266 				bpf_jit_inlines_helper_call(call->imm));
17267 		cs->is_void = fn->ret_type == RET_VOID;
17268 		cs->num_params = 0;
17269 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
17270 			if (fn->arg_type[i] == ARG_DONTCARE)
17271 				break;
17272 			cs->num_params++;
17273 		}
17274 		return true;
17275 	}
17276 
17277 	if (bpf_pseudo_kfunc_call(call)) {
17278 		int err;
17279 
17280 		err = fetch_kfunc_meta(env, call, &meta, NULL);
17281 		if (err < 0)
17282 			/* error would be reported later */
17283 			return false;
17284 		cs->num_params = btf_type_vlen(meta.func_proto);
17285 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
17286 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
17287 		return true;
17288 	}
17289 
17290 	return false;
17291 }
17292 
17293 /* LLVM define a bpf_fastcall function attribute.
17294  * This attribute means that function scratches only some of
17295  * the caller saved registers defined by ABI.
17296  * For BPF the set of such registers could be defined as follows:
17297  * - R0 is scratched only if function is non-void;
17298  * - R1-R5 are scratched only if corresponding parameter type is defined
17299  *   in the function prototype.
17300  *
17301  * The contract between kernel and clang allows to simultaneously use
17302  * such functions and maintain backwards compatibility with old
17303  * kernels that don't understand bpf_fastcall calls:
17304  *
17305  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
17306  *   registers are not scratched by the call;
17307  *
17308  * - as a post-processing step, clang visits each bpf_fastcall call and adds
17309  *   spill/fill for every live r0-r5;
17310  *
17311  * - stack offsets used for the spill/fill are allocated as lowest
17312  *   stack offsets in whole function and are not used for any other
17313  *   purposes;
17314  *
17315  * - when kernel loads a program, it looks for such patterns
17316  *   (bpf_fastcall function surrounded by spills/fills) and checks if
17317  *   spill/fill stack offsets are used exclusively in fastcall patterns;
17318  *
17319  * - if so, and if verifier or current JIT inlines the call to the
17320  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
17321  *   spill/fill pairs;
17322  *
17323  * - when old kernel loads a program, presence of spill/fill pairs
17324  *   keeps BPF program valid, albeit slightly less efficient.
17325  *
17326  * For example:
17327  *
17328  *   r1 = 1;
17329  *   r2 = 2;
17330  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17331  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
17332  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17333  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
17334  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
17335  *   r0 = r1;                            exit;
17336  *   r0 += r2;
17337  *   exit;
17338  *
17339  * The purpose of mark_fastcall_pattern_for_call is to:
17340  * - look for such patterns;
17341  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
17342  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
17343  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
17344  *   at which bpf_fastcall spill/fill stack slots start;
17345  * - update env->subprog_info[*]->keep_fastcall_stack.
17346  *
17347  * The .fastcall_pattern and .fastcall_stack_off are used by
17348  * check_fastcall_stack_contract() to check if every stack access to
17349  * fastcall spill/fill stack slot originates from spill/fill
17350  * instructions, members of fastcall patterns.
17351  *
17352  * If such condition holds true for a subprogram, fastcall patterns could
17353  * be rewritten by remove_fastcall_spills_fills().
17354  * Otherwise bpf_fastcall patterns are not changed in the subprogram
17355  * (code, presumably, generated by an older clang version).
17356  *
17357  * For example, it is *not* safe to remove spill/fill below:
17358  *
17359  *   r1 = 1;
17360  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17361  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17362  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
17363  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
17364  *   r0 += r1;                           exit;
17365  *   exit;
17366  */
17367 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
17368 					   struct bpf_subprog_info *subprog,
17369 					   int insn_idx, s16 lowest_off)
17370 {
17371 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
17372 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
17373 	u32 clobbered_regs_mask;
17374 	struct call_summary cs;
17375 	u32 expected_regs_mask;
17376 	s16 off;
17377 	int i;
17378 
17379 	if (!get_call_summary(env, call, &cs))
17380 		return;
17381 
17382 	/* A bitmask specifying which caller saved registers are clobbered
17383 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
17384 	 * bpf_fastcall contract:
17385 	 * - includes R0 if function is non-void;
17386 	 * - includes R1-R5 if corresponding parameter has is described
17387 	 *   in the function prototype.
17388 	 */
17389 	clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
17390 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
17391 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
17392 
17393 	/* match pairs of form:
17394 	 *
17395 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
17396 	 * ...
17397 	 * call %[to_be_inlined]
17398 	 * ...
17399 	 * rX = *(u64 *)(r10 - Y)
17400 	 */
17401 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
17402 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
17403 			break;
17404 		stx = &insns[insn_idx - i];
17405 		ldx = &insns[insn_idx + i];
17406 		/* must be a stack spill/fill pair */
17407 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17408 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
17409 		    stx->dst_reg != BPF_REG_10 ||
17410 		    ldx->src_reg != BPF_REG_10)
17411 			break;
17412 		/* must be a spill/fill for the same reg */
17413 		if (stx->src_reg != ldx->dst_reg)
17414 			break;
17415 		/* must be one of the previously unseen registers */
17416 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
17417 			break;
17418 		/* must be a spill/fill for the same expected offset,
17419 		 * no need to check offset alignment, BPF_DW stack access
17420 		 * is always 8-byte aligned.
17421 		 */
17422 		if (stx->off != off || ldx->off != off)
17423 			break;
17424 		expected_regs_mask &= ~BIT(stx->src_reg);
17425 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
17426 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
17427 	}
17428 	if (i == 1)
17429 		return;
17430 
17431 	/* Conditionally set 'fastcall_spills_num' to allow forward
17432 	 * compatibility when more helper functions are marked as
17433 	 * bpf_fastcall at compile time than current kernel supports, e.g:
17434 	 *
17435 	 *   1: *(u64 *)(r10 - 8) = r1
17436 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
17437 	 *   3: r1 = *(u64 *)(r10 - 8)
17438 	 *   4: *(u64 *)(r10 - 8) = r1
17439 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
17440 	 *   6: r1 = *(u64 *)(r10 - 8)
17441 	 *
17442 	 * There is no need to block bpf_fastcall rewrite for such program.
17443 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
17444 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
17445 	 * does not remove spill/fill pair {4,6}.
17446 	 */
17447 	if (cs.fastcall)
17448 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
17449 	else
17450 		subprog->keep_fastcall_stack = 1;
17451 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
17452 }
17453 
17454 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
17455 {
17456 	struct bpf_subprog_info *subprog = env->subprog_info;
17457 	struct bpf_insn *insn;
17458 	s16 lowest_off;
17459 	int s, i;
17460 
17461 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
17462 		/* find lowest stack spill offset used in this subprog */
17463 		lowest_off = 0;
17464 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17465 			insn = env->prog->insnsi + i;
17466 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17467 			    insn->dst_reg != BPF_REG_10)
17468 				continue;
17469 			lowest_off = min(lowest_off, insn->off);
17470 		}
17471 		/* use this offset to find fastcall patterns */
17472 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17473 			insn = env->prog->insnsi + i;
17474 			if (insn->code != (BPF_JMP | BPF_CALL))
17475 				continue;
17476 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
17477 		}
17478 	}
17479 	return 0;
17480 }
17481 
17482 /* Visits the instruction at index t and returns one of the following:
17483  *  < 0 - an error occurred
17484  *  DONE_EXPLORING - the instruction was fully explored
17485  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
17486  */
17487 static int visit_insn(int t, struct bpf_verifier_env *env)
17488 {
17489 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
17490 	int ret, off, insn_sz;
17491 
17492 	if (bpf_pseudo_func(insn))
17493 		return visit_func_call_insn(t, insns, env, true);
17494 
17495 	/* All non-branch instructions have a single fall-through edge. */
17496 	if (BPF_CLASS(insn->code) != BPF_JMP &&
17497 	    BPF_CLASS(insn->code) != BPF_JMP32) {
17498 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
17499 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
17500 	}
17501 
17502 	switch (BPF_OP(insn->code)) {
17503 	case BPF_EXIT:
17504 		return DONE_EXPLORING;
17505 
17506 	case BPF_CALL:
17507 		if (is_async_callback_calling_insn(insn))
17508 			/* Mark this call insn as a prune point to trigger
17509 			 * is_state_visited() check before call itself is
17510 			 * processed by __check_func_call(). Otherwise new
17511 			 * async state will be pushed for further exploration.
17512 			 */
17513 			mark_prune_point(env, t);
17514 		/* For functions that invoke callbacks it is not known how many times
17515 		 * callback would be called. Verifier models callback calling functions
17516 		 * by repeatedly visiting callback bodies and returning to origin call
17517 		 * instruction.
17518 		 * In order to stop such iteration verifier needs to identify when a
17519 		 * state identical some state from a previous iteration is reached.
17520 		 * Check below forces creation of checkpoint before callback calling
17521 		 * instruction to allow search for such identical states.
17522 		 */
17523 		if (is_sync_callback_calling_insn(insn)) {
17524 			mark_calls_callback(env, t);
17525 			mark_force_checkpoint(env, t);
17526 			mark_prune_point(env, t);
17527 			mark_jmp_point(env, t);
17528 		}
17529 		if (bpf_helper_call(insn)) {
17530 			const struct bpf_func_proto *fp;
17531 
17532 			ret = get_helper_proto(env, insn->imm, &fp);
17533 			/* If called in a non-sleepable context program will be
17534 			 * rejected anyway, so we should end up with precise
17535 			 * sleepable marks on subprogs, except for dead code
17536 			 * elimination.
17537 			 */
17538 			if (ret == 0 && fp->might_sleep)
17539 				mark_subprog_might_sleep(env, t);
17540 			if (bpf_helper_changes_pkt_data(insn->imm))
17541 				mark_subprog_changes_pkt_data(env, t);
17542 		} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17543 			struct bpf_kfunc_call_arg_meta meta;
17544 
17545 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
17546 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
17547 				mark_prune_point(env, t);
17548 				/* Checking and saving state checkpoints at iter_next() call
17549 				 * is crucial for fast convergence of open-coded iterator loop
17550 				 * logic, so we need to force it. If we don't do that,
17551 				 * is_state_visited() might skip saving a checkpoint, causing
17552 				 * unnecessarily long sequence of not checkpointed
17553 				 * instructions and jumps, leading to exhaustion of jump
17554 				 * history buffer, and potentially other undesired outcomes.
17555 				 * It is expected that with correct open-coded iterators
17556 				 * convergence will happen quickly, so we don't run a risk of
17557 				 * exhausting memory.
17558 				 */
17559 				mark_force_checkpoint(env, t);
17560 			}
17561 			/* Same as helpers, if called in a non-sleepable context
17562 			 * program will be rejected anyway, so we should end up
17563 			 * with precise sleepable marks on subprogs, except for
17564 			 * dead code elimination.
17565 			 */
17566 			if (ret == 0 && is_kfunc_sleepable(&meta))
17567 				mark_subprog_might_sleep(env, t);
17568 		}
17569 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
17570 
17571 	case BPF_JA:
17572 		if (BPF_SRC(insn->code) != BPF_K)
17573 			return -EINVAL;
17574 
17575 		if (BPF_CLASS(insn->code) == BPF_JMP)
17576 			off = insn->off;
17577 		else
17578 			off = insn->imm;
17579 
17580 		/* unconditional jump with single edge */
17581 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
17582 		if (ret)
17583 			return ret;
17584 
17585 		mark_prune_point(env, t + off + 1);
17586 		mark_jmp_point(env, t + off + 1);
17587 
17588 		return ret;
17589 
17590 	default:
17591 		/* conditional jump with two edges */
17592 		mark_prune_point(env, t);
17593 		if (is_may_goto_insn(insn))
17594 			mark_force_checkpoint(env, t);
17595 
17596 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
17597 		if (ret)
17598 			return ret;
17599 
17600 		return push_insn(t, t + insn->off + 1, BRANCH, env);
17601 	}
17602 }
17603 
17604 /* non-recursive depth-first-search to detect loops in BPF program
17605  * loop == back-edge in directed graph
17606  */
17607 static int check_cfg(struct bpf_verifier_env *env)
17608 {
17609 	int insn_cnt = env->prog->len;
17610 	int *insn_stack, *insn_state, *insn_postorder;
17611 	int ex_insn_beg, i, ret = 0;
17612 
17613 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
17614 	if (!insn_state)
17615 		return -ENOMEM;
17616 
17617 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
17618 	if (!insn_stack) {
17619 		kvfree(insn_state);
17620 		return -ENOMEM;
17621 	}
17622 
17623 	insn_postorder = env->cfg.insn_postorder = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
17624 	if (!insn_postorder) {
17625 		kvfree(insn_state);
17626 		kvfree(insn_stack);
17627 		return -ENOMEM;
17628 	}
17629 
17630 	ex_insn_beg = env->exception_callback_subprog
17631 		      ? env->subprog_info[env->exception_callback_subprog].start
17632 		      : 0;
17633 
17634 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
17635 	insn_stack[0] = 0; /* 0 is the first instruction */
17636 	env->cfg.cur_stack = 1;
17637 
17638 walk_cfg:
17639 	while (env->cfg.cur_stack > 0) {
17640 		int t = insn_stack[env->cfg.cur_stack - 1];
17641 
17642 		ret = visit_insn(t, env);
17643 		switch (ret) {
17644 		case DONE_EXPLORING:
17645 			insn_state[t] = EXPLORED;
17646 			env->cfg.cur_stack--;
17647 			insn_postorder[env->cfg.cur_postorder++] = t;
17648 			break;
17649 		case KEEP_EXPLORING:
17650 			break;
17651 		default:
17652 			if (ret > 0) {
17653 				verbose(env, "visit_insn internal bug\n");
17654 				ret = -EFAULT;
17655 			}
17656 			goto err_free;
17657 		}
17658 	}
17659 
17660 	if (env->cfg.cur_stack < 0) {
17661 		verbose(env, "pop stack internal bug\n");
17662 		ret = -EFAULT;
17663 		goto err_free;
17664 	}
17665 
17666 	if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) {
17667 		insn_state[ex_insn_beg] = DISCOVERED;
17668 		insn_stack[0] = ex_insn_beg;
17669 		env->cfg.cur_stack = 1;
17670 		goto walk_cfg;
17671 	}
17672 
17673 	for (i = 0; i < insn_cnt; i++) {
17674 		struct bpf_insn *insn = &env->prog->insnsi[i];
17675 
17676 		if (insn_state[i] != EXPLORED) {
17677 			verbose(env, "unreachable insn %d\n", i);
17678 			ret = -EINVAL;
17679 			goto err_free;
17680 		}
17681 		if (bpf_is_ldimm64(insn)) {
17682 			if (insn_state[i + 1] != 0) {
17683 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
17684 				ret = -EINVAL;
17685 				goto err_free;
17686 			}
17687 			i++; /* skip second half of ldimm64 */
17688 		}
17689 	}
17690 	ret = 0; /* cfg looks good */
17691 	env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
17692 	env->prog->aux->might_sleep = env->subprog_info[0].might_sleep;
17693 
17694 err_free:
17695 	kvfree(insn_state);
17696 	kvfree(insn_stack);
17697 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
17698 	return ret;
17699 }
17700 
17701 static int check_abnormal_return(struct bpf_verifier_env *env)
17702 {
17703 	int i;
17704 
17705 	for (i = 1; i < env->subprog_cnt; i++) {
17706 		if (env->subprog_info[i].has_ld_abs) {
17707 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
17708 			return -EINVAL;
17709 		}
17710 		if (env->subprog_info[i].has_tail_call) {
17711 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
17712 			return -EINVAL;
17713 		}
17714 	}
17715 	return 0;
17716 }
17717 
17718 /* The minimum supported BTF func info size */
17719 #define MIN_BPF_FUNCINFO_SIZE	8
17720 #define MAX_FUNCINFO_REC_SIZE	252
17721 
17722 static int check_btf_func_early(struct bpf_verifier_env *env,
17723 				const union bpf_attr *attr,
17724 				bpfptr_t uattr)
17725 {
17726 	u32 krec_size = sizeof(struct bpf_func_info);
17727 	const struct btf_type *type, *func_proto;
17728 	u32 i, nfuncs, urec_size, min_size;
17729 	struct bpf_func_info *krecord;
17730 	struct bpf_prog *prog;
17731 	const struct btf *btf;
17732 	u32 prev_offset = 0;
17733 	bpfptr_t urecord;
17734 	int ret = -ENOMEM;
17735 
17736 	nfuncs = attr->func_info_cnt;
17737 	if (!nfuncs) {
17738 		if (check_abnormal_return(env))
17739 			return -EINVAL;
17740 		return 0;
17741 	}
17742 
17743 	urec_size = attr->func_info_rec_size;
17744 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
17745 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
17746 	    urec_size % sizeof(u32)) {
17747 		verbose(env, "invalid func info rec size %u\n", urec_size);
17748 		return -EINVAL;
17749 	}
17750 
17751 	prog = env->prog;
17752 	btf = prog->aux->btf;
17753 
17754 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
17755 	min_size = min_t(u32, krec_size, urec_size);
17756 
17757 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
17758 	if (!krecord)
17759 		return -ENOMEM;
17760 
17761 	for (i = 0; i < nfuncs; i++) {
17762 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
17763 		if (ret) {
17764 			if (ret == -E2BIG) {
17765 				verbose(env, "nonzero tailing record in func info");
17766 				/* set the size kernel expects so loader can zero
17767 				 * out the rest of the record.
17768 				 */
17769 				if (copy_to_bpfptr_offset(uattr,
17770 							  offsetof(union bpf_attr, func_info_rec_size),
17771 							  &min_size, sizeof(min_size)))
17772 					ret = -EFAULT;
17773 			}
17774 			goto err_free;
17775 		}
17776 
17777 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
17778 			ret = -EFAULT;
17779 			goto err_free;
17780 		}
17781 
17782 		/* check insn_off */
17783 		ret = -EINVAL;
17784 		if (i == 0) {
17785 			if (krecord[i].insn_off) {
17786 				verbose(env,
17787 					"nonzero insn_off %u for the first func info record",
17788 					krecord[i].insn_off);
17789 				goto err_free;
17790 			}
17791 		} else if (krecord[i].insn_off <= prev_offset) {
17792 			verbose(env,
17793 				"same or smaller insn offset (%u) than previous func info record (%u)",
17794 				krecord[i].insn_off, prev_offset);
17795 			goto err_free;
17796 		}
17797 
17798 		/* check type_id */
17799 		type = btf_type_by_id(btf, krecord[i].type_id);
17800 		if (!type || !btf_type_is_func(type)) {
17801 			verbose(env, "invalid type id %d in func info",
17802 				krecord[i].type_id);
17803 			goto err_free;
17804 		}
17805 
17806 		func_proto = btf_type_by_id(btf, type->type);
17807 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
17808 			/* btf_func_check() already verified it during BTF load */
17809 			goto err_free;
17810 
17811 		prev_offset = krecord[i].insn_off;
17812 		bpfptr_add(&urecord, urec_size);
17813 	}
17814 
17815 	prog->aux->func_info = krecord;
17816 	prog->aux->func_info_cnt = nfuncs;
17817 	return 0;
17818 
17819 err_free:
17820 	kvfree(krecord);
17821 	return ret;
17822 }
17823 
17824 static int check_btf_func(struct bpf_verifier_env *env,
17825 			  const union bpf_attr *attr,
17826 			  bpfptr_t uattr)
17827 {
17828 	const struct btf_type *type, *func_proto, *ret_type;
17829 	u32 i, nfuncs, urec_size;
17830 	struct bpf_func_info *krecord;
17831 	struct bpf_func_info_aux *info_aux = NULL;
17832 	struct bpf_prog *prog;
17833 	const struct btf *btf;
17834 	bpfptr_t urecord;
17835 	bool scalar_return;
17836 	int ret = -ENOMEM;
17837 
17838 	nfuncs = attr->func_info_cnt;
17839 	if (!nfuncs) {
17840 		if (check_abnormal_return(env))
17841 			return -EINVAL;
17842 		return 0;
17843 	}
17844 	if (nfuncs != env->subprog_cnt) {
17845 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
17846 		return -EINVAL;
17847 	}
17848 
17849 	urec_size = attr->func_info_rec_size;
17850 
17851 	prog = env->prog;
17852 	btf = prog->aux->btf;
17853 
17854 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
17855 
17856 	krecord = prog->aux->func_info;
17857 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
17858 	if (!info_aux)
17859 		return -ENOMEM;
17860 
17861 	for (i = 0; i < nfuncs; i++) {
17862 		/* check insn_off */
17863 		ret = -EINVAL;
17864 
17865 		if (env->subprog_info[i].start != krecord[i].insn_off) {
17866 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
17867 			goto err_free;
17868 		}
17869 
17870 		/* Already checked type_id */
17871 		type = btf_type_by_id(btf, krecord[i].type_id);
17872 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
17873 		/* Already checked func_proto */
17874 		func_proto = btf_type_by_id(btf, type->type);
17875 
17876 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
17877 		scalar_return =
17878 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
17879 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
17880 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
17881 			goto err_free;
17882 		}
17883 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
17884 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
17885 			goto err_free;
17886 		}
17887 
17888 		bpfptr_add(&urecord, urec_size);
17889 	}
17890 
17891 	prog->aux->func_info_aux = info_aux;
17892 	return 0;
17893 
17894 err_free:
17895 	kfree(info_aux);
17896 	return ret;
17897 }
17898 
17899 static void adjust_btf_func(struct bpf_verifier_env *env)
17900 {
17901 	struct bpf_prog_aux *aux = env->prog->aux;
17902 	int i;
17903 
17904 	if (!aux->func_info)
17905 		return;
17906 
17907 	/* func_info is not available for hidden subprogs */
17908 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
17909 		aux->func_info[i].insn_off = env->subprog_info[i].start;
17910 }
17911 
17912 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
17913 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
17914 
17915 static int check_btf_line(struct bpf_verifier_env *env,
17916 			  const union bpf_attr *attr,
17917 			  bpfptr_t uattr)
17918 {
17919 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
17920 	struct bpf_subprog_info *sub;
17921 	struct bpf_line_info *linfo;
17922 	struct bpf_prog *prog;
17923 	const struct btf *btf;
17924 	bpfptr_t ulinfo;
17925 	int err;
17926 
17927 	nr_linfo = attr->line_info_cnt;
17928 	if (!nr_linfo)
17929 		return 0;
17930 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
17931 		return -EINVAL;
17932 
17933 	rec_size = attr->line_info_rec_size;
17934 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
17935 	    rec_size > MAX_LINEINFO_REC_SIZE ||
17936 	    rec_size & (sizeof(u32) - 1))
17937 		return -EINVAL;
17938 
17939 	/* Need to zero it in case the userspace may
17940 	 * pass in a smaller bpf_line_info object.
17941 	 */
17942 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
17943 			 GFP_KERNEL | __GFP_NOWARN);
17944 	if (!linfo)
17945 		return -ENOMEM;
17946 
17947 	prog = env->prog;
17948 	btf = prog->aux->btf;
17949 
17950 	s = 0;
17951 	sub = env->subprog_info;
17952 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
17953 	expected_size = sizeof(struct bpf_line_info);
17954 	ncopy = min_t(u32, expected_size, rec_size);
17955 	for (i = 0; i < nr_linfo; i++) {
17956 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
17957 		if (err) {
17958 			if (err == -E2BIG) {
17959 				verbose(env, "nonzero tailing record in line_info");
17960 				if (copy_to_bpfptr_offset(uattr,
17961 							  offsetof(union bpf_attr, line_info_rec_size),
17962 							  &expected_size, sizeof(expected_size)))
17963 					err = -EFAULT;
17964 			}
17965 			goto err_free;
17966 		}
17967 
17968 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
17969 			err = -EFAULT;
17970 			goto err_free;
17971 		}
17972 
17973 		/*
17974 		 * Check insn_off to ensure
17975 		 * 1) strictly increasing AND
17976 		 * 2) bounded by prog->len
17977 		 *
17978 		 * The linfo[0].insn_off == 0 check logically falls into
17979 		 * the later "missing bpf_line_info for func..." case
17980 		 * because the first linfo[0].insn_off must be the
17981 		 * first sub also and the first sub must have
17982 		 * subprog_info[0].start == 0.
17983 		 */
17984 		if ((i && linfo[i].insn_off <= prev_offset) ||
17985 		    linfo[i].insn_off >= prog->len) {
17986 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
17987 				i, linfo[i].insn_off, prev_offset,
17988 				prog->len);
17989 			err = -EINVAL;
17990 			goto err_free;
17991 		}
17992 
17993 		if (!prog->insnsi[linfo[i].insn_off].code) {
17994 			verbose(env,
17995 				"Invalid insn code at line_info[%u].insn_off\n",
17996 				i);
17997 			err = -EINVAL;
17998 			goto err_free;
17999 		}
18000 
18001 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
18002 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
18003 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
18004 			err = -EINVAL;
18005 			goto err_free;
18006 		}
18007 
18008 		if (s != env->subprog_cnt) {
18009 			if (linfo[i].insn_off == sub[s].start) {
18010 				sub[s].linfo_idx = i;
18011 				s++;
18012 			} else if (sub[s].start < linfo[i].insn_off) {
18013 				verbose(env, "missing bpf_line_info for func#%u\n", s);
18014 				err = -EINVAL;
18015 				goto err_free;
18016 			}
18017 		}
18018 
18019 		prev_offset = linfo[i].insn_off;
18020 		bpfptr_add(&ulinfo, rec_size);
18021 	}
18022 
18023 	if (s != env->subprog_cnt) {
18024 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
18025 			env->subprog_cnt - s, s);
18026 		err = -EINVAL;
18027 		goto err_free;
18028 	}
18029 
18030 	prog->aux->linfo = linfo;
18031 	prog->aux->nr_linfo = nr_linfo;
18032 
18033 	return 0;
18034 
18035 err_free:
18036 	kvfree(linfo);
18037 	return err;
18038 }
18039 
18040 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
18041 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
18042 
18043 static int check_core_relo(struct bpf_verifier_env *env,
18044 			   const union bpf_attr *attr,
18045 			   bpfptr_t uattr)
18046 {
18047 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
18048 	struct bpf_core_relo core_relo = {};
18049 	struct bpf_prog *prog = env->prog;
18050 	const struct btf *btf = prog->aux->btf;
18051 	struct bpf_core_ctx ctx = {
18052 		.log = &env->log,
18053 		.btf = btf,
18054 	};
18055 	bpfptr_t u_core_relo;
18056 	int err;
18057 
18058 	nr_core_relo = attr->core_relo_cnt;
18059 	if (!nr_core_relo)
18060 		return 0;
18061 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
18062 		return -EINVAL;
18063 
18064 	rec_size = attr->core_relo_rec_size;
18065 	if (rec_size < MIN_CORE_RELO_SIZE ||
18066 	    rec_size > MAX_CORE_RELO_SIZE ||
18067 	    rec_size % sizeof(u32))
18068 		return -EINVAL;
18069 
18070 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
18071 	expected_size = sizeof(struct bpf_core_relo);
18072 	ncopy = min_t(u32, expected_size, rec_size);
18073 
18074 	/* Unlike func_info and line_info, copy and apply each CO-RE
18075 	 * relocation record one at a time.
18076 	 */
18077 	for (i = 0; i < nr_core_relo; i++) {
18078 		/* future proofing when sizeof(bpf_core_relo) changes */
18079 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
18080 		if (err) {
18081 			if (err == -E2BIG) {
18082 				verbose(env, "nonzero tailing record in core_relo");
18083 				if (copy_to_bpfptr_offset(uattr,
18084 							  offsetof(union bpf_attr, core_relo_rec_size),
18085 							  &expected_size, sizeof(expected_size)))
18086 					err = -EFAULT;
18087 			}
18088 			break;
18089 		}
18090 
18091 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
18092 			err = -EFAULT;
18093 			break;
18094 		}
18095 
18096 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
18097 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
18098 				i, core_relo.insn_off, prog->len);
18099 			err = -EINVAL;
18100 			break;
18101 		}
18102 
18103 		err = bpf_core_apply(&ctx, &core_relo, i,
18104 				     &prog->insnsi[core_relo.insn_off / 8]);
18105 		if (err)
18106 			break;
18107 		bpfptr_add(&u_core_relo, rec_size);
18108 	}
18109 	return err;
18110 }
18111 
18112 static int check_btf_info_early(struct bpf_verifier_env *env,
18113 				const union bpf_attr *attr,
18114 				bpfptr_t uattr)
18115 {
18116 	struct btf *btf;
18117 	int err;
18118 
18119 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18120 		if (check_abnormal_return(env))
18121 			return -EINVAL;
18122 		return 0;
18123 	}
18124 
18125 	btf = btf_get_by_fd(attr->prog_btf_fd);
18126 	if (IS_ERR(btf))
18127 		return PTR_ERR(btf);
18128 	if (btf_is_kernel(btf)) {
18129 		btf_put(btf);
18130 		return -EACCES;
18131 	}
18132 	env->prog->aux->btf = btf;
18133 
18134 	err = check_btf_func_early(env, attr, uattr);
18135 	if (err)
18136 		return err;
18137 	return 0;
18138 }
18139 
18140 static int check_btf_info(struct bpf_verifier_env *env,
18141 			  const union bpf_attr *attr,
18142 			  bpfptr_t uattr)
18143 {
18144 	int err;
18145 
18146 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18147 		if (check_abnormal_return(env))
18148 			return -EINVAL;
18149 		return 0;
18150 	}
18151 
18152 	err = check_btf_func(env, attr, uattr);
18153 	if (err)
18154 		return err;
18155 
18156 	err = check_btf_line(env, attr, uattr);
18157 	if (err)
18158 		return err;
18159 
18160 	err = check_core_relo(env, attr, uattr);
18161 	if (err)
18162 		return err;
18163 
18164 	return 0;
18165 }
18166 
18167 /* check %cur's range satisfies %old's */
18168 static bool range_within(const struct bpf_reg_state *old,
18169 			 const struct bpf_reg_state *cur)
18170 {
18171 	return old->umin_value <= cur->umin_value &&
18172 	       old->umax_value >= cur->umax_value &&
18173 	       old->smin_value <= cur->smin_value &&
18174 	       old->smax_value >= cur->smax_value &&
18175 	       old->u32_min_value <= cur->u32_min_value &&
18176 	       old->u32_max_value >= cur->u32_max_value &&
18177 	       old->s32_min_value <= cur->s32_min_value &&
18178 	       old->s32_max_value >= cur->s32_max_value;
18179 }
18180 
18181 /* If in the old state two registers had the same id, then they need to have
18182  * the same id in the new state as well.  But that id could be different from
18183  * the old state, so we need to track the mapping from old to new ids.
18184  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
18185  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
18186  * regs with a different old id could still have new id 9, we don't care about
18187  * that.
18188  * So we look through our idmap to see if this old id has been seen before.  If
18189  * so, we require the new id to match; otherwise, we add the id pair to the map.
18190  */
18191 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18192 {
18193 	struct bpf_id_pair *map = idmap->map;
18194 	unsigned int i;
18195 
18196 	/* either both IDs should be set or both should be zero */
18197 	if (!!old_id != !!cur_id)
18198 		return false;
18199 
18200 	if (old_id == 0) /* cur_id == 0 as well */
18201 		return true;
18202 
18203 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
18204 		if (!map[i].old) {
18205 			/* Reached an empty slot; haven't seen this id before */
18206 			map[i].old = old_id;
18207 			map[i].cur = cur_id;
18208 			return true;
18209 		}
18210 		if (map[i].old == old_id)
18211 			return map[i].cur == cur_id;
18212 		if (map[i].cur == cur_id)
18213 			return false;
18214 	}
18215 	/* We ran out of idmap slots, which should be impossible */
18216 	WARN_ON_ONCE(1);
18217 	return false;
18218 }
18219 
18220 /* Similar to check_ids(), but allocate a unique temporary ID
18221  * for 'old_id' or 'cur_id' of zero.
18222  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
18223  */
18224 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18225 {
18226 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
18227 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
18228 
18229 	return check_ids(old_id, cur_id, idmap);
18230 }
18231 
18232 static void clean_func_state(struct bpf_verifier_env *env,
18233 			     struct bpf_func_state *st)
18234 {
18235 	enum bpf_reg_liveness live;
18236 	int i, j;
18237 
18238 	for (i = 0; i < BPF_REG_FP; i++) {
18239 		live = st->regs[i].live;
18240 		/* liveness must not touch this register anymore */
18241 		st->regs[i].live |= REG_LIVE_DONE;
18242 		if (!(live & REG_LIVE_READ))
18243 			/* since the register is unused, clear its state
18244 			 * to make further comparison simpler
18245 			 */
18246 			__mark_reg_not_init(env, &st->regs[i]);
18247 	}
18248 
18249 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
18250 		live = st->stack[i].spilled_ptr.live;
18251 		/* liveness must not touch this stack slot anymore */
18252 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
18253 		if (!(live & REG_LIVE_READ)) {
18254 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
18255 			for (j = 0; j < BPF_REG_SIZE; j++)
18256 				st->stack[i].slot_type[j] = STACK_INVALID;
18257 		}
18258 	}
18259 }
18260 
18261 static void clean_verifier_state(struct bpf_verifier_env *env,
18262 				 struct bpf_verifier_state *st)
18263 {
18264 	int i;
18265 
18266 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
18267 		/* all regs in this state in all frames were already marked */
18268 		return;
18269 
18270 	for (i = 0; i <= st->curframe; i++)
18271 		clean_func_state(env, st->frame[i]);
18272 }
18273 
18274 /* the parentage chains form a tree.
18275  * the verifier states are added to state lists at given insn and
18276  * pushed into state stack for future exploration.
18277  * when the verifier reaches bpf_exit insn some of the verifer states
18278  * stored in the state lists have their final liveness state already,
18279  * but a lot of states will get revised from liveness point of view when
18280  * the verifier explores other branches.
18281  * Example:
18282  * 1: r0 = 1
18283  * 2: if r1 == 100 goto pc+1
18284  * 3: r0 = 2
18285  * 4: exit
18286  * when the verifier reaches exit insn the register r0 in the state list of
18287  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
18288  * of insn 2 and goes exploring further. At the insn 4 it will walk the
18289  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
18290  *
18291  * Since the verifier pushes the branch states as it sees them while exploring
18292  * the program the condition of walking the branch instruction for the second
18293  * time means that all states below this branch were already explored and
18294  * their final liveness marks are already propagated.
18295  * Hence when the verifier completes the search of state list in is_state_visited()
18296  * we can call this clean_live_states() function to mark all liveness states
18297  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
18298  * will not be used.
18299  * This function also clears the registers and stack for states that !READ
18300  * to simplify state merging.
18301  *
18302  * Important note here that walking the same branch instruction in the callee
18303  * doesn't meant that the states are DONE. The verifier has to compare
18304  * the callsites
18305  */
18306 static void clean_live_states(struct bpf_verifier_env *env, int insn,
18307 			      struct bpf_verifier_state *cur)
18308 {
18309 	struct bpf_verifier_state *loop_entry;
18310 	struct bpf_verifier_state_list *sl;
18311 	struct list_head *pos, *head;
18312 
18313 	head = explored_state(env, insn);
18314 	list_for_each(pos, head) {
18315 		sl = container_of(pos, struct bpf_verifier_state_list, node);
18316 		if (sl->state.branches)
18317 			continue;
18318 		loop_entry = get_loop_entry(env, &sl->state);
18319 		if (!IS_ERR_OR_NULL(loop_entry) && loop_entry->branches)
18320 			continue;
18321 		if (sl->state.insn_idx != insn ||
18322 		    !same_callsites(&sl->state, cur))
18323 			continue;
18324 		clean_verifier_state(env, &sl->state);
18325 	}
18326 }
18327 
18328 static bool regs_exact(const struct bpf_reg_state *rold,
18329 		       const struct bpf_reg_state *rcur,
18330 		       struct bpf_idmap *idmap)
18331 {
18332 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
18333 	       check_ids(rold->id, rcur->id, idmap) &&
18334 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
18335 }
18336 
18337 enum exact_level {
18338 	NOT_EXACT,
18339 	EXACT,
18340 	RANGE_WITHIN
18341 };
18342 
18343 /* Returns true if (rold safe implies rcur safe) */
18344 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
18345 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
18346 		    enum exact_level exact)
18347 {
18348 	if (exact == EXACT)
18349 		return regs_exact(rold, rcur, idmap);
18350 
18351 	if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
18352 		/* explored state didn't use this */
18353 		return true;
18354 	if (rold->type == NOT_INIT) {
18355 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
18356 			/* explored state can't have used this */
18357 			return true;
18358 	}
18359 
18360 	/* Enforce that register types have to match exactly, including their
18361 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
18362 	 * rule.
18363 	 *
18364 	 * One can make a point that using a pointer register as unbounded
18365 	 * SCALAR would be technically acceptable, but this could lead to
18366 	 * pointer leaks because scalars are allowed to leak while pointers
18367 	 * are not. We could make this safe in special cases if root is
18368 	 * calling us, but it's probably not worth the hassle.
18369 	 *
18370 	 * Also, register types that are *not* MAYBE_NULL could technically be
18371 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
18372 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
18373 	 * to the same map).
18374 	 * However, if the old MAYBE_NULL register then got NULL checked,
18375 	 * doing so could have affected others with the same id, and we can't
18376 	 * check for that because we lost the id when we converted to
18377 	 * a non-MAYBE_NULL variant.
18378 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
18379 	 * non-MAYBE_NULL registers as well.
18380 	 */
18381 	if (rold->type != rcur->type)
18382 		return false;
18383 
18384 	switch (base_type(rold->type)) {
18385 	case SCALAR_VALUE:
18386 		if (env->explore_alu_limits) {
18387 			/* explore_alu_limits disables tnum_in() and range_within()
18388 			 * logic and requires everything to be strict
18389 			 */
18390 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
18391 			       check_scalar_ids(rold->id, rcur->id, idmap);
18392 		}
18393 		if (!rold->precise && exact == NOT_EXACT)
18394 			return true;
18395 		if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
18396 			return false;
18397 		if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
18398 			return false;
18399 		/* Why check_ids() for scalar registers?
18400 		 *
18401 		 * Consider the following BPF code:
18402 		 *   1: r6 = ... unbound scalar, ID=a ...
18403 		 *   2: r7 = ... unbound scalar, ID=b ...
18404 		 *   3: if (r6 > r7) goto +1
18405 		 *   4: r6 = r7
18406 		 *   5: if (r6 > X) goto ...
18407 		 *   6: ... memory operation using r7 ...
18408 		 *
18409 		 * First verification path is [1-6]:
18410 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
18411 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
18412 		 *   r7 <= X, because r6 and r7 share same id.
18413 		 * Next verification path is [1-4, 6].
18414 		 *
18415 		 * Instruction (6) would be reached in two states:
18416 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
18417 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
18418 		 *
18419 		 * Use check_ids() to distinguish these states.
18420 		 * ---
18421 		 * Also verify that new value satisfies old value range knowledge.
18422 		 */
18423 		return range_within(rold, rcur) &&
18424 		       tnum_in(rold->var_off, rcur->var_off) &&
18425 		       check_scalar_ids(rold->id, rcur->id, idmap);
18426 	case PTR_TO_MAP_KEY:
18427 	case PTR_TO_MAP_VALUE:
18428 	case PTR_TO_MEM:
18429 	case PTR_TO_BUF:
18430 	case PTR_TO_TP_BUFFER:
18431 		/* If the new min/max/var_off satisfy the old ones and
18432 		 * everything else matches, we are OK.
18433 		 */
18434 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
18435 		       range_within(rold, rcur) &&
18436 		       tnum_in(rold->var_off, rcur->var_off) &&
18437 		       check_ids(rold->id, rcur->id, idmap) &&
18438 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
18439 	case PTR_TO_PACKET_META:
18440 	case PTR_TO_PACKET:
18441 		/* We must have at least as much range as the old ptr
18442 		 * did, so that any accesses which were safe before are
18443 		 * still safe.  This is true even if old range < old off,
18444 		 * since someone could have accessed through (ptr - k), or
18445 		 * even done ptr -= k in a register, to get a safe access.
18446 		 */
18447 		if (rold->range > rcur->range)
18448 			return false;
18449 		/* If the offsets don't match, we can't trust our alignment;
18450 		 * nor can we be sure that we won't fall out of range.
18451 		 */
18452 		if (rold->off != rcur->off)
18453 			return false;
18454 		/* id relations must be preserved */
18455 		if (!check_ids(rold->id, rcur->id, idmap))
18456 			return false;
18457 		/* new val must satisfy old val knowledge */
18458 		return range_within(rold, rcur) &&
18459 		       tnum_in(rold->var_off, rcur->var_off);
18460 	case PTR_TO_STACK:
18461 		/* two stack pointers are equal only if they're pointing to
18462 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
18463 		 */
18464 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
18465 	case PTR_TO_ARENA:
18466 		return true;
18467 	default:
18468 		return regs_exact(rold, rcur, idmap);
18469 	}
18470 }
18471 
18472 static struct bpf_reg_state unbound_reg;
18473 
18474 static __init int unbound_reg_init(void)
18475 {
18476 	__mark_reg_unknown_imprecise(&unbound_reg);
18477 	unbound_reg.live |= REG_LIVE_READ;
18478 	return 0;
18479 }
18480 late_initcall(unbound_reg_init);
18481 
18482 static bool is_stack_all_misc(struct bpf_verifier_env *env,
18483 			      struct bpf_stack_state *stack)
18484 {
18485 	u32 i;
18486 
18487 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
18488 		if ((stack->slot_type[i] == STACK_MISC) ||
18489 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
18490 			continue;
18491 		return false;
18492 	}
18493 
18494 	return true;
18495 }
18496 
18497 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
18498 						  struct bpf_stack_state *stack)
18499 {
18500 	if (is_spilled_scalar_reg64(stack))
18501 		return &stack->spilled_ptr;
18502 
18503 	if (is_stack_all_misc(env, stack))
18504 		return &unbound_reg;
18505 
18506 	return NULL;
18507 }
18508 
18509 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
18510 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
18511 		      enum exact_level exact)
18512 {
18513 	int i, spi;
18514 
18515 	/* walk slots of the explored stack and ignore any additional
18516 	 * slots in the current stack, since explored(safe) state
18517 	 * didn't use them
18518 	 */
18519 	for (i = 0; i < old->allocated_stack; i++) {
18520 		struct bpf_reg_state *old_reg, *cur_reg;
18521 
18522 		spi = i / BPF_REG_SIZE;
18523 
18524 		if (exact != NOT_EXACT &&
18525 		    (i >= cur->allocated_stack ||
18526 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
18527 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
18528 			return false;
18529 
18530 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
18531 		    && exact == NOT_EXACT) {
18532 			i += BPF_REG_SIZE - 1;
18533 			/* explored state didn't use this */
18534 			continue;
18535 		}
18536 
18537 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
18538 			continue;
18539 
18540 		if (env->allow_uninit_stack &&
18541 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
18542 			continue;
18543 
18544 		/* explored stack has more populated slots than current stack
18545 		 * and these slots were used
18546 		 */
18547 		if (i >= cur->allocated_stack)
18548 			return false;
18549 
18550 		/* 64-bit scalar spill vs all slots MISC and vice versa.
18551 		 * Load from all slots MISC produces unbound scalar.
18552 		 * Construct a fake register for such stack and call
18553 		 * regsafe() to ensure scalar ids are compared.
18554 		 */
18555 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
18556 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
18557 		if (old_reg && cur_reg) {
18558 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
18559 				return false;
18560 			i += BPF_REG_SIZE - 1;
18561 			continue;
18562 		}
18563 
18564 		/* if old state was safe with misc data in the stack
18565 		 * it will be safe with zero-initialized stack.
18566 		 * The opposite is not true
18567 		 */
18568 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
18569 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
18570 			continue;
18571 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
18572 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
18573 			/* Ex: old explored (safe) state has STACK_SPILL in
18574 			 * this stack slot, but current has STACK_MISC ->
18575 			 * this verifier states are not equivalent,
18576 			 * return false to continue verification of this path
18577 			 */
18578 			return false;
18579 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
18580 			continue;
18581 		/* Both old and cur are having same slot_type */
18582 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
18583 		case STACK_SPILL:
18584 			/* when explored and current stack slot are both storing
18585 			 * spilled registers, check that stored pointers types
18586 			 * are the same as well.
18587 			 * Ex: explored safe path could have stored
18588 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
18589 			 * but current path has stored:
18590 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
18591 			 * such verifier states are not equivalent.
18592 			 * return false to continue verification of this path
18593 			 */
18594 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
18595 				     &cur->stack[spi].spilled_ptr, idmap, exact))
18596 				return false;
18597 			break;
18598 		case STACK_DYNPTR:
18599 			old_reg = &old->stack[spi].spilled_ptr;
18600 			cur_reg = &cur->stack[spi].spilled_ptr;
18601 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
18602 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
18603 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18604 				return false;
18605 			break;
18606 		case STACK_ITER:
18607 			old_reg = &old->stack[spi].spilled_ptr;
18608 			cur_reg = &cur->stack[spi].spilled_ptr;
18609 			/* iter.depth is not compared between states as it
18610 			 * doesn't matter for correctness and would otherwise
18611 			 * prevent convergence; we maintain it only to prevent
18612 			 * infinite loop check triggering, see
18613 			 * iter_active_depths_differ()
18614 			 */
18615 			if (old_reg->iter.btf != cur_reg->iter.btf ||
18616 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
18617 			    old_reg->iter.state != cur_reg->iter.state ||
18618 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
18619 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18620 				return false;
18621 			break;
18622 		case STACK_IRQ_FLAG:
18623 			old_reg = &old->stack[spi].spilled_ptr;
18624 			cur_reg = &cur->stack[spi].spilled_ptr;
18625 			if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) ||
18626 			    old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class)
18627 				return false;
18628 			break;
18629 		case STACK_MISC:
18630 		case STACK_ZERO:
18631 		case STACK_INVALID:
18632 			continue;
18633 		/* Ensure that new unhandled slot types return false by default */
18634 		default:
18635 			return false;
18636 		}
18637 	}
18638 	return true;
18639 }
18640 
18641 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
18642 		    struct bpf_idmap *idmap)
18643 {
18644 	int i;
18645 
18646 	if (old->acquired_refs != cur->acquired_refs)
18647 		return false;
18648 
18649 	if (old->active_locks != cur->active_locks)
18650 		return false;
18651 
18652 	if (old->active_preempt_locks != cur->active_preempt_locks)
18653 		return false;
18654 
18655 	if (old->active_rcu_lock != cur->active_rcu_lock)
18656 		return false;
18657 
18658 	if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
18659 		return false;
18660 
18661 	if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) ||
18662 	    old->active_lock_ptr != cur->active_lock_ptr)
18663 		return false;
18664 
18665 	for (i = 0; i < old->acquired_refs; i++) {
18666 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
18667 		    old->refs[i].type != cur->refs[i].type)
18668 			return false;
18669 		switch (old->refs[i].type) {
18670 		case REF_TYPE_PTR:
18671 		case REF_TYPE_IRQ:
18672 			break;
18673 		case REF_TYPE_LOCK:
18674 		case REF_TYPE_RES_LOCK:
18675 		case REF_TYPE_RES_LOCK_IRQ:
18676 			if (old->refs[i].ptr != cur->refs[i].ptr)
18677 				return false;
18678 			break;
18679 		default:
18680 			WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
18681 			return false;
18682 		}
18683 	}
18684 
18685 	return true;
18686 }
18687 
18688 /* compare two verifier states
18689  *
18690  * all states stored in state_list are known to be valid, since
18691  * verifier reached 'bpf_exit' instruction through them
18692  *
18693  * this function is called when verifier exploring different branches of
18694  * execution popped from the state stack. If it sees an old state that has
18695  * more strict register state and more strict stack state then this execution
18696  * branch doesn't need to be explored further, since verifier already
18697  * concluded that more strict state leads to valid finish.
18698  *
18699  * Therefore two states are equivalent if register state is more conservative
18700  * and explored stack state is more conservative than the current one.
18701  * Example:
18702  *       explored                   current
18703  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
18704  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
18705  *
18706  * In other words if current stack state (one being explored) has more
18707  * valid slots than old one that already passed validation, it means
18708  * the verifier can stop exploring and conclude that current state is valid too
18709  *
18710  * Similarly with registers. If explored state has register type as invalid
18711  * whereas register type in current state is meaningful, it means that
18712  * the current state will reach 'bpf_exit' instruction safely
18713  */
18714 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
18715 			      struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact)
18716 {
18717 	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
18718 	u16 i;
18719 
18720 	if (old->callback_depth > cur->callback_depth)
18721 		return false;
18722 
18723 	for (i = 0; i < MAX_BPF_REG; i++)
18724 		if (((1 << i) & live_regs) &&
18725 		    !regsafe(env, &old->regs[i], &cur->regs[i],
18726 			     &env->idmap_scratch, exact))
18727 			return false;
18728 
18729 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
18730 		return false;
18731 
18732 	return true;
18733 }
18734 
18735 static void reset_idmap_scratch(struct bpf_verifier_env *env)
18736 {
18737 	env->idmap_scratch.tmp_id_gen = env->id_gen;
18738 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
18739 }
18740 
18741 static bool states_equal(struct bpf_verifier_env *env,
18742 			 struct bpf_verifier_state *old,
18743 			 struct bpf_verifier_state *cur,
18744 			 enum exact_level exact)
18745 {
18746 	u32 insn_idx;
18747 	int i;
18748 
18749 	if (old->curframe != cur->curframe)
18750 		return false;
18751 
18752 	reset_idmap_scratch(env);
18753 
18754 	/* Verification state from speculative execution simulation
18755 	 * must never prune a non-speculative execution one.
18756 	 */
18757 	if (old->speculative && !cur->speculative)
18758 		return false;
18759 
18760 	if (old->in_sleepable != cur->in_sleepable)
18761 		return false;
18762 
18763 	if (!refsafe(old, cur, &env->idmap_scratch))
18764 		return false;
18765 
18766 	/* for states to be equal callsites have to be the same
18767 	 * and all frame states need to be equivalent
18768 	 */
18769 	for (i = 0; i <= old->curframe; i++) {
18770 		insn_idx = i == old->curframe
18771 			   ? env->insn_idx
18772 			   : old->frame[i + 1]->callsite;
18773 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
18774 			return false;
18775 		if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
18776 			return false;
18777 	}
18778 	return true;
18779 }
18780 
18781 /* Return 0 if no propagation happened. Return negative error code if error
18782  * happened. Otherwise, return the propagated bit.
18783  */
18784 static int propagate_liveness_reg(struct bpf_verifier_env *env,
18785 				  struct bpf_reg_state *reg,
18786 				  struct bpf_reg_state *parent_reg)
18787 {
18788 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
18789 	u8 flag = reg->live & REG_LIVE_READ;
18790 	int err;
18791 
18792 	/* When comes here, read flags of PARENT_REG or REG could be any of
18793 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
18794 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
18795 	 */
18796 	if (parent_flag == REG_LIVE_READ64 ||
18797 	    /* Or if there is no read flag from REG. */
18798 	    !flag ||
18799 	    /* Or if the read flag from REG is the same as PARENT_REG. */
18800 	    parent_flag == flag)
18801 		return 0;
18802 
18803 	err = mark_reg_read(env, reg, parent_reg, flag);
18804 	if (err)
18805 		return err;
18806 
18807 	return flag;
18808 }
18809 
18810 /* A write screens off any subsequent reads; but write marks come from the
18811  * straight-line code between a state and its parent.  When we arrive at an
18812  * equivalent state (jump target or such) we didn't arrive by the straight-line
18813  * code, so read marks in the state must propagate to the parent regardless
18814  * of the state's write marks. That's what 'parent == state->parent' comparison
18815  * in mark_reg_read() is for.
18816  */
18817 static int propagate_liveness(struct bpf_verifier_env *env,
18818 			      const struct bpf_verifier_state *vstate,
18819 			      struct bpf_verifier_state *vparent)
18820 {
18821 	struct bpf_reg_state *state_reg, *parent_reg;
18822 	struct bpf_func_state *state, *parent;
18823 	int i, frame, err = 0;
18824 
18825 	if (vparent->curframe != vstate->curframe) {
18826 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
18827 		     vparent->curframe, vstate->curframe);
18828 		return -EFAULT;
18829 	}
18830 	/* Propagate read liveness of registers... */
18831 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
18832 	for (frame = 0; frame <= vstate->curframe; frame++) {
18833 		parent = vparent->frame[frame];
18834 		state = vstate->frame[frame];
18835 		parent_reg = parent->regs;
18836 		state_reg = state->regs;
18837 		/* We don't need to worry about FP liveness, it's read-only */
18838 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
18839 			err = propagate_liveness_reg(env, &state_reg[i],
18840 						     &parent_reg[i]);
18841 			if (err < 0)
18842 				return err;
18843 			if (err == REG_LIVE_READ64)
18844 				mark_insn_zext(env, &parent_reg[i]);
18845 		}
18846 
18847 		/* Propagate stack slots. */
18848 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
18849 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
18850 			parent_reg = &parent->stack[i].spilled_ptr;
18851 			state_reg = &state->stack[i].spilled_ptr;
18852 			err = propagate_liveness_reg(env, state_reg,
18853 						     parent_reg);
18854 			if (err < 0)
18855 				return err;
18856 		}
18857 	}
18858 	return 0;
18859 }
18860 
18861 /* find precise scalars in the previous equivalent state and
18862  * propagate them into the current state
18863  */
18864 static int propagate_precision(struct bpf_verifier_env *env,
18865 			       const struct bpf_verifier_state *old)
18866 {
18867 	struct bpf_reg_state *state_reg;
18868 	struct bpf_func_state *state;
18869 	int i, err = 0, fr;
18870 	bool first;
18871 
18872 	for (fr = old->curframe; fr >= 0; fr--) {
18873 		state = old->frame[fr];
18874 		state_reg = state->regs;
18875 		first = true;
18876 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
18877 			if (state_reg->type != SCALAR_VALUE ||
18878 			    !state_reg->precise ||
18879 			    !(state_reg->live & REG_LIVE_READ))
18880 				continue;
18881 			if (env->log.level & BPF_LOG_LEVEL2) {
18882 				if (first)
18883 					verbose(env, "frame %d: propagating r%d", fr, i);
18884 				else
18885 					verbose(env, ",r%d", i);
18886 			}
18887 			bt_set_frame_reg(&env->bt, fr, i);
18888 			first = false;
18889 		}
18890 
18891 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
18892 			if (!is_spilled_reg(&state->stack[i]))
18893 				continue;
18894 			state_reg = &state->stack[i].spilled_ptr;
18895 			if (state_reg->type != SCALAR_VALUE ||
18896 			    !state_reg->precise ||
18897 			    !(state_reg->live & REG_LIVE_READ))
18898 				continue;
18899 			if (env->log.level & BPF_LOG_LEVEL2) {
18900 				if (first)
18901 					verbose(env, "frame %d: propagating fp%d",
18902 						fr, (-i - 1) * BPF_REG_SIZE);
18903 				else
18904 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
18905 			}
18906 			bt_set_frame_slot(&env->bt, fr, i);
18907 			first = false;
18908 		}
18909 		if (!first)
18910 			verbose(env, "\n");
18911 	}
18912 
18913 	err = mark_chain_precision_batch(env);
18914 	if (err < 0)
18915 		return err;
18916 
18917 	return 0;
18918 }
18919 
18920 static bool states_maybe_looping(struct bpf_verifier_state *old,
18921 				 struct bpf_verifier_state *cur)
18922 {
18923 	struct bpf_func_state *fold, *fcur;
18924 	int i, fr = cur->curframe;
18925 
18926 	if (old->curframe != fr)
18927 		return false;
18928 
18929 	fold = old->frame[fr];
18930 	fcur = cur->frame[fr];
18931 	for (i = 0; i < MAX_BPF_REG; i++)
18932 		if (memcmp(&fold->regs[i], &fcur->regs[i],
18933 			   offsetof(struct bpf_reg_state, parent)))
18934 			return false;
18935 	return true;
18936 }
18937 
18938 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
18939 {
18940 	return env->insn_aux_data[insn_idx].is_iter_next;
18941 }
18942 
18943 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
18944  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
18945  * states to match, which otherwise would look like an infinite loop. So while
18946  * iter_next() calls are taken care of, we still need to be careful and
18947  * prevent erroneous and too eager declaration of "ininite loop", when
18948  * iterators are involved.
18949  *
18950  * Here's a situation in pseudo-BPF assembly form:
18951  *
18952  *   0: again:                          ; set up iter_next() call args
18953  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
18954  *   2:   call bpf_iter_num_next        ; this is iter_next() call
18955  *   3:   if r0 == 0 goto done
18956  *   4:   ... something useful here ...
18957  *   5:   goto again                    ; another iteration
18958  *   6: done:
18959  *   7:   r1 = &it
18960  *   8:   call bpf_iter_num_destroy     ; clean up iter state
18961  *   9:   exit
18962  *
18963  * This is a typical loop. Let's assume that we have a prune point at 1:,
18964  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
18965  * again`, assuming other heuristics don't get in a way).
18966  *
18967  * When we first time come to 1:, let's say we have some state X. We proceed
18968  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
18969  * Now we come back to validate that forked ACTIVE state. We proceed through
18970  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
18971  * are converging. But the problem is that we don't know that yet, as this
18972  * convergence has to happen at iter_next() call site only. So if nothing is
18973  * done, at 1: verifier will use bounded loop logic and declare infinite
18974  * looping (and would be *technically* correct, if not for iterator's
18975  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
18976  * don't want that. So what we do in process_iter_next_call() when we go on
18977  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
18978  * a different iteration. So when we suspect an infinite loop, we additionally
18979  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
18980  * pretend we are not looping and wait for next iter_next() call.
18981  *
18982  * This only applies to ACTIVE state. In DRAINED state we don't expect to
18983  * loop, because that would actually mean infinite loop, as DRAINED state is
18984  * "sticky", and so we'll keep returning into the same instruction with the
18985  * same state (at least in one of possible code paths).
18986  *
18987  * This approach allows to keep infinite loop heuristic even in the face of
18988  * active iterator. E.g., C snippet below is and will be detected as
18989  * inifintely looping:
18990  *
18991  *   struct bpf_iter_num it;
18992  *   int *p, x;
18993  *
18994  *   bpf_iter_num_new(&it, 0, 10);
18995  *   while ((p = bpf_iter_num_next(&t))) {
18996  *       x = p;
18997  *       while (x--) {} // <<-- infinite loop here
18998  *   }
18999  *
19000  */
19001 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
19002 {
19003 	struct bpf_reg_state *slot, *cur_slot;
19004 	struct bpf_func_state *state;
19005 	int i, fr;
19006 
19007 	for (fr = old->curframe; fr >= 0; fr--) {
19008 		state = old->frame[fr];
19009 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19010 			if (state->stack[i].slot_type[0] != STACK_ITER)
19011 				continue;
19012 
19013 			slot = &state->stack[i].spilled_ptr;
19014 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
19015 				continue;
19016 
19017 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
19018 			if (cur_slot->iter.depth != slot->iter.depth)
19019 				return true;
19020 		}
19021 	}
19022 	return false;
19023 }
19024 
19025 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
19026 {
19027 	struct bpf_verifier_state_list *new_sl;
19028 	struct bpf_verifier_state_list *sl;
19029 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
19030 	int i, j, n, err, states_cnt = 0;
19031 	bool force_new_state, add_new_state, force_exact;
19032 	struct list_head *pos, *tmp, *head;
19033 
19034 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
19035 			  /* Avoid accumulating infinitely long jmp history */
19036 			  cur->insn_hist_end - cur->insn_hist_start > 40;
19037 
19038 	/* bpf progs typically have pruning point every 4 instructions
19039 	 * http://vger.kernel.org/bpfconf2019.html#session-1
19040 	 * Do not add new state for future pruning if the verifier hasn't seen
19041 	 * at least 2 jumps and at least 8 instructions.
19042 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
19043 	 * In tests that amounts to up to 50% reduction into total verifier
19044 	 * memory consumption and 20% verifier time speedup.
19045 	 */
19046 	add_new_state = force_new_state;
19047 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
19048 	    env->insn_processed - env->prev_insn_processed >= 8)
19049 		add_new_state = true;
19050 
19051 	clean_live_states(env, insn_idx, cur);
19052 
19053 	head = explored_state(env, insn_idx);
19054 	list_for_each_safe(pos, tmp, head) {
19055 		sl = container_of(pos, struct bpf_verifier_state_list, node);
19056 		states_cnt++;
19057 		if (sl->state.insn_idx != insn_idx)
19058 			continue;
19059 
19060 		if (sl->state.branches) {
19061 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
19062 
19063 			if (frame->in_async_callback_fn &&
19064 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
19065 				/* Different async_entry_cnt means that the verifier is
19066 				 * processing another entry into async callback.
19067 				 * Seeing the same state is not an indication of infinite
19068 				 * loop or infinite recursion.
19069 				 * But finding the same state doesn't mean that it's safe
19070 				 * to stop processing the current state. The previous state
19071 				 * hasn't yet reached bpf_exit, since state.branches > 0.
19072 				 * Checking in_async_callback_fn alone is not enough either.
19073 				 * Since the verifier still needs to catch infinite loops
19074 				 * inside async callbacks.
19075 				 */
19076 				goto skip_inf_loop_check;
19077 			}
19078 			/* BPF open-coded iterators loop detection is special.
19079 			 * states_maybe_looping() logic is too simplistic in detecting
19080 			 * states that *might* be equivalent, because it doesn't know
19081 			 * about ID remapping, so don't even perform it.
19082 			 * See process_iter_next_call() and iter_active_depths_differ()
19083 			 * for overview of the logic. When current and one of parent
19084 			 * states are detected as equivalent, it's a good thing: we prove
19085 			 * convergence and can stop simulating further iterations.
19086 			 * It's safe to assume that iterator loop will finish, taking into
19087 			 * account iter_next() contract of eventually returning
19088 			 * sticky NULL result.
19089 			 *
19090 			 * Note, that states have to be compared exactly in this case because
19091 			 * read and precision marks might not be finalized inside the loop.
19092 			 * E.g. as in the program below:
19093 			 *
19094 			 *     1. r7 = -16
19095 			 *     2. r6 = bpf_get_prandom_u32()
19096 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
19097 			 *     4.   if (r6 != 42) {
19098 			 *     5.     r7 = -32
19099 			 *     6.     r6 = bpf_get_prandom_u32()
19100 			 *     7.     continue
19101 			 *     8.   }
19102 			 *     9.   r0 = r10
19103 			 *    10.   r0 += r7
19104 			 *    11.   r8 = *(u64 *)(r0 + 0)
19105 			 *    12.   r6 = bpf_get_prandom_u32()
19106 			 *    13. }
19107 			 *
19108 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
19109 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
19110 			 * not have read or precision mark for r7 yet, thus inexact states
19111 			 * comparison would discard current state with r7=-32
19112 			 * => unsafe memory access at 11 would not be caught.
19113 			 */
19114 			if (is_iter_next_insn(env, insn_idx)) {
19115 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19116 					struct bpf_func_state *cur_frame;
19117 					struct bpf_reg_state *iter_state, *iter_reg;
19118 					int spi;
19119 
19120 					cur_frame = cur->frame[cur->curframe];
19121 					/* btf_check_iter_kfuncs() enforces that
19122 					 * iter state pointer is always the first arg
19123 					 */
19124 					iter_reg = &cur_frame->regs[BPF_REG_1];
19125 					/* current state is valid due to states_equal(),
19126 					 * so we can assume valid iter and reg state,
19127 					 * no need for extra (re-)validations
19128 					 */
19129 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
19130 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
19131 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
19132 						update_loop_entry(env, cur, &sl->state);
19133 						goto hit;
19134 					}
19135 				}
19136 				goto skip_inf_loop_check;
19137 			}
19138 			if (is_may_goto_insn_at(env, insn_idx)) {
19139 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
19140 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19141 					update_loop_entry(env, cur, &sl->state);
19142 					goto hit;
19143 				}
19144 			}
19145 			if (calls_callback(env, insn_idx)) {
19146 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
19147 					goto hit;
19148 				goto skip_inf_loop_check;
19149 			}
19150 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
19151 			if (states_maybe_looping(&sl->state, cur) &&
19152 			    states_equal(env, &sl->state, cur, EXACT) &&
19153 			    !iter_active_depths_differ(&sl->state, cur) &&
19154 			    sl->state.may_goto_depth == cur->may_goto_depth &&
19155 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
19156 				verbose_linfo(env, insn_idx, "; ");
19157 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
19158 				verbose(env, "cur state:");
19159 				print_verifier_state(env, cur, cur->curframe, true);
19160 				verbose(env, "old state:");
19161 				print_verifier_state(env, &sl->state, cur->curframe, true);
19162 				return -EINVAL;
19163 			}
19164 			/* if the verifier is processing a loop, avoid adding new state
19165 			 * too often, since different loop iterations have distinct
19166 			 * states and may not help future pruning.
19167 			 * This threshold shouldn't be too low to make sure that
19168 			 * a loop with large bound will be rejected quickly.
19169 			 * The most abusive loop will be:
19170 			 * r1 += 1
19171 			 * if r1 < 1000000 goto pc-2
19172 			 * 1M insn_procssed limit / 100 == 10k peak states.
19173 			 * This threshold shouldn't be too high either, since states
19174 			 * at the end of the loop are likely to be useful in pruning.
19175 			 */
19176 skip_inf_loop_check:
19177 			if (!force_new_state &&
19178 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
19179 			    env->insn_processed - env->prev_insn_processed < 100)
19180 				add_new_state = false;
19181 			goto miss;
19182 		}
19183 		/* If sl->state is a part of a loop and this loop's entry is a part of
19184 		 * current verification path then states have to be compared exactly.
19185 		 * 'force_exact' is needed to catch the following case:
19186 		 *
19187 		 *                initial     Here state 'succ' was processed first,
19188 		 *                  |         it was eventually tracked to produce a
19189 		 *                  V         state identical to 'hdr'.
19190 		 *     .---------> hdr        All branches from 'succ' had been explored
19191 		 *     |            |         and thus 'succ' has its .branches == 0.
19192 		 *     |            V
19193 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
19194 		 *     |    |       |         to the same instruction + callsites.
19195 		 *     |    V       V         In such case it is necessary to check
19196 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
19197 		 *     |    |       |         If 'succ' and 'cur' are a part of the
19198 		 *     |    V       V         same loop exact flag has to be set.
19199 		 *     |   succ <- cur        To check if that is the case, verify
19200 		 *     |    |                 if loop entry of 'succ' is in current
19201 		 *     |    V                 DFS path.
19202 		 *     |   ...
19203 		 *     |    |
19204 		 *     '----'
19205 		 *
19206 		 * Additional details are in the comment before get_loop_entry().
19207 		 */
19208 		loop_entry = get_loop_entry(env, &sl->state);
19209 		if (IS_ERR(loop_entry))
19210 			return PTR_ERR(loop_entry);
19211 		force_exact = loop_entry && loop_entry->branches > 0;
19212 		if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) {
19213 			if (force_exact)
19214 				update_loop_entry(env, cur, loop_entry);
19215 hit:
19216 			sl->hit_cnt++;
19217 			/* reached equivalent register/stack state,
19218 			 * prune the search.
19219 			 * Registers read by the continuation are read by us.
19220 			 * If we have any write marks in env->cur_state, they
19221 			 * will prevent corresponding reads in the continuation
19222 			 * from reaching our parent (an explored_state).  Our
19223 			 * own state will get the read marks recorded, but
19224 			 * they'll be immediately forgotten as we're pruning
19225 			 * this state and will pop a new one.
19226 			 */
19227 			err = propagate_liveness(env, &sl->state, cur);
19228 
19229 			/* if previous state reached the exit with precision and
19230 			 * current state is equivalent to it (except precision marks)
19231 			 * the precision needs to be propagated back in
19232 			 * the current state.
19233 			 */
19234 			if (is_jmp_point(env, env->insn_idx))
19235 				err = err ? : push_insn_history(env, cur, 0, 0);
19236 			err = err ? : propagate_precision(env, &sl->state);
19237 			if (err)
19238 				return err;
19239 			return 1;
19240 		}
19241 miss:
19242 		/* when new state is not going to be added do not increase miss count.
19243 		 * Otherwise several loop iterations will remove the state
19244 		 * recorded earlier. The goal of these heuristics is to have
19245 		 * states from some iterations of the loop (some in the beginning
19246 		 * and some at the end) to help pruning.
19247 		 */
19248 		if (add_new_state)
19249 			sl->miss_cnt++;
19250 		/* heuristic to determine whether this state is beneficial
19251 		 * to keep checking from state equivalence point of view.
19252 		 * Higher numbers increase max_states_per_insn and verification time,
19253 		 * but do not meaningfully decrease insn_processed.
19254 		 * 'n' controls how many times state could miss before eviction.
19255 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
19256 		 * too early would hinder iterator convergence.
19257 		 */
19258 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
19259 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
19260 			/* the state is unlikely to be useful. Remove it to
19261 			 * speed up verification
19262 			 */
19263 			sl->in_free_list = true;
19264 			list_del(&sl->node);
19265 			list_add(&sl->node, &env->free_list);
19266 			env->free_list_size++;
19267 			env->explored_states_size--;
19268 			maybe_free_verifier_state(env, sl);
19269 		}
19270 	}
19271 
19272 	if (env->max_states_per_insn < states_cnt)
19273 		env->max_states_per_insn = states_cnt;
19274 
19275 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
19276 		return 0;
19277 
19278 	if (!add_new_state)
19279 		return 0;
19280 
19281 	/* There were no equivalent states, remember the current one.
19282 	 * Technically the current state is not proven to be safe yet,
19283 	 * but it will either reach outer most bpf_exit (which means it's safe)
19284 	 * or it will be rejected. When there are no loops the verifier won't be
19285 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
19286 	 * again on the way to bpf_exit.
19287 	 * When looping the sl->state.branches will be > 0 and this state
19288 	 * will not be considered for equivalence until branches == 0.
19289 	 */
19290 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
19291 	if (!new_sl)
19292 		return -ENOMEM;
19293 	env->total_states++;
19294 	env->explored_states_size++;
19295 	update_peak_states(env);
19296 	env->prev_jmps_processed = env->jmps_processed;
19297 	env->prev_insn_processed = env->insn_processed;
19298 
19299 	/* forget precise markings we inherited, see __mark_chain_precision */
19300 	if (env->bpf_capable)
19301 		mark_all_scalars_imprecise(env, cur);
19302 
19303 	/* add new state to the head of linked list */
19304 	new = &new_sl->state;
19305 	err = copy_verifier_state(new, cur);
19306 	if (err) {
19307 		free_verifier_state(new, false);
19308 		kfree(new_sl);
19309 		return err;
19310 	}
19311 	new->insn_idx = insn_idx;
19312 	WARN_ONCE(new->branches != 1,
19313 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
19314 
19315 	cur->parent = new;
19316 	cur->first_insn_idx = insn_idx;
19317 	cur->insn_hist_start = cur->insn_hist_end;
19318 	cur->dfs_depth = new->dfs_depth + 1;
19319 	list_add(&new_sl->node, head);
19320 
19321 	/* connect new state to parentage chain. Current frame needs all
19322 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
19323 	 * to the stack implicitly by JITs) so in callers' frames connect just
19324 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
19325 	 * the state of the call instruction (with WRITTEN set), and r0 comes
19326 	 * from callee with its full parentage chain, anyway.
19327 	 */
19328 	/* clear write marks in current state: the writes we did are not writes
19329 	 * our child did, so they don't screen off its reads from us.
19330 	 * (There are no read marks in current state, because reads always mark
19331 	 * their parent and current state never has children yet.  Only
19332 	 * explored_states can get read marks.)
19333 	 */
19334 	for (j = 0; j <= cur->curframe; j++) {
19335 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
19336 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
19337 		for (i = 0; i < BPF_REG_FP; i++)
19338 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
19339 	}
19340 
19341 	/* all stack frames are accessible from callee, clear them all */
19342 	for (j = 0; j <= cur->curframe; j++) {
19343 		struct bpf_func_state *frame = cur->frame[j];
19344 		struct bpf_func_state *newframe = new->frame[j];
19345 
19346 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
19347 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
19348 			frame->stack[i].spilled_ptr.parent =
19349 						&newframe->stack[i].spilled_ptr;
19350 		}
19351 	}
19352 	return 0;
19353 }
19354 
19355 /* Return true if it's OK to have the same insn return a different type. */
19356 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
19357 {
19358 	switch (base_type(type)) {
19359 	case PTR_TO_CTX:
19360 	case PTR_TO_SOCKET:
19361 	case PTR_TO_SOCK_COMMON:
19362 	case PTR_TO_TCP_SOCK:
19363 	case PTR_TO_XDP_SOCK:
19364 	case PTR_TO_BTF_ID:
19365 	case PTR_TO_ARENA:
19366 		return false;
19367 	default:
19368 		return true;
19369 	}
19370 }
19371 
19372 /* If an instruction was previously used with particular pointer types, then we
19373  * need to be careful to avoid cases such as the below, where it may be ok
19374  * for one branch accessing the pointer, but not ok for the other branch:
19375  *
19376  * R1 = sock_ptr
19377  * goto X;
19378  * ...
19379  * R1 = some_other_valid_ptr;
19380  * goto X;
19381  * ...
19382  * R2 = *(u32 *)(R1 + 0);
19383  */
19384 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
19385 {
19386 	return src != prev && (!reg_type_mismatch_ok(src) ||
19387 			       !reg_type_mismatch_ok(prev));
19388 }
19389 
19390 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
19391 			     bool allow_trust_mismatch)
19392 {
19393 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
19394 
19395 	if (*prev_type == NOT_INIT) {
19396 		/* Saw a valid insn
19397 		 * dst_reg = *(u32 *)(src_reg + off)
19398 		 * save type to validate intersecting paths
19399 		 */
19400 		*prev_type = type;
19401 	} else if (reg_type_mismatch(type, *prev_type)) {
19402 		/* Abuser program is trying to use the same insn
19403 		 * dst_reg = *(u32*) (src_reg + off)
19404 		 * with different pointer types:
19405 		 * src_reg == ctx in one branch and
19406 		 * src_reg == stack|map in some other branch.
19407 		 * Reject it.
19408 		 */
19409 		if (allow_trust_mismatch &&
19410 		    base_type(type) == PTR_TO_BTF_ID &&
19411 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
19412 			/*
19413 			 * Have to support a use case when one path through
19414 			 * the program yields TRUSTED pointer while another
19415 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
19416 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
19417 			 */
19418 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
19419 		} else {
19420 			verbose(env, "same insn cannot be used with different pointers\n");
19421 			return -EINVAL;
19422 		}
19423 	}
19424 
19425 	return 0;
19426 }
19427 
19428 static int do_check(struct bpf_verifier_env *env)
19429 {
19430 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19431 	struct bpf_verifier_state *state = env->cur_state;
19432 	struct bpf_insn *insns = env->prog->insnsi;
19433 	struct bpf_reg_state *regs;
19434 	int insn_cnt = env->prog->len;
19435 	bool do_print_state = false;
19436 	int prev_insn_idx = -1;
19437 
19438 	for (;;) {
19439 		bool exception_exit = false;
19440 		struct bpf_insn *insn;
19441 		u8 class;
19442 		int err;
19443 
19444 		/* reset current history entry on each new instruction */
19445 		env->cur_hist_ent = NULL;
19446 
19447 		env->prev_insn_idx = prev_insn_idx;
19448 		if (env->insn_idx >= insn_cnt) {
19449 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
19450 				env->insn_idx, insn_cnt);
19451 			return -EFAULT;
19452 		}
19453 
19454 		insn = &insns[env->insn_idx];
19455 		class = BPF_CLASS(insn->code);
19456 
19457 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
19458 			verbose(env,
19459 				"BPF program is too large. Processed %d insn\n",
19460 				env->insn_processed);
19461 			return -E2BIG;
19462 		}
19463 
19464 		state->last_insn_idx = env->prev_insn_idx;
19465 
19466 		if (is_prune_point(env, env->insn_idx)) {
19467 			err = is_state_visited(env, env->insn_idx);
19468 			if (err < 0)
19469 				return err;
19470 			if (err == 1) {
19471 				/* found equivalent state, can prune the search */
19472 				if (env->log.level & BPF_LOG_LEVEL) {
19473 					if (do_print_state)
19474 						verbose(env, "\nfrom %d to %d%s: safe\n",
19475 							env->prev_insn_idx, env->insn_idx,
19476 							env->cur_state->speculative ?
19477 							" (speculative execution)" : "");
19478 					else
19479 						verbose(env, "%d: safe\n", env->insn_idx);
19480 				}
19481 				goto process_bpf_exit;
19482 			}
19483 		}
19484 
19485 		if (is_jmp_point(env, env->insn_idx)) {
19486 			err = push_insn_history(env, state, 0, 0);
19487 			if (err)
19488 				return err;
19489 		}
19490 
19491 		if (signal_pending(current))
19492 			return -EAGAIN;
19493 
19494 		if (need_resched())
19495 			cond_resched();
19496 
19497 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
19498 			verbose(env, "\nfrom %d to %d%s:",
19499 				env->prev_insn_idx, env->insn_idx,
19500 				env->cur_state->speculative ?
19501 				" (speculative execution)" : "");
19502 			print_verifier_state(env, state, state->curframe, true);
19503 			do_print_state = false;
19504 		}
19505 
19506 		if (env->log.level & BPF_LOG_LEVEL) {
19507 			if (verifier_state_scratched(env))
19508 				print_insn_state(env, state, state->curframe);
19509 
19510 			verbose_linfo(env, env->insn_idx, "; ");
19511 			env->prev_log_pos = env->log.end_pos;
19512 			verbose(env, "%d: ", env->insn_idx);
19513 			verbose_insn(env, insn);
19514 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
19515 			env->prev_log_pos = env->log.end_pos;
19516 		}
19517 
19518 		if (bpf_prog_is_offloaded(env->prog->aux)) {
19519 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
19520 							   env->prev_insn_idx);
19521 			if (err)
19522 				return err;
19523 		}
19524 
19525 		regs = cur_regs(env);
19526 		sanitize_mark_insn_seen(env);
19527 		prev_insn_idx = env->insn_idx;
19528 
19529 		if (class == BPF_ALU || class == BPF_ALU64) {
19530 			err = check_alu_op(env, insn);
19531 			if (err)
19532 				return err;
19533 
19534 		} else if (class == BPF_LDX) {
19535 			bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX;
19536 
19537 			/* Check for reserved fields is already done in
19538 			 * resolve_pseudo_ldimm64().
19539 			 */
19540 			err = check_load_mem(env, insn, false, is_ldsx, true,
19541 					     "ldx");
19542 			if (err)
19543 				return err;
19544 		} else if (class == BPF_STX) {
19545 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
19546 				err = check_atomic(env, insn);
19547 				if (err)
19548 					return err;
19549 				env->insn_idx++;
19550 				continue;
19551 			}
19552 
19553 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
19554 				verbose(env, "BPF_STX uses reserved fields\n");
19555 				return -EINVAL;
19556 			}
19557 
19558 			err = check_store_reg(env, insn, false);
19559 			if (err)
19560 				return err;
19561 		} else if (class == BPF_ST) {
19562 			enum bpf_reg_type dst_reg_type;
19563 
19564 			if (BPF_MODE(insn->code) != BPF_MEM ||
19565 			    insn->src_reg != BPF_REG_0) {
19566 				verbose(env, "BPF_ST uses reserved fields\n");
19567 				return -EINVAL;
19568 			}
19569 			/* check src operand */
19570 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
19571 			if (err)
19572 				return err;
19573 
19574 			dst_reg_type = regs[insn->dst_reg].type;
19575 
19576 			/* check that memory (dst_reg + off) is writeable */
19577 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
19578 					       insn->off, BPF_SIZE(insn->code),
19579 					       BPF_WRITE, -1, false, false);
19580 			if (err)
19581 				return err;
19582 
19583 			err = save_aux_ptr_type(env, dst_reg_type, false);
19584 			if (err)
19585 				return err;
19586 		} else if (class == BPF_JMP || class == BPF_JMP32) {
19587 			u8 opcode = BPF_OP(insn->code);
19588 
19589 			env->jmps_processed++;
19590 			if (opcode == BPF_CALL) {
19591 				if (BPF_SRC(insn->code) != BPF_K ||
19592 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
19593 				     && insn->off != 0) ||
19594 				    (insn->src_reg != BPF_REG_0 &&
19595 				     insn->src_reg != BPF_PSEUDO_CALL &&
19596 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
19597 				    insn->dst_reg != BPF_REG_0 ||
19598 				    class == BPF_JMP32) {
19599 					verbose(env, "BPF_CALL uses reserved fields\n");
19600 					return -EINVAL;
19601 				}
19602 
19603 				if (env->cur_state->active_locks) {
19604 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
19605 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
19606 					     (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
19607 						verbose(env, "function calls are not allowed while holding a lock\n");
19608 						return -EINVAL;
19609 					}
19610 				}
19611 				if (insn->src_reg == BPF_PSEUDO_CALL) {
19612 					err = check_func_call(env, insn, &env->insn_idx);
19613 				} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19614 					err = check_kfunc_call(env, insn, &env->insn_idx);
19615 					if (!err && is_bpf_throw_kfunc(insn)) {
19616 						exception_exit = true;
19617 						goto process_bpf_exit_full;
19618 					}
19619 				} else {
19620 					err = check_helper_call(env, insn, &env->insn_idx);
19621 				}
19622 				if (err)
19623 					return err;
19624 
19625 				mark_reg_scratched(env, BPF_REG_0);
19626 			} else if (opcode == BPF_JA) {
19627 				if (BPF_SRC(insn->code) != BPF_K ||
19628 				    insn->src_reg != BPF_REG_0 ||
19629 				    insn->dst_reg != BPF_REG_0 ||
19630 				    (class == BPF_JMP && insn->imm != 0) ||
19631 				    (class == BPF_JMP32 && insn->off != 0)) {
19632 					verbose(env, "BPF_JA uses reserved fields\n");
19633 					return -EINVAL;
19634 				}
19635 
19636 				if (class == BPF_JMP)
19637 					env->insn_idx += insn->off + 1;
19638 				else
19639 					env->insn_idx += insn->imm + 1;
19640 				continue;
19641 
19642 			} else if (opcode == BPF_EXIT) {
19643 				if (BPF_SRC(insn->code) != BPF_K ||
19644 				    insn->imm != 0 ||
19645 				    insn->src_reg != BPF_REG_0 ||
19646 				    insn->dst_reg != BPF_REG_0 ||
19647 				    class == BPF_JMP32) {
19648 					verbose(env, "BPF_EXIT uses reserved fields\n");
19649 					return -EINVAL;
19650 				}
19651 process_bpf_exit_full:
19652 				/* We must do check_reference_leak here before
19653 				 * prepare_func_exit to handle the case when
19654 				 * state->curframe > 0, it may be a callback
19655 				 * function, for which reference_state must
19656 				 * match caller reference state when it exits.
19657 				 */
19658 				err = check_resource_leak(env, exception_exit, !env->cur_state->curframe,
19659 							  "BPF_EXIT instruction in main prog");
19660 				if (err)
19661 					return err;
19662 
19663 				/* The side effect of the prepare_func_exit
19664 				 * which is being skipped is that it frees
19665 				 * bpf_func_state. Typically, process_bpf_exit
19666 				 * will only be hit with outermost exit.
19667 				 * copy_verifier_state in pop_stack will handle
19668 				 * freeing of any extra bpf_func_state left over
19669 				 * from not processing all nested function
19670 				 * exits. We also skip return code checks as
19671 				 * they are not needed for exceptional exits.
19672 				 */
19673 				if (exception_exit)
19674 					goto process_bpf_exit;
19675 
19676 				if (state->curframe) {
19677 					/* exit from nested function */
19678 					err = prepare_func_exit(env, &env->insn_idx);
19679 					if (err)
19680 						return err;
19681 					do_print_state = true;
19682 					continue;
19683 				}
19684 
19685 				err = check_return_code(env, BPF_REG_0, "R0");
19686 				if (err)
19687 					return err;
19688 process_bpf_exit:
19689 				mark_verifier_state_scratched(env);
19690 				update_branch_counts(env, env->cur_state);
19691 				err = pop_stack(env, &prev_insn_idx,
19692 						&env->insn_idx, pop_log);
19693 				if (err < 0) {
19694 					if (err != -ENOENT)
19695 						return err;
19696 					break;
19697 				} else {
19698 					if (verifier_bug_if(env->cur_state->loop_entry, env,
19699 							    "broken loop detection"))
19700 						return -EFAULT;
19701 					do_print_state = true;
19702 					continue;
19703 				}
19704 			} else {
19705 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
19706 				if (err)
19707 					return err;
19708 			}
19709 		} else if (class == BPF_LD) {
19710 			u8 mode = BPF_MODE(insn->code);
19711 
19712 			if (mode == BPF_ABS || mode == BPF_IND) {
19713 				err = check_ld_abs(env, insn);
19714 				if (err)
19715 					return err;
19716 
19717 			} else if (mode == BPF_IMM) {
19718 				err = check_ld_imm(env, insn);
19719 				if (err)
19720 					return err;
19721 
19722 				env->insn_idx++;
19723 				sanitize_mark_insn_seen(env);
19724 			} else {
19725 				verbose(env, "invalid BPF_LD mode\n");
19726 				return -EINVAL;
19727 			}
19728 		} else {
19729 			verbose(env, "unknown insn class %d\n", class);
19730 			return -EINVAL;
19731 		}
19732 
19733 		env->insn_idx++;
19734 	}
19735 
19736 	return 0;
19737 }
19738 
19739 static int find_btf_percpu_datasec(struct btf *btf)
19740 {
19741 	const struct btf_type *t;
19742 	const char *tname;
19743 	int i, n;
19744 
19745 	/*
19746 	 * Both vmlinux and module each have their own ".data..percpu"
19747 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
19748 	 * types to look at only module's own BTF types.
19749 	 */
19750 	n = btf_nr_types(btf);
19751 	if (btf_is_module(btf))
19752 		i = btf_nr_types(btf_vmlinux);
19753 	else
19754 		i = 1;
19755 
19756 	for(; i < n; i++) {
19757 		t = btf_type_by_id(btf, i);
19758 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
19759 			continue;
19760 
19761 		tname = btf_name_by_offset(btf, t->name_off);
19762 		if (!strcmp(tname, ".data..percpu"))
19763 			return i;
19764 	}
19765 
19766 	return -ENOENT;
19767 }
19768 
19769 /*
19770  * Add btf to the used_btfs array and return the index. (If the btf was
19771  * already added, then just return the index.) Upon successful insertion
19772  * increase btf refcnt, and, if present, also refcount the corresponding
19773  * kernel module.
19774  */
19775 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
19776 {
19777 	struct btf_mod_pair *btf_mod;
19778 	int i;
19779 
19780 	/* check whether we recorded this BTF (and maybe module) already */
19781 	for (i = 0; i < env->used_btf_cnt; i++)
19782 		if (env->used_btfs[i].btf == btf)
19783 			return i;
19784 
19785 	if (env->used_btf_cnt >= MAX_USED_BTFS)
19786 		return -E2BIG;
19787 
19788 	btf_get(btf);
19789 
19790 	btf_mod = &env->used_btfs[env->used_btf_cnt];
19791 	btf_mod->btf = btf;
19792 	btf_mod->module = NULL;
19793 
19794 	/* if we reference variables from kernel module, bump its refcount */
19795 	if (btf_is_module(btf)) {
19796 		btf_mod->module = btf_try_get_module(btf);
19797 		if (!btf_mod->module) {
19798 			btf_put(btf);
19799 			return -ENXIO;
19800 		}
19801 	}
19802 
19803 	return env->used_btf_cnt++;
19804 }
19805 
19806 /* replace pseudo btf_id with kernel symbol address */
19807 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
19808 				 struct bpf_insn *insn,
19809 				 struct bpf_insn_aux_data *aux,
19810 				 struct btf *btf)
19811 {
19812 	const struct btf_var_secinfo *vsi;
19813 	const struct btf_type *datasec;
19814 	const struct btf_type *t;
19815 	const char *sym_name;
19816 	bool percpu = false;
19817 	u32 type, id = insn->imm;
19818 	s32 datasec_id;
19819 	u64 addr;
19820 	int i;
19821 
19822 	t = btf_type_by_id(btf, id);
19823 	if (!t) {
19824 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
19825 		return -ENOENT;
19826 	}
19827 
19828 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
19829 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
19830 		return -EINVAL;
19831 	}
19832 
19833 	sym_name = btf_name_by_offset(btf, t->name_off);
19834 	addr = kallsyms_lookup_name(sym_name);
19835 	if (!addr) {
19836 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
19837 			sym_name);
19838 		return -ENOENT;
19839 	}
19840 	insn[0].imm = (u32)addr;
19841 	insn[1].imm = addr >> 32;
19842 
19843 	if (btf_type_is_func(t)) {
19844 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
19845 		aux->btf_var.mem_size = 0;
19846 		return 0;
19847 	}
19848 
19849 	datasec_id = find_btf_percpu_datasec(btf);
19850 	if (datasec_id > 0) {
19851 		datasec = btf_type_by_id(btf, datasec_id);
19852 		for_each_vsi(i, datasec, vsi) {
19853 			if (vsi->type == id) {
19854 				percpu = true;
19855 				break;
19856 			}
19857 		}
19858 	}
19859 
19860 	type = t->type;
19861 	t = btf_type_skip_modifiers(btf, type, NULL);
19862 	if (percpu) {
19863 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
19864 		aux->btf_var.btf = btf;
19865 		aux->btf_var.btf_id = type;
19866 	} else if (!btf_type_is_struct(t)) {
19867 		const struct btf_type *ret;
19868 		const char *tname;
19869 		u32 tsize;
19870 
19871 		/* resolve the type size of ksym. */
19872 		ret = btf_resolve_size(btf, t, &tsize);
19873 		if (IS_ERR(ret)) {
19874 			tname = btf_name_by_offset(btf, t->name_off);
19875 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
19876 				tname, PTR_ERR(ret));
19877 			return -EINVAL;
19878 		}
19879 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
19880 		aux->btf_var.mem_size = tsize;
19881 	} else {
19882 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
19883 		aux->btf_var.btf = btf;
19884 		aux->btf_var.btf_id = type;
19885 	}
19886 
19887 	return 0;
19888 }
19889 
19890 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
19891 			       struct bpf_insn *insn,
19892 			       struct bpf_insn_aux_data *aux)
19893 {
19894 	struct btf *btf;
19895 	int btf_fd;
19896 	int err;
19897 
19898 	btf_fd = insn[1].imm;
19899 	if (btf_fd) {
19900 		CLASS(fd, f)(btf_fd);
19901 
19902 		btf = __btf_get_by_fd(f);
19903 		if (IS_ERR(btf)) {
19904 			verbose(env, "invalid module BTF object FD specified.\n");
19905 			return -EINVAL;
19906 		}
19907 	} else {
19908 		if (!btf_vmlinux) {
19909 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
19910 			return -EINVAL;
19911 		}
19912 		btf = btf_vmlinux;
19913 	}
19914 
19915 	err = __check_pseudo_btf_id(env, insn, aux, btf);
19916 	if (err)
19917 		return err;
19918 
19919 	err = __add_used_btf(env, btf);
19920 	if (err < 0)
19921 		return err;
19922 	return 0;
19923 }
19924 
19925 static bool is_tracing_prog_type(enum bpf_prog_type type)
19926 {
19927 	switch (type) {
19928 	case BPF_PROG_TYPE_KPROBE:
19929 	case BPF_PROG_TYPE_TRACEPOINT:
19930 	case BPF_PROG_TYPE_PERF_EVENT:
19931 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
19932 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
19933 		return true;
19934 	default:
19935 		return false;
19936 	}
19937 }
19938 
19939 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
19940 {
19941 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
19942 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
19943 }
19944 
19945 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
19946 					struct bpf_map *map,
19947 					struct bpf_prog *prog)
19948 
19949 {
19950 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
19951 
19952 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
19953 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
19954 		if (is_tracing_prog_type(prog_type)) {
19955 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
19956 			return -EINVAL;
19957 		}
19958 	}
19959 
19960 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
19961 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
19962 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
19963 			return -EINVAL;
19964 		}
19965 
19966 		if (is_tracing_prog_type(prog_type)) {
19967 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
19968 			return -EINVAL;
19969 		}
19970 	}
19971 
19972 	if (btf_record_has_field(map->record, BPF_TIMER)) {
19973 		if (is_tracing_prog_type(prog_type)) {
19974 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
19975 			return -EINVAL;
19976 		}
19977 	}
19978 
19979 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
19980 		if (is_tracing_prog_type(prog_type)) {
19981 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
19982 			return -EINVAL;
19983 		}
19984 	}
19985 
19986 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
19987 	    !bpf_offload_prog_map_match(prog, map)) {
19988 		verbose(env, "offload device mismatch between prog and map\n");
19989 		return -EINVAL;
19990 	}
19991 
19992 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
19993 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
19994 		return -EINVAL;
19995 	}
19996 
19997 	if (prog->sleepable)
19998 		switch (map->map_type) {
19999 		case BPF_MAP_TYPE_HASH:
20000 		case BPF_MAP_TYPE_LRU_HASH:
20001 		case BPF_MAP_TYPE_ARRAY:
20002 		case BPF_MAP_TYPE_PERCPU_HASH:
20003 		case BPF_MAP_TYPE_PERCPU_ARRAY:
20004 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
20005 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
20006 		case BPF_MAP_TYPE_HASH_OF_MAPS:
20007 		case BPF_MAP_TYPE_RINGBUF:
20008 		case BPF_MAP_TYPE_USER_RINGBUF:
20009 		case BPF_MAP_TYPE_INODE_STORAGE:
20010 		case BPF_MAP_TYPE_SK_STORAGE:
20011 		case BPF_MAP_TYPE_TASK_STORAGE:
20012 		case BPF_MAP_TYPE_CGRP_STORAGE:
20013 		case BPF_MAP_TYPE_QUEUE:
20014 		case BPF_MAP_TYPE_STACK:
20015 		case BPF_MAP_TYPE_ARENA:
20016 			break;
20017 		default:
20018 			verbose(env,
20019 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
20020 			return -EINVAL;
20021 		}
20022 
20023 	if (bpf_map_is_cgroup_storage(map) &&
20024 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
20025 		verbose(env, "only one cgroup storage of each type is allowed\n");
20026 		return -EBUSY;
20027 	}
20028 
20029 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
20030 		if (env->prog->aux->arena) {
20031 			verbose(env, "Only one arena per program\n");
20032 			return -EBUSY;
20033 		}
20034 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
20035 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
20036 			return -EPERM;
20037 		}
20038 		if (!env->prog->jit_requested) {
20039 			verbose(env, "JIT is required to use arena\n");
20040 			return -EOPNOTSUPP;
20041 		}
20042 		if (!bpf_jit_supports_arena()) {
20043 			verbose(env, "JIT doesn't support arena\n");
20044 			return -EOPNOTSUPP;
20045 		}
20046 		env->prog->aux->arena = (void *)map;
20047 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
20048 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
20049 			return -EINVAL;
20050 		}
20051 	}
20052 
20053 	return 0;
20054 }
20055 
20056 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
20057 {
20058 	int i, err;
20059 
20060 	/* check whether we recorded this map already */
20061 	for (i = 0; i < env->used_map_cnt; i++)
20062 		if (env->used_maps[i] == map)
20063 			return i;
20064 
20065 	if (env->used_map_cnt >= MAX_USED_MAPS) {
20066 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
20067 			MAX_USED_MAPS);
20068 		return -E2BIG;
20069 	}
20070 
20071 	err = check_map_prog_compatibility(env, map, env->prog);
20072 	if (err)
20073 		return err;
20074 
20075 	if (env->prog->sleepable)
20076 		atomic64_inc(&map->sleepable_refcnt);
20077 
20078 	/* hold the map. If the program is rejected by verifier,
20079 	 * the map will be released by release_maps() or it
20080 	 * will be used by the valid program until it's unloaded
20081 	 * and all maps are released in bpf_free_used_maps()
20082 	 */
20083 	bpf_map_inc(map);
20084 
20085 	env->used_maps[env->used_map_cnt++] = map;
20086 
20087 	return env->used_map_cnt - 1;
20088 }
20089 
20090 /* Add map behind fd to used maps list, if it's not already there, and return
20091  * its index.
20092  * Returns <0 on error, or >= 0 index, on success.
20093  */
20094 static int add_used_map(struct bpf_verifier_env *env, int fd)
20095 {
20096 	struct bpf_map *map;
20097 	CLASS(fd, f)(fd);
20098 
20099 	map = __bpf_map_get(f);
20100 	if (IS_ERR(map)) {
20101 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
20102 		return PTR_ERR(map);
20103 	}
20104 
20105 	return __add_used_map(env, map);
20106 }
20107 
20108 /* find and rewrite pseudo imm in ld_imm64 instructions:
20109  *
20110  * 1. if it accesses map FD, replace it with actual map pointer.
20111  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
20112  *
20113  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
20114  */
20115 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
20116 {
20117 	struct bpf_insn *insn = env->prog->insnsi;
20118 	int insn_cnt = env->prog->len;
20119 	int i, err;
20120 
20121 	err = bpf_prog_calc_tag(env->prog);
20122 	if (err)
20123 		return err;
20124 
20125 	for (i = 0; i < insn_cnt; i++, insn++) {
20126 		if (BPF_CLASS(insn->code) == BPF_LDX &&
20127 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
20128 		    insn->imm != 0)) {
20129 			verbose(env, "BPF_LDX uses reserved fields\n");
20130 			return -EINVAL;
20131 		}
20132 
20133 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
20134 			struct bpf_insn_aux_data *aux;
20135 			struct bpf_map *map;
20136 			int map_idx;
20137 			u64 addr;
20138 			u32 fd;
20139 
20140 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
20141 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
20142 			    insn[1].off != 0) {
20143 				verbose(env, "invalid bpf_ld_imm64 insn\n");
20144 				return -EINVAL;
20145 			}
20146 
20147 			if (insn[0].src_reg == 0)
20148 				/* valid generic load 64-bit imm */
20149 				goto next_insn;
20150 
20151 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
20152 				aux = &env->insn_aux_data[i];
20153 				err = check_pseudo_btf_id(env, insn, aux);
20154 				if (err)
20155 					return err;
20156 				goto next_insn;
20157 			}
20158 
20159 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
20160 				aux = &env->insn_aux_data[i];
20161 				aux->ptr_type = PTR_TO_FUNC;
20162 				goto next_insn;
20163 			}
20164 
20165 			/* In final convert_pseudo_ld_imm64() step, this is
20166 			 * converted into regular 64-bit imm load insn.
20167 			 */
20168 			switch (insn[0].src_reg) {
20169 			case BPF_PSEUDO_MAP_VALUE:
20170 			case BPF_PSEUDO_MAP_IDX_VALUE:
20171 				break;
20172 			case BPF_PSEUDO_MAP_FD:
20173 			case BPF_PSEUDO_MAP_IDX:
20174 				if (insn[1].imm == 0)
20175 					break;
20176 				fallthrough;
20177 			default:
20178 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
20179 				return -EINVAL;
20180 			}
20181 
20182 			switch (insn[0].src_reg) {
20183 			case BPF_PSEUDO_MAP_IDX_VALUE:
20184 			case BPF_PSEUDO_MAP_IDX:
20185 				if (bpfptr_is_null(env->fd_array)) {
20186 					verbose(env, "fd_idx without fd_array is invalid\n");
20187 					return -EPROTO;
20188 				}
20189 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
20190 							    insn[0].imm * sizeof(fd),
20191 							    sizeof(fd)))
20192 					return -EFAULT;
20193 				break;
20194 			default:
20195 				fd = insn[0].imm;
20196 				break;
20197 			}
20198 
20199 			map_idx = add_used_map(env, fd);
20200 			if (map_idx < 0)
20201 				return map_idx;
20202 			map = env->used_maps[map_idx];
20203 
20204 			aux = &env->insn_aux_data[i];
20205 			aux->map_index = map_idx;
20206 
20207 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
20208 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
20209 				addr = (unsigned long)map;
20210 			} else {
20211 				u32 off = insn[1].imm;
20212 
20213 				if (off >= BPF_MAX_VAR_OFF) {
20214 					verbose(env, "direct value offset of %u is not allowed\n", off);
20215 					return -EINVAL;
20216 				}
20217 
20218 				if (!map->ops->map_direct_value_addr) {
20219 					verbose(env, "no direct value access support for this map type\n");
20220 					return -EINVAL;
20221 				}
20222 
20223 				err = map->ops->map_direct_value_addr(map, &addr, off);
20224 				if (err) {
20225 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
20226 						map->value_size, off);
20227 					return err;
20228 				}
20229 
20230 				aux->map_off = off;
20231 				addr += off;
20232 			}
20233 
20234 			insn[0].imm = (u32)addr;
20235 			insn[1].imm = addr >> 32;
20236 
20237 next_insn:
20238 			insn++;
20239 			i++;
20240 			continue;
20241 		}
20242 
20243 		/* Basic sanity check before we invest more work here. */
20244 		if (!bpf_opcode_in_insntable(insn->code)) {
20245 			verbose(env, "unknown opcode %02x\n", insn->code);
20246 			return -EINVAL;
20247 		}
20248 	}
20249 
20250 	/* now all pseudo BPF_LD_IMM64 instructions load valid
20251 	 * 'struct bpf_map *' into a register instead of user map_fd.
20252 	 * These pointers will be used later by verifier to validate map access.
20253 	 */
20254 	return 0;
20255 }
20256 
20257 /* drop refcnt of maps used by the rejected program */
20258 static void release_maps(struct bpf_verifier_env *env)
20259 {
20260 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
20261 			     env->used_map_cnt);
20262 }
20263 
20264 /* drop refcnt of maps used by the rejected program */
20265 static void release_btfs(struct bpf_verifier_env *env)
20266 {
20267 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
20268 }
20269 
20270 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
20271 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
20272 {
20273 	struct bpf_insn *insn = env->prog->insnsi;
20274 	int insn_cnt = env->prog->len;
20275 	int i;
20276 
20277 	for (i = 0; i < insn_cnt; i++, insn++) {
20278 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
20279 			continue;
20280 		if (insn->src_reg == BPF_PSEUDO_FUNC)
20281 			continue;
20282 		insn->src_reg = 0;
20283 	}
20284 }
20285 
20286 /* single env->prog->insni[off] instruction was replaced with the range
20287  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
20288  * [0, off) and [off, end) to new locations, so the patched range stays zero
20289  */
20290 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
20291 				 struct bpf_insn_aux_data *new_data,
20292 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
20293 {
20294 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
20295 	struct bpf_insn *insn = new_prog->insnsi;
20296 	u32 old_seen = old_data[off].seen;
20297 	u32 prog_len;
20298 	int i;
20299 
20300 	/* aux info at OFF always needs adjustment, no matter fast path
20301 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
20302 	 * original insn at old prog.
20303 	 */
20304 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
20305 
20306 	if (cnt == 1)
20307 		return;
20308 	prog_len = new_prog->len;
20309 
20310 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
20311 	memcpy(new_data + off + cnt - 1, old_data + off,
20312 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
20313 	for (i = off; i < off + cnt - 1; i++) {
20314 		/* Expand insni[off]'s seen count to the patched range. */
20315 		new_data[i].seen = old_seen;
20316 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
20317 	}
20318 	env->insn_aux_data = new_data;
20319 	vfree(old_data);
20320 }
20321 
20322 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
20323 {
20324 	int i;
20325 
20326 	if (len == 1)
20327 		return;
20328 	/* NOTE: fake 'exit' subprog should be updated as well. */
20329 	for (i = 0; i <= env->subprog_cnt; i++) {
20330 		if (env->subprog_info[i].start <= off)
20331 			continue;
20332 		env->subprog_info[i].start += len - 1;
20333 	}
20334 }
20335 
20336 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
20337 {
20338 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
20339 	int i, sz = prog->aux->size_poke_tab;
20340 	struct bpf_jit_poke_descriptor *desc;
20341 
20342 	for (i = 0; i < sz; i++) {
20343 		desc = &tab[i];
20344 		if (desc->insn_idx <= off)
20345 			continue;
20346 		desc->insn_idx += len - 1;
20347 	}
20348 }
20349 
20350 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
20351 					    const struct bpf_insn *patch, u32 len)
20352 {
20353 	struct bpf_prog *new_prog;
20354 	struct bpf_insn_aux_data *new_data = NULL;
20355 
20356 	if (len > 1) {
20357 		new_data = vzalloc(array_size(env->prog->len + len - 1,
20358 					      sizeof(struct bpf_insn_aux_data)));
20359 		if (!new_data)
20360 			return NULL;
20361 	}
20362 
20363 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
20364 	if (IS_ERR(new_prog)) {
20365 		if (PTR_ERR(new_prog) == -ERANGE)
20366 			verbose(env,
20367 				"insn %d cannot be patched due to 16-bit range\n",
20368 				env->insn_aux_data[off].orig_idx);
20369 		vfree(new_data);
20370 		return NULL;
20371 	}
20372 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
20373 	adjust_subprog_starts(env, off, len);
20374 	adjust_poke_descs(new_prog, off, len);
20375 	return new_prog;
20376 }
20377 
20378 /*
20379  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
20380  * jump offset by 'delta'.
20381  */
20382 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
20383 {
20384 	struct bpf_insn *insn = prog->insnsi;
20385 	u32 insn_cnt = prog->len, i;
20386 	s32 imm;
20387 	s16 off;
20388 
20389 	for (i = 0; i < insn_cnt; i++, insn++) {
20390 		u8 code = insn->code;
20391 
20392 		if (tgt_idx <= i && i < tgt_idx + delta)
20393 			continue;
20394 
20395 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
20396 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
20397 			continue;
20398 
20399 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
20400 			if (i + 1 + insn->imm != tgt_idx)
20401 				continue;
20402 			if (check_add_overflow(insn->imm, delta, &imm))
20403 				return -ERANGE;
20404 			insn->imm = imm;
20405 		} else {
20406 			if (i + 1 + insn->off != tgt_idx)
20407 				continue;
20408 			if (check_add_overflow(insn->off, delta, &off))
20409 				return -ERANGE;
20410 			insn->off = off;
20411 		}
20412 	}
20413 	return 0;
20414 }
20415 
20416 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
20417 					      u32 off, u32 cnt)
20418 {
20419 	int i, j;
20420 
20421 	/* find first prog starting at or after off (first to remove) */
20422 	for (i = 0; i < env->subprog_cnt; i++)
20423 		if (env->subprog_info[i].start >= off)
20424 			break;
20425 	/* find first prog starting at or after off + cnt (first to stay) */
20426 	for (j = i; j < env->subprog_cnt; j++)
20427 		if (env->subprog_info[j].start >= off + cnt)
20428 			break;
20429 	/* if j doesn't start exactly at off + cnt, we are just removing
20430 	 * the front of previous prog
20431 	 */
20432 	if (env->subprog_info[j].start != off + cnt)
20433 		j--;
20434 
20435 	if (j > i) {
20436 		struct bpf_prog_aux *aux = env->prog->aux;
20437 		int move;
20438 
20439 		/* move fake 'exit' subprog as well */
20440 		move = env->subprog_cnt + 1 - j;
20441 
20442 		memmove(env->subprog_info + i,
20443 			env->subprog_info + j,
20444 			sizeof(*env->subprog_info) * move);
20445 		env->subprog_cnt -= j - i;
20446 
20447 		/* remove func_info */
20448 		if (aux->func_info) {
20449 			move = aux->func_info_cnt - j;
20450 
20451 			memmove(aux->func_info + i,
20452 				aux->func_info + j,
20453 				sizeof(*aux->func_info) * move);
20454 			aux->func_info_cnt -= j - i;
20455 			/* func_info->insn_off is set after all code rewrites,
20456 			 * in adjust_btf_func() - no need to adjust
20457 			 */
20458 		}
20459 	} else {
20460 		/* convert i from "first prog to remove" to "first to adjust" */
20461 		if (env->subprog_info[i].start == off)
20462 			i++;
20463 	}
20464 
20465 	/* update fake 'exit' subprog as well */
20466 	for (; i <= env->subprog_cnt; i++)
20467 		env->subprog_info[i].start -= cnt;
20468 
20469 	return 0;
20470 }
20471 
20472 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
20473 				      u32 cnt)
20474 {
20475 	struct bpf_prog *prog = env->prog;
20476 	u32 i, l_off, l_cnt, nr_linfo;
20477 	struct bpf_line_info *linfo;
20478 
20479 	nr_linfo = prog->aux->nr_linfo;
20480 	if (!nr_linfo)
20481 		return 0;
20482 
20483 	linfo = prog->aux->linfo;
20484 
20485 	/* find first line info to remove, count lines to be removed */
20486 	for (i = 0; i < nr_linfo; i++)
20487 		if (linfo[i].insn_off >= off)
20488 			break;
20489 
20490 	l_off = i;
20491 	l_cnt = 0;
20492 	for (; i < nr_linfo; i++)
20493 		if (linfo[i].insn_off < off + cnt)
20494 			l_cnt++;
20495 		else
20496 			break;
20497 
20498 	/* First live insn doesn't match first live linfo, it needs to "inherit"
20499 	 * last removed linfo.  prog is already modified, so prog->len == off
20500 	 * means no live instructions after (tail of the program was removed).
20501 	 */
20502 	if (prog->len != off && l_cnt &&
20503 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
20504 		l_cnt--;
20505 		linfo[--i].insn_off = off + cnt;
20506 	}
20507 
20508 	/* remove the line info which refer to the removed instructions */
20509 	if (l_cnt) {
20510 		memmove(linfo + l_off, linfo + i,
20511 			sizeof(*linfo) * (nr_linfo - i));
20512 
20513 		prog->aux->nr_linfo -= l_cnt;
20514 		nr_linfo = prog->aux->nr_linfo;
20515 	}
20516 
20517 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
20518 	for (i = l_off; i < nr_linfo; i++)
20519 		linfo[i].insn_off -= cnt;
20520 
20521 	/* fix up all subprogs (incl. 'exit') which start >= off */
20522 	for (i = 0; i <= env->subprog_cnt; i++)
20523 		if (env->subprog_info[i].linfo_idx > l_off) {
20524 			/* program may have started in the removed region but
20525 			 * may not be fully removed
20526 			 */
20527 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
20528 				env->subprog_info[i].linfo_idx -= l_cnt;
20529 			else
20530 				env->subprog_info[i].linfo_idx = l_off;
20531 		}
20532 
20533 	return 0;
20534 }
20535 
20536 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
20537 {
20538 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20539 	unsigned int orig_prog_len = env->prog->len;
20540 	int err;
20541 
20542 	if (bpf_prog_is_offloaded(env->prog->aux))
20543 		bpf_prog_offload_remove_insns(env, off, cnt);
20544 
20545 	err = bpf_remove_insns(env->prog, off, cnt);
20546 	if (err)
20547 		return err;
20548 
20549 	err = adjust_subprog_starts_after_remove(env, off, cnt);
20550 	if (err)
20551 		return err;
20552 
20553 	err = bpf_adj_linfo_after_remove(env, off, cnt);
20554 	if (err)
20555 		return err;
20556 
20557 	memmove(aux_data + off,	aux_data + off + cnt,
20558 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
20559 
20560 	return 0;
20561 }
20562 
20563 /* The verifier does more data flow analysis than llvm and will not
20564  * explore branches that are dead at run time. Malicious programs can
20565  * have dead code too. Therefore replace all dead at-run-time code
20566  * with 'ja -1'.
20567  *
20568  * Just nops are not optimal, e.g. if they would sit at the end of the
20569  * program and through another bug we would manage to jump there, then
20570  * we'd execute beyond program memory otherwise. Returning exception
20571  * code also wouldn't work since we can have subprogs where the dead
20572  * code could be located.
20573  */
20574 static void sanitize_dead_code(struct bpf_verifier_env *env)
20575 {
20576 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20577 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
20578 	struct bpf_insn *insn = env->prog->insnsi;
20579 	const int insn_cnt = env->prog->len;
20580 	int i;
20581 
20582 	for (i = 0; i < insn_cnt; i++) {
20583 		if (aux_data[i].seen)
20584 			continue;
20585 		memcpy(insn + i, &trap, sizeof(trap));
20586 		aux_data[i].zext_dst = false;
20587 	}
20588 }
20589 
20590 static bool insn_is_cond_jump(u8 code)
20591 {
20592 	u8 op;
20593 
20594 	op = BPF_OP(code);
20595 	if (BPF_CLASS(code) == BPF_JMP32)
20596 		return op != BPF_JA;
20597 
20598 	if (BPF_CLASS(code) != BPF_JMP)
20599 		return false;
20600 
20601 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
20602 }
20603 
20604 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
20605 {
20606 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20607 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
20608 	struct bpf_insn *insn = env->prog->insnsi;
20609 	const int insn_cnt = env->prog->len;
20610 	int i;
20611 
20612 	for (i = 0; i < insn_cnt; i++, insn++) {
20613 		if (!insn_is_cond_jump(insn->code))
20614 			continue;
20615 
20616 		if (!aux_data[i + 1].seen)
20617 			ja.off = insn->off;
20618 		else if (!aux_data[i + 1 + insn->off].seen)
20619 			ja.off = 0;
20620 		else
20621 			continue;
20622 
20623 		if (bpf_prog_is_offloaded(env->prog->aux))
20624 			bpf_prog_offload_replace_insn(env, i, &ja);
20625 
20626 		memcpy(insn, &ja, sizeof(ja));
20627 	}
20628 }
20629 
20630 static int opt_remove_dead_code(struct bpf_verifier_env *env)
20631 {
20632 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20633 	int insn_cnt = env->prog->len;
20634 	int i, err;
20635 
20636 	for (i = 0; i < insn_cnt; i++) {
20637 		int j;
20638 
20639 		j = 0;
20640 		while (i + j < insn_cnt && !aux_data[i + j].seen)
20641 			j++;
20642 		if (!j)
20643 			continue;
20644 
20645 		err = verifier_remove_insns(env, i, j);
20646 		if (err)
20647 			return err;
20648 		insn_cnt = env->prog->len;
20649 	}
20650 
20651 	return 0;
20652 }
20653 
20654 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
20655 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0);
20656 
20657 static int opt_remove_nops(struct bpf_verifier_env *env)
20658 {
20659 	struct bpf_insn *insn = env->prog->insnsi;
20660 	int insn_cnt = env->prog->len;
20661 	bool is_may_goto_0, is_ja;
20662 	int i, err;
20663 
20664 	for (i = 0; i < insn_cnt; i++) {
20665 		is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
20666 		is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP));
20667 
20668 		if (!is_may_goto_0 && !is_ja)
20669 			continue;
20670 
20671 		err = verifier_remove_insns(env, i, 1);
20672 		if (err)
20673 			return err;
20674 		insn_cnt--;
20675 		/* Go back one insn to catch may_goto +1; may_goto +0 sequence */
20676 		i -= (is_may_goto_0 && i > 0) ? 2 : 1;
20677 	}
20678 
20679 	return 0;
20680 }
20681 
20682 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
20683 					 const union bpf_attr *attr)
20684 {
20685 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
20686 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
20687 	int i, patch_len, delta = 0, len = env->prog->len;
20688 	struct bpf_insn *insns = env->prog->insnsi;
20689 	struct bpf_prog *new_prog;
20690 	bool rnd_hi32;
20691 
20692 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
20693 	zext_patch[1] = BPF_ZEXT_REG(0);
20694 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
20695 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
20696 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
20697 	for (i = 0; i < len; i++) {
20698 		int adj_idx = i + delta;
20699 		struct bpf_insn insn;
20700 		int load_reg;
20701 
20702 		insn = insns[adj_idx];
20703 		load_reg = insn_def_regno(&insn);
20704 		if (!aux[adj_idx].zext_dst) {
20705 			u8 code, class;
20706 			u32 imm_rnd;
20707 
20708 			if (!rnd_hi32)
20709 				continue;
20710 
20711 			code = insn.code;
20712 			class = BPF_CLASS(code);
20713 			if (load_reg == -1)
20714 				continue;
20715 
20716 			/* NOTE: arg "reg" (the fourth one) is only used for
20717 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
20718 			 *       here.
20719 			 */
20720 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
20721 				if (class == BPF_LD &&
20722 				    BPF_MODE(code) == BPF_IMM)
20723 					i++;
20724 				continue;
20725 			}
20726 
20727 			/* ctx load could be transformed into wider load. */
20728 			if (class == BPF_LDX &&
20729 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
20730 				continue;
20731 
20732 			imm_rnd = get_random_u32();
20733 			rnd_hi32_patch[0] = insn;
20734 			rnd_hi32_patch[1].imm = imm_rnd;
20735 			rnd_hi32_patch[3].dst_reg = load_reg;
20736 			patch = rnd_hi32_patch;
20737 			patch_len = 4;
20738 			goto apply_patch_buffer;
20739 		}
20740 
20741 		/* Add in an zero-extend instruction if a) the JIT has requested
20742 		 * it or b) it's a CMPXCHG.
20743 		 *
20744 		 * The latter is because: BPF_CMPXCHG always loads a value into
20745 		 * R0, therefore always zero-extends. However some archs'
20746 		 * equivalent instruction only does this load when the
20747 		 * comparison is successful. This detail of CMPXCHG is
20748 		 * orthogonal to the general zero-extension behaviour of the
20749 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
20750 		 */
20751 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
20752 			continue;
20753 
20754 		/* Zero-extension is done by the caller. */
20755 		if (bpf_pseudo_kfunc_call(&insn))
20756 			continue;
20757 
20758 		if (verifier_bug_if(load_reg == -1, env,
20759 				    "zext_dst is set, but no reg is defined"))
20760 			return -EFAULT;
20761 
20762 		zext_patch[0] = insn;
20763 		zext_patch[1].dst_reg = load_reg;
20764 		zext_patch[1].src_reg = load_reg;
20765 		patch = zext_patch;
20766 		patch_len = 2;
20767 apply_patch_buffer:
20768 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
20769 		if (!new_prog)
20770 			return -ENOMEM;
20771 		env->prog = new_prog;
20772 		insns = new_prog->insnsi;
20773 		aux = env->insn_aux_data;
20774 		delta += patch_len - 1;
20775 	}
20776 
20777 	return 0;
20778 }
20779 
20780 /* convert load instructions that access fields of a context type into a
20781  * sequence of instructions that access fields of the underlying structure:
20782  *     struct __sk_buff    -> struct sk_buff
20783  *     struct bpf_sock_ops -> struct sock
20784  */
20785 static int convert_ctx_accesses(struct bpf_verifier_env *env)
20786 {
20787 	struct bpf_subprog_info *subprogs = env->subprog_info;
20788 	const struct bpf_verifier_ops *ops = env->ops;
20789 	int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
20790 	const int insn_cnt = env->prog->len;
20791 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
20792 	struct bpf_insn *insn_buf = env->insn_buf;
20793 	struct bpf_insn *insn;
20794 	u32 target_size, size_default, off;
20795 	struct bpf_prog *new_prog;
20796 	enum bpf_access_type type;
20797 	bool is_narrower_load;
20798 	int epilogue_idx = 0;
20799 
20800 	if (ops->gen_epilogue) {
20801 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
20802 						 -(subprogs[0].stack_depth + 8));
20803 		if (epilogue_cnt >= INSN_BUF_SIZE) {
20804 			verbose(env, "bpf verifier is misconfigured\n");
20805 			return -EINVAL;
20806 		} else if (epilogue_cnt) {
20807 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
20808 			cnt = 0;
20809 			subprogs[0].stack_depth += 8;
20810 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
20811 						      -subprogs[0].stack_depth);
20812 			insn_buf[cnt++] = env->prog->insnsi[0];
20813 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
20814 			if (!new_prog)
20815 				return -ENOMEM;
20816 			env->prog = new_prog;
20817 			delta += cnt - 1;
20818 
20819 			ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
20820 			if (ret < 0)
20821 				return ret;
20822 		}
20823 	}
20824 
20825 	if (ops->gen_prologue || env->seen_direct_write) {
20826 		if (!ops->gen_prologue) {
20827 			verbose(env, "bpf verifier is misconfigured\n");
20828 			return -EINVAL;
20829 		}
20830 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
20831 					env->prog);
20832 		if (cnt >= INSN_BUF_SIZE) {
20833 			verbose(env, "bpf verifier is misconfigured\n");
20834 			return -EINVAL;
20835 		} else if (cnt) {
20836 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
20837 			if (!new_prog)
20838 				return -ENOMEM;
20839 
20840 			env->prog = new_prog;
20841 			delta += cnt - 1;
20842 
20843 			ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
20844 			if (ret < 0)
20845 				return ret;
20846 		}
20847 	}
20848 
20849 	if (delta)
20850 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
20851 
20852 	if (bpf_prog_is_offloaded(env->prog->aux))
20853 		return 0;
20854 
20855 	insn = env->prog->insnsi + delta;
20856 
20857 	for (i = 0; i < insn_cnt; i++, insn++) {
20858 		bpf_convert_ctx_access_t convert_ctx_access;
20859 		u8 mode;
20860 
20861 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
20862 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
20863 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
20864 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
20865 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
20866 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
20867 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
20868 			type = BPF_READ;
20869 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
20870 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
20871 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
20872 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
20873 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
20874 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
20875 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
20876 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
20877 			type = BPF_WRITE;
20878 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) ||
20879 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) ||
20880 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
20881 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
20882 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
20883 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
20884 			env->prog->aux->num_exentries++;
20885 			continue;
20886 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
20887 			   epilogue_cnt &&
20888 			   i + delta < subprogs[1].start) {
20889 			/* Generate epilogue for the main prog */
20890 			if (epilogue_idx) {
20891 				/* jump back to the earlier generated epilogue */
20892 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
20893 				cnt = 1;
20894 			} else {
20895 				memcpy(insn_buf, epilogue_buf,
20896 				       epilogue_cnt * sizeof(*epilogue_buf));
20897 				cnt = epilogue_cnt;
20898 				/* epilogue_idx cannot be 0. It must have at
20899 				 * least one ctx ptr saving insn before the
20900 				 * epilogue.
20901 				 */
20902 				epilogue_idx = i + delta;
20903 			}
20904 			goto patch_insn_buf;
20905 		} else {
20906 			continue;
20907 		}
20908 
20909 		if (type == BPF_WRITE &&
20910 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
20911 			struct bpf_insn patch[] = {
20912 				*insn,
20913 				BPF_ST_NOSPEC(),
20914 			};
20915 
20916 			cnt = ARRAY_SIZE(patch);
20917 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
20918 			if (!new_prog)
20919 				return -ENOMEM;
20920 
20921 			delta    += cnt - 1;
20922 			env->prog = new_prog;
20923 			insn      = new_prog->insnsi + i + delta;
20924 			continue;
20925 		}
20926 
20927 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
20928 		case PTR_TO_CTX:
20929 			if (!ops->convert_ctx_access)
20930 				continue;
20931 			convert_ctx_access = ops->convert_ctx_access;
20932 			break;
20933 		case PTR_TO_SOCKET:
20934 		case PTR_TO_SOCK_COMMON:
20935 			convert_ctx_access = bpf_sock_convert_ctx_access;
20936 			break;
20937 		case PTR_TO_TCP_SOCK:
20938 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
20939 			break;
20940 		case PTR_TO_XDP_SOCK:
20941 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
20942 			break;
20943 		case PTR_TO_BTF_ID:
20944 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
20945 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
20946 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
20947 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
20948 		 * any faults for loads into such types. BPF_WRITE is disallowed
20949 		 * for this case.
20950 		 */
20951 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
20952 			if (type == BPF_READ) {
20953 				if (BPF_MODE(insn->code) == BPF_MEM)
20954 					insn->code = BPF_LDX | BPF_PROBE_MEM |
20955 						     BPF_SIZE((insn)->code);
20956 				else
20957 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
20958 						     BPF_SIZE((insn)->code);
20959 				env->prog->aux->num_exentries++;
20960 			}
20961 			continue;
20962 		case PTR_TO_ARENA:
20963 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
20964 				verbose(env, "sign extending loads from arena are not supported yet\n");
20965 				return -EOPNOTSUPP;
20966 			}
20967 			insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
20968 			env->prog->aux->num_exentries++;
20969 			continue;
20970 		default:
20971 			continue;
20972 		}
20973 
20974 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
20975 		size = BPF_LDST_BYTES(insn);
20976 		mode = BPF_MODE(insn->code);
20977 
20978 		/* If the read access is a narrower load of the field,
20979 		 * convert to a 4/8-byte load, to minimum program type specific
20980 		 * convert_ctx_access changes. If conversion is successful,
20981 		 * we will apply proper mask to the result.
20982 		 */
20983 		is_narrower_load = size < ctx_field_size;
20984 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
20985 		off = insn->off;
20986 		if (is_narrower_load) {
20987 			u8 size_code;
20988 
20989 			if (type == BPF_WRITE) {
20990 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
20991 				return -EINVAL;
20992 			}
20993 
20994 			size_code = BPF_H;
20995 			if (ctx_field_size == 4)
20996 				size_code = BPF_W;
20997 			else if (ctx_field_size == 8)
20998 				size_code = BPF_DW;
20999 
21000 			insn->off = off & ~(size_default - 1);
21001 			insn->code = BPF_LDX | BPF_MEM | size_code;
21002 		}
21003 
21004 		target_size = 0;
21005 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
21006 					 &target_size);
21007 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
21008 		    (ctx_field_size && !target_size)) {
21009 			verbose(env, "bpf verifier is misconfigured\n");
21010 			return -EINVAL;
21011 		}
21012 
21013 		if (is_narrower_load && size < target_size) {
21014 			u8 shift = bpf_ctx_narrow_access_offset(
21015 				off, size, size_default) * 8;
21016 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
21017 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
21018 				return -EINVAL;
21019 			}
21020 			if (ctx_field_size <= 4) {
21021 				if (shift)
21022 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
21023 									insn->dst_reg,
21024 									shift);
21025 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
21026 								(1 << size * 8) - 1);
21027 			} else {
21028 				if (shift)
21029 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
21030 									insn->dst_reg,
21031 									shift);
21032 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
21033 								(1ULL << size * 8) - 1);
21034 			}
21035 		}
21036 		if (mode == BPF_MEMSX)
21037 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
21038 						       insn->dst_reg, insn->dst_reg,
21039 						       size * 8, 0);
21040 
21041 patch_insn_buf:
21042 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21043 		if (!new_prog)
21044 			return -ENOMEM;
21045 
21046 		delta += cnt - 1;
21047 
21048 		/* keep walking new program and skip insns we just inserted */
21049 		env->prog = new_prog;
21050 		insn      = new_prog->insnsi + i + delta;
21051 	}
21052 
21053 	return 0;
21054 }
21055 
21056 static int jit_subprogs(struct bpf_verifier_env *env)
21057 {
21058 	struct bpf_prog *prog = env->prog, **func, *tmp;
21059 	int i, j, subprog_start, subprog_end = 0, len, subprog;
21060 	struct bpf_map *map_ptr;
21061 	struct bpf_insn *insn;
21062 	void *old_bpf_func;
21063 	int err, num_exentries;
21064 
21065 	if (env->subprog_cnt <= 1)
21066 		return 0;
21067 
21068 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21069 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
21070 			continue;
21071 
21072 		/* Upon error here we cannot fall back to interpreter but
21073 		 * need a hard reject of the program. Thus -EFAULT is
21074 		 * propagated in any case.
21075 		 */
21076 		subprog = find_subprog(env, i + insn->imm + 1);
21077 		if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d",
21078 				    i + insn->imm + 1))
21079 			return -EFAULT;
21080 		/* temporarily remember subprog id inside insn instead of
21081 		 * aux_data, since next loop will split up all insns into funcs
21082 		 */
21083 		insn->off = subprog;
21084 		/* remember original imm in case JIT fails and fallback
21085 		 * to interpreter will be needed
21086 		 */
21087 		env->insn_aux_data[i].call_imm = insn->imm;
21088 		/* point imm to __bpf_call_base+1 from JITs point of view */
21089 		insn->imm = 1;
21090 		if (bpf_pseudo_func(insn)) {
21091 #if defined(MODULES_VADDR)
21092 			u64 addr = MODULES_VADDR;
21093 #else
21094 			u64 addr = VMALLOC_START;
21095 #endif
21096 			/* jit (e.g. x86_64) may emit fewer instructions
21097 			 * if it learns a u32 imm is the same as a u64 imm.
21098 			 * Set close enough to possible prog address.
21099 			 */
21100 			insn[0].imm = (u32)addr;
21101 			insn[1].imm = addr >> 32;
21102 		}
21103 	}
21104 
21105 	err = bpf_prog_alloc_jited_linfo(prog);
21106 	if (err)
21107 		goto out_undo_insn;
21108 
21109 	err = -ENOMEM;
21110 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
21111 	if (!func)
21112 		goto out_undo_insn;
21113 
21114 	for (i = 0; i < env->subprog_cnt; i++) {
21115 		subprog_start = subprog_end;
21116 		subprog_end = env->subprog_info[i + 1].start;
21117 
21118 		len = subprog_end - subprog_start;
21119 		/* bpf_prog_run() doesn't call subprogs directly,
21120 		 * hence main prog stats include the runtime of subprogs.
21121 		 * subprogs don't have IDs and not reachable via prog_get_next_id
21122 		 * func[i]->stats will never be accessed and stays NULL
21123 		 */
21124 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
21125 		if (!func[i])
21126 			goto out_free;
21127 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
21128 		       len * sizeof(struct bpf_insn));
21129 		func[i]->type = prog->type;
21130 		func[i]->len = len;
21131 		if (bpf_prog_calc_tag(func[i]))
21132 			goto out_free;
21133 		func[i]->is_func = 1;
21134 		func[i]->sleepable = prog->sleepable;
21135 		func[i]->aux->func_idx = i;
21136 		/* Below members will be freed only at prog->aux */
21137 		func[i]->aux->btf = prog->aux->btf;
21138 		func[i]->aux->func_info = prog->aux->func_info;
21139 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
21140 		func[i]->aux->poke_tab = prog->aux->poke_tab;
21141 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
21142 
21143 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
21144 			struct bpf_jit_poke_descriptor *poke;
21145 
21146 			poke = &prog->aux->poke_tab[j];
21147 			if (poke->insn_idx < subprog_end &&
21148 			    poke->insn_idx >= subprog_start)
21149 				poke->aux = func[i]->aux;
21150 		}
21151 
21152 		func[i]->aux->name[0] = 'F';
21153 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
21154 		if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
21155 			func[i]->aux->jits_use_priv_stack = true;
21156 
21157 		func[i]->jit_requested = 1;
21158 		func[i]->blinding_requested = prog->blinding_requested;
21159 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
21160 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
21161 		func[i]->aux->linfo = prog->aux->linfo;
21162 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
21163 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
21164 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
21165 		func[i]->aux->arena = prog->aux->arena;
21166 		num_exentries = 0;
21167 		insn = func[i]->insnsi;
21168 		for (j = 0; j < func[i]->len; j++, insn++) {
21169 			if (BPF_CLASS(insn->code) == BPF_LDX &&
21170 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
21171 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
21172 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
21173 				num_exentries++;
21174 			if ((BPF_CLASS(insn->code) == BPF_STX ||
21175 			     BPF_CLASS(insn->code) == BPF_ST) &&
21176 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
21177 				num_exentries++;
21178 			if (BPF_CLASS(insn->code) == BPF_STX &&
21179 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
21180 				num_exentries++;
21181 		}
21182 		func[i]->aux->num_exentries = num_exentries;
21183 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
21184 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
21185 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
21186 		func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
21187 		if (!i)
21188 			func[i]->aux->exception_boundary = env->seen_exception;
21189 		func[i] = bpf_int_jit_compile(func[i]);
21190 		if (!func[i]->jited) {
21191 			err = -ENOTSUPP;
21192 			goto out_free;
21193 		}
21194 		cond_resched();
21195 	}
21196 
21197 	/* at this point all bpf functions were successfully JITed
21198 	 * now populate all bpf_calls with correct addresses and
21199 	 * run last pass of JIT
21200 	 */
21201 	for (i = 0; i < env->subprog_cnt; i++) {
21202 		insn = func[i]->insnsi;
21203 		for (j = 0; j < func[i]->len; j++, insn++) {
21204 			if (bpf_pseudo_func(insn)) {
21205 				subprog = insn->off;
21206 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
21207 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
21208 				continue;
21209 			}
21210 			if (!bpf_pseudo_call(insn))
21211 				continue;
21212 			subprog = insn->off;
21213 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
21214 		}
21215 
21216 		/* we use the aux data to keep a list of the start addresses
21217 		 * of the JITed images for each function in the program
21218 		 *
21219 		 * for some architectures, such as powerpc64, the imm field
21220 		 * might not be large enough to hold the offset of the start
21221 		 * address of the callee's JITed image from __bpf_call_base
21222 		 *
21223 		 * in such cases, we can lookup the start address of a callee
21224 		 * by using its subprog id, available from the off field of
21225 		 * the call instruction, as an index for this list
21226 		 */
21227 		func[i]->aux->func = func;
21228 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
21229 		func[i]->aux->real_func_cnt = env->subprog_cnt;
21230 	}
21231 	for (i = 0; i < env->subprog_cnt; i++) {
21232 		old_bpf_func = func[i]->bpf_func;
21233 		tmp = bpf_int_jit_compile(func[i]);
21234 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
21235 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
21236 			err = -ENOTSUPP;
21237 			goto out_free;
21238 		}
21239 		cond_resched();
21240 	}
21241 
21242 	/* finally lock prog and jit images for all functions and
21243 	 * populate kallsysm. Begin at the first subprogram, since
21244 	 * bpf_prog_load will add the kallsyms for the main program.
21245 	 */
21246 	for (i = 1; i < env->subprog_cnt; i++) {
21247 		err = bpf_prog_lock_ro(func[i]);
21248 		if (err)
21249 			goto out_free;
21250 	}
21251 
21252 	for (i = 1; i < env->subprog_cnt; i++)
21253 		bpf_prog_kallsyms_add(func[i]);
21254 
21255 	/* Last step: make now unused interpreter insns from main
21256 	 * prog consistent for later dump requests, so they can
21257 	 * later look the same as if they were interpreted only.
21258 	 */
21259 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21260 		if (bpf_pseudo_func(insn)) {
21261 			insn[0].imm = env->insn_aux_data[i].call_imm;
21262 			insn[1].imm = insn->off;
21263 			insn->off = 0;
21264 			continue;
21265 		}
21266 		if (!bpf_pseudo_call(insn))
21267 			continue;
21268 		insn->off = env->insn_aux_data[i].call_imm;
21269 		subprog = find_subprog(env, i + insn->off + 1);
21270 		insn->imm = subprog;
21271 	}
21272 
21273 	prog->jited = 1;
21274 	prog->bpf_func = func[0]->bpf_func;
21275 	prog->jited_len = func[0]->jited_len;
21276 	prog->aux->extable = func[0]->aux->extable;
21277 	prog->aux->num_exentries = func[0]->aux->num_exentries;
21278 	prog->aux->func = func;
21279 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
21280 	prog->aux->real_func_cnt = env->subprog_cnt;
21281 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
21282 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
21283 	bpf_prog_jit_attempt_done(prog);
21284 	return 0;
21285 out_free:
21286 	/* We failed JIT'ing, so at this point we need to unregister poke
21287 	 * descriptors from subprogs, so that kernel is not attempting to
21288 	 * patch it anymore as we're freeing the subprog JIT memory.
21289 	 */
21290 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
21291 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
21292 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
21293 	}
21294 	/* At this point we're guaranteed that poke descriptors are not
21295 	 * live anymore. We can just unlink its descriptor table as it's
21296 	 * released with the main prog.
21297 	 */
21298 	for (i = 0; i < env->subprog_cnt; i++) {
21299 		if (!func[i])
21300 			continue;
21301 		func[i]->aux->poke_tab = NULL;
21302 		bpf_jit_free(func[i]);
21303 	}
21304 	kfree(func);
21305 out_undo_insn:
21306 	/* cleanup main prog to be interpreted */
21307 	prog->jit_requested = 0;
21308 	prog->blinding_requested = 0;
21309 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21310 		if (!bpf_pseudo_call(insn))
21311 			continue;
21312 		insn->off = 0;
21313 		insn->imm = env->insn_aux_data[i].call_imm;
21314 	}
21315 	bpf_prog_jit_attempt_done(prog);
21316 	return err;
21317 }
21318 
21319 static int fixup_call_args(struct bpf_verifier_env *env)
21320 {
21321 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
21322 	struct bpf_prog *prog = env->prog;
21323 	struct bpf_insn *insn = prog->insnsi;
21324 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
21325 	int i, depth;
21326 #endif
21327 	int err = 0;
21328 
21329 	if (env->prog->jit_requested &&
21330 	    !bpf_prog_is_offloaded(env->prog->aux)) {
21331 		err = jit_subprogs(env);
21332 		if (err == 0)
21333 			return 0;
21334 		if (err == -EFAULT)
21335 			return err;
21336 	}
21337 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
21338 	if (has_kfunc_call) {
21339 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
21340 		return -EINVAL;
21341 	}
21342 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
21343 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
21344 		 * have to be rejected, since interpreter doesn't support them yet.
21345 		 */
21346 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
21347 		return -EINVAL;
21348 	}
21349 	for (i = 0; i < prog->len; i++, insn++) {
21350 		if (bpf_pseudo_func(insn)) {
21351 			/* When JIT fails the progs with callback calls
21352 			 * have to be rejected, since interpreter doesn't support them yet.
21353 			 */
21354 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
21355 			return -EINVAL;
21356 		}
21357 
21358 		if (!bpf_pseudo_call(insn))
21359 			continue;
21360 		depth = get_callee_stack_depth(env, insn, i);
21361 		if (depth < 0)
21362 			return depth;
21363 		bpf_patch_call_args(insn, depth);
21364 	}
21365 	err = 0;
21366 #endif
21367 	return err;
21368 }
21369 
21370 /* replace a generic kfunc with a specialized version if necessary */
21371 static void specialize_kfunc(struct bpf_verifier_env *env,
21372 			     u32 func_id, u16 offset, unsigned long *addr)
21373 {
21374 	struct bpf_prog *prog = env->prog;
21375 	bool seen_direct_write;
21376 	void *xdp_kfunc;
21377 	bool is_rdonly;
21378 
21379 	if (bpf_dev_bound_kfunc_id(func_id)) {
21380 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
21381 		if (xdp_kfunc) {
21382 			*addr = (unsigned long)xdp_kfunc;
21383 			return;
21384 		}
21385 		/* fallback to default kfunc when not supported by netdev */
21386 	}
21387 
21388 	if (offset)
21389 		return;
21390 
21391 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
21392 		seen_direct_write = env->seen_direct_write;
21393 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
21394 
21395 		if (is_rdonly)
21396 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
21397 
21398 		/* restore env->seen_direct_write to its original value, since
21399 		 * may_access_direct_pkt_data mutates it
21400 		 */
21401 		env->seen_direct_write = seen_direct_write;
21402 	}
21403 
21404 	if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr] &&
21405 	    bpf_lsm_has_d_inode_locked(prog))
21406 		*addr = (unsigned long)bpf_set_dentry_xattr_locked;
21407 
21408 	if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr] &&
21409 	    bpf_lsm_has_d_inode_locked(prog))
21410 		*addr = (unsigned long)bpf_remove_dentry_xattr_locked;
21411 }
21412 
21413 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
21414 					    u16 struct_meta_reg,
21415 					    u16 node_offset_reg,
21416 					    struct bpf_insn *insn,
21417 					    struct bpf_insn *insn_buf,
21418 					    int *cnt)
21419 {
21420 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
21421 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
21422 
21423 	insn_buf[0] = addr[0];
21424 	insn_buf[1] = addr[1];
21425 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
21426 	insn_buf[3] = *insn;
21427 	*cnt = 4;
21428 }
21429 
21430 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
21431 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
21432 {
21433 	const struct bpf_kfunc_desc *desc;
21434 
21435 	if (!insn->imm) {
21436 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
21437 		return -EINVAL;
21438 	}
21439 
21440 	*cnt = 0;
21441 
21442 	/* insn->imm has the btf func_id. Replace it with an offset relative to
21443 	 * __bpf_call_base, unless the JIT needs to call functions that are
21444 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
21445 	 */
21446 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
21447 	if (!desc) {
21448 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
21449 			insn->imm);
21450 		return -EFAULT;
21451 	}
21452 
21453 	if (!bpf_jit_supports_far_kfunc_call())
21454 		insn->imm = BPF_CALL_IMM(desc->addr);
21455 	if (insn->off)
21456 		return 0;
21457 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
21458 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
21459 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21460 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
21461 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
21462 
21463 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
21464 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
21465 				insn_idx);
21466 			return -EFAULT;
21467 		}
21468 
21469 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
21470 		insn_buf[1] = addr[0];
21471 		insn_buf[2] = addr[1];
21472 		insn_buf[3] = *insn;
21473 		*cnt = 4;
21474 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
21475 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
21476 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
21477 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21478 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
21479 
21480 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
21481 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
21482 				insn_idx);
21483 			return -EFAULT;
21484 		}
21485 
21486 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
21487 		    !kptr_struct_meta) {
21488 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
21489 				insn_idx);
21490 			return -EFAULT;
21491 		}
21492 
21493 		insn_buf[0] = addr[0];
21494 		insn_buf[1] = addr[1];
21495 		insn_buf[2] = *insn;
21496 		*cnt = 3;
21497 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
21498 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
21499 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
21500 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21501 		int struct_meta_reg = BPF_REG_3;
21502 		int node_offset_reg = BPF_REG_4;
21503 
21504 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
21505 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
21506 			struct_meta_reg = BPF_REG_4;
21507 			node_offset_reg = BPF_REG_5;
21508 		}
21509 
21510 		if (!kptr_struct_meta) {
21511 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
21512 				insn_idx);
21513 			return -EFAULT;
21514 		}
21515 
21516 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
21517 						node_offset_reg, insn, insn_buf, cnt);
21518 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
21519 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
21520 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
21521 		*cnt = 1;
21522 	}
21523 
21524 	if (env->insn_aux_data[insn_idx].arg_prog) {
21525 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
21526 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
21527 		int idx = *cnt;
21528 
21529 		insn_buf[idx++] = ld_addrs[0];
21530 		insn_buf[idx++] = ld_addrs[1];
21531 		insn_buf[idx++] = *insn;
21532 		*cnt = idx;
21533 	}
21534 	return 0;
21535 }
21536 
21537 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
21538 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
21539 {
21540 	struct bpf_subprog_info *info = env->subprog_info;
21541 	int cnt = env->subprog_cnt;
21542 	struct bpf_prog *prog;
21543 
21544 	/* We only reserve one slot for hidden subprogs in subprog_info. */
21545 	if (env->hidden_subprog_cnt) {
21546 		verbose(env, "verifier internal error: only one hidden subprog supported\n");
21547 		return -EFAULT;
21548 	}
21549 	/* We're not patching any existing instruction, just appending the new
21550 	 * ones for the hidden subprog. Hence all of the adjustment operations
21551 	 * in bpf_patch_insn_data are no-ops.
21552 	 */
21553 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
21554 	if (!prog)
21555 		return -ENOMEM;
21556 	env->prog = prog;
21557 	info[cnt + 1].start = info[cnt].start;
21558 	info[cnt].start = prog->len - len + 1;
21559 	env->subprog_cnt++;
21560 	env->hidden_subprog_cnt++;
21561 	return 0;
21562 }
21563 
21564 /* Do various post-verification rewrites in a single program pass.
21565  * These rewrites simplify JIT and interpreter implementations.
21566  */
21567 static int do_misc_fixups(struct bpf_verifier_env *env)
21568 {
21569 	struct bpf_prog *prog = env->prog;
21570 	enum bpf_attach_type eatype = prog->expected_attach_type;
21571 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
21572 	struct bpf_insn *insn = prog->insnsi;
21573 	const struct bpf_func_proto *fn;
21574 	const int insn_cnt = prog->len;
21575 	const struct bpf_map_ops *ops;
21576 	struct bpf_insn_aux_data *aux;
21577 	struct bpf_insn *insn_buf = env->insn_buf;
21578 	struct bpf_prog *new_prog;
21579 	struct bpf_map *map_ptr;
21580 	int i, ret, cnt, delta = 0, cur_subprog = 0;
21581 	struct bpf_subprog_info *subprogs = env->subprog_info;
21582 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
21583 	u16 stack_depth_extra = 0;
21584 
21585 	if (env->seen_exception && !env->exception_callback_subprog) {
21586 		struct bpf_insn patch[] = {
21587 			env->prog->insnsi[insn_cnt - 1],
21588 			BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
21589 			BPF_EXIT_INSN(),
21590 		};
21591 
21592 		ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
21593 		if (ret < 0)
21594 			return ret;
21595 		prog = env->prog;
21596 		insn = prog->insnsi;
21597 
21598 		env->exception_callback_subprog = env->subprog_cnt - 1;
21599 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
21600 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
21601 	}
21602 
21603 	for (i = 0; i < insn_cnt;) {
21604 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
21605 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
21606 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
21607 				/* convert to 32-bit mov that clears upper 32-bit */
21608 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
21609 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
21610 				insn->off = 0;
21611 				insn->imm = 0;
21612 			} /* cast from as(0) to as(1) should be handled by JIT */
21613 			goto next_insn;
21614 		}
21615 
21616 		if (env->insn_aux_data[i + delta].needs_zext)
21617 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
21618 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
21619 
21620 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
21621 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
21622 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
21623 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
21624 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
21625 		    insn->off == 1 && insn->imm == -1) {
21626 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
21627 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
21628 			struct bpf_insn *patchlet;
21629 			struct bpf_insn chk_and_sdiv[] = {
21630 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21631 					     BPF_NEG | BPF_K, insn->dst_reg,
21632 					     0, 0, 0),
21633 			};
21634 			struct bpf_insn chk_and_smod[] = {
21635 				BPF_MOV32_IMM(insn->dst_reg, 0),
21636 			};
21637 
21638 			patchlet = isdiv ? chk_and_sdiv : chk_and_smod;
21639 			cnt = isdiv ? ARRAY_SIZE(chk_and_sdiv) : ARRAY_SIZE(chk_and_smod);
21640 
21641 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
21642 			if (!new_prog)
21643 				return -ENOMEM;
21644 
21645 			delta    += cnt - 1;
21646 			env->prog = prog = new_prog;
21647 			insn      = new_prog->insnsi + i + delta;
21648 			goto next_insn;
21649 		}
21650 
21651 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
21652 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
21653 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
21654 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
21655 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
21656 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
21657 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
21658 			bool is_sdiv = isdiv && insn->off == 1;
21659 			bool is_smod = !isdiv && insn->off == 1;
21660 			struct bpf_insn *patchlet;
21661 			struct bpf_insn chk_and_div[] = {
21662 				/* [R,W]x div 0 -> 0 */
21663 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21664 					     BPF_JNE | BPF_K, insn->src_reg,
21665 					     0, 2, 0),
21666 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
21667 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21668 				*insn,
21669 			};
21670 			struct bpf_insn chk_and_mod[] = {
21671 				/* [R,W]x mod 0 -> [R,W]x */
21672 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21673 					     BPF_JEQ | BPF_K, insn->src_reg,
21674 					     0, 1 + (is64 ? 0 : 1), 0),
21675 				*insn,
21676 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21677 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
21678 			};
21679 			struct bpf_insn chk_and_sdiv[] = {
21680 				/* [R,W]x sdiv 0 -> 0
21681 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
21682 				 * INT_MIN sdiv -1 -> INT_MIN
21683 				 */
21684 				BPF_MOV64_REG(BPF_REG_AX, insn->src_reg),
21685 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21686 					     BPF_ADD | BPF_K, BPF_REG_AX,
21687 					     0, 0, 1),
21688 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21689 					     BPF_JGT | BPF_K, BPF_REG_AX,
21690 					     0, 4, 1),
21691 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21692 					     BPF_JEQ | BPF_K, BPF_REG_AX,
21693 					     0, 1, 0),
21694 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21695 					     BPF_MOV | BPF_K, insn->dst_reg,
21696 					     0, 0, 0),
21697 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
21698 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21699 					     BPF_NEG | BPF_K, insn->dst_reg,
21700 					     0, 0, 0),
21701 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21702 				*insn,
21703 			};
21704 			struct bpf_insn chk_and_smod[] = {
21705 				/* [R,W]x mod 0 -> [R,W]x */
21706 				/* [R,W]x mod -1 -> 0 */
21707 				BPF_MOV64_REG(BPF_REG_AX, insn->src_reg),
21708 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21709 					     BPF_ADD | BPF_K, BPF_REG_AX,
21710 					     0, 0, 1),
21711 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21712 					     BPF_JGT | BPF_K, BPF_REG_AX,
21713 					     0, 3, 1),
21714 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21715 					     BPF_JEQ | BPF_K, BPF_REG_AX,
21716 					     0, 3 + (is64 ? 0 : 1), 1),
21717 				BPF_MOV32_IMM(insn->dst_reg, 0),
21718 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21719 				*insn,
21720 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21721 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
21722 			};
21723 
21724 			if (is_sdiv) {
21725 				patchlet = chk_and_sdiv;
21726 				cnt = ARRAY_SIZE(chk_and_sdiv);
21727 			} else if (is_smod) {
21728 				patchlet = chk_and_smod;
21729 				cnt = ARRAY_SIZE(chk_and_smod) - (is64 ? 2 : 0);
21730 			} else {
21731 				patchlet = isdiv ? chk_and_div : chk_and_mod;
21732 				cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
21733 					      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
21734 			}
21735 
21736 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
21737 			if (!new_prog)
21738 				return -ENOMEM;
21739 
21740 			delta    += cnt - 1;
21741 			env->prog = prog = new_prog;
21742 			insn      = new_prog->insnsi + i + delta;
21743 			goto next_insn;
21744 		}
21745 
21746 		/* Make it impossible to de-reference a userspace address */
21747 		if (BPF_CLASS(insn->code) == BPF_LDX &&
21748 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
21749 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
21750 			struct bpf_insn *patch = &insn_buf[0];
21751 			u64 uaddress_limit = bpf_arch_uaddress_limit();
21752 
21753 			if (!uaddress_limit)
21754 				goto next_insn;
21755 
21756 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
21757 			if (insn->off)
21758 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
21759 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
21760 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
21761 			*patch++ = *insn;
21762 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
21763 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
21764 
21765 			cnt = patch - insn_buf;
21766 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21767 			if (!new_prog)
21768 				return -ENOMEM;
21769 
21770 			delta    += cnt - 1;
21771 			env->prog = prog = new_prog;
21772 			insn      = new_prog->insnsi + i + delta;
21773 			goto next_insn;
21774 		}
21775 
21776 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
21777 		if (BPF_CLASS(insn->code) == BPF_LD &&
21778 		    (BPF_MODE(insn->code) == BPF_ABS ||
21779 		     BPF_MODE(insn->code) == BPF_IND)) {
21780 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
21781 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
21782 				verbose(env, "bpf verifier is misconfigured\n");
21783 				return -EINVAL;
21784 			}
21785 
21786 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21787 			if (!new_prog)
21788 				return -ENOMEM;
21789 
21790 			delta    += cnt - 1;
21791 			env->prog = prog = new_prog;
21792 			insn      = new_prog->insnsi + i + delta;
21793 			goto next_insn;
21794 		}
21795 
21796 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
21797 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
21798 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
21799 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
21800 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
21801 			struct bpf_insn *patch = &insn_buf[0];
21802 			bool issrc, isneg, isimm;
21803 			u32 off_reg;
21804 
21805 			aux = &env->insn_aux_data[i + delta];
21806 			if (!aux->alu_state ||
21807 			    aux->alu_state == BPF_ALU_NON_POINTER)
21808 				goto next_insn;
21809 
21810 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
21811 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
21812 				BPF_ALU_SANITIZE_SRC;
21813 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
21814 
21815 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
21816 			if (isimm) {
21817 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
21818 			} else {
21819 				if (isneg)
21820 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
21821 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
21822 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
21823 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
21824 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
21825 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
21826 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
21827 			}
21828 			if (!issrc)
21829 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
21830 			insn->src_reg = BPF_REG_AX;
21831 			if (isneg)
21832 				insn->code = insn->code == code_add ?
21833 					     code_sub : code_add;
21834 			*patch++ = *insn;
21835 			if (issrc && isneg && !isimm)
21836 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
21837 			cnt = patch - insn_buf;
21838 
21839 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21840 			if (!new_prog)
21841 				return -ENOMEM;
21842 
21843 			delta    += cnt - 1;
21844 			env->prog = prog = new_prog;
21845 			insn      = new_prog->insnsi + i + delta;
21846 			goto next_insn;
21847 		}
21848 
21849 		if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) {
21850 			int stack_off_cnt = -stack_depth - 16;
21851 
21852 			/*
21853 			 * Two 8 byte slots, depth-16 stores the count, and
21854 			 * depth-8 stores the start timestamp of the loop.
21855 			 *
21856 			 * The starting value of count is BPF_MAX_TIMED_LOOPS
21857 			 * (0xffff).  Every iteration loads it and subs it by 1,
21858 			 * until the value becomes 0 in AX (thus, 1 in stack),
21859 			 * after which we call arch_bpf_timed_may_goto, which
21860 			 * either sets AX to 0xffff to keep looping, or to 0
21861 			 * upon timeout. AX is then stored into the stack. In
21862 			 * the next iteration, we either see 0 and break out, or
21863 			 * continue iterating until the next time value is 0
21864 			 * after subtraction, rinse and repeat.
21865 			 */
21866 			stack_depth_extra = 16;
21867 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt);
21868 			if (insn->off >= 0)
21869 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5);
21870 			else
21871 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
21872 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
21873 			insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
21874 			/*
21875 			 * AX is used as an argument to pass in stack_off_cnt
21876 			 * (to add to r10/fp), and also as the return value of
21877 			 * the call to arch_bpf_timed_may_goto.
21878 			 */
21879 			insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt);
21880 			insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
21881 			insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt);
21882 			cnt = 7;
21883 
21884 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21885 			if (!new_prog)
21886 				return -ENOMEM;
21887 
21888 			delta += cnt - 1;
21889 			env->prog = prog = new_prog;
21890 			insn = new_prog->insnsi + i + delta;
21891 			goto next_insn;
21892 		} else if (is_may_goto_insn(insn)) {
21893 			int stack_off = -stack_depth - 8;
21894 
21895 			stack_depth_extra = 8;
21896 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
21897 			if (insn->off >= 0)
21898 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
21899 			else
21900 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
21901 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
21902 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
21903 			cnt = 4;
21904 
21905 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21906 			if (!new_prog)
21907 				return -ENOMEM;
21908 
21909 			delta += cnt - 1;
21910 			env->prog = prog = new_prog;
21911 			insn = new_prog->insnsi + i + delta;
21912 			goto next_insn;
21913 		}
21914 
21915 		if (insn->code != (BPF_JMP | BPF_CALL))
21916 			goto next_insn;
21917 		if (insn->src_reg == BPF_PSEUDO_CALL)
21918 			goto next_insn;
21919 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
21920 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
21921 			if (ret)
21922 				return ret;
21923 			if (cnt == 0)
21924 				goto next_insn;
21925 
21926 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21927 			if (!new_prog)
21928 				return -ENOMEM;
21929 
21930 			delta	 += cnt - 1;
21931 			env->prog = prog = new_prog;
21932 			insn	  = new_prog->insnsi + i + delta;
21933 			goto next_insn;
21934 		}
21935 
21936 		/* Skip inlining the helper call if the JIT does it. */
21937 		if (bpf_jit_inlines_helper_call(insn->imm))
21938 			goto next_insn;
21939 
21940 		if (insn->imm == BPF_FUNC_get_route_realm)
21941 			prog->dst_needed = 1;
21942 		if (insn->imm == BPF_FUNC_get_prandom_u32)
21943 			bpf_user_rnd_init_once();
21944 		if (insn->imm == BPF_FUNC_override_return)
21945 			prog->kprobe_override = 1;
21946 		if (insn->imm == BPF_FUNC_tail_call) {
21947 			/* If we tail call into other programs, we
21948 			 * cannot make any assumptions since they can
21949 			 * be replaced dynamically during runtime in
21950 			 * the program array.
21951 			 */
21952 			prog->cb_access = 1;
21953 			if (!allow_tail_call_in_subprogs(env))
21954 				prog->aux->stack_depth = MAX_BPF_STACK;
21955 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
21956 
21957 			/* mark bpf_tail_call as different opcode to avoid
21958 			 * conditional branch in the interpreter for every normal
21959 			 * call and to prevent accidental JITing by JIT compiler
21960 			 * that doesn't support bpf_tail_call yet
21961 			 */
21962 			insn->imm = 0;
21963 			insn->code = BPF_JMP | BPF_TAIL_CALL;
21964 
21965 			aux = &env->insn_aux_data[i + delta];
21966 			if (env->bpf_capable && !prog->blinding_requested &&
21967 			    prog->jit_requested &&
21968 			    !bpf_map_key_poisoned(aux) &&
21969 			    !bpf_map_ptr_poisoned(aux) &&
21970 			    !bpf_map_ptr_unpriv(aux)) {
21971 				struct bpf_jit_poke_descriptor desc = {
21972 					.reason = BPF_POKE_REASON_TAIL_CALL,
21973 					.tail_call.map = aux->map_ptr_state.map_ptr,
21974 					.tail_call.key = bpf_map_key_immediate(aux),
21975 					.insn_idx = i + delta,
21976 				};
21977 
21978 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
21979 				if (ret < 0) {
21980 					verbose(env, "adding tail call poke descriptor failed\n");
21981 					return ret;
21982 				}
21983 
21984 				insn->imm = ret + 1;
21985 				goto next_insn;
21986 			}
21987 
21988 			if (!bpf_map_ptr_unpriv(aux))
21989 				goto next_insn;
21990 
21991 			/* instead of changing every JIT dealing with tail_call
21992 			 * emit two extra insns:
21993 			 * if (index >= max_entries) goto out;
21994 			 * index &= array->index_mask;
21995 			 * to avoid out-of-bounds cpu speculation
21996 			 */
21997 			if (bpf_map_ptr_poisoned(aux)) {
21998 				verbose(env, "tail_call abusing map_ptr\n");
21999 				return -EINVAL;
22000 			}
22001 
22002 			map_ptr = aux->map_ptr_state.map_ptr;
22003 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
22004 						  map_ptr->max_entries, 2);
22005 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
22006 						    container_of(map_ptr,
22007 								 struct bpf_array,
22008 								 map)->index_mask);
22009 			insn_buf[2] = *insn;
22010 			cnt = 3;
22011 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22012 			if (!new_prog)
22013 				return -ENOMEM;
22014 
22015 			delta    += cnt - 1;
22016 			env->prog = prog = new_prog;
22017 			insn      = new_prog->insnsi + i + delta;
22018 			goto next_insn;
22019 		}
22020 
22021 		if (insn->imm == BPF_FUNC_timer_set_callback) {
22022 			/* The verifier will process callback_fn as many times as necessary
22023 			 * with different maps and the register states prepared by
22024 			 * set_timer_callback_state will be accurate.
22025 			 *
22026 			 * The following use case is valid:
22027 			 *   map1 is shared by prog1, prog2, prog3.
22028 			 *   prog1 calls bpf_timer_init for some map1 elements
22029 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
22030 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
22031 			 *   prog3 calls bpf_timer_start for some map1 elements.
22032 			 *     Those that were not both bpf_timer_init-ed and
22033 			 *     bpf_timer_set_callback-ed will return -EINVAL.
22034 			 */
22035 			struct bpf_insn ld_addrs[2] = {
22036 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
22037 			};
22038 
22039 			insn_buf[0] = ld_addrs[0];
22040 			insn_buf[1] = ld_addrs[1];
22041 			insn_buf[2] = *insn;
22042 			cnt = 3;
22043 
22044 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22045 			if (!new_prog)
22046 				return -ENOMEM;
22047 
22048 			delta    += cnt - 1;
22049 			env->prog = prog = new_prog;
22050 			insn      = new_prog->insnsi + i + delta;
22051 			goto patch_call_imm;
22052 		}
22053 
22054 		if (is_storage_get_function(insn->imm)) {
22055 			if (!in_sleepable(env) ||
22056 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
22057 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
22058 			else
22059 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
22060 			insn_buf[1] = *insn;
22061 			cnt = 2;
22062 
22063 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22064 			if (!new_prog)
22065 				return -ENOMEM;
22066 
22067 			delta += cnt - 1;
22068 			env->prog = prog = new_prog;
22069 			insn = new_prog->insnsi + i + delta;
22070 			goto patch_call_imm;
22071 		}
22072 
22073 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
22074 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
22075 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
22076 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
22077 			 */
22078 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
22079 			insn_buf[1] = *insn;
22080 			cnt = 2;
22081 
22082 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22083 			if (!new_prog)
22084 				return -ENOMEM;
22085 
22086 			delta += cnt - 1;
22087 			env->prog = prog = new_prog;
22088 			insn = new_prog->insnsi + i + delta;
22089 			goto patch_call_imm;
22090 		}
22091 
22092 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
22093 		 * and other inlining handlers are currently limited to 64 bit
22094 		 * only.
22095 		 */
22096 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22097 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
22098 		     insn->imm == BPF_FUNC_map_update_elem ||
22099 		     insn->imm == BPF_FUNC_map_delete_elem ||
22100 		     insn->imm == BPF_FUNC_map_push_elem   ||
22101 		     insn->imm == BPF_FUNC_map_pop_elem    ||
22102 		     insn->imm == BPF_FUNC_map_peek_elem   ||
22103 		     insn->imm == BPF_FUNC_redirect_map    ||
22104 		     insn->imm == BPF_FUNC_for_each_map_elem ||
22105 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
22106 			aux = &env->insn_aux_data[i + delta];
22107 			if (bpf_map_ptr_poisoned(aux))
22108 				goto patch_call_imm;
22109 
22110 			map_ptr = aux->map_ptr_state.map_ptr;
22111 			ops = map_ptr->ops;
22112 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
22113 			    ops->map_gen_lookup) {
22114 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
22115 				if (cnt == -EOPNOTSUPP)
22116 					goto patch_map_ops_generic;
22117 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
22118 					verbose(env, "bpf verifier is misconfigured\n");
22119 					return -EINVAL;
22120 				}
22121 
22122 				new_prog = bpf_patch_insn_data(env, i + delta,
22123 							       insn_buf, cnt);
22124 				if (!new_prog)
22125 					return -ENOMEM;
22126 
22127 				delta    += cnt - 1;
22128 				env->prog = prog = new_prog;
22129 				insn      = new_prog->insnsi + i + delta;
22130 				goto next_insn;
22131 			}
22132 
22133 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
22134 				     (void *(*)(struct bpf_map *map, void *key))NULL));
22135 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
22136 				     (long (*)(struct bpf_map *map, void *key))NULL));
22137 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
22138 				     (long (*)(struct bpf_map *map, void *key, void *value,
22139 					      u64 flags))NULL));
22140 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
22141 				     (long (*)(struct bpf_map *map, void *value,
22142 					      u64 flags))NULL));
22143 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
22144 				     (long (*)(struct bpf_map *map, void *value))NULL));
22145 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
22146 				     (long (*)(struct bpf_map *map, void *value))NULL));
22147 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
22148 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
22149 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
22150 				     (long (*)(struct bpf_map *map,
22151 					      bpf_callback_t callback_fn,
22152 					      void *callback_ctx,
22153 					      u64 flags))NULL));
22154 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
22155 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
22156 
22157 patch_map_ops_generic:
22158 			switch (insn->imm) {
22159 			case BPF_FUNC_map_lookup_elem:
22160 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
22161 				goto next_insn;
22162 			case BPF_FUNC_map_update_elem:
22163 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
22164 				goto next_insn;
22165 			case BPF_FUNC_map_delete_elem:
22166 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
22167 				goto next_insn;
22168 			case BPF_FUNC_map_push_elem:
22169 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
22170 				goto next_insn;
22171 			case BPF_FUNC_map_pop_elem:
22172 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
22173 				goto next_insn;
22174 			case BPF_FUNC_map_peek_elem:
22175 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
22176 				goto next_insn;
22177 			case BPF_FUNC_redirect_map:
22178 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
22179 				goto next_insn;
22180 			case BPF_FUNC_for_each_map_elem:
22181 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
22182 				goto next_insn;
22183 			case BPF_FUNC_map_lookup_percpu_elem:
22184 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
22185 				goto next_insn;
22186 			}
22187 
22188 			goto patch_call_imm;
22189 		}
22190 
22191 		/* Implement bpf_jiffies64 inline. */
22192 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22193 		    insn->imm == BPF_FUNC_jiffies64) {
22194 			struct bpf_insn ld_jiffies_addr[2] = {
22195 				BPF_LD_IMM64(BPF_REG_0,
22196 					     (unsigned long)&jiffies),
22197 			};
22198 
22199 			insn_buf[0] = ld_jiffies_addr[0];
22200 			insn_buf[1] = ld_jiffies_addr[1];
22201 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
22202 						  BPF_REG_0, 0);
22203 			cnt = 3;
22204 
22205 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
22206 						       cnt);
22207 			if (!new_prog)
22208 				return -ENOMEM;
22209 
22210 			delta    += cnt - 1;
22211 			env->prog = prog = new_prog;
22212 			insn      = new_prog->insnsi + i + delta;
22213 			goto next_insn;
22214 		}
22215 
22216 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
22217 		/* Implement bpf_get_smp_processor_id() inline. */
22218 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
22219 		    verifier_inlines_helper_call(env, insn->imm)) {
22220 			/* BPF_FUNC_get_smp_processor_id inlining is an
22221 			 * optimization, so if cpu_number is ever
22222 			 * changed in some incompatible and hard to support
22223 			 * way, it's fine to back out this inlining logic
22224 			 */
22225 #ifdef CONFIG_SMP
22226 			insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number);
22227 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
22228 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
22229 			cnt = 3;
22230 #else
22231 			insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
22232 			cnt = 1;
22233 #endif
22234 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22235 			if (!new_prog)
22236 				return -ENOMEM;
22237 
22238 			delta    += cnt - 1;
22239 			env->prog = prog = new_prog;
22240 			insn      = new_prog->insnsi + i + delta;
22241 			goto next_insn;
22242 		}
22243 #endif
22244 		/* Implement bpf_get_func_arg inline. */
22245 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22246 		    insn->imm == BPF_FUNC_get_func_arg) {
22247 			/* Load nr_args from ctx - 8 */
22248 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22249 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
22250 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
22251 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
22252 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
22253 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
22254 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
22255 			insn_buf[7] = BPF_JMP_A(1);
22256 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
22257 			cnt = 9;
22258 
22259 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22260 			if (!new_prog)
22261 				return -ENOMEM;
22262 
22263 			delta    += cnt - 1;
22264 			env->prog = prog = new_prog;
22265 			insn      = new_prog->insnsi + i + delta;
22266 			goto next_insn;
22267 		}
22268 
22269 		/* Implement bpf_get_func_ret inline. */
22270 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22271 		    insn->imm == BPF_FUNC_get_func_ret) {
22272 			if (eatype == BPF_TRACE_FEXIT ||
22273 			    eatype == BPF_MODIFY_RETURN) {
22274 				/* Load nr_args from ctx - 8 */
22275 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22276 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
22277 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
22278 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
22279 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
22280 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
22281 				cnt = 6;
22282 			} else {
22283 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
22284 				cnt = 1;
22285 			}
22286 
22287 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22288 			if (!new_prog)
22289 				return -ENOMEM;
22290 
22291 			delta    += cnt - 1;
22292 			env->prog = prog = new_prog;
22293 			insn      = new_prog->insnsi + i + delta;
22294 			goto next_insn;
22295 		}
22296 
22297 		/* Implement get_func_arg_cnt inline. */
22298 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22299 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
22300 			/* Load nr_args from ctx - 8 */
22301 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22302 
22303 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
22304 			if (!new_prog)
22305 				return -ENOMEM;
22306 
22307 			env->prog = prog = new_prog;
22308 			insn      = new_prog->insnsi + i + delta;
22309 			goto next_insn;
22310 		}
22311 
22312 		/* Implement bpf_get_func_ip inline. */
22313 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22314 		    insn->imm == BPF_FUNC_get_func_ip) {
22315 			/* Load IP address from ctx - 16 */
22316 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
22317 
22318 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
22319 			if (!new_prog)
22320 				return -ENOMEM;
22321 
22322 			env->prog = prog = new_prog;
22323 			insn      = new_prog->insnsi + i + delta;
22324 			goto next_insn;
22325 		}
22326 
22327 		/* Implement bpf_get_branch_snapshot inline. */
22328 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
22329 		    prog->jit_requested && BITS_PER_LONG == 64 &&
22330 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
22331 			/* We are dealing with the following func protos:
22332 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
22333 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
22334 			 */
22335 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
22336 
22337 			/* struct perf_branch_entry is part of UAPI and is
22338 			 * used as an array element, so extremely unlikely to
22339 			 * ever grow or shrink
22340 			 */
22341 			BUILD_BUG_ON(br_entry_size != 24);
22342 
22343 			/* if (unlikely(flags)) return -EINVAL */
22344 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
22345 
22346 			/* Transform size (bytes) into number of entries (cnt = size / 24).
22347 			 * But to avoid expensive division instruction, we implement
22348 			 * divide-by-3 through multiplication, followed by further
22349 			 * division by 8 through 3-bit right shift.
22350 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
22351 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
22352 			 *
22353 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
22354 			 */
22355 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
22356 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
22357 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
22358 
22359 			/* call perf_snapshot_branch_stack implementation */
22360 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
22361 			/* if (entry_cnt == 0) return -ENOENT */
22362 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
22363 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
22364 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
22365 			insn_buf[7] = BPF_JMP_A(3);
22366 			/* return -EINVAL; */
22367 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
22368 			insn_buf[9] = BPF_JMP_A(1);
22369 			/* return -ENOENT; */
22370 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
22371 			cnt = 11;
22372 
22373 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22374 			if (!new_prog)
22375 				return -ENOMEM;
22376 
22377 			delta    += cnt - 1;
22378 			env->prog = prog = new_prog;
22379 			insn      = new_prog->insnsi + i + delta;
22380 			goto next_insn;
22381 		}
22382 
22383 		/* Implement bpf_kptr_xchg inline */
22384 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22385 		    insn->imm == BPF_FUNC_kptr_xchg &&
22386 		    bpf_jit_supports_ptr_xchg()) {
22387 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
22388 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
22389 			cnt = 2;
22390 
22391 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22392 			if (!new_prog)
22393 				return -ENOMEM;
22394 
22395 			delta    += cnt - 1;
22396 			env->prog = prog = new_prog;
22397 			insn      = new_prog->insnsi + i + delta;
22398 			goto next_insn;
22399 		}
22400 patch_call_imm:
22401 		fn = env->ops->get_func_proto(insn->imm, env->prog);
22402 		/* all functions that have prototype and verifier allowed
22403 		 * programs to call them, must be real in-kernel functions
22404 		 */
22405 		if (!fn->func) {
22406 			verbose(env,
22407 				"kernel subsystem misconfigured func %s#%d\n",
22408 				func_id_name(insn->imm), insn->imm);
22409 			return -EFAULT;
22410 		}
22411 		insn->imm = fn->func - __bpf_call_base;
22412 next_insn:
22413 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
22414 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
22415 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
22416 
22417 			stack_depth = subprogs[cur_subprog].stack_depth;
22418 			if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) {
22419 				verbose(env, "stack size %d(extra %d) is too large\n",
22420 					stack_depth, stack_depth_extra);
22421 				return -EINVAL;
22422 			}
22423 			cur_subprog++;
22424 			stack_depth = subprogs[cur_subprog].stack_depth;
22425 			stack_depth_extra = 0;
22426 		}
22427 		i++;
22428 		insn++;
22429 	}
22430 
22431 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
22432 	for (i = 0; i < env->subprog_cnt; i++) {
22433 		int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1;
22434 		int subprog_start = subprogs[i].start;
22435 		int stack_slots = subprogs[i].stack_extra / 8;
22436 		int slots = delta, cnt = 0;
22437 
22438 		if (!stack_slots)
22439 			continue;
22440 		/* We need two slots in case timed may_goto is supported. */
22441 		if (stack_slots > slots) {
22442 			verifier_bug(env, "stack_slots supports may_goto only");
22443 			return -EFAULT;
22444 		}
22445 
22446 		stack_depth = subprogs[i].stack_depth;
22447 		if (bpf_jit_supports_timed_may_goto()) {
22448 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
22449 						     BPF_MAX_TIMED_LOOPS);
22450 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0);
22451 		} else {
22452 			/* Add ST insn to subprog prologue to init extra stack */
22453 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
22454 						     BPF_MAX_LOOPS);
22455 		}
22456 		/* Copy first actual insn to preserve it */
22457 		insn_buf[cnt++] = env->prog->insnsi[subprog_start];
22458 
22459 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt);
22460 		if (!new_prog)
22461 			return -ENOMEM;
22462 		env->prog = prog = new_prog;
22463 		/*
22464 		 * If may_goto is a first insn of a prog there could be a jmp
22465 		 * insn that points to it, hence adjust all such jmps to point
22466 		 * to insn after BPF_ST that inits may_goto count.
22467 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
22468 		 */
22469 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta));
22470 	}
22471 
22472 	/* Since poke tab is now finalized, publish aux to tracker. */
22473 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
22474 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
22475 		if (!map_ptr->ops->map_poke_track ||
22476 		    !map_ptr->ops->map_poke_untrack ||
22477 		    !map_ptr->ops->map_poke_run) {
22478 			verbose(env, "bpf verifier is misconfigured\n");
22479 			return -EINVAL;
22480 		}
22481 
22482 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
22483 		if (ret < 0) {
22484 			verbose(env, "tracking tail call prog failed\n");
22485 			return ret;
22486 		}
22487 	}
22488 
22489 	sort_kfunc_descs_by_imm_off(env->prog);
22490 
22491 	return 0;
22492 }
22493 
22494 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
22495 					int position,
22496 					s32 stack_base,
22497 					u32 callback_subprogno,
22498 					u32 *total_cnt)
22499 {
22500 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
22501 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
22502 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
22503 	int reg_loop_max = BPF_REG_6;
22504 	int reg_loop_cnt = BPF_REG_7;
22505 	int reg_loop_ctx = BPF_REG_8;
22506 
22507 	struct bpf_insn *insn_buf = env->insn_buf;
22508 	struct bpf_prog *new_prog;
22509 	u32 callback_start;
22510 	u32 call_insn_offset;
22511 	s32 callback_offset;
22512 	u32 cnt = 0;
22513 
22514 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
22515 	 * be careful to modify this code in sync.
22516 	 */
22517 
22518 	/* Return error and jump to the end of the patch if
22519 	 * expected number of iterations is too big.
22520 	 */
22521 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
22522 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
22523 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
22524 	/* spill R6, R7, R8 to use these as loop vars */
22525 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
22526 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
22527 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
22528 	/* initialize loop vars */
22529 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
22530 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
22531 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
22532 	/* loop header,
22533 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
22534 	 */
22535 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
22536 	/* callback call,
22537 	 * correct callback offset would be set after patching
22538 	 */
22539 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
22540 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
22541 	insn_buf[cnt++] = BPF_CALL_REL(0);
22542 	/* increment loop counter */
22543 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
22544 	/* jump to loop header if callback returned 0 */
22545 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
22546 	/* return value of bpf_loop,
22547 	 * set R0 to the number of iterations
22548 	 */
22549 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
22550 	/* restore original values of R6, R7, R8 */
22551 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
22552 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
22553 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
22554 
22555 	*total_cnt = cnt;
22556 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
22557 	if (!new_prog)
22558 		return new_prog;
22559 
22560 	/* callback start is known only after patching */
22561 	callback_start = env->subprog_info[callback_subprogno].start;
22562 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
22563 	call_insn_offset = position + 12;
22564 	callback_offset = callback_start - call_insn_offset - 1;
22565 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
22566 
22567 	return new_prog;
22568 }
22569 
22570 static bool is_bpf_loop_call(struct bpf_insn *insn)
22571 {
22572 	return insn->code == (BPF_JMP | BPF_CALL) &&
22573 		insn->src_reg == 0 &&
22574 		insn->imm == BPF_FUNC_loop;
22575 }
22576 
22577 /* For all sub-programs in the program (including main) check
22578  * insn_aux_data to see if there are bpf_loop calls that require
22579  * inlining. If such calls are found the calls are replaced with a
22580  * sequence of instructions produced by `inline_bpf_loop` function and
22581  * subprog stack_depth is increased by the size of 3 registers.
22582  * This stack space is used to spill values of the R6, R7, R8.  These
22583  * registers are used to store the loop bound, counter and context
22584  * variables.
22585  */
22586 static int optimize_bpf_loop(struct bpf_verifier_env *env)
22587 {
22588 	struct bpf_subprog_info *subprogs = env->subprog_info;
22589 	int i, cur_subprog = 0, cnt, delta = 0;
22590 	struct bpf_insn *insn = env->prog->insnsi;
22591 	int insn_cnt = env->prog->len;
22592 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
22593 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
22594 	u16 stack_depth_extra = 0;
22595 
22596 	for (i = 0; i < insn_cnt; i++, insn++) {
22597 		struct bpf_loop_inline_state *inline_state =
22598 			&env->insn_aux_data[i + delta].loop_inline_state;
22599 
22600 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
22601 			struct bpf_prog *new_prog;
22602 
22603 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
22604 			new_prog = inline_bpf_loop(env,
22605 						   i + delta,
22606 						   -(stack_depth + stack_depth_extra),
22607 						   inline_state->callback_subprogno,
22608 						   &cnt);
22609 			if (!new_prog)
22610 				return -ENOMEM;
22611 
22612 			delta     += cnt - 1;
22613 			env->prog  = new_prog;
22614 			insn       = new_prog->insnsi + i + delta;
22615 		}
22616 
22617 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
22618 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
22619 			cur_subprog++;
22620 			stack_depth = subprogs[cur_subprog].stack_depth;
22621 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
22622 			stack_depth_extra = 0;
22623 		}
22624 	}
22625 
22626 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
22627 
22628 	return 0;
22629 }
22630 
22631 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
22632  * adjust subprograms stack depth when possible.
22633  */
22634 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
22635 {
22636 	struct bpf_subprog_info *subprog = env->subprog_info;
22637 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
22638 	struct bpf_insn *insn = env->prog->insnsi;
22639 	int insn_cnt = env->prog->len;
22640 	u32 spills_num;
22641 	bool modified = false;
22642 	int i, j;
22643 
22644 	for (i = 0; i < insn_cnt; i++, insn++) {
22645 		if (aux[i].fastcall_spills_num > 0) {
22646 			spills_num = aux[i].fastcall_spills_num;
22647 			/* NOPs would be removed by opt_remove_nops() */
22648 			for (j = 1; j <= spills_num; ++j) {
22649 				*(insn - j) = NOP;
22650 				*(insn + j) = NOP;
22651 			}
22652 			modified = true;
22653 		}
22654 		if ((subprog + 1)->start == i + 1) {
22655 			if (modified && !subprog->keep_fastcall_stack)
22656 				subprog->stack_depth = -subprog->fastcall_stack_off;
22657 			subprog++;
22658 			modified = false;
22659 		}
22660 	}
22661 
22662 	return 0;
22663 }
22664 
22665 static void free_states(struct bpf_verifier_env *env)
22666 {
22667 	struct bpf_verifier_state_list *sl;
22668 	struct list_head *head, *pos, *tmp;
22669 	int i;
22670 
22671 	list_for_each_safe(pos, tmp, &env->free_list) {
22672 		sl = container_of(pos, struct bpf_verifier_state_list, node);
22673 		free_verifier_state(&sl->state, false);
22674 		kfree(sl);
22675 	}
22676 	INIT_LIST_HEAD(&env->free_list);
22677 
22678 	if (!env->explored_states)
22679 		return;
22680 
22681 	for (i = 0; i < state_htab_size(env); i++) {
22682 		head = &env->explored_states[i];
22683 
22684 		list_for_each_safe(pos, tmp, head) {
22685 			sl = container_of(pos, struct bpf_verifier_state_list, node);
22686 			free_verifier_state(&sl->state, false);
22687 			kfree(sl);
22688 		}
22689 		INIT_LIST_HEAD(&env->explored_states[i]);
22690 	}
22691 }
22692 
22693 static int do_check_common(struct bpf_verifier_env *env, int subprog)
22694 {
22695 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
22696 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
22697 	struct bpf_prog_aux *aux = env->prog->aux;
22698 	struct bpf_verifier_state *state;
22699 	struct bpf_reg_state *regs;
22700 	int ret, i;
22701 
22702 	env->prev_linfo = NULL;
22703 	env->pass_cnt++;
22704 
22705 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
22706 	if (!state)
22707 		return -ENOMEM;
22708 	state->curframe = 0;
22709 	state->speculative = false;
22710 	state->branches = 1;
22711 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
22712 	if (!state->frame[0]) {
22713 		kfree(state);
22714 		return -ENOMEM;
22715 	}
22716 	env->cur_state = state;
22717 	init_func_state(env, state->frame[0],
22718 			BPF_MAIN_FUNC /* callsite */,
22719 			0 /* frameno */,
22720 			subprog);
22721 	state->first_insn_idx = env->subprog_info[subprog].start;
22722 	state->last_insn_idx = -1;
22723 
22724 	regs = state->frame[state->curframe]->regs;
22725 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
22726 		const char *sub_name = subprog_name(env, subprog);
22727 		struct bpf_subprog_arg_info *arg;
22728 		struct bpf_reg_state *reg;
22729 
22730 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
22731 		ret = btf_prepare_func_args(env, subprog);
22732 		if (ret)
22733 			goto out;
22734 
22735 		if (subprog_is_exc_cb(env, subprog)) {
22736 			state->frame[0]->in_exception_callback_fn = true;
22737 			/* We have already ensured that the callback returns an integer, just
22738 			 * like all global subprogs. We need to determine it only has a single
22739 			 * scalar argument.
22740 			 */
22741 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
22742 				verbose(env, "exception cb only supports single integer argument\n");
22743 				ret = -EINVAL;
22744 				goto out;
22745 			}
22746 		}
22747 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
22748 			arg = &sub->args[i - BPF_REG_1];
22749 			reg = &regs[i];
22750 
22751 			if (arg->arg_type == ARG_PTR_TO_CTX) {
22752 				reg->type = PTR_TO_CTX;
22753 				mark_reg_known_zero(env, regs, i);
22754 			} else if (arg->arg_type == ARG_ANYTHING) {
22755 				reg->type = SCALAR_VALUE;
22756 				mark_reg_unknown(env, regs, i);
22757 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
22758 				/* assume unspecial LOCAL dynptr type */
22759 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
22760 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
22761 				reg->type = PTR_TO_MEM;
22762 				if (arg->arg_type & PTR_MAYBE_NULL)
22763 					reg->type |= PTR_MAYBE_NULL;
22764 				mark_reg_known_zero(env, regs, i);
22765 				reg->mem_size = arg->mem_size;
22766 				reg->id = ++env->id_gen;
22767 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
22768 				reg->type = PTR_TO_BTF_ID;
22769 				if (arg->arg_type & PTR_MAYBE_NULL)
22770 					reg->type |= PTR_MAYBE_NULL;
22771 				if (arg->arg_type & PTR_UNTRUSTED)
22772 					reg->type |= PTR_UNTRUSTED;
22773 				if (arg->arg_type & PTR_TRUSTED)
22774 					reg->type |= PTR_TRUSTED;
22775 				mark_reg_known_zero(env, regs, i);
22776 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
22777 				reg->btf_id = arg->btf_id;
22778 				reg->id = ++env->id_gen;
22779 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
22780 				/* caller can pass either PTR_TO_ARENA or SCALAR */
22781 				mark_reg_unknown(env, regs, i);
22782 			} else {
22783 				WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
22784 					  i - BPF_REG_1, arg->arg_type);
22785 				ret = -EFAULT;
22786 				goto out;
22787 			}
22788 		}
22789 	} else {
22790 		/* if main BPF program has associated BTF info, validate that
22791 		 * it's matching expected signature, and otherwise mark BTF
22792 		 * info for main program as unreliable
22793 		 */
22794 		if (env->prog->aux->func_info_aux) {
22795 			ret = btf_prepare_func_args(env, 0);
22796 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
22797 				env->prog->aux->func_info_aux[0].unreliable = true;
22798 		}
22799 
22800 		/* 1st arg to a function */
22801 		regs[BPF_REG_1].type = PTR_TO_CTX;
22802 		mark_reg_known_zero(env, regs, BPF_REG_1);
22803 	}
22804 
22805 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
22806 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
22807 		for (i = 0; i < aux->ctx_arg_info_size; i++)
22808 			aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ?
22809 							  acquire_reference(env, 0) : 0;
22810 	}
22811 
22812 	ret = do_check(env);
22813 out:
22814 	/* check for NULL is necessary, since cur_state can be freed inside
22815 	 * do_check() under memory pressure.
22816 	 */
22817 	if (env->cur_state) {
22818 		free_verifier_state(env->cur_state, true);
22819 		env->cur_state = NULL;
22820 	}
22821 	while (!pop_stack(env, NULL, NULL, false));
22822 	if (!ret && pop_log)
22823 		bpf_vlog_reset(&env->log, 0);
22824 	free_states(env);
22825 	return ret;
22826 }
22827 
22828 /* Lazily verify all global functions based on their BTF, if they are called
22829  * from main BPF program or any of subprograms transitively.
22830  * BPF global subprogs called from dead code are not validated.
22831  * All callable global functions must pass verification.
22832  * Otherwise the whole program is rejected.
22833  * Consider:
22834  * int bar(int);
22835  * int foo(int f)
22836  * {
22837  *    return bar(f);
22838  * }
22839  * int bar(int b)
22840  * {
22841  *    ...
22842  * }
22843  * foo() will be verified first for R1=any_scalar_value. During verification it
22844  * will be assumed that bar() already verified successfully and call to bar()
22845  * from foo() will be checked for type match only. Later bar() will be verified
22846  * independently to check that it's safe for R1=any_scalar_value.
22847  */
22848 static int do_check_subprogs(struct bpf_verifier_env *env)
22849 {
22850 	struct bpf_prog_aux *aux = env->prog->aux;
22851 	struct bpf_func_info_aux *sub_aux;
22852 	int i, ret, new_cnt;
22853 
22854 	if (!aux->func_info)
22855 		return 0;
22856 
22857 	/* exception callback is presumed to be always called */
22858 	if (env->exception_callback_subprog)
22859 		subprog_aux(env, env->exception_callback_subprog)->called = true;
22860 
22861 again:
22862 	new_cnt = 0;
22863 	for (i = 1; i < env->subprog_cnt; i++) {
22864 		if (!subprog_is_global(env, i))
22865 			continue;
22866 
22867 		sub_aux = subprog_aux(env, i);
22868 		if (!sub_aux->called || sub_aux->verified)
22869 			continue;
22870 
22871 		env->insn_idx = env->subprog_info[i].start;
22872 		WARN_ON_ONCE(env->insn_idx == 0);
22873 		ret = do_check_common(env, i);
22874 		if (ret) {
22875 			return ret;
22876 		} else if (env->log.level & BPF_LOG_LEVEL) {
22877 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
22878 				i, subprog_name(env, i));
22879 		}
22880 
22881 		/* We verified new global subprog, it might have called some
22882 		 * more global subprogs that we haven't verified yet, so we
22883 		 * need to do another pass over subprogs to verify those.
22884 		 */
22885 		sub_aux->verified = true;
22886 		new_cnt++;
22887 	}
22888 
22889 	/* We can't loop forever as we verify at least one global subprog on
22890 	 * each pass.
22891 	 */
22892 	if (new_cnt)
22893 		goto again;
22894 
22895 	return 0;
22896 }
22897 
22898 static int do_check_main(struct bpf_verifier_env *env)
22899 {
22900 	int ret;
22901 
22902 	env->insn_idx = 0;
22903 	ret = do_check_common(env, 0);
22904 	if (!ret)
22905 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
22906 	return ret;
22907 }
22908 
22909 
22910 static void print_verification_stats(struct bpf_verifier_env *env)
22911 {
22912 	int i;
22913 
22914 	if (env->log.level & BPF_LOG_STATS) {
22915 		verbose(env, "verification time %lld usec\n",
22916 			div_u64(env->verification_time, 1000));
22917 		verbose(env, "stack depth ");
22918 		for (i = 0; i < env->subprog_cnt; i++) {
22919 			u32 depth = env->subprog_info[i].stack_depth;
22920 
22921 			verbose(env, "%d", depth);
22922 			if (i + 1 < env->subprog_cnt)
22923 				verbose(env, "+");
22924 		}
22925 		verbose(env, "\n");
22926 	}
22927 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
22928 		"total_states %d peak_states %d mark_read %d\n",
22929 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
22930 		env->max_states_per_insn, env->total_states,
22931 		env->peak_states, env->longest_mark_read_walk);
22932 }
22933 
22934 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
22935 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
22936 {
22937 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL);
22938 	prog->aux->ctx_arg_info_size = cnt;
22939 
22940 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
22941 }
22942 
22943 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
22944 {
22945 	const struct btf_type *t, *func_proto;
22946 	const struct bpf_struct_ops_desc *st_ops_desc;
22947 	const struct bpf_struct_ops *st_ops;
22948 	const struct btf_member *member;
22949 	struct bpf_prog *prog = env->prog;
22950 	bool has_refcounted_arg = false;
22951 	u32 btf_id, member_idx, member_off;
22952 	struct btf *btf;
22953 	const char *mname;
22954 	int i, err;
22955 
22956 	if (!prog->gpl_compatible) {
22957 		verbose(env, "struct ops programs must have a GPL compatible license\n");
22958 		return -EINVAL;
22959 	}
22960 
22961 	if (!prog->aux->attach_btf_id)
22962 		return -ENOTSUPP;
22963 
22964 	btf = prog->aux->attach_btf;
22965 	if (btf_is_module(btf)) {
22966 		/* Make sure st_ops is valid through the lifetime of env */
22967 		env->attach_btf_mod = btf_try_get_module(btf);
22968 		if (!env->attach_btf_mod) {
22969 			verbose(env, "struct_ops module %s is not found\n",
22970 				btf_get_name(btf));
22971 			return -ENOTSUPP;
22972 		}
22973 	}
22974 
22975 	btf_id = prog->aux->attach_btf_id;
22976 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
22977 	if (!st_ops_desc) {
22978 		verbose(env, "attach_btf_id %u is not a supported struct\n",
22979 			btf_id);
22980 		return -ENOTSUPP;
22981 	}
22982 	st_ops = st_ops_desc->st_ops;
22983 
22984 	t = st_ops_desc->type;
22985 	member_idx = prog->expected_attach_type;
22986 	if (member_idx >= btf_type_vlen(t)) {
22987 		verbose(env, "attach to invalid member idx %u of struct %s\n",
22988 			member_idx, st_ops->name);
22989 		return -EINVAL;
22990 	}
22991 
22992 	member = &btf_type_member(t)[member_idx];
22993 	mname = btf_name_by_offset(btf, member->name_off);
22994 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
22995 					       NULL);
22996 	if (!func_proto) {
22997 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
22998 			mname, member_idx, st_ops->name);
22999 		return -EINVAL;
23000 	}
23001 
23002 	member_off = __btf_member_bit_offset(t, member) / 8;
23003 	err = bpf_struct_ops_supported(st_ops, member_off);
23004 	if (err) {
23005 		verbose(env, "attach to unsupported member %s of struct %s\n",
23006 			mname, st_ops->name);
23007 		return err;
23008 	}
23009 
23010 	if (st_ops->check_member) {
23011 		err = st_ops->check_member(t, member, prog);
23012 
23013 		if (err) {
23014 			verbose(env, "attach to unsupported member %s of struct %s\n",
23015 				mname, st_ops->name);
23016 			return err;
23017 		}
23018 	}
23019 
23020 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
23021 		verbose(env, "Private stack not supported by jit\n");
23022 		return -EACCES;
23023 	}
23024 
23025 	for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) {
23026 		if (st_ops_desc->arg_info[member_idx].info->refcounted) {
23027 			has_refcounted_arg = true;
23028 			break;
23029 		}
23030 	}
23031 
23032 	/* Tail call is not allowed for programs with refcounted arguments since we
23033 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
23034 	 */
23035 	for (i = 0; i < env->subprog_cnt; i++) {
23036 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
23037 			verbose(env, "program with __ref argument cannot tail call\n");
23038 			return -EINVAL;
23039 		}
23040 	}
23041 
23042 	prog->aux->st_ops = st_ops;
23043 	prog->aux->attach_st_ops_member_off = member_off;
23044 
23045 	prog->aux->attach_func_proto = func_proto;
23046 	prog->aux->attach_func_name = mname;
23047 	env->ops = st_ops->verifier_ops;
23048 
23049 	return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info,
23050 					  st_ops_desc->arg_info[member_idx].cnt);
23051 }
23052 #define SECURITY_PREFIX "security_"
23053 
23054 static int check_attach_modify_return(unsigned long addr, const char *func_name)
23055 {
23056 	if (within_error_injection_list(addr) ||
23057 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
23058 		return 0;
23059 
23060 	return -EINVAL;
23061 }
23062 
23063 /* list of non-sleepable functions that are otherwise on
23064  * ALLOW_ERROR_INJECTION list
23065  */
23066 BTF_SET_START(btf_non_sleepable_error_inject)
23067 /* Three functions below can be called from sleepable and non-sleepable context.
23068  * Assume non-sleepable from bpf safety point of view.
23069  */
23070 BTF_ID(func, __filemap_add_folio)
23071 #ifdef CONFIG_FAIL_PAGE_ALLOC
23072 BTF_ID(func, should_fail_alloc_page)
23073 #endif
23074 #ifdef CONFIG_FAILSLAB
23075 BTF_ID(func, should_failslab)
23076 #endif
23077 BTF_SET_END(btf_non_sleepable_error_inject)
23078 
23079 static int check_non_sleepable_error_inject(u32 btf_id)
23080 {
23081 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
23082 }
23083 
23084 int bpf_check_attach_target(struct bpf_verifier_log *log,
23085 			    const struct bpf_prog *prog,
23086 			    const struct bpf_prog *tgt_prog,
23087 			    u32 btf_id,
23088 			    struct bpf_attach_target_info *tgt_info)
23089 {
23090 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
23091 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
23092 	char trace_symbol[KSYM_SYMBOL_LEN];
23093 	const char prefix[] = "btf_trace_";
23094 	struct bpf_raw_event_map *btp;
23095 	int ret = 0, subprog = -1, i;
23096 	const struct btf_type *t;
23097 	bool conservative = true;
23098 	const char *tname, *fname;
23099 	struct btf *btf;
23100 	long addr = 0;
23101 	struct module *mod = NULL;
23102 
23103 	if (!btf_id) {
23104 		bpf_log(log, "Tracing programs must provide btf_id\n");
23105 		return -EINVAL;
23106 	}
23107 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
23108 	if (!btf) {
23109 		bpf_log(log,
23110 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
23111 		return -EINVAL;
23112 	}
23113 	t = btf_type_by_id(btf, btf_id);
23114 	if (!t) {
23115 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
23116 		return -EINVAL;
23117 	}
23118 	tname = btf_name_by_offset(btf, t->name_off);
23119 	if (!tname) {
23120 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
23121 		return -EINVAL;
23122 	}
23123 	if (tgt_prog) {
23124 		struct bpf_prog_aux *aux = tgt_prog->aux;
23125 		bool tgt_changes_pkt_data;
23126 		bool tgt_might_sleep;
23127 
23128 		if (bpf_prog_is_dev_bound(prog->aux) &&
23129 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
23130 			bpf_log(log, "Target program bound device mismatch");
23131 			return -EINVAL;
23132 		}
23133 
23134 		for (i = 0; i < aux->func_info_cnt; i++)
23135 			if (aux->func_info[i].type_id == btf_id) {
23136 				subprog = i;
23137 				break;
23138 			}
23139 		if (subprog == -1) {
23140 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
23141 			return -EINVAL;
23142 		}
23143 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
23144 			bpf_log(log,
23145 				"%s programs cannot attach to exception callback\n",
23146 				prog_extension ? "Extension" : "FENTRY/FEXIT");
23147 			return -EINVAL;
23148 		}
23149 		conservative = aux->func_info_aux[subprog].unreliable;
23150 		if (prog_extension) {
23151 			if (conservative) {
23152 				bpf_log(log,
23153 					"Cannot replace static functions\n");
23154 				return -EINVAL;
23155 			}
23156 			if (!prog->jit_requested) {
23157 				bpf_log(log,
23158 					"Extension programs should be JITed\n");
23159 				return -EINVAL;
23160 			}
23161 			tgt_changes_pkt_data = aux->func
23162 					       ? aux->func[subprog]->aux->changes_pkt_data
23163 					       : aux->changes_pkt_data;
23164 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
23165 				bpf_log(log,
23166 					"Extension program changes packet data, while original does not\n");
23167 				return -EINVAL;
23168 			}
23169 
23170 			tgt_might_sleep = aux->func
23171 					  ? aux->func[subprog]->aux->might_sleep
23172 					  : aux->might_sleep;
23173 			if (prog->aux->might_sleep && !tgt_might_sleep) {
23174 				bpf_log(log,
23175 					"Extension program may sleep, while original does not\n");
23176 				return -EINVAL;
23177 			}
23178 		}
23179 		if (!tgt_prog->jited) {
23180 			bpf_log(log, "Can attach to only JITed progs\n");
23181 			return -EINVAL;
23182 		}
23183 		if (prog_tracing) {
23184 			if (aux->attach_tracing_prog) {
23185 				/*
23186 				 * Target program is an fentry/fexit which is already attached
23187 				 * to another tracing program. More levels of nesting
23188 				 * attachment are not allowed.
23189 				 */
23190 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
23191 				return -EINVAL;
23192 			}
23193 		} else if (tgt_prog->type == prog->type) {
23194 			/*
23195 			 * To avoid potential call chain cycles, prevent attaching of a
23196 			 * program extension to another extension. It's ok to attach
23197 			 * fentry/fexit to extension program.
23198 			 */
23199 			bpf_log(log, "Cannot recursively attach\n");
23200 			return -EINVAL;
23201 		}
23202 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
23203 		    prog_extension &&
23204 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
23205 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
23206 			/* Program extensions can extend all program types
23207 			 * except fentry/fexit. The reason is the following.
23208 			 * The fentry/fexit programs are used for performance
23209 			 * analysis, stats and can be attached to any program
23210 			 * type. When extension program is replacing XDP function
23211 			 * it is necessary to allow performance analysis of all
23212 			 * functions. Both original XDP program and its program
23213 			 * extension. Hence attaching fentry/fexit to
23214 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
23215 			 * fentry/fexit was allowed it would be possible to create
23216 			 * long call chain fentry->extension->fentry->extension
23217 			 * beyond reasonable stack size. Hence extending fentry
23218 			 * is not allowed.
23219 			 */
23220 			bpf_log(log, "Cannot extend fentry/fexit\n");
23221 			return -EINVAL;
23222 		}
23223 	} else {
23224 		if (prog_extension) {
23225 			bpf_log(log, "Cannot replace kernel functions\n");
23226 			return -EINVAL;
23227 		}
23228 	}
23229 
23230 	switch (prog->expected_attach_type) {
23231 	case BPF_TRACE_RAW_TP:
23232 		if (tgt_prog) {
23233 			bpf_log(log,
23234 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
23235 			return -EINVAL;
23236 		}
23237 		if (!btf_type_is_typedef(t)) {
23238 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
23239 				btf_id);
23240 			return -EINVAL;
23241 		}
23242 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
23243 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
23244 				btf_id, tname);
23245 			return -EINVAL;
23246 		}
23247 		tname += sizeof(prefix) - 1;
23248 
23249 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
23250 		 * names. Thus using bpf_raw_event_map to get argument names.
23251 		 */
23252 		btp = bpf_get_raw_tracepoint(tname);
23253 		if (!btp)
23254 			return -EINVAL;
23255 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
23256 					trace_symbol);
23257 		bpf_put_raw_tracepoint(btp);
23258 
23259 		if (fname)
23260 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
23261 
23262 		if (!fname || ret < 0) {
23263 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
23264 				prefix, tname);
23265 			t = btf_type_by_id(btf, t->type);
23266 			if (!btf_type_is_ptr(t))
23267 				/* should never happen in valid vmlinux build */
23268 				return -EINVAL;
23269 		} else {
23270 			t = btf_type_by_id(btf, ret);
23271 			if (!btf_type_is_func(t))
23272 				/* should never happen in valid vmlinux build */
23273 				return -EINVAL;
23274 		}
23275 
23276 		t = btf_type_by_id(btf, t->type);
23277 		if (!btf_type_is_func_proto(t))
23278 			/* should never happen in valid vmlinux build */
23279 			return -EINVAL;
23280 
23281 		break;
23282 	case BPF_TRACE_ITER:
23283 		if (!btf_type_is_func(t)) {
23284 			bpf_log(log, "attach_btf_id %u is not a function\n",
23285 				btf_id);
23286 			return -EINVAL;
23287 		}
23288 		t = btf_type_by_id(btf, t->type);
23289 		if (!btf_type_is_func_proto(t))
23290 			return -EINVAL;
23291 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
23292 		if (ret)
23293 			return ret;
23294 		break;
23295 	default:
23296 		if (!prog_extension)
23297 			return -EINVAL;
23298 		fallthrough;
23299 	case BPF_MODIFY_RETURN:
23300 	case BPF_LSM_MAC:
23301 	case BPF_LSM_CGROUP:
23302 	case BPF_TRACE_FENTRY:
23303 	case BPF_TRACE_FEXIT:
23304 		if (!btf_type_is_func(t)) {
23305 			bpf_log(log, "attach_btf_id %u is not a function\n",
23306 				btf_id);
23307 			return -EINVAL;
23308 		}
23309 		if (prog_extension &&
23310 		    btf_check_type_match(log, prog, btf, t))
23311 			return -EINVAL;
23312 		t = btf_type_by_id(btf, t->type);
23313 		if (!btf_type_is_func_proto(t))
23314 			return -EINVAL;
23315 
23316 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
23317 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
23318 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
23319 			return -EINVAL;
23320 
23321 		if (tgt_prog && conservative)
23322 			t = NULL;
23323 
23324 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
23325 		if (ret < 0)
23326 			return ret;
23327 
23328 		if (tgt_prog) {
23329 			if (subprog == 0)
23330 				addr = (long) tgt_prog->bpf_func;
23331 			else
23332 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
23333 		} else {
23334 			if (btf_is_module(btf)) {
23335 				mod = btf_try_get_module(btf);
23336 				if (mod)
23337 					addr = find_kallsyms_symbol_value(mod, tname);
23338 				else
23339 					addr = 0;
23340 			} else {
23341 				addr = kallsyms_lookup_name(tname);
23342 			}
23343 			if (!addr) {
23344 				module_put(mod);
23345 				bpf_log(log,
23346 					"The address of function %s cannot be found\n",
23347 					tname);
23348 				return -ENOENT;
23349 			}
23350 		}
23351 
23352 		if (prog->sleepable) {
23353 			ret = -EINVAL;
23354 			switch (prog->type) {
23355 			case BPF_PROG_TYPE_TRACING:
23356 
23357 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
23358 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
23359 				 */
23360 				if (!check_non_sleepable_error_inject(btf_id) &&
23361 				    within_error_injection_list(addr))
23362 					ret = 0;
23363 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
23364 				 * in the fmodret id set with the KF_SLEEPABLE flag.
23365 				 */
23366 				else {
23367 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
23368 										prog);
23369 
23370 					if (flags && (*flags & KF_SLEEPABLE))
23371 						ret = 0;
23372 				}
23373 				break;
23374 			case BPF_PROG_TYPE_LSM:
23375 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
23376 				 * Only some of them are sleepable.
23377 				 */
23378 				if (bpf_lsm_is_sleepable_hook(btf_id))
23379 					ret = 0;
23380 				break;
23381 			default:
23382 				break;
23383 			}
23384 			if (ret) {
23385 				module_put(mod);
23386 				bpf_log(log, "%s is not sleepable\n", tname);
23387 				return ret;
23388 			}
23389 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
23390 			if (tgt_prog) {
23391 				module_put(mod);
23392 				bpf_log(log, "can't modify return codes of BPF programs\n");
23393 				return -EINVAL;
23394 			}
23395 			ret = -EINVAL;
23396 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
23397 			    !check_attach_modify_return(addr, tname))
23398 				ret = 0;
23399 			if (ret) {
23400 				module_put(mod);
23401 				bpf_log(log, "%s() is not modifiable\n", tname);
23402 				return ret;
23403 			}
23404 		}
23405 
23406 		break;
23407 	}
23408 	tgt_info->tgt_addr = addr;
23409 	tgt_info->tgt_name = tname;
23410 	tgt_info->tgt_type = t;
23411 	tgt_info->tgt_mod = mod;
23412 	return 0;
23413 }
23414 
23415 BTF_SET_START(btf_id_deny)
23416 BTF_ID_UNUSED
23417 #ifdef CONFIG_SMP
23418 BTF_ID(func, migrate_disable)
23419 BTF_ID(func, migrate_enable)
23420 #endif
23421 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
23422 BTF_ID(func, rcu_read_unlock_strict)
23423 #endif
23424 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
23425 BTF_ID(func, preempt_count_add)
23426 BTF_ID(func, preempt_count_sub)
23427 #endif
23428 #ifdef CONFIG_PREEMPT_RCU
23429 BTF_ID(func, __rcu_read_lock)
23430 BTF_ID(func, __rcu_read_unlock)
23431 #endif
23432 BTF_SET_END(btf_id_deny)
23433 
23434 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
23435  * Currently, we must manually list all __noreturn functions here. Once a more
23436  * robust solution is implemented, this workaround can be removed.
23437  */
23438 BTF_SET_START(noreturn_deny)
23439 #ifdef CONFIG_IA32_EMULATION
23440 BTF_ID(func, __ia32_sys_exit)
23441 BTF_ID(func, __ia32_sys_exit_group)
23442 #endif
23443 #ifdef CONFIG_KUNIT
23444 BTF_ID(func, __kunit_abort)
23445 BTF_ID(func, kunit_try_catch_throw)
23446 #endif
23447 #ifdef CONFIG_MODULES
23448 BTF_ID(func, __module_put_and_kthread_exit)
23449 #endif
23450 #ifdef CONFIG_X86_64
23451 BTF_ID(func, __x64_sys_exit)
23452 BTF_ID(func, __x64_sys_exit_group)
23453 #endif
23454 BTF_ID(func, do_exit)
23455 BTF_ID(func, do_group_exit)
23456 BTF_ID(func, kthread_complete_and_exit)
23457 BTF_ID(func, kthread_exit)
23458 BTF_ID(func, make_task_dead)
23459 BTF_SET_END(noreturn_deny)
23460 
23461 static bool can_be_sleepable(struct bpf_prog *prog)
23462 {
23463 	if (prog->type == BPF_PROG_TYPE_TRACING) {
23464 		switch (prog->expected_attach_type) {
23465 		case BPF_TRACE_FENTRY:
23466 		case BPF_TRACE_FEXIT:
23467 		case BPF_MODIFY_RETURN:
23468 		case BPF_TRACE_ITER:
23469 			return true;
23470 		default:
23471 			return false;
23472 		}
23473 	}
23474 	return prog->type == BPF_PROG_TYPE_LSM ||
23475 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
23476 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
23477 }
23478 
23479 static int check_attach_btf_id(struct bpf_verifier_env *env)
23480 {
23481 	struct bpf_prog *prog = env->prog;
23482 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
23483 	struct bpf_attach_target_info tgt_info = {};
23484 	u32 btf_id = prog->aux->attach_btf_id;
23485 	struct bpf_trampoline *tr;
23486 	int ret;
23487 	u64 key;
23488 
23489 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
23490 		if (prog->sleepable)
23491 			/* attach_btf_id checked to be zero already */
23492 			return 0;
23493 		verbose(env, "Syscall programs can only be sleepable\n");
23494 		return -EINVAL;
23495 	}
23496 
23497 	if (prog->sleepable && !can_be_sleepable(prog)) {
23498 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
23499 		return -EINVAL;
23500 	}
23501 
23502 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
23503 		return check_struct_ops_btf_id(env);
23504 
23505 	if (prog->type != BPF_PROG_TYPE_TRACING &&
23506 	    prog->type != BPF_PROG_TYPE_LSM &&
23507 	    prog->type != BPF_PROG_TYPE_EXT)
23508 		return 0;
23509 
23510 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
23511 	if (ret)
23512 		return ret;
23513 
23514 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
23515 		/* to make freplace equivalent to their targets, they need to
23516 		 * inherit env->ops and expected_attach_type for the rest of the
23517 		 * verification
23518 		 */
23519 		env->ops = bpf_verifier_ops[tgt_prog->type];
23520 		prog->expected_attach_type = tgt_prog->expected_attach_type;
23521 	}
23522 
23523 	/* store info about the attachment target that will be used later */
23524 	prog->aux->attach_func_proto = tgt_info.tgt_type;
23525 	prog->aux->attach_func_name = tgt_info.tgt_name;
23526 	prog->aux->mod = tgt_info.tgt_mod;
23527 
23528 	if (tgt_prog) {
23529 		prog->aux->saved_dst_prog_type = tgt_prog->type;
23530 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
23531 	}
23532 
23533 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
23534 		prog->aux->attach_btf_trace = true;
23535 		return 0;
23536 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
23537 		return bpf_iter_prog_supported(prog);
23538 	}
23539 
23540 	if (prog->type == BPF_PROG_TYPE_LSM) {
23541 		ret = bpf_lsm_verify_prog(&env->log, prog);
23542 		if (ret < 0)
23543 			return ret;
23544 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
23545 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
23546 		return -EINVAL;
23547 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
23548 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
23549 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
23550 		verbose(env, "Attaching fexit/fmod_ret to __noreturn functions is rejected.\n");
23551 		return -EINVAL;
23552 	}
23553 
23554 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
23555 	tr = bpf_trampoline_get(key, &tgt_info);
23556 	if (!tr)
23557 		return -ENOMEM;
23558 
23559 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
23560 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
23561 
23562 	prog->aux->dst_trampoline = tr;
23563 	return 0;
23564 }
23565 
23566 struct btf *bpf_get_btf_vmlinux(void)
23567 {
23568 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
23569 		mutex_lock(&bpf_verifier_lock);
23570 		if (!btf_vmlinux)
23571 			btf_vmlinux = btf_parse_vmlinux();
23572 		mutex_unlock(&bpf_verifier_lock);
23573 	}
23574 	return btf_vmlinux;
23575 }
23576 
23577 /*
23578  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
23579  * this case expect that every file descriptor in the array is either a map or
23580  * a BTF. Everything else is considered to be trash.
23581  */
23582 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
23583 {
23584 	struct bpf_map *map;
23585 	struct btf *btf;
23586 	CLASS(fd, f)(fd);
23587 	int err;
23588 
23589 	map = __bpf_map_get(f);
23590 	if (!IS_ERR(map)) {
23591 		err = __add_used_map(env, map);
23592 		if (err < 0)
23593 			return err;
23594 		return 0;
23595 	}
23596 
23597 	btf = __btf_get_by_fd(f);
23598 	if (!IS_ERR(btf)) {
23599 		err = __add_used_btf(env, btf);
23600 		if (err < 0)
23601 			return err;
23602 		return 0;
23603 	}
23604 
23605 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
23606 	return PTR_ERR(map);
23607 }
23608 
23609 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
23610 {
23611 	size_t size = sizeof(int);
23612 	int ret;
23613 	int fd;
23614 	u32 i;
23615 
23616 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
23617 
23618 	/*
23619 	 * The only difference between old (no fd_array_cnt is given) and new
23620 	 * APIs is that in the latter case the fd_array is expected to be
23621 	 * continuous and is scanned for map fds right away
23622 	 */
23623 	if (!attr->fd_array_cnt)
23624 		return 0;
23625 
23626 	/* Check for integer overflow */
23627 	if (attr->fd_array_cnt >= (U32_MAX / size)) {
23628 		verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
23629 		return -EINVAL;
23630 	}
23631 
23632 	for (i = 0; i < attr->fd_array_cnt; i++) {
23633 		if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
23634 			return -EFAULT;
23635 
23636 		ret = add_fd_from_fd_array(env, fd);
23637 		if (ret)
23638 			return ret;
23639 	}
23640 
23641 	return 0;
23642 }
23643 
23644 static bool can_fallthrough(struct bpf_insn *insn)
23645 {
23646 	u8 class = BPF_CLASS(insn->code);
23647 	u8 opcode = BPF_OP(insn->code);
23648 
23649 	if (class != BPF_JMP && class != BPF_JMP32)
23650 		return true;
23651 
23652 	if (opcode == BPF_EXIT || opcode == BPF_JA)
23653 		return false;
23654 
23655 	return true;
23656 }
23657 
23658 static bool can_jump(struct bpf_insn *insn)
23659 {
23660 	u8 class = BPF_CLASS(insn->code);
23661 	u8 opcode = BPF_OP(insn->code);
23662 
23663 	if (class != BPF_JMP && class != BPF_JMP32)
23664 		return false;
23665 
23666 	switch (opcode) {
23667 	case BPF_JA:
23668 	case BPF_JEQ:
23669 	case BPF_JNE:
23670 	case BPF_JLT:
23671 	case BPF_JLE:
23672 	case BPF_JGT:
23673 	case BPF_JGE:
23674 	case BPF_JSGT:
23675 	case BPF_JSGE:
23676 	case BPF_JSLT:
23677 	case BPF_JSLE:
23678 	case BPF_JCOND:
23679 		return true;
23680 	}
23681 
23682 	return false;
23683 }
23684 
23685 static int insn_successors(struct bpf_prog *prog, u32 idx, u32 succ[2])
23686 {
23687 	struct bpf_insn *insn = &prog->insnsi[idx];
23688 	int i = 0, insn_sz;
23689 	u32 dst;
23690 
23691 	insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
23692 	if (can_fallthrough(insn) && idx + 1 < prog->len)
23693 		succ[i++] = idx + insn_sz;
23694 
23695 	if (can_jump(insn)) {
23696 		dst = idx + jmp_offset(insn) + 1;
23697 		if (i == 0 || succ[0] != dst)
23698 			succ[i++] = dst;
23699 	}
23700 
23701 	return i;
23702 }
23703 
23704 /* Each field is a register bitmask */
23705 struct insn_live_regs {
23706 	u16 use;	/* registers read by instruction */
23707 	u16 def;	/* registers written by instruction */
23708 	u16 in;		/* registers that may be alive before instruction */
23709 	u16 out;	/* registers that may be alive after instruction */
23710 };
23711 
23712 /* Bitmask with 1s for all caller saved registers */
23713 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
23714 
23715 /* Compute info->{use,def} fields for the instruction */
23716 static void compute_insn_live_regs(struct bpf_verifier_env *env,
23717 				   struct bpf_insn *insn,
23718 				   struct insn_live_regs *info)
23719 {
23720 	struct call_summary cs;
23721 	u8 class = BPF_CLASS(insn->code);
23722 	u8 code = BPF_OP(insn->code);
23723 	u8 mode = BPF_MODE(insn->code);
23724 	u16 src = BIT(insn->src_reg);
23725 	u16 dst = BIT(insn->dst_reg);
23726 	u16 r0  = BIT(0);
23727 	u16 def = 0;
23728 	u16 use = 0xffff;
23729 
23730 	switch (class) {
23731 	case BPF_LD:
23732 		switch (mode) {
23733 		case BPF_IMM:
23734 			if (BPF_SIZE(insn->code) == BPF_DW) {
23735 				def = dst;
23736 				use = 0;
23737 			}
23738 			break;
23739 		case BPF_LD | BPF_ABS:
23740 		case BPF_LD | BPF_IND:
23741 			/* stick with defaults */
23742 			break;
23743 		}
23744 		break;
23745 	case BPF_LDX:
23746 		switch (mode) {
23747 		case BPF_MEM:
23748 		case BPF_MEMSX:
23749 			def = dst;
23750 			use = src;
23751 			break;
23752 		}
23753 		break;
23754 	case BPF_ST:
23755 		switch (mode) {
23756 		case BPF_MEM:
23757 			def = 0;
23758 			use = dst;
23759 			break;
23760 		}
23761 		break;
23762 	case BPF_STX:
23763 		switch (mode) {
23764 		case BPF_MEM:
23765 			def = 0;
23766 			use = dst | src;
23767 			break;
23768 		case BPF_ATOMIC:
23769 			switch (insn->imm) {
23770 			case BPF_CMPXCHG:
23771 				use = r0 | dst | src;
23772 				def = r0;
23773 				break;
23774 			case BPF_LOAD_ACQ:
23775 				def = dst;
23776 				use = src;
23777 				break;
23778 			case BPF_STORE_REL:
23779 				def = 0;
23780 				use = dst | src;
23781 				break;
23782 			default:
23783 				use = dst | src;
23784 				if (insn->imm & BPF_FETCH)
23785 					def = src;
23786 				else
23787 					def = 0;
23788 			}
23789 			break;
23790 		}
23791 		break;
23792 	case BPF_ALU:
23793 	case BPF_ALU64:
23794 		switch (code) {
23795 		case BPF_END:
23796 			use = dst;
23797 			def = dst;
23798 			break;
23799 		case BPF_MOV:
23800 			def = dst;
23801 			if (BPF_SRC(insn->code) == BPF_K)
23802 				use = 0;
23803 			else
23804 				use = src;
23805 			break;
23806 		default:
23807 			def = dst;
23808 			if (BPF_SRC(insn->code) == BPF_K)
23809 				use = dst;
23810 			else
23811 				use = dst | src;
23812 		}
23813 		break;
23814 	case BPF_JMP:
23815 	case BPF_JMP32:
23816 		switch (code) {
23817 		case BPF_JA:
23818 		case BPF_JCOND:
23819 			def = 0;
23820 			use = 0;
23821 			break;
23822 		case BPF_EXIT:
23823 			def = 0;
23824 			use = r0;
23825 			break;
23826 		case BPF_CALL:
23827 			def = ALL_CALLER_SAVED_REGS;
23828 			use = def & ~BIT(BPF_REG_0);
23829 			if (get_call_summary(env, insn, &cs))
23830 				use = GENMASK(cs.num_params, 1);
23831 			break;
23832 		default:
23833 			def = 0;
23834 			if (BPF_SRC(insn->code) == BPF_K)
23835 				use = dst;
23836 			else
23837 				use = dst | src;
23838 		}
23839 		break;
23840 	}
23841 
23842 	info->def = def;
23843 	info->use = use;
23844 }
23845 
23846 /* Compute may-live registers after each instruction in the program.
23847  * The register is live after the instruction I if it is read by some
23848  * instruction S following I during program execution and is not
23849  * overwritten between I and S.
23850  *
23851  * Store result in env->insn_aux_data[i].live_regs.
23852  */
23853 static int compute_live_registers(struct bpf_verifier_env *env)
23854 {
23855 	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
23856 	struct bpf_insn *insns = env->prog->insnsi;
23857 	struct insn_live_regs *state;
23858 	int insn_cnt = env->prog->len;
23859 	int err = 0, i, j;
23860 	bool changed;
23861 
23862 	/* Use the following algorithm:
23863 	 * - define the following:
23864 	 *   - I.use : a set of all registers read by instruction I;
23865 	 *   - I.def : a set of all registers written by instruction I;
23866 	 *   - I.in  : a set of all registers that may be alive before I execution;
23867 	 *   - I.out : a set of all registers that may be alive after I execution;
23868 	 *   - insn_successors(I): a set of instructions S that might immediately
23869 	 *                         follow I for some program execution;
23870 	 * - associate separate empty sets 'I.in' and 'I.out' with each instruction;
23871 	 * - visit each instruction in a postorder and update
23872 	 *   state[i].in, state[i].out as follows:
23873 	 *
23874 	 *       state[i].out = U [state[s].in for S in insn_successors(i)]
23875 	 *       state[i].in  = (state[i].out / state[i].def) U state[i].use
23876 	 *
23877 	 *   (where U stands for set union, / stands for set difference)
23878 	 * - repeat the computation while {in,out} fields changes for
23879 	 *   any instruction.
23880 	 */
23881 	state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL);
23882 	if (!state) {
23883 		err = -ENOMEM;
23884 		goto out;
23885 	}
23886 
23887 	for (i = 0; i < insn_cnt; ++i)
23888 		compute_insn_live_regs(env, &insns[i], &state[i]);
23889 
23890 	changed = true;
23891 	while (changed) {
23892 		changed = false;
23893 		for (i = 0; i < env->cfg.cur_postorder; ++i) {
23894 			int insn_idx = env->cfg.insn_postorder[i];
23895 			struct insn_live_regs *live = &state[insn_idx];
23896 			int succ_num;
23897 			u32 succ[2];
23898 			u16 new_out = 0;
23899 			u16 new_in = 0;
23900 
23901 			succ_num = insn_successors(env->prog, insn_idx, succ);
23902 			for (int s = 0; s < succ_num; ++s)
23903 				new_out |= state[succ[s]].in;
23904 			new_in = (new_out & ~live->def) | live->use;
23905 			if (new_out != live->out || new_in != live->in) {
23906 				live->in = new_in;
23907 				live->out = new_out;
23908 				changed = true;
23909 			}
23910 		}
23911 	}
23912 
23913 	for (i = 0; i < insn_cnt; ++i)
23914 		insn_aux[i].live_regs_before = state[i].in;
23915 
23916 	if (env->log.level & BPF_LOG_LEVEL2) {
23917 		verbose(env, "Live regs before insn:\n");
23918 		for (i = 0; i < insn_cnt; ++i) {
23919 			verbose(env, "%3d: ", i);
23920 			for (j = BPF_REG_0; j < BPF_REG_10; ++j)
23921 				if (insn_aux[i].live_regs_before & BIT(j))
23922 					verbose(env, "%d", j);
23923 				else
23924 					verbose(env, ".");
23925 			verbose(env, " ");
23926 			verbose_insn(env, &insns[i]);
23927 			if (bpf_is_ldimm64(&insns[i]))
23928 				i++;
23929 		}
23930 	}
23931 
23932 out:
23933 	kvfree(state);
23934 	kvfree(env->cfg.insn_postorder);
23935 	env->cfg.insn_postorder = NULL;
23936 	env->cfg.cur_postorder = 0;
23937 	return err;
23938 }
23939 
23940 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
23941 {
23942 	u64 start_time = ktime_get_ns();
23943 	struct bpf_verifier_env *env;
23944 	int i, len, ret = -EINVAL, err;
23945 	u32 log_true_size;
23946 	bool is_priv;
23947 
23948 	/* no program is valid */
23949 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
23950 		return -EINVAL;
23951 
23952 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
23953 	 * allocate/free it every time bpf_check() is called
23954 	 */
23955 	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
23956 	if (!env)
23957 		return -ENOMEM;
23958 
23959 	env->bt.env = env;
23960 
23961 	len = (*prog)->len;
23962 	env->insn_aux_data =
23963 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
23964 	ret = -ENOMEM;
23965 	if (!env->insn_aux_data)
23966 		goto err_free_env;
23967 	for (i = 0; i < len; i++)
23968 		env->insn_aux_data[i].orig_idx = i;
23969 	env->prog = *prog;
23970 	env->ops = bpf_verifier_ops[env->prog->type];
23971 
23972 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
23973 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
23974 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
23975 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
23976 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
23977 
23978 	bpf_get_btf_vmlinux();
23979 
23980 	/* grab the mutex to protect few globals used by verifier */
23981 	if (!is_priv)
23982 		mutex_lock(&bpf_verifier_lock);
23983 
23984 	/* user could have requested verbose verifier output
23985 	 * and supplied buffer to store the verification trace
23986 	 */
23987 	ret = bpf_vlog_init(&env->log, attr->log_level,
23988 			    (char __user *) (unsigned long) attr->log_buf,
23989 			    attr->log_size);
23990 	if (ret)
23991 		goto err_unlock;
23992 
23993 	ret = process_fd_array(env, attr, uattr);
23994 	if (ret)
23995 		goto skip_full_check;
23996 
23997 	mark_verifier_state_clean(env);
23998 
23999 	if (IS_ERR(btf_vmlinux)) {
24000 		/* Either gcc or pahole or kernel are broken. */
24001 		verbose(env, "in-kernel BTF is malformed\n");
24002 		ret = PTR_ERR(btf_vmlinux);
24003 		goto skip_full_check;
24004 	}
24005 
24006 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
24007 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
24008 		env->strict_alignment = true;
24009 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
24010 		env->strict_alignment = false;
24011 
24012 	if (is_priv)
24013 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
24014 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
24015 
24016 	env->explored_states = kvcalloc(state_htab_size(env),
24017 				       sizeof(struct list_head),
24018 				       GFP_USER);
24019 	ret = -ENOMEM;
24020 	if (!env->explored_states)
24021 		goto skip_full_check;
24022 
24023 	for (i = 0; i < state_htab_size(env); i++)
24024 		INIT_LIST_HEAD(&env->explored_states[i]);
24025 	INIT_LIST_HEAD(&env->free_list);
24026 
24027 	ret = check_btf_info_early(env, attr, uattr);
24028 	if (ret < 0)
24029 		goto skip_full_check;
24030 
24031 	ret = add_subprog_and_kfunc(env);
24032 	if (ret < 0)
24033 		goto skip_full_check;
24034 
24035 	ret = check_subprogs(env);
24036 	if (ret < 0)
24037 		goto skip_full_check;
24038 
24039 	ret = check_btf_info(env, attr, uattr);
24040 	if (ret < 0)
24041 		goto skip_full_check;
24042 
24043 	ret = resolve_pseudo_ldimm64(env);
24044 	if (ret < 0)
24045 		goto skip_full_check;
24046 
24047 	if (bpf_prog_is_offloaded(env->prog->aux)) {
24048 		ret = bpf_prog_offload_verifier_prep(env->prog);
24049 		if (ret)
24050 			goto skip_full_check;
24051 	}
24052 
24053 	ret = check_cfg(env);
24054 	if (ret < 0)
24055 		goto skip_full_check;
24056 
24057 	ret = check_attach_btf_id(env);
24058 	if (ret)
24059 		goto skip_full_check;
24060 
24061 	ret = compute_live_registers(env);
24062 	if (ret < 0)
24063 		goto skip_full_check;
24064 
24065 	ret = mark_fastcall_patterns(env);
24066 	if (ret < 0)
24067 		goto skip_full_check;
24068 
24069 	ret = do_check_main(env);
24070 	ret = ret ?: do_check_subprogs(env);
24071 
24072 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
24073 		ret = bpf_prog_offload_finalize(env);
24074 
24075 skip_full_check:
24076 	kvfree(env->explored_states);
24077 
24078 	/* might decrease stack depth, keep it before passes that
24079 	 * allocate additional slots.
24080 	 */
24081 	if (ret == 0)
24082 		ret = remove_fastcall_spills_fills(env);
24083 
24084 	if (ret == 0)
24085 		ret = check_max_stack_depth(env);
24086 
24087 	/* instruction rewrites happen after this point */
24088 	if (ret == 0)
24089 		ret = optimize_bpf_loop(env);
24090 
24091 	if (is_priv) {
24092 		if (ret == 0)
24093 			opt_hard_wire_dead_code_branches(env);
24094 		if (ret == 0)
24095 			ret = opt_remove_dead_code(env);
24096 		if (ret == 0)
24097 			ret = opt_remove_nops(env);
24098 	} else {
24099 		if (ret == 0)
24100 			sanitize_dead_code(env);
24101 	}
24102 
24103 	if (ret == 0)
24104 		/* program is valid, convert *(u32*)(ctx + off) accesses */
24105 		ret = convert_ctx_accesses(env);
24106 
24107 	if (ret == 0)
24108 		ret = do_misc_fixups(env);
24109 
24110 	/* do 32-bit optimization after insn patching has done so those patched
24111 	 * insns could be handled correctly.
24112 	 */
24113 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
24114 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
24115 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
24116 								     : false;
24117 	}
24118 
24119 	if (ret == 0)
24120 		ret = fixup_call_args(env);
24121 
24122 	env->verification_time = ktime_get_ns() - start_time;
24123 	print_verification_stats(env);
24124 	env->prog->aux->verified_insns = env->insn_processed;
24125 
24126 	/* preserve original error even if log finalization is successful */
24127 	err = bpf_vlog_finalize(&env->log, &log_true_size);
24128 	if (err)
24129 		ret = err;
24130 
24131 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
24132 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
24133 				  &log_true_size, sizeof(log_true_size))) {
24134 		ret = -EFAULT;
24135 		goto err_release_maps;
24136 	}
24137 
24138 	if (ret)
24139 		goto err_release_maps;
24140 
24141 	if (env->used_map_cnt) {
24142 		/* if program passed verifier, update used_maps in bpf_prog_info */
24143 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
24144 							  sizeof(env->used_maps[0]),
24145 							  GFP_KERNEL);
24146 
24147 		if (!env->prog->aux->used_maps) {
24148 			ret = -ENOMEM;
24149 			goto err_release_maps;
24150 		}
24151 
24152 		memcpy(env->prog->aux->used_maps, env->used_maps,
24153 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
24154 		env->prog->aux->used_map_cnt = env->used_map_cnt;
24155 	}
24156 	if (env->used_btf_cnt) {
24157 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
24158 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
24159 							  sizeof(env->used_btfs[0]),
24160 							  GFP_KERNEL);
24161 		if (!env->prog->aux->used_btfs) {
24162 			ret = -ENOMEM;
24163 			goto err_release_maps;
24164 		}
24165 
24166 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
24167 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
24168 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
24169 	}
24170 	if (env->used_map_cnt || env->used_btf_cnt) {
24171 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
24172 		 * bpf_ld_imm64 instructions
24173 		 */
24174 		convert_pseudo_ld_imm64(env);
24175 	}
24176 
24177 	adjust_btf_func(env);
24178 
24179 err_release_maps:
24180 	if (!env->prog->aux->used_maps)
24181 		/* if we didn't copy map pointers into bpf_prog_info, release
24182 		 * them now. Otherwise free_used_maps() will release them.
24183 		 */
24184 		release_maps(env);
24185 	if (!env->prog->aux->used_btfs)
24186 		release_btfs(env);
24187 
24188 	/* extension progs temporarily inherit the attach_type of their targets
24189 	   for verification purposes, so set it back to zero before returning
24190 	 */
24191 	if (env->prog->type == BPF_PROG_TYPE_EXT)
24192 		env->prog->expected_attach_type = 0;
24193 
24194 	*prog = env->prog;
24195 
24196 	module_put(env->attach_btf_mod);
24197 err_unlock:
24198 	if (!is_priv)
24199 		mutex_unlock(&bpf_verifier_lock);
24200 	vfree(env->insn_aux_data);
24201 	kvfree(env->insn_hist);
24202 err_free_env:
24203 	kvfree(env->cfg.insn_postorder);
24204 	kvfree(env);
24205 	return ret;
24206 }
24207