xref: /linux/kernel/bpf/verifier.c (revision a6a6a98094116b60e5523a571d9443c53325f5b1)
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 
32 #include "disasm.h"
33 
34 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
35 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
36 	[_id] = & _name ## _verifier_ops,
37 #define BPF_MAP_TYPE(_id, _ops)
38 #define BPF_LINK_TYPE(_id, _name)
39 #include <linux/bpf_types.h>
40 #undef BPF_PROG_TYPE
41 #undef BPF_MAP_TYPE
42 #undef BPF_LINK_TYPE
43 };
44 
45 struct bpf_mem_alloc bpf_global_percpu_ma;
46 static bool bpf_global_percpu_ma_set;
47 
48 /* bpf_check() is a static code analyzer that walks eBPF program
49  * instruction by instruction and updates register/stack state.
50  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
51  *
52  * The first pass is depth-first-search to check that the program is a DAG.
53  * It rejects the following programs:
54  * - larger than BPF_MAXINSNS insns
55  * - if loop is present (detected via back-edge)
56  * - unreachable insns exist (shouldn't be a forest. program = one function)
57  * - out of bounds or malformed jumps
58  * The second pass is all possible path descent from the 1st insn.
59  * Since it's analyzing all paths through the program, the length of the
60  * analysis is limited to 64k insn, which may be hit even if total number of
61  * insn is less then 4K, but there are too many branches that change stack/regs.
62  * Number of 'branches to be analyzed' is limited to 1k
63  *
64  * On entry to each instruction, each register has a type, and the instruction
65  * changes the types of the registers depending on instruction semantics.
66  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
67  * copied to R1.
68  *
69  * All registers are 64-bit.
70  * R0 - return register
71  * R1-R5 argument passing registers
72  * R6-R9 callee saved registers
73  * R10 - frame pointer read-only
74  *
75  * At the start of BPF program the register R1 contains a pointer to bpf_context
76  * and has type PTR_TO_CTX.
77  *
78  * Verifier tracks arithmetic operations on pointers in case:
79  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
80  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
81  * 1st insn copies R10 (which has FRAME_PTR) type into R1
82  * and 2nd arithmetic instruction is pattern matched to recognize
83  * that it wants to construct a pointer to some element within stack.
84  * So after 2nd insn, the register R1 has type PTR_TO_STACK
85  * (and -20 constant is saved for further stack bounds checking).
86  * Meaning that this reg is a pointer to stack plus known immediate constant.
87  *
88  * Most of the time the registers have SCALAR_VALUE type, which
89  * means the register has some value, but it's not a valid pointer.
90  * (like pointer plus pointer becomes SCALAR_VALUE type)
91  *
92  * When verifier sees load or store instructions the type of base register
93  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
94  * four pointer types recognized by check_mem_access() function.
95  *
96  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
97  * and the range of [ptr, ptr + map's value_size) is accessible.
98  *
99  * registers used to pass values to function calls are checked against
100  * function argument constraints.
101  *
102  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
103  * It means that the register type passed to this function must be
104  * PTR_TO_STACK and it will be used inside the function as
105  * 'pointer to map element key'
106  *
107  * For example the argument constraints for bpf_map_lookup_elem():
108  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
109  *   .arg1_type = ARG_CONST_MAP_PTR,
110  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
111  *
112  * ret_type says that this function returns 'pointer to map elem value or null'
113  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
114  * 2nd argument should be a pointer to stack, which will be used inside
115  * the helper function as a pointer to map element key.
116  *
117  * On the kernel side the helper function looks like:
118  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
119  * {
120  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
121  *    void *key = (void *) (unsigned long) r2;
122  *    void *value;
123  *
124  *    here kernel can access 'key' and 'map' pointers safely, knowing that
125  *    [key, key + map->key_size) bytes are valid and were initialized on
126  *    the stack of eBPF program.
127  * }
128  *
129  * Corresponding eBPF program may look like:
130  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
131  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
132  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
133  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
134  * here verifier looks at prototype of map_lookup_elem() and sees:
135  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
136  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
137  *
138  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
139  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
140  * and were initialized prior to this call.
141  * If it's ok, then verifier allows this BPF_CALL insn and looks at
142  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
143  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
144  * returns either pointer to map value or NULL.
145  *
146  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
147  * insn, the register holding that pointer in the true branch changes state to
148  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
149  * branch. See check_cond_jmp_op().
150  *
151  * After the call R0 is set to return type of the function and registers R1-R5
152  * are set to NOT_INIT to indicate that they are no longer readable.
153  *
154  * The following reference types represent a potential reference to a kernel
155  * resource which, after first being allocated, must be checked and freed by
156  * the BPF program:
157  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
158  *
159  * When the verifier sees a helper call return a reference type, it allocates a
160  * pointer id for the reference and stores it in the current function state.
161  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
162  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
163  * passes through a NULL-check conditional. For the branch wherein the state is
164  * changed to CONST_IMM, the verifier releases the reference.
165  *
166  * For each helper function that allocates a reference, such as
167  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
168  * bpf_sk_release(). When a reference type passes into the release function,
169  * the verifier also releases the reference. If any unchecked or unreleased
170  * reference remains at the end of the program, the verifier rejects it.
171  */
172 
173 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
174 struct bpf_verifier_stack_elem {
175 	/* verifier state is 'st'
176 	 * before processing instruction 'insn_idx'
177 	 * and after processing instruction 'prev_insn_idx'
178 	 */
179 	struct bpf_verifier_state st;
180 	int insn_idx;
181 	int prev_insn_idx;
182 	struct bpf_verifier_stack_elem *next;
183 	/* length of verifier log at the time this state was pushed on stack */
184 	u32 log_pos;
185 };
186 
187 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
188 #define BPF_COMPLEXITY_LIMIT_STATES	64
189 
190 #define BPF_MAP_KEY_POISON	(1ULL << 63)
191 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
192 
193 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
194 
195 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
196 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
197 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
198 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
199 static int ref_set_non_owning(struct bpf_verifier_env *env,
200 			      struct bpf_reg_state *reg);
201 static void specialize_kfunc(struct bpf_verifier_env *env,
202 			     u32 func_id, u16 offset, unsigned long *addr);
203 static bool is_trusted_reg(const struct bpf_reg_state *reg);
204 
205 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
206 {
207 	return aux->map_ptr_state.poison;
208 }
209 
210 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
211 {
212 	return aux->map_ptr_state.unpriv;
213 }
214 
215 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
216 			      struct bpf_map *map,
217 			      bool unpriv, bool poison)
218 {
219 	unpriv |= bpf_map_ptr_unpriv(aux);
220 	aux->map_ptr_state.unpriv = unpriv;
221 	aux->map_ptr_state.poison = poison;
222 	aux->map_ptr_state.map_ptr = map;
223 }
224 
225 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
226 {
227 	return aux->map_key_state & BPF_MAP_KEY_POISON;
228 }
229 
230 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
231 {
232 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
233 }
234 
235 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
236 {
237 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
238 }
239 
240 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
241 {
242 	bool poisoned = bpf_map_key_poisoned(aux);
243 
244 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
245 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
246 }
247 
248 static bool bpf_helper_call(const struct bpf_insn *insn)
249 {
250 	return insn->code == (BPF_JMP | BPF_CALL) &&
251 	       insn->src_reg == 0;
252 }
253 
254 static bool bpf_pseudo_call(const struct bpf_insn *insn)
255 {
256 	return insn->code == (BPF_JMP | BPF_CALL) &&
257 	       insn->src_reg == BPF_PSEUDO_CALL;
258 }
259 
260 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
261 {
262 	return insn->code == (BPF_JMP | BPF_CALL) &&
263 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
264 }
265 
266 struct bpf_call_arg_meta {
267 	struct bpf_map *map_ptr;
268 	bool raw_mode;
269 	bool pkt_access;
270 	u8 release_regno;
271 	int regno;
272 	int access_size;
273 	int mem_size;
274 	u64 msize_max_value;
275 	int ref_obj_id;
276 	int dynptr_id;
277 	int map_uid;
278 	int func_id;
279 	struct btf *btf;
280 	u32 btf_id;
281 	struct btf *ret_btf;
282 	u32 ret_btf_id;
283 	u32 subprogno;
284 	struct btf_field *kptr_field;
285 };
286 
287 struct bpf_kfunc_call_arg_meta {
288 	/* In parameters */
289 	struct btf *btf;
290 	u32 func_id;
291 	u32 kfunc_flags;
292 	const struct btf_type *func_proto;
293 	const char *func_name;
294 	/* Out parameters */
295 	u32 ref_obj_id;
296 	u8 release_regno;
297 	bool r0_rdonly;
298 	u32 ret_btf_id;
299 	u64 r0_size;
300 	u32 subprogno;
301 	struct {
302 		u64 value;
303 		bool found;
304 	} arg_constant;
305 
306 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
307 	 * generally to pass info about user-defined local kptr types to later
308 	 * verification logic
309 	 *   bpf_obj_drop/bpf_percpu_obj_drop
310 	 *     Record the local kptr type to be drop'd
311 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
312 	 *     Record the local kptr type to be refcount_incr'd and use
313 	 *     arg_owning_ref to determine whether refcount_acquire should be
314 	 *     fallible
315 	 */
316 	struct btf *arg_btf;
317 	u32 arg_btf_id;
318 	bool arg_owning_ref;
319 
320 	struct {
321 		struct btf_field *field;
322 	} arg_list_head;
323 	struct {
324 		struct btf_field *field;
325 	} arg_rbtree_root;
326 	struct {
327 		enum bpf_dynptr_type type;
328 		u32 id;
329 		u32 ref_obj_id;
330 	} initialized_dynptr;
331 	struct {
332 		u8 spi;
333 		u8 frameno;
334 	} iter;
335 	struct {
336 		struct bpf_map *ptr;
337 		int uid;
338 	} map;
339 	u64 mem_size;
340 };
341 
342 struct btf *btf_vmlinux;
343 
344 static const char *btf_type_name(const struct btf *btf, u32 id)
345 {
346 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
347 }
348 
349 static DEFINE_MUTEX(bpf_verifier_lock);
350 static DEFINE_MUTEX(bpf_percpu_ma_lock);
351 
352 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
353 {
354 	struct bpf_verifier_env *env = private_data;
355 	va_list args;
356 
357 	if (!bpf_verifier_log_needed(&env->log))
358 		return;
359 
360 	va_start(args, fmt);
361 	bpf_verifier_vlog(&env->log, fmt, args);
362 	va_end(args);
363 }
364 
365 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
366 				   struct bpf_reg_state *reg,
367 				   struct bpf_retval_range range, const char *ctx,
368 				   const char *reg_name)
369 {
370 	bool unknown = true;
371 
372 	verbose(env, "%s the register %s has", ctx, reg_name);
373 	if (reg->smin_value > S64_MIN) {
374 		verbose(env, " smin=%lld", reg->smin_value);
375 		unknown = false;
376 	}
377 	if (reg->smax_value < S64_MAX) {
378 		verbose(env, " smax=%lld", reg->smax_value);
379 		unknown = false;
380 	}
381 	if (unknown)
382 		verbose(env, " unknown scalar value");
383 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
384 }
385 
386 static bool type_may_be_null(u32 type)
387 {
388 	return type & PTR_MAYBE_NULL;
389 }
390 
391 static bool reg_not_null(const struct bpf_reg_state *reg)
392 {
393 	enum bpf_reg_type type;
394 
395 	type = reg->type;
396 	if (type_may_be_null(type))
397 		return false;
398 
399 	type = base_type(type);
400 	return type == PTR_TO_SOCKET ||
401 		type == PTR_TO_TCP_SOCK ||
402 		type == PTR_TO_MAP_VALUE ||
403 		type == PTR_TO_MAP_KEY ||
404 		type == PTR_TO_SOCK_COMMON ||
405 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
406 		type == PTR_TO_MEM;
407 }
408 
409 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
410 {
411 	struct btf_record *rec = NULL;
412 	struct btf_struct_meta *meta;
413 
414 	if (reg->type == PTR_TO_MAP_VALUE) {
415 		rec = reg->map_ptr->record;
416 	} else if (type_is_ptr_alloc_obj(reg->type)) {
417 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
418 		if (meta)
419 			rec = meta->record;
420 	}
421 	return rec;
422 }
423 
424 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
425 {
426 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
427 
428 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
429 }
430 
431 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
432 {
433 	struct bpf_func_info *info;
434 
435 	if (!env->prog->aux->func_info)
436 		return "";
437 
438 	info = &env->prog->aux->func_info[subprog];
439 	return btf_type_name(env->prog->aux->btf, info->type_id);
440 }
441 
442 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
443 {
444 	struct bpf_subprog_info *info = subprog_info(env, subprog);
445 
446 	info->is_cb = true;
447 	info->is_async_cb = true;
448 	info->is_exception_cb = true;
449 }
450 
451 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
452 {
453 	return subprog_info(env, subprog)->is_exception_cb;
454 }
455 
456 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
457 {
458 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
459 }
460 
461 static bool type_is_rdonly_mem(u32 type)
462 {
463 	return type & MEM_RDONLY;
464 }
465 
466 static bool is_acquire_function(enum bpf_func_id func_id,
467 				const struct bpf_map *map)
468 {
469 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
470 
471 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
472 	    func_id == BPF_FUNC_sk_lookup_udp ||
473 	    func_id == BPF_FUNC_skc_lookup_tcp ||
474 	    func_id == BPF_FUNC_ringbuf_reserve ||
475 	    func_id == BPF_FUNC_kptr_xchg)
476 		return true;
477 
478 	if (func_id == BPF_FUNC_map_lookup_elem &&
479 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
480 	     map_type == BPF_MAP_TYPE_SOCKHASH))
481 		return true;
482 
483 	return false;
484 }
485 
486 static bool is_ptr_cast_function(enum bpf_func_id func_id)
487 {
488 	return func_id == BPF_FUNC_tcp_sock ||
489 		func_id == BPF_FUNC_sk_fullsock ||
490 		func_id == BPF_FUNC_skc_to_tcp_sock ||
491 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
492 		func_id == BPF_FUNC_skc_to_udp6_sock ||
493 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
494 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
495 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
496 }
497 
498 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
499 {
500 	return func_id == BPF_FUNC_dynptr_data;
501 }
502 
503 static bool is_sync_callback_calling_kfunc(u32 btf_id);
504 static bool is_async_callback_calling_kfunc(u32 btf_id);
505 static bool is_callback_calling_kfunc(u32 btf_id);
506 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
507 
508 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
509 
510 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
511 {
512 	return func_id == BPF_FUNC_for_each_map_elem ||
513 	       func_id == BPF_FUNC_find_vma ||
514 	       func_id == BPF_FUNC_loop ||
515 	       func_id == BPF_FUNC_user_ringbuf_drain;
516 }
517 
518 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
519 {
520 	return func_id == BPF_FUNC_timer_set_callback;
521 }
522 
523 static bool is_callback_calling_function(enum bpf_func_id func_id)
524 {
525 	return is_sync_callback_calling_function(func_id) ||
526 	       is_async_callback_calling_function(func_id);
527 }
528 
529 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
530 {
531 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
532 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
533 }
534 
535 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
536 {
537 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
538 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
539 }
540 
541 static bool is_may_goto_insn(struct bpf_insn *insn)
542 {
543 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
544 }
545 
546 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
547 {
548 	return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
549 }
550 
551 static bool is_storage_get_function(enum bpf_func_id func_id)
552 {
553 	return func_id == BPF_FUNC_sk_storage_get ||
554 	       func_id == BPF_FUNC_inode_storage_get ||
555 	       func_id == BPF_FUNC_task_storage_get ||
556 	       func_id == BPF_FUNC_cgrp_storage_get;
557 }
558 
559 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
560 					const struct bpf_map *map)
561 {
562 	int ref_obj_uses = 0;
563 
564 	if (is_ptr_cast_function(func_id))
565 		ref_obj_uses++;
566 	if (is_acquire_function(func_id, map))
567 		ref_obj_uses++;
568 	if (is_dynptr_ref_function(func_id))
569 		ref_obj_uses++;
570 
571 	return ref_obj_uses > 1;
572 }
573 
574 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
575 {
576 	return BPF_CLASS(insn->code) == BPF_STX &&
577 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
578 	       insn->imm == BPF_CMPXCHG;
579 }
580 
581 static int __get_spi(s32 off)
582 {
583 	return (-off - 1) / BPF_REG_SIZE;
584 }
585 
586 static struct bpf_func_state *func(struct bpf_verifier_env *env,
587 				   const struct bpf_reg_state *reg)
588 {
589 	struct bpf_verifier_state *cur = env->cur_state;
590 
591 	return cur->frame[reg->frameno];
592 }
593 
594 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
595 {
596        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
597 
598        /* We need to check that slots between [spi - nr_slots + 1, spi] are
599 	* within [0, allocated_stack).
600 	*
601 	* Please note that the spi grows downwards. For example, a dynptr
602 	* takes the size of two stack slots; the first slot will be at
603 	* spi and the second slot will be at spi - 1.
604 	*/
605        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
606 }
607 
608 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
609 			          const char *obj_kind, int nr_slots)
610 {
611 	int off, spi;
612 
613 	if (!tnum_is_const(reg->var_off)) {
614 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
615 		return -EINVAL;
616 	}
617 
618 	off = reg->off + reg->var_off.value;
619 	if (off % BPF_REG_SIZE) {
620 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
621 		return -EINVAL;
622 	}
623 
624 	spi = __get_spi(off);
625 	if (spi + 1 < nr_slots) {
626 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
627 		return -EINVAL;
628 	}
629 
630 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
631 		return -ERANGE;
632 	return spi;
633 }
634 
635 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
636 {
637 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
638 }
639 
640 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
641 {
642 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
643 }
644 
645 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
646 {
647 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
648 	case DYNPTR_TYPE_LOCAL:
649 		return BPF_DYNPTR_TYPE_LOCAL;
650 	case DYNPTR_TYPE_RINGBUF:
651 		return BPF_DYNPTR_TYPE_RINGBUF;
652 	case DYNPTR_TYPE_SKB:
653 		return BPF_DYNPTR_TYPE_SKB;
654 	case DYNPTR_TYPE_XDP:
655 		return BPF_DYNPTR_TYPE_XDP;
656 	default:
657 		return BPF_DYNPTR_TYPE_INVALID;
658 	}
659 }
660 
661 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
662 {
663 	switch (type) {
664 	case BPF_DYNPTR_TYPE_LOCAL:
665 		return DYNPTR_TYPE_LOCAL;
666 	case BPF_DYNPTR_TYPE_RINGBUF:
667 		return DYNPTR_TYPE_RINGBUF;
668 	case BPF_DYNPTR_TYPE_SKB:
669 		return DYNPTR_TYPE_SKB;
670 	case BPF_DYNPTR_TYPE_XDP:
671 		return DYNPTR_TYPE_XDP;
672 	default:
673 		return 0;
674 	}
675 }
676 
677 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
678 {
679 	return type == BPF_DYNPTR_TYPE_RINGBUF;
680 }
681 
682 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
683 			      enum bpf_dynptr_type type,
684 			      bool first_slot, int dynptr_id);
685 
686 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
687 				struct bpf_reg_state *reg);
688 
689 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
690 				   struct bpf_reg_state *sreg1,
691 				   struct bpf_reg_state *sreg2,
692 				   enum bpf_dynptr_type type)
693 {
694 	int id = ++env->id_gen;
695 
696 	__mark_dynptr_reg(sreg1, type, true, id);
697 	__mark_dynptr_reg(sreg2, type, false, id);
698 }
699 
700 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
701 			       struct bpf_reg_state *reg,
702 			       enum bpf_dynptr_type type)
703 {
704 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
705 }
706 
707 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
708 				        struct bpf_func_state *state, int spi);
709 
710 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
711 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
712 {
713 	struct bpf_func_state *state = func(env, reg);
714 	enum bpf_dynptr_type type;
715 	int spi, i, err;
716 
717 	spi = dynptr_get_spi(env, reg);
718 	if (spi < 0)
719 		return spi;
720 
721 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
722 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
723 	 * to ensure that for the following example:
724 	 *	[d1][d1][d2][d2]
725 	 * spi    3   2   1   0
726 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
727 	 * case they do belong to same dynptr, second call won't see slot_type
728 	 * as STACK_DYNPTR and will simply skip destruction.
729 	 */
730 	err = destroy_if_dynptr_stack_slot(env, state, spi);
731 	if (err)
732 		return err;
733 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
734 	if (err)
735 		return err;
736 
737 	for (i = 0; i < BPF_REG_SIZE; i++) {
738 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
739 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
740 	}
741 
742 	type = arg_to_dynptr_type(arg_type);
743 	if (type == BPF_DYNPTR_TYPE_INVALID)
744 		return -EINVAL;
745 
746 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
747 			       &state->stack[spi - 1].spilled_ptr, type);
748 
749 	if (dynptr_type_refcounted(type)) {
750 		/* The id is used to track proper releasing */
751 		int id;
752 
753 		if (clone_ref_obj_id)
754 			id = clone_ref_obj_id;
755 		else
756 			id = acquire_reference_state(env, insn_idx);
757 
758 		if (id < 0)
759 			return id;
760 
761 		state->stack[spi].spilled_ptr.ref_obj_id = id;
762 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
763 	}
764 
765 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
766 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
767 
768 	return 0;
769 }
770 
771 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
772 {
773 	int i;
774 
775 	for (i = 0; i < BPF_REG_SIZE; i++) {
776 		state->stack[spi].slot_type[i] = STACK_INVALID;
777 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
778 	}
779 
780 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
781 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
782 
783 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
784 	 *
785 	 * While we don't allow reading STACK_INVALID, it is still possible to
786 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
787 	 * helpers or insns can do partial read of that part without failing,
788 	 * but check_stack_range_initialized, check_stack_read_var_off, and
789 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
790 	 * the slot conservatively. Hence we need to prevent those liveness
791 	 * marking walks.
792 	 *
793 	 * This was not a problem before because STACK_INVALID is only set by
794 	 * default (where the default reg state has its reg->parent as NULL), or
795 	 * in clean_live_states after REG_LIVE_DONE (at which point
796 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
797 	 * verifier state exploration (like we did above). Hence, for our case
798 	 * parentage chain will still be live (i.e. reg->parent may be
799 	 * non-NULL), while earlier reg->parent was NULL, so we need
800 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
801 	 * done later on reads or by mark_dynptr_read as well to unnecessary
802 	 * mark registers in verifier state.
803 	 */
804 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
805 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
806 }
807 
808 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
809 {
810 	struct bpf_func_state *state = func(env, reg);
811 	int spi, ref_obj_id, i;
812 
813 	spi = dynptr_get_spi(env, reg);
814 	if (spi < 0)
815 		return spi;
816 
817 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
818 		invalidate_dynptr(env, state, spi);
819 		return 0;
820 	}
821 
822 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
823 
824 	/* If the dynptr has a ref_obj_id, then we need to invalidate
825 	 * two things:
826 	 *
827 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
828 	 * 2) Any slices derived from this dynptr.
829 	 */
830 
831 	/* Invalidate any slices associated with this dynptr */
832 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
833 
834 	/* Invalidate any dynptr clones */
835 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
836 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
837 			continue;
838 
839 		/* it should always be the case that if the ref obj id
840 		 * matches then the stack slot also belongs to a
841 		 * dynptr
842 		 */
843 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
844 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
845 			return -EFAULT;
846 		}
847 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
848 			invalidate_dynptr(env, state, i);
849 	}
850 
851 	return 0;
852 }
853 
854 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
855 			       struct bpf_reg_state *reg);
856 
857 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
858 {
859 	if (!env->allow_ptr_leaks)
860 		__mark_reg_not_init(env, reg);
861 	else
862 		__mark_reg_unknown(env, reg);
863 }
864 
865 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
866 				        struct bpf_func_state *state, int spi)
867 {
868 	struct bpf_func_state *fstate;
869 	struct bpf_reg_state *dreg;
870 	int i, dynptr_id;
871 
872 	/* We always ensure that STACK_DYNPTR is never set partially,
873 	 * hence just checking for slot_type[0] is enough. This is
874 	 * different for STACK_SPILL, where it may be only set for
875 	 * 1 byte, so code has to use is_spilled_reg.
876 	 */
877 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
878 		return 0;
879 
880 	/* Reposition spi to first slot */
881 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
882 		spi = spi + 1;
883 
884 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
885 		verbose(env, "cannot overwrite referenced dynptr\n");
886 		return -EINVAL;
887 	}
888 
889 	mark_stack_slot_scratched(env, spi);
890 	mark_stack_slot_scratched(env, spi - 1);
891 
892 	/* Writing partially to one dynptr stack slot destroys both. */
893 	for (i = 0; i < BPF_REG_SIZE; i++) {
894 		state->stack[spi].slot_type[i] = STACK_INVALID;
895 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
896 	}
897 
898 	dynptr_id = state->stack[spi].spilled_ptr.id;
899 	/* Invalidate any slices associated with this dynptr */
900 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
901 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
902 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
903 			continue;
904 		if (dreg->dynptr_id == dynptr_id)
905 			mark_reg_invalid(env, dreg);
906 	}));
907 
908 	/* Do not release reference state, we are destroying dynptr on stack,
909 	 * not using some helper to release it. Just reset register.
910 	 */
911 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
912 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
913 
914 	/* Same reason as unmark_stack_slots_dynptr above */
915 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
916 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
917 
918 	return 0;
919 }
920 
921 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
922 {
923 	int spi;
924 
925 	if (reg->type == CONST_PTR_TO_DYNPTR)
926 		return false;
927 
928 	spi = dynptr_get_spi(env, reg);
929 
930 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
931 	 * error because this just means the stack state hasn't been updated yet.
932 	 * We will do check_mem_access to check and update stack bounds later.
933 	 */
934 	if (spi < 0 && spi != -ERANGE)
935 		return false;
936 
937 	/* We don't need to check if the stack slots are marked by previous
938 	 * dynptr initializations because we allow overwriting existing unreferenced
939 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
940 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
941 	 * touching are completely destructed before we reinitialize them for a new
942 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
943 	 * instead of delaying it until the end where the user will get "Unreleased
944 	 * reference" error.
945 	 */
946 	return true;
947 }
948 
949 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
950 {
951 	struct bpf_func_state *state = func(env, reg);
952 	int i, spi;
953 
954 	/* This already represents first slot of initialized bpf_dynptr.
955 	 *
956 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
957 	 * check_func_arg_reg_off's logic, so we don't need to check its
958 	 * offset and alignment.
959 	 */
960 	if (reg->type == CONST_PTR_TO_DYNPTR)
961 		return true;
962 
963 	spi = dynptr_get_spi(env, reg);
964 	if (spi < 0)
965 		return false;
966 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
967 		return false;
968 
969 	for (i = 0; i < BPF_REG_SIZE; i++) {
970 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
971 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
972 			return false;
973 	}
974 
975 	return true;
976 }
977 
978 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
979 				    enum bpf_arg_type arg_type)
980 {
981 	struct bpf_func_state *state = func(env, reg);
982 	enum bpf_dynptr_type dynptr_type;
983 	int spi;
984 
985 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
986 	if (arg_type == ARG_PTR_TO_DYNPTR)
987 		return true;
988 
989 	dynptr_type = arg_to_dynptr_type(arg_type);
990 	if (reg->type == CONST_PTR_TO_DYNPTR) {
991 		return reg->dynptr.type == dynptr_type;
992 	} else {
993 		spi = dynptr_get_spi(env, reg);
994 		if (spi < 0)
995 			return false;
996 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
997 	}
998 }
999 
1000 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1001 
1002 static bool in_rcu_cs(struct bpf_verifier_env *env);
1003 
1004 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1005 
1006 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1007 				 struct bpf_kfunc_call_arg_meta *meta,
1008 				 struct bpf_reg_state *reg, int insn_idx,
1009 				 struct btf *btf, u32 btf_id, int nr_slots)
1010 {
1011 	struct bpf_func_state *state = func(env, reg);
1012 	int spi, i, j, id;
1013 
1014 	spi = iter_get_spi(env, reg, nr_slots);
1015 	if (spi < 0)
1016 		return spi;
1017 
1018 	id = acquire_reference_state(env, insn_idx);
1019 	if (id < 0)
1020 		return id;
1021 
1022 	for (i = 0; i < nr_slots; i++) {
1023 		struct bpf_stack_state *slot = &state->stack[spi - i];
1024 		struct bpf_reg_state *st = &slot->spilled_ptr;
1025 
1026 		__mark_reg_known_zero(st);
1027 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1028 		if (is_kfunc_rcu_protected(meta)) {
1029 			if (in_rcu_cs(env))
1030 				st->type |= MEM_RCU;
1031 			else
1032 				st->type |= PTR_UNTRUSTED;
1033 		}
1034 		st->live |= REG_LIVE_WRITTEN;
1035 		st->ref_obj_id = i == 0 ? id : 0;
1036 		st->iter.btf = btf;
1037 		st->iter.btf_id = btf_id;
1038 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1039 		st->iter.depth = 0;
1040 
1041 		for (j = 0; j < BPF_REG_SIZE; j++)
1042 			slot->slot_type[j] = STACK_ITER;
1043 
1044 		mark_stack_slot_scratched(env, spi - i);
1045 	}
1046 
1047 	return 0;
1048 }
1049 
1050 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1051 				   struct bpf_reg_state *reg, int nr_slots)
1052 {
1053 	struct bpf_func_state *state = func(env, reg);
1054 	int spi, i, j;
1055 
1056 	spi = iter_get_spi(env, reg, nr_slots);
1057 	if (spi < 0)
1058 		return spi;
1059 
1060 	for (i = 0; i < nr_slots; i++) {
1061 		struct bpf_stack_state *slot = &state->stack[spi - i];
1062 		struct bpf_reg_state *st = &slot->spilled_ptr;
1063 
1064 		if (i == 0)
1065 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1066 
1067 		__mark_reg_not_init(env, st);
1068 
1069 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1070 		st->live |= REG_LIVE_WRITTEN;
1071 
1072 		for (j = 0; j < BPF_REG_SIZE; j++)
1073 			slot->slot_type[j] = STACK_INVALID;
1074 
1075 		mark_stack_slot_scratched(env, spi - i);
1076 	}
1077 
1078 	return 0;
1079 }
1080 
1081 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1082 				     struct bpf_reg_state *reg, int nr_slots)
1083 {
1084 	struct bpf_func_state *state = func(env, reg);
1085 	int spi, i, j;
1086 
1087 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1088 	 * will do check_mem_access to check and update stack bounds later, so
1089 	 * return true for that case.
1090 	 */
1091 	spi = iter_get_spi(env, reg, nr_slots);
1092 	if (spi == -ERANGE)
1093 		return true;
1094 	if (spi < 0)
1095 		return false;
1096 
1097 	for (i = 0; i < nr_slots; i++) {
1098 		struct bpf_stack_state *slot = &state->stack[spi - i];
1099 
1100 		for (j = 0; j < BPF_REG_SIZE; j++)
1101 			if (slot->slot_type[j] == STACK_ITER)
1102 				return false;
1103 	}
1104 
1105 	return true;
1106 }
1107 
1108 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1109 				   struct btf *btf, u32 btf_id, int nr_slots)
1110 {
1111 	struct bpf_func_state *state = func(env, reg);
1112 	int spi, i, j;
1113 
1114 	spi = iter_get_spi(env, reg, nr_slots);
1115 	if (spi < 0)
1116 		return -EINVAL;
1117 
1118 	for (i = 0; i < nr_slots; i++) {
1119 		struct bpf_stack_state *slot = &state->stack[spi - i];
1120 		struct bpf_reg_state *st = &slot->spilled_ptr;
1121 
1122 		if (st->type & PTR_UNTRUSTED)
1123 			return -EPROTO;
1124 		/* only main (first) slot has ref_obj_id set */
1125 		if (i == 0 && !st->ref_obj_id)
1126 			return -EINVAL;
1127 		if (i != 0 && st->ref_obj_id)
1128 			return -EINVAL;
1129 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1130 			return -EINVAL;
1131 
1132 		for (j = 0; j < BPF_REG_SIZE; j++)
1133 			if (slot->slot_type[j] != STACK_ITER)
1134 				return -EINVAL;
1135 	}
1136 
1137 	return 0;
1138 }
1139 
1140 /* Check if given stack slot is "special":
1141  *   - spilled register state (STACK_SPILL);
1142  *   - dynptr state (STACK_DYNPTR);
1143  *   - iter state (STACK_ITER).
1144  */
1145 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1146 {
1147 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1148 
1149 	switch (type) {
1150 	case STACK_SPILL:
1151 	case STACK_DYNPTR:
1152 	case STACK_ITER:
1153 		return true;
1154 	case STACK_INVALID:
1155 	case STACK_MISC:
1156 	case STACK_ZERO:
1157 		return false;
1158 	default:
1159 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1160 		return true;
1161 	}
1162 }
1163 
1164 /* The reg state of a pointer or a bounded scalar was saved when
1165  * it was spilled to the stack.
1166  */
1167 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1168 {
1169 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1170 }
1171 
1172 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1173 {
1174 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1175 	       stack->spilled_ptr.type == SCALAR_VALUE;
1176 }
1177 
1178 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1179 {
1180 	return stack->slot_type[0] == STACK_SPILL &&
1181 	       stack->spilled_ptr.type == SCALAR_VALUE;
1182 }
1183 
1184 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1185  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1186  * more precise STACK_ZERO.
1187  * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take
1188  * env->allow_ptr_leaks into account and force STACK_MISC, if necessary.
1189  */
1190 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1191 {
1192 	if (*stype == STACK_ZERO)
1193 		return;
1194 	if (env->allow_ptr_leaks && *stype == STACK_INVALID)
1195 		return;
1196 	*stype = STACK_MISC;
1197 }
1198 
1199 static void scrub_spilled_slot(u8 *stype)
1200 {
1201 	if (*stype != STACK_INVALID)
1202 		*stype = STACK_MISC;
1203 }
1204 
1205 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1206  * small to hold src. This is different from krealloc since we don't want to preserve
1207  * the contents of dst.
1208  *
1209  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1210  * not be allocated.
1211  */
1212 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1213 {
1214 	size_t alloc_bytes;
1215 	void *orig = dst;
1216 	size_t bytes;
1217 
1218 	if (ZERO_OR_NULL_PTR(src))
1219 		goto out;
1220 
1221 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1222 		return NULL;
1223 
1224 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1225 	dst = krealloc(orig, alloc_bytes, flags);
1226 	if (!dst) {
1227 		kfree(orig);
1228 		return NULL;
1229 	}
1230 
1231 	memcpy(dst, src, bytes);
1232 out:
1233 	return dst ? dst : ZERO_SIZE_PTR;
1234 }
1235 
1236 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1237  * small to hold new_n items. new items are zeroed out if the array grows.
1238  *
1239  * Contrary to krealloc_array, does not free arr if new_n is zero.
1240  */
1241 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1242 {
1243 	size_t alloc_size;
1244 	void *new_arr;
1245 
1246 	if (!new_n || old_n == new_n)
1247 		goto out;
1248 
1249 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1250 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1251 	if (!new_arr) {
1252 		kfree(arr);
1253 		return NULL;
1254 	}
1255 	arr = new_arr;
1256 
1257 	if (new_n > old_n)
1258 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1259 
1260 out:
1261 	return arr ? arr : ZERO_SIZE_PTR;
1262 }
1263 
1264 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1265 {
1266 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1267 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1268 	if (!dst->refs)
1269 		return -ENOMEM;
1270 
1271 	dst->acquired_refs = src->acquired_refs;
1272 	return 0;
1273 }
1274 
1275 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1276 {
1277 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1278 
1279 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1280 				GFP_KERNEL);
1281 	if (!dst->stack)
1282 		return -ENOMEM;
1283 
1284 	dst->allocated_stack = src->allocated_stack;
1285 	return 0;
1286 }
1287 
1288 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1289 {
1290 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1291 				    sizeof(struct bpf_reference_state));
1292 	if (!state->refs)
1293 		return -ENOMEM;
1294 
1295 	state->acquired_refs = n;
1296 	return 0;
1297 }
1298 
1299 /* Possibly update state->allocated_stack to be at least size bytes. Also
1300  * possibly update the function's high-water mark in its bpf_subprog_info.
1301  */
1302 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1303 {
1304 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1305 
1306 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1307 	size = round_up(size, BPF_REG_SIZE);
1308 	n = size / BPF_REG_SIZE;
1309 
1310 	if (old_n >= n)
1311 		return 0;
1312 
1313 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1314 	if (!state->stack)
1315 		return -ENOMEM;
1316 
1317 	state->allocated_stack = size;
1318 
1319 	/* update known max for given subprogram */
1320 	if (env->subprog_info[state->subprogno].stack_depth < size)
1321 		env->subprog_info[state->subprogno].stack_depth = size;
1322 
1323 	return 0;
1324 }
1325 
1326 /* Acquire a pointer id from the env and update the state->refs to include
1327  * this new pointer reference.
1328  * On success, returns a valid pointer id to associate with the register
1329  * On failure, returns a negative errno.
1330  */
1331 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1332 {
1333 	struct bpf_func_state *state = cur_func(env);
1334 	int new_ofs = state->acquired_refs;
1335 	int id, err;
1336 
1337 	err = resize_reference_state(state, state->acquired_refs + 1);
1338 	if (err)
1339 		return err;
1340 	id = ++env->id_gen;
1341 	state->refs[new_ofs].id = id;
1342 	state->refs[new_ofs].insn_idx = insn_idx;
1343 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1344 
1345 	return id;
1346 }
1347 
1348 /* release function corresponding to acquire_reference_state(). Idempotent. */
1349 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1350 {
1351 	int i, last_idx;
1352 
1353 	last_idx = state->acquired_refs - 1;
1354 	for (i = 0; i < state->acquired_refs; i++) {
1355 		if (state->refs[i].id == ptr_id) {
1356 			/* Cannot release caller references in callbacks */
1357 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1358 				return -EINVAL;
1359 			if (last_idx && i != last_idx)
1360 				memcpy(&state->refs[i], &state->refs[last_idx],
1361 				       sizeof(*state->refs));
1362 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1363 			state->acquired_refs--;
1364 			return 0;
1365 		}
1366 	}
1367 	return -EINVAL;
1368 }
1369 
1370 static void free_func_state(struct bpf_func_state *state)
1371 {
1372 	if (!state)
1373 		return;
1374 	kfree(state->refs);
1375 	kfree(state->stack);
1376 	kfree(state);
1377 }
1378 
1379 static void clear_jmp_history(struct bpf_verifier_state *state)
1380 {
1381 	kfree(state->jmp_history);
1382 	state->jmp_history = NULL;
1383 	state->jmp_history_cnt = 0;
1384 }
1385 
1386 static void free_verifier_state(struct bpf_verifier_state *state,
1387 				bool free_self)
1388 {
1389 	int i;
1390 
1391 	for (i = 0; i <= state->curframe; i++) {
1392 		free_func_state(state->frame[i]);
1393 		state->frame[i] = NULL;
1394 	}
1395 	clear_jmp_history(state);
1396 	if (free_self)
1397 		kfree(state);
1398 }
1399 
1400 /* copy verifier state from src to dst growing dst stack space
1401  * when necessary to accommodate larger src stack
1402  */
1403 static int copy_func_state(struct bpf_func_state *dst,
1404 			   const struct bpf_func_state *src)
1405 {
1406 	int err;
1407 
1408 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1409 	err = copy_reference_state(dst, src);
1410 	if (err)
1411 		return err;
1412 	return copy_stack_state(dst, src);
1413 }
1414 
1415 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1416 			       const struct bpf_verifier_state *src)
1417 {
1418 	struct bpf_func_state *dst;
1419 	int i, err;
1420 
1421 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1422 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1423 					  GFP_USER);
1424 	if (!dst_state->jmp_history)
1425 		return -ENOMEM;
1426 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1427 
1428 	/* if dst has more stack frames then src frame, free them, this is also
1429 	 * necessary in case of exceptional exits using bpf_throw.
1430 	 */
1431 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1432 		free_func_state(dst_state->frame[i]);
1433 		dst_state->frame[i] = NULL;
1434 	}
1435 	dst_state->speculative = src->speculative;
1436 	dst_state->active_rcu_lock = src->active_rcu_lock;
1437 	dst_state->active_preempt_lock = src->active_preempt_lock;
1438 	dst_state->in_sleepable = src->in_sleepable;
1439 	dst_state->curframe = src->curframe;
1440 	dst_state->active_lock.ptr = src->active_lock.ptr;
1441 	dst_state->active_lock.id = src->active_lock.id;
1442 	dst_state->branches = src->branches;
1443 	dst_state->parent = src->parent;
1444 	dst_state->first_insn_idx = src->first_insn_idx;
1445 	dst_state->last_insn_idx = src->last_insn_idx;
1446 	dst_state->dfs_depth = src->dfs_depth;
1447 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1448 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1449 	dst_state->may_goto_depth = src->may_goto_depth;
1450 	for (i = 0; i <= src->curframe; i++) {
1451 		dst = dst_state->frame[i];
1452 		if (!dst) {
1453 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1454 			if (!dst)
1455 				return -ENOMEM;
1456 			dst_state->frame[i] = dst;
1457 		}
1458 		err = copy_func_state(dst, src->frame[i]);
1459 		if (err)
1460 			return err;
1461 	}
1462 	return 0;
1463 }
1464 
1465 static u32 state_htab_size(struct bpf_verifier_env *env)
1466 {
1467 	return env->prog->len;
1468 }
1469 
1470 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1471 {
1472 	struct bpf_verifier_state *cur = env->cur_state;
1473 	struct bpf_func_state *state = cur->frame[cur->curframe];
1474 
1475 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1476 }
1477 
1478 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1479 {
1480 	int fr;
1481 
1482 	if (a->curframe != b->curframe)
1483 		return false;
1484 
1485 	for (fr = a->curframe; fr >= 0; fr--)
1486 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1487 			return false;
1488 
1489 	return true;
1490 }
1491 
1492 /* Open coded iterators allow back-edges in the state graph in order to
1493  * check unbounded loops that iterators.
1494  *
1495  * In is_state_visited() it is necessary to know if explored states are
1496  * part of some loops in order to decide whether non-exact states
1497  * comparison could be used:
1498  * - non-exact states comparison establishes sub-state relation and uses
1499  *   read and precision marks to do so, these marks are propagated from
1500  *   children states and thus are not guaranteed to be final in a loop;
1501  * - exact states comparison just checks if current and explored states
1502  *   are identical (and thus form a back-edge).
1503  *
1504  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1505  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1506  * algorithm for loop structure detection and gives an overview of
1507  * relevant terminology. It also has helpful illustrations.
1508  *
1509  * [1] https://api.semanticscholar.org/CorpusID:15784067
1510  *
1511  * We use a similar algorithm but because loop nested structure is
1512  * irrelevant for verifier ours is significantly simpler and resembles
1513  * strongly connected components algorithm from Sedgewick's textbook.
1514  *
1515  * Define topmost loop entry as a first node of the loop traversed in a
1516  * depth first search starting from initial state. The goal of the loop
1517  * tracking algorithm is to associate topmost loop entries with states
1518  * derived from these entries.
1519  *
1520  * For each step in the DFS states traversal algorithm needs to identify
1521  * the following situations:
1522  *
1523  *          initial                     initial                   initial
1524  *            |                           |                         |
1525  *            V                           V                         V
1526  *           ...                         ...           .---------> hdr
1527  *            |                           |            |            |
1528  *            V                           V            |            V
1529  *           cur                     .-> succ          |    .------...
1530  *            |                      |    |            |    |       |
1531  *            V                      |    V            |    V       V
1532  *           succ                    '-- cur           |   ...     ...
1533  *                                                     |    |       |
1534  *                                                     |    V       V
1535  *                                                     |   succ <- cur
1536  *                                                     |    |
1537  *                                                     |    V
1538  *                                                     |   ...
1539  *                                                     |    |
1540  *                                                     '----'
1541  *
1542  *  (A) successor state of cur   (B) successor state of cur or it's entry
1543  *      not yet traversed            are in current DFS path, thus cur and succ
1544  *                                   are members of the same outermost loop
1545  *
1546  *                      initial                  initial
1547  *                        |                        |
1548  *                        V                        V
1549  *                       ...                      ...
1550  *                        |                        |
1551  *                        V                        V
1552  *                .------...               .------...
1553  *                |       |                |       |
1554  *                V       V                V       V
1555  *           .-> hdr     ...              ...     ...
1556  *           |    |       |                |       |
1557  *           |    V       V                V       V
1558  *           |   succ <- cur              succ <- cur
1559  *           |    |                        |
1560  *           |    V                        V
1561  *           |   ...                      ...
1562  *           |    |                        |
1563  *           '----'                       exit
1564  *
1565  * (C) successor state of cur is a part of some loop but this loop
1566  *     does not include cur or successor state is not in a loop at all.
1567  *
1568  * Algorithm could be described as the following python code:
1569  *
1570  *     traversed = set()   # Set of traversed nodes
1571  *     entries = {}        # Mapping from node to loop entry
1572  *     depths = {}         # Depth level assigned to graph node
1573  *     path = set()        # Current DFS path
1574  *
1575  *     # Find outermost loop entry known for n
1576  *     def get_loop_entry(n):
1577  *         h = entries.get(n, None)
1578  *         while h in entries and entries[h] != h:
1579  *             h = entries[h]
1580  *         return h
1581  *
1582  *     # Update n's loop entry if h's outermost entry comes
1583  *     # before n's outermost entry in current DFS path.
1584  *     def update_loop_entry(n, h):
1585  *         n1 = get_loop_entry(n) or n
1586  *         h1 = get_loop_entry(h) or h
1587  *         if h1 in path and depths[h1] <= depths[n1]:
1588  *             entries[n] = h1
1589  *
1590  *     def dfs(n, depth):
1591  *         traversed.add(n)
1592  *         path.add(n)
1593  *         depths[n] = depth
1594  *         for succ in G.successors(n):
1595  *             if succ not in traversed:
1596  *                 # Case A: explore succ and update cur's loop entry
1597  *                 #         only if succ's entry is in current DFS path.
1598  *                 dfs(succ, depth + 1)
1599  *                 h = get_loop_entry(succ)
1600  *                 update_loop_entry(n, h)
1601  *             else:
1602  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1603  *                 update_loop_entry(n, succ)
1604  *         path.remove(n)
1605  *
1606  * To adapt this algorithm for use with verifier:
1607  * - use st->branch == 0 as a signal that DFS of succ had been finished
1608  *   and cur's loop entry has to be updated (case A), handle this in
1609  *   update_branch_counts();
1610  * - use st->branch > 0 as a signal that st is in the current DFS path;
1611  * - handle cases B and C in is_state_visited();
1612  * - update topmost loop entry for intermediate states in get_loop_entry().
1613  */
1614 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1615 {
1616 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1617 
1618 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1619 		topmost = topmost->loop_entry;
1620 	/* Update loop entries for intermediate states to avoid this
1621 	 * traversal in future get_loop_entry() calls.
1622 	 */
1623 	while (st && st->loop_entry != topmost) {
1624 		old = st->loop_entry;
1625 		st->loop_entry = topmost;
1626 		st = old;
1627 	}
1628 	return topmost;
1629 }
1630 
1631 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1632 {
1633 	struct bpf_verifier_state *cur1, *hdr1;
1634 
1635 	cur1 = get_loop_entry(cur) ?: cur;
1636 	hdr1 = get_loop_entry(hdr) ?: hdr;
1637 	/* The head1->branches check decides between cases B and C in
1638 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1639 	 * head's topmost loop entry is not in current DFS path,
1640 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1641 	 * no need to update cur->loop_entry.
1642 	 */
1643 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1644 		cur->loop_entry = hdr;
1645 		hdr->used_as_loop_entry = true;
1646 	}
1647 }
1648 
1649 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1650 {
1651 	while (st) {
1652 		u32 br = --st->branches;
1653 
1654 		/* br == 0 signals that DFS exploration for 'st' is finished,
1655 		 * thus it is necessary to update parent's loop entry if it
1656 		 * turned out that st is a part of some loop.
1657 		 * This is a part of 'case A' in get_loop_entry() comment.
1658 		 */
1659 		if (br == 0 && st->parent && st->loop_entry)
1660 			update_loop_entry(st->parent, st->loop_entry);
1661 
1662 		/* WARN_ON(br > 1) technically makes sense here,
1663 		 * but see comment in push_stack(), hence:
1664 		 */
1665 		WARN_ONCE((int)br < 0,
1666 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1667 			  br);
1668 		if (br)
1669 			break;
1670 		st = st->parent;
1671 	}
1672 }
1673 
1674 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1675 		     int *insn_idx, bool pop_log)
1676 {
1677 	struct bpf_verifier_state *cur = env->cur_state;
1678 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1679 	int err;
1680 
1681 	if (env->head == NULL)
1682 		return -ENOENT;
1683 
1684 	if (cur) {
1685 		err = copy_verifier_state(cur, &head->st);
1686 		if (err)
1687 			return err;
1688 	}
1689 	if (pop_log)
1690 		bpf_vlog_reset(&env->log, head->log_pos);
1691 	if (insn_idx)
1692 		*insn_idx = head->insn_idx;
1693 	if (prev_insn_idx)
1694 		*prev_insn_idx = head->prev_insn_idx;
1695 	elem = head->next;
1696 	free_verifier_state(&head->st, false);
1697 	kfree(head);
1698 	env->head = elem;
1699 	env->stack_size--;
1700 	return 0;
1701 }
1702 
1703 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1704 					     int insn_idx, int prev_insn_idx,
1705 					     bool speculative)
1706 {
1707 	struct bpf_verifier_state *cur = env->cur_state;
1708 	struct bpf_verifier_stack_elem *elem;
1709 	int err;
1710 
1711 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1712 	if (!elem)
1713 		goto err;
1714 
1715 	elem->insn_idx = insn_idx;
1716 	elem->prev_insn_idx = prev_insn_idx;
1717 	elem->next = env->head;
1718 	elem->log_pos = env->log.end_pos;
1719 	env->head = elem;
1720 	env->stack_size++;
1721 	err = copy_verifier_state(&elem->st, cur);
1722 	if (err)
1723 		goto err;
1724 	elem->st.speculative |= speculative;
1725 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1726 		verbose(env, "The sequence of %d jumps is too complex.\n",
1727 			env->stack_size);
1728 		goto err;
1729 	}
1730 	if (elem->st.parent) {
1731 		++elem->st.parent->branches;
1732 		/* WARN_ON(branches > 2) technically makes sense here,
1733 		 * but
1734 		 * 1. speculative states will bump 'branches' for non-branch
1735 		 * instructions
1736 		 * 2. is_state_visited() heuristics may decide not to create
1737 		 * a new state for a sequence of branches and all such current
1738 		 * and cloned states will be pointing to a single parent state
1739 		 * which might have large 'branches' count.
1740 		 */
1741 	}
1742 	return &elem->st;
1743 err:
1744 	free_verifier_state(env->cur_state, true);
1745 	env->cur_state = NULL;
1746 	/* pop all elements and return */
1747 	while (!pop_stack(env, NULL, NULL, false));
1748 	return NULL;
1749 }
1750 
1751 #define CALLER_SAVED_REGS 6
1752 static const int caller_saved[CALLER_SAVED_REGS] = {
1753 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1754 };
1755 
1756 /* This helper doesn't clear reg->id */
1757 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1758 {
1759 	reg->var_off = tnum_const(imm);
1760 	reg->smin_value = (s64)imm;
1761 	reg->smax_value = (s64)imm;
1762 	reg->umin_value = imm;
1763 	reg->umax_value = imm;
1764 
1765 	reg->s32_min_value = (s32)imm;
1766 	reg->s32_max_value = (s32)imm;
1767 	reg->u32_min_value = (u32)imm;
1768 	reg->u32_max_value = (u32)imm;
1769 }
1770 
1771 /* Mark the unknown part of a register (variable offset or scalar value) as
1772  * known to have the value @imm.
1773  */
1774 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1775 {
1776 	/* Clear off and union(map_ptr, range) */
1777 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1778 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1779 	reg->id = 0;
1780 	reg->ref_obj_id = 0;
1781 	___mark_reg_known(reg, imm);
1782 }
1783 
1784 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1785 {
1786 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1787 	reg->s32_min_value = (s32)imm;
1788 	reg->s32_max_value = (s32)imm;
1789 	reg->u32_min_value = (u32)imm;
1790 	reg->u32_max_value = (u32)imm;
1791 }
1792 
1793 /* Mark the 'variable offset' part of a register as zero.  This should be
1794  * used only on registers holding a pointer type.
1795  */
1796 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1797 {
1798 	__mark_reg_known(reg, 0);
1799 }
1800 
1801 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1802 {
1803 	__mark_reg_known(reg, 0);
1804 	reg->type = SCALAR_VALUE;
1805 	/* all scalars are assumed imprecise initially (unless unprivileged,
1806 	 * in which case everything is forced to be precise)
1807 	 */
1808 	reg->precise = !env->bpf_capable;
1809 }
1810 
1811 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1812 				struct bpf_reg_state *regs, u32 regno)
1813 {
1814 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1815 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1816 		/* Something bad happened, let's kill all regs */
1817 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1818 			__mark_reg_not_init(env, regs + regno);
1819 		return;
1820 	}
1821 	__mark_reg_known_zero(regs + regno);
1822 }
1823 
1824 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1825 			      bool first_slot, int dynptr_id)
1826 {
1827 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1828 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1829 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1830 	 */
1831 	__mark_reg_known_zero(reg);
1832 	reg->type = CONST_PTR_TO_DYNPTR;
1833 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1834 	reg->id = dynptr_id;
1835 	reg->dynptr.type = type;
1836 	reg->dynptr.first_slot = first_slot;
1837 }
1838 
1839 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1840 {
1841 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1842 		const struct bpf_map *map = reg->map_ptr;
1843 
1844 		if (map->inner_map_meta) {
1845 			reg->type = CONST_PTR_TO_MAP;
1846 			reg->map_ptr = map->inner_map_meta;
1847 			/* transfer reg's id which is unique for every map_lookup_elem
1848 			 * as UID of the inner map.
1849 			 */
1850 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1851 				reg->map_uid = reg->id;
1852 			if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE))
1853 				reg->map_uid = reg->id;
1854 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1855 			reg->type = PTR_TO_XDP_SOCK;
1856 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1857 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1858 			reg->type = PTR_TO_SOCKET;
1859 		} else {
1860 			reg->type = PTR_TO_MAP_VALUE;
1861 		}
1862 		return;
1863 	}
1864 
1865 	reg->type &= ~PTR_MAYBE_NULL;
1866 }
1867 
1868 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1869 				struct btf_field_graph_root *ds_head)
1870 {
1871 	__mark_reg_known_zero(&regs[regno]);
1872 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1873 	regs[regno].btf = ds_head->btf;
1874 	regs[regno].btf_id = ds_head->value_btf_id;
1875 	regs[regno].off = ds_head->node_offset;
1876 }
1877 
1878 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1879 {
1880 	return type_is_pkt_pointer(reg->type);
1881 }
1882 
1883 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1884 {
1885 	return reg_is_pkt_pointer(reg) ||
1886 	       reg->type == PTR_TO_PACKET_END;
1887 }
1888 
1889 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1890 {
1891 	return base_type(reg->type) == PTR_TO_MEM &&
1892 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1893 }
1894 
1895 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1896 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1897 				    enum bpf_reg_type which)
1898 {
1899 	/* The register can already have a range from prior markings.
1900 	 * This is fine as long as it hasn't been advanced from its
1901 	 * origin.
1902 	 */
1903 	return reg->type == which &&
1904 	       reg->id == 0 &&
1905 	       reg->off == 0 &&
1906 	       tnum_equals_const(reg->var_off, 0);
1907 }
1908 
1909 /* Reset the min/max bounds of a register */
1910 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1911 {
1912 	reg->smin_value = S64_MIN;
1913 	reg->smax_value = S64_MAX;
1914 	reg->umin_value = 0;
1915 	reg->umax_value = U64_MAX;
1916 
1917 	reg->s32_min_value = S32_MIN;
1918 	reg->s32_max_value = S32_MAX;
1919 	reg->u32_min_value = 0;
1920 	reg->u32_max_value = U32_MAX;
1921 }
1922 
1923 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1924 {
1925 	reg->smin_value = S64_MIN;
1926 	reg->smax_value = S64_MAX;
1927 	reg->umin_value = 0;
1928 	reg->umax_value = U64_MAX;
1929 }
1930 
1931 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1932 {
1933 	reg->s32_min_value = S32_MIN;
1934 	reg->s32_max_value = S32_MAX;
1935 	reg->u32_min_value = 0;
1936 	reg->u32_max_value = U32_MAX;
1937 }
1938 
1939 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1940 {
1941 	struct tnum var32_off = tnum_subreg(reg->var_off);
1942 
1943 	/* min signed is max(sign bit) | min(other bits) */
1944 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1945 			var32_off.value | (var32_off.mask & S32_MIN));
1946 	/* max signed is min(sign bit) | max(other bits) */
1947 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1948 			var32_off.value | (var32_off.mask & S32_MAX));
1949 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1950 	reg->u32_max_value = min(reg->u32_max_value,
1951 				 (u32)(var32_off.value | var32_off.mask));
1952 }
1953 
1954 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1955 {
1956 	/* min signed is max(sign bit) | min(other bits) */
1957 	reg->smin_value = max_t(s64, reg->smin_value,
1958 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1959 	/* max signed is min(sign bit) | max(other bits) */
1960 	reg->smax_value = min_t(s64, reg->smax_value,
1961 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1962 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1963 	reg->umax_value = min(reg->umax_value,
1964 			      reg->var_off.value | reg->var_off.mask);
1965 }
1966 
1967 static void __update_reg_bounds(struct bpf_reg_state *reg)
1968 {
1969 	__update_reg32_bounds(reg);
1970 	__update_reg64_bounds(reg);
1971 }
1972 
1973 /* Uses signed min/max values to inform unsigned, and vice-versa */
1974 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1975 {
1976 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
1977 	 * bits to improve our u32/s32 boundaries.
1978 	 *
1979 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
1980 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
1981 	 * [10, 20] range. But this property holds for any 64-bit range as
1982 	 * long as upper 32 bits in that entire range of values stay the same.
1983 	 *
1984 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
1985 	 * in decimal) has the same upper 32 bits throughout all the values in
1986 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
1987 	 * range.
1988 	 *
1989 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
1990 	 * following the rules outlined below about u64/s64 correspondence
1991 	 * (which equally applies to u32 vs s32 correspondence). In general it
1992 	 * depends on actual hexadecimal values of 32-bit range. They can form
1993 	 * only valid u32, or only valid s32 ranges in some cases.
1994 	 *
1995 	 * So we use all these insights to derive bounds for subregisters here.
1996 	 */
1997 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
1998 		/* u64 to u32 casting preserves validity of low 32 bits as
1999 		 * a range, if upper 32 bits are the same
2000 		 */
2001 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2002 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2003 
2004 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2005 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2006 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2007 		}
2008 	}
2009 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2010 		/* low 32 bits should form a proper u32 range */
2011 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2012 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2013 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2014 		}
2015 		/* low 32 bits should form a proper s32 range */
2016 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2017 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2018 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2019 		}
2020 	}
2021 	/* Special case where upper bits form a small sequence of two
2022 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2023 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2024 	 * going from negative numbers to positive numbers. E.g., let's say we
2025 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2026 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2027 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2028 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2029 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2030 	 * upper 32 bits. As a random example, s64 range
2031 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2032 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2033 	 */
2034 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2035 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2036 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2037 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2038 	}
2039 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2040 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2041 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2042 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2043 	}
2044 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2045 	 * try to learn from that
2046 	 */
2047 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2048 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2049 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2050 	}
2051 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2052 	 * are the same, so combine.  This works even in the negative case, e.g.
2053 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2054 	 */
2055 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2056 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2057 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2058 	}
2059 }
2060 
2061 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2062 {
2063 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2064 	 * try to learn from that. Let's do a bit of ASCII art to see when
2065 	 * this is happening. Let's take u64 range first:
2066 	 *
2067 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2068 	 * |-------------------------------|--------------------------------|
2069 	 *
2070 	 * Valid u64 range is formed when umin and umax are anywhere in the
2071 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2072 	 * straightforward. Let's see how s64 range maps onto the same range
2073 	 * of values, annotated below the line for comparison:
2074 	 *
2075 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2076 	 * |-------------------------------|--------------------------------|
2077 	 * 0                        S64_MAX S64_MIN                        -1
2078 	 *
2079 	 * So s64 values basically start in the middle and they are logically
2080 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2081 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2082 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2083 	 * more visually as mapped to sign-agnostic range of hex values.
2084 	 *
2085 	 *  u64 start                                               u64 end
2086 	 *  _______________________________________________________________
2087 	 * /                                                               \
2088 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2089 	 * |-------------------------------|--------------------------------|
2090 	 * 0                        S64_MAX S64_MIN                        -1
2091 	 *                                / \
2092 	 * >------------------------------   ------------------------------->
2093 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2094 	 *
2095 	 * What this means is that, in general, we can't always derive
2096 	 * something new about u64 from any random s64 range, and vice versa.
2097 	 *
2098 	 * But we can do that in two particular cases. One is when entire
2099 	 * u64/s64 range is *entirely* contained within left half of the above
2100 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2101 	 *
2102 	 * |-------------------------------|--------------------------------|
2103 	 *     ^                   ^            ^                 ^
2104 	 *     A                   B            C                 D
2105 	 *
2106 	 * [A, B] and [C, D] are contained entirely in their respective halves
2107 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2108 	 * will be non-negative both as u64 and s64 (and in fact it will be
2109 	 * identical ranges no matter the signedness). [C, D] treated as s64
2110 	 * will be a range of negative values, while in u64 it will be
2111 	 * non-negative range of values larger than 0x8000000000000000.
2112 	 *
2113 	 * Now, any other range here can't be represented in both u64 and s64
2114 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2115 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2116 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2117 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2118 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2119 	 * ranges as u64. Currently reg_state can't represent two segments per
2120 	 * numeric domain, so in such situations we can only derive maximal
2121 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2122 	 *
2123 	 * So we use these facts to derive umin/umax from smin/smax and vice
2124 	 * versa only if they stay within the same "half". This is equivalent
2125 	 * to checking sign bit: lower half will have sign bit as zero, upper
2126 	 * half have sign bit 1. Below in code we simplify this by just
2127 	 * casting umin/umax as smin/smax and checking if they form valid
2128 	 * range, and vice versa. Those are equivalent checks.
2129 	 */
2130 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2131 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2132 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2133 	}
2134 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2135 	 * are the same, so combine.  This works even in the negative case, e.g.
2136 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2137 	 */
2138 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2139 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2140 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2141 	}
2142 }
2143 
2144 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2145 {
2146 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2147 	 * values on both sides of 64-bit range in hope to have tighter range.
2148 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2149 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2150 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2151 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2152 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2153 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2154 	 * We just need to make sure that derived bounds we are intersecting
2155 	 * with are well-formed ranges in respective s64 or u64 domain, just
2156 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2157 	 */
2158 	__u64 new_umin, new_umax;
2159 	__s64 new_smin, new_smax;
2160 
2161 	/* u32 -> u64 tightening, it's always well-formed */
2162 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2163 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2164 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2165 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2166 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2167 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2168 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2169 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2170 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2171 
2172 	/* if s32 can be treated as valid u32 range, we can use it as well */
2173 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2174 		/* s32 -> u64 tightening */
2175 		new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2176 		new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2177 		reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2178 		reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2179 		/* s32 -> s64 tightening */
2180 		new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2181 		new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2182 		reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2183 		reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2184 	}
2185 }
2186 
2187 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2188 {
2189 	__reg32_deduce_bounds(reg);
2190 	__reg64_deduce_bounds(reg);
2191 	__reg_deduce_mixed_bounds(reg);
2192 }
2193 
2194 /* Attempts to improve var_off based on unsigned min/max information */
2195 static void __reg_bound_offset(struct bpf_reg_state *reg)
2196 {
2197 	struct tnum var64_off = tnum_intersect(reg->var_off,
2198 					       tnum_range(reg->umin_value,
2199 							  reg->umax_value));
2200 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2201 					       tnum_range(reg->u32_min_value,
2202 							  reg->u32_max_value));
2203 
2204 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2205 }
2206 
2207 static void reg_bounds_sync(struct bpf_reg_state *reg)
2208 {
2209 	/* We might have learned new bounds from the var_off. */
2210 	__update_reg_bounds(reg);
2211 	/* We might have learned something about the sign bit. */
2212 	__reg_deduce_bounds(reg);
2213 	__reg_deduce_bounds(reg);
2214 	/* We might have learned some bits from the bounds. */
2215 	__reg_bound_offset(reg);
2216 	/* Intersecting with the old var_off might have improved our bounds
2217 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2218 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2219 	 */
2220 	__update_reg_bounds(reg);
2221 }
2222 
2223 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2224 				   struct bpf_reg_state *reg, const char *ctx)
2225 {
2226 	const char *msg;
2227 
2228 	if (reg->umin_value > reg->umax_value ||
2229 	    reg->smin_value > reg->smax_value ||
2230 	    reg->u32_min_value > reg->u32_max_value ||
2231 	    reg->s32_min_value > reg->s32_max_value) {
2232 		    msg = "range bounds violation";
2233 		    goto out;
2234 	}
2235 
2236 	if (tnum_is_const(reg->var_off)) {
2237 		u64 uval = reg->var_off.value;
2238 		s64 sval = (s64)uval;
2239 
2240 		if (reg->umin_value != uval || reg->umax_value != uval ||
2241 		    reg->smin_value != sval || reg->smax_value != sval) {
2242 			msg = "const tnum out of sync with range bounds";
2243 			goto out;
2244 		}
2245 	}
2246 
2247 	if (tnum_subreg_is_const(reg->var_off)) {
2248 		u32 uval32 = tnum_subreg(reg->var_off).value;
2249 		s32 sval32 = (s32)uval32;
2250 
2251 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2252 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2253 			msg = "const subreg tnum out of sync with range bounds";
2254 			goto out;
2255 		}
2256 	}
2257 
2258 	return 0;
2259 out:
2260 	verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2261 		"s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2262 		ctx, msg, reg->umin_value, reg->umax_value,
2263 		reg->smin_value, reg->smax_value,
2264 		reg->u32_min_value, reg->u32_max_value,
2265 		reg->s32_min_value, reg->s32_max_value,
2266 		reg->var_off.value, reg->var_off.mask);
2267 	if (env->test_reg_invariants)
2268 		return -EFAULT;
2269 	__mark_reg_unbounded(reg);
2270 	return 0;
2271 }
2272 
2273 static bool __reg32_bound_s64(s32 a)
2274 {
2275 	return a >= 0 && a <= S32_MAX;
2276 }
2277 
2278 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2279 {
2280 	reg->umin_value = reg->u32_min_value;
2281 	reg->umax_value = reg->u32_max_value;
2282 
2283 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2284 	 * be positive otherwise set to worse case bounds and refine later
2285 	 * from tnum.
2286 	 */
2287 	if (__reg32_bound_s64(reg->s32_min_value) &&
2288 	    __reg32_bound_s64(reg->s32_max_value)) {
2289 		reg->smin_value = reg->s32_min_value;
2290 		reg->smax_value = reg->s32_max_value;
2291 	} else {
2292 		reg->smin_value = 0;
2293 		reg->smax_value = U32_MAX;
2294 	}
2295 }
2296 
2297 /* Mark a register as having a completely unknown (scalar) value. */
2298 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2299 {
2300 	/*
2301 	 * Clear type, off, and union(map_ptr, range) and
2302 	 * padding between 'type' and union
2303 	 */
2304 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2305 	reg->type = SCALAR_VALUE;
2306 	reg->id = 0;
2307 	reg->ref_obj_id = 0;
2308 	reg->var_off = tnum_unknown;
2309 	reg->frameno = 0;
2310 	reg->precise = false;
2311 	__mark_reg_unbounded(reg);
2312 }
2313 
2314 /* Mark a register as having a completely unknown (scalar) value,
2315  * initialize .precise as true when not bpf capable.
2316  */
2317 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2318 			       struct bpf_reg_state *reg)
2319 {
2320 	__mark_reg_unknown_imprecise(reg);
2321 	reg->precise = !env->bpf_capable;
2322 }
2323 
2324 static void mark_reg_unknown(struct bpf_verifier_env *env,
2325 			     struct bpf_reg_state *regs, u32 regno)
2326 {
2327 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2328 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2329 		/* Something bad happened, let's kill all regs except FP */
2330 		for (regno = 0; regno < BPF_REG_FP; regno++)
2331 			__mark_reg_not_init(env, regs + regno);
2332 		return;
2333 	}
2334 	__mark_reg_unknown(env, regs + regno);
2335 }
2336 
2337 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2338 				struct bpf_reg_state *reg)
2339 {
2340 	__mark_reg_unknown(env, reg);
2341 	reg->type = NOT_INIT;
2342 }
2343 
2344 static void mark_reg_not_init(struct bpf_verifier_env *env,
2345 			      struct bpf_reg_state *regs, u32 regno)
2346 {
2347 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2348 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2349 		/* Something bad happened, let's kill all regs except FP */
2350 		for (regno = 0; regno < BPF_REG_FP; regno++)
2351 			__mark_reg_not_init(env, regs + regno);
2352 		return;
2353 	}
2354 	__mark_reg_not_init(env, regs + regno);
2355 }
2356 
2357 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2358 			    struct bpf_reg_state *regs, u32 regno,
2359 			    enum bpf_reg_type reg_type,
2360 			    struct btf *btf, u32 btf_id,
2361 			    enum bpf_type_flag flag)
2362 {
2363 	if (reg_type == SCALAR_VALUE) {
2364 		mark_reg_unknown(env, regs, regno);
2365 		return;
2366 	}
2367 	mark_reg_known_zero(env, regs, regno);
2368 	regs[regno].type = PTR_TO_BTF_ID | flag;
2369 	regs[regno].btf = btf;
2370 	regs[regno].btf_id = btf_id;
2371 	if (type_may_be_null(flag))
2372 		regs[regno].id = ++env->id_gen;
2373 }
2374 
2375 #define DEF_NOT_SUBREG	(0)
2376 static void init_reg_state(struct bpf_verifier_env *env,
2377 			   struct bpf_func_state *state)
2378 {
2379 	struct bpf_reg_state *regs = state->regs;
2380 	int i;
2381 
2382 	for (i = 0; i < MAX_BPF_REG; i++) {
2383 		mark_reg_not_init(env, regs, i);
2384 		regs[i].live = REG_LIVE_NONE;
2385 		regs[i].parent = NULL;
2386 		regs[i].subreg_def = DEF_NOT_SUBREG;
2387 	}
2388 
2389 	/* frame pointer */
2390 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2391 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2392 	regs[BPF_REG_FP].frameno = state->frameno;
2393 }
2394 
2395 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2396 {
2397 	return (struct bpf_retval_range){ minval, maxval };
2398 }
2399 
2400 #define BPF_MAIN_FUNC (-1)
2401 static void init_func_state(struct bpf_verifier_env *env,
2402 			    struct bpf_func_state *state,
2403 			    int callsite, int frameno, int subprogno)
2404 {
2405 	state->callsite = callsite;
2406 	state->frameno = frameno;
2407 	state->subprogno = subprogno;
2408 	state->callback_ret_range = retval_range(0, 0);
2409 	init_reg_state(env, state);
2410 	mark_verifier_state_scratched(env);
2411 }
2412 
2413 /* Similar to push_stack(), but for async callbacks */
2414 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2415 						int insn_idx, int prev_insn_idx,
2416 						int subprog, bool is_sleepable)
2417 {
2418 	struct bpf_verifier_stack_elem *elem;
2419 	struct bpf_func_state *frame;
2420 
2421 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2422 	if (!elem)
2423 		goto err;
2424 
2425 	elem->insn_idx = insn_idx;
2426 	elem->prev_insn_idx = prev_insn_idx;
2427 	elem->next = env->head;
2428 	elem->log_pos = env->log.end_pos;
2429 	env->head = elem;
2430 	env->stack_size++;
2431 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2432 		verbose(env,
2433 			"The sequence of %d jumps is too complex for async cb.\n",
2434 			env->stack_size);
2435 		goto err;
2436 	}
2437 	/* Unlike push_stack() do not copy_verifier_state().
2438 	 * The caller state doesn't matter.
2439 	 * This is async callback. It starts in a fresh stack.
2440 	 * Initialize it similar to do_check_common().
2441 	 */
2442 	elem->st.branches = 1;
2443 	elem->st.in_sleepable = is_sleepable;
2444 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2445 	if (!frame)
2446 		goto err;
2447 	init_func_state(env, frame,
2448 			BPF_MAIN_FUNC /* callsite */,
2449 			0 /* frameno within this callchain */,
2450 			subprog /* subprog number within this prog */);
2451 	elem->st.frame[0] = frame;
2452 	return &elem->st;
2453 err:
2454 	free_verifier_state(env->cur_state, true);
2455 	env->cur_state = NULL;
2456 	/* pop all elements and return */
2457 	while (!pop_stack(env, NULL, NULL, false));
2458 	return NULL;
2459 }
2460 
2461 
2462 enum reg_arg_type {
2463 	SRC_OP,		/* register is used as source operand */
2464 	DST_OP,		/* register is used as destination operand */
2465 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2466 };
2467 
2468 static int cmp_subprogs(const void *a, const void *b)
2469 {
2470 	return ((struct bpf_subprog_info *)a)->start -
2471 	       ((struct bpf_subprog_info *)b)->start;
2472 }
2473 
2474 static int find_subprog(struct bpf_verifier_env *env, int off)
2475 {
2476 	struct bpf_subprog_info *p;
2477 
2478 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2479 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2480 	if (!p)
2481 		return -ENOENT;
2482 	return p - env->subprog_info;
2483 
2484 }
2485 
2486 static int add_subprog(struct bpf_verifier_env *env, int off)
2487 {
2488 	int insn_cnt = env->prog->len;
2489 	int ret;
2490 
2491 	if (off >= insn_cnt || off < 0) {
2492 		verbose(env, "call to invalid destination\n");
2493 		return -EINVAL;
2494 	}
2495 	ret = find_subprog(env, off);
2496 	if (ret >= 0)
2497 		return ret;
2498 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2499 		verbose(env, "too many subprograms\n");
2500 		return -E2BIG;
2501 	}
2502 	/* determine subprog starts. The end is one before the next starts */
2503 	env->subprog_info[env->subprog_cnt++].start = off;
2504 	sort(env->subprog_info, env->subprog_cnt,
2505 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2506 	return env->subprog_cnt - 1;
2507 }
2508 
2509 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2510 {
2511 	struct bpf_prog_aux *aux = env->prog->aux;
2512 	struct btf *btf = aux->btf;
2513 	const struct btf_type *t;
2514 	u32 main_btf_id, id;
2515 	const char *name;
2516 	int ret, i;
2517 
2518 	/* Non-zero func_info_cnt implies valid btf */
2519 	if (!aux->func_info_cnt)
2520 		return 0;
2521 	main_btf_id = aux->func_info[0].type_id;
2522 
2523 	t = btf_type_by_id(btf, main_btf_id);
2524 	if (!t) {
2525 		verbose(env, "invalid btf id for main subprog in func_info\n");
2526 		return -EINVAL;
2527 	}
2528 
2529 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2530 	if (IS_ERR(name)) {
2531 		ret = PTR_ERR(name);
2532 		/* If there is no tag present, there is no exception callback */
2533 		if (ret == -ENOENT)
2534 			ret = 0;
2535 		else if (ret == -EEXIST)
2536 			verbose(env, "multiple exception callback tags for main subprog\n");
2537 		return ret;
2538 	}
2539 
2540 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2541 	if (ret < 0) {
2542 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2543 		return ret;
2544 	}
2545 	id = ret;
2546 	t = btf_type_by_id(btf, id);
2547 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2548 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2549 		return -EINVAL;
2550 	}
2551 	ret = 0;
2552 	for (i = 0; i < aux->func_info_cnt; i++) {
2553 		if (aux->func_info[i].type_id != id)
2554 			continue;
2555 		ret = aux->func_info[i].insn_off;
2556 		/* Further func_info and subprog checks will also happen
2557 		 * later, so assume this is the right insn_off for now.
2558 		 */
2559 		if (!ret) {
2560 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2561 			ret = -EINVAL;
2562 		}
2563 	}
2564 	if (!ret) {
2565 		verbose(env, "exception callback type id not found in func_info\n");
2566 		ret = -EINVAL;
2567 	}
2568 	return ret;
2569 }
2570 
2571 #define MAX_KFUNC_DESCS 256
2572 #define MAX_KFUNC_BTFS	256
2573 
2574 struct bpf_kfunc_desc {
2575 	struct btf_func_model func_model;
2576 	u32 func_id;
2577 	s32 imm;
2578 	u16 offset;
2579 	unsigned long addr;
2580 };
2581 
2582 struct bpf_kfunc_btf {
2583 	struct btf *btf;
2584 	struct module *module;
2585 	u16 offset;
2586 };
2587 
2588 struct bpf_kfunc_desc_tab {
2589 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2590 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2591 	 * available, therefore at the end of verification do_misc_fixups()
2592 	 * sorts this by imm and offset.
2593 	 */
2594 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2595 	u32 nr_descs;
2596 };
2597 
2598 struct bpf_kfunc_btf_tab {
2599 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2600 	u32 nr_descs;
2601 };
2602 
2603 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2604 {
2605 	const struct bpf_kfunc_desc *d0 = a;
2606 	const struct bpf_kfunc_desc *d1 = b;
2607 
2608 	/* func_id is not greater than BTF_MAX_TYPE */
2609 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2610 }
2611 
2612 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2613 {
2614 	const struct bpf_kfunc_btf *d0 = a;
2615 	const struct bpf_kfunc_btf *d1 = b;
2616 
2617 	return d0->offset - d1->offset;
2618 }
2619 
2620 static const struct bpf_kfunc_desc *
2621 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2622 {
2623 	struct bpf_kfunc_desc desc = {
2624 		.func_id = func_id,
2625 		.offset = offset,
2626 	};
2627 	struct bpf_kfunc_desc_tab *tab;
2628 
2629 	tab = prog->aux->kfunc_tab;
2630 	return bsearch(&desc, tab->descs, tab->nr_descs,
2631 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2632 }
2633 
2634 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2635 		       u16 btf_fd_idx, u8 **func_addr)
2636 {
2637 	const struct bpf_kfunc_desc *desc;
2638 
2639 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2640 	if (!desc)
2641 		return -EFAULT;
2642 
2643 	*func_addr = (u8 *)desc->addr;
2644 	return 0;
2645 }
2646 
2647 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2648 					 s16 offset)
2649 {
2650 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2651 	struct bpf_kfunc_btf_tab *tab;
2652 	struct bpf_kfunc_btf *b;
2653 	struct module *mod;
2654 	struct btf *btf;
2655 	int btf_fd;
2656 
2657 	tab = env->prog->aux->kfunc_btf_tab;
2658 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2659 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2660 	if (!b) {
2661 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2662 			verbose(env, "too many different module BTFs\n");
2663 			return ERR_PTR(-E2BIG);
2664 		}
2665 
2666 		if (bpfptr_is_null(env->fd_array)) {
2667 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2668 			return ERR_PTR(-EPROTO);
2669 		}
2670 
2671 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2672 					    offset * sizeof(btf_fd),
2673 					    sizeof(btf_fd)))
2674 			return ERR_PTR(-EFAULT);
2675 
2676 		btf = btf_get_by_fd(btf_fd);
2677 		if (IS_ERR(btf)) {
2678 			verbose(env, "invalid module BTF fd specified\n");
2679 			return btf;
2680 		}
2681 
2682 		if (!btf_is_module(btf)) {
2683 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2684 			btf_put(btf);
2685 			return ERR_PTR(-EINVAL);
2686 		}
2687 
2688 		mod = btf_try_get_module(btf);
2689 		if (!mod) {
2690 			btf_put(btf);
2691 			return ERR_PTR(-ENXIO);
2692 		}
2693 
2694 		b = &tab->descs[tab->nr_descs++];
2695 		b->btf = btf;
2696 		b->module = mod;
2697 		b->offset = offset;
2698 
2699 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2700 		     kfunc_btf_cmp_by_off, NULL);
2701 	}
2702 	return b->btf;
2703 }
2704 
2705 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2706 {
2707 	if (!tab)
2708 		return;
2709 
2710 	while (tab->nr_descs--) {
2711 		module_put(tab->descs[tab->nr_descs].module);
2712 		btf_put(tab->descs[tab->nr_descs].btf);
2713 	}
2714 	kfree(tab);
2715 }
2716 
2717 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2718 {
2719 	if (offset) {
2720 		if (offset < 0) {
2721 			/* In the future, this can be allowed to increase limit
2722 			 * of fd index into fd_array, interpreted as u16.
2723 			 */
2724 			verbose(env, "negative offset disallowed for kernel module function call\n");
2725 			return ERR_PTR(-EINVAL);
2726 		}
2727 
2728 		return __find_kfunc_desc_btf(env, offset);
2729 	}
2730 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2731 }
2732 
2733 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2734 {
2735 	const struct btf_type *func, *func_proto;
2736 	struct bpf_kfunc_btf_tab *btf_tab;
2737 	struct bpf_kfunc_desc_tab *tab;
2738 	struct bpf_prog_aux *prog_aux;
2739 	struct bpf_kfunc_desc *desc;
2740 	const char *func_name;
2741 	struct btf *desc_btf;
2742 	unsigned long call_imm;
2743 	unsigned long addr;
2744 	int err;
2745 
2746 	prog_aux = env->prog->aux;
2747 	tab = prog_aux->kfunc_tab;
2748 	btf_tab = prog_aux->kfunc_btf_tab;
2749 	if (!tab) {
2750 		if (!btf_vmlinux) {
2751 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2752 			return -ENOTSUPP;
2753 		}
2754 
2755 		if (!env->prog->jit_requested) {
2756 			verbose(env, "JIT is required for calling kernel function\n");
2757 			return -ENOTSUPP;
2758 		}
2759 
2760 		if (!bpf_jit_supports_kfunc_call()) {
2761 			verbose(env, "JIT does not support calling kernel function\n");
2762 			return -ENOTSUPP;
2763 		}
2764 
2765 		if (!env->prog->gpl_compatible) {
2766 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2767 			return -EINVAL;
2768 		}
2769 
2770 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2771 		if (!tab)
2772 			return -ENOMEM;
2773 		prog_aux->kfunc_tab = tab;
2774 	}
2775 
2776 	/* func_id == 0 is always invalid, but instead of returning an error, be
2777 	 * conservative and wait until the code elimination pass before returning
2778 	 * error, so that invalid calls that get pruned out can be in BPF programs
2779 	 * loaded from userspace.  It is also required that offset be untouched
2780 	 * for such calls.
2781 	 */
2782 	if (!func_id && !offset)
2783 		return 0;
2784 
2785 	if (!btf_tab && offset) {
2786 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2787 		if (!btf_tab)
2788 			return -ENOMEM;
2789 		prog_aux->kfunc_btf_tab = btf_tab;
2790 	}
2791 
2792 	desc_btf = find_kfunc_desc_btf(env, offset);
2793 	if (IS_ERR(desc_btf)) {
2794 		verbose(env, "failed to find BTF for kernel function\n");
2795 		return PTR_ERR(desc_btf);
2796 	}
2797 
2798 	if (find_kfunc_desc(env->prog, func_id, offset))
2799 		return 0;
2800 
2801 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2802 		verbose(env, "too many different kernel function calls\n");
2803 		return -E2BIG;
2804 	}
2805 
2806 	func = btf_type_by_id(desc_btf, func_id);
2807 	if (!func || !btf_type_is_func(func)) {
2808 		verbose(env, "kernel btf_id %u is not a function\n",
2809 			func_id);
2810 		return -EINVAL;
2811 	}
2812 	func_proto = btf_type_by_id(desc_btf, func->type);
2813 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2814 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2815 			func_id);
2816 		return -EINVAL;
2817 	}
2818 
2819 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2820 	addr = kallsyms_lookup_name(func_name);
2821 	if (!addr) {
2822 		verbose(env, "cannot find address for kernel function %s\n",
2823 			func_name);
2824 		return -EINVAL;
2825 	}
2826 	specialize_kfunc(env, func_id, offset, &addr);
2827 
2828 	if (bpf_jit_supports_far_kfunc_call()) {
2829 		call_imm = func_id;
2830 	} else {
2831 		call_imm = BPF_CALL_IMM(addr);
2832 		/* Check whether the relative offset overflows desc->imm */
2833 		if ((unsigned long)(s32)call_imm != call_imm) {
2834 			verbose(env, "address of kernel function %s is out of range\n",
2835 				func_name);
2836 			return -EINVAL;
2837 		}
2838 	}
2839 
2840 	if (bpf_dev_bound_kfunc_id(func_id)) {
2841 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2842 		if (err)
2843 			return err;
2844 	}
2845 
2846 	desc = &tab->descs[tab->nr_descs++];
2847 	desc->func_id = func_id;
2848 	desc->imm = call_imm;
2849 	desc->offset = offset;
2850 	desc->addr = addr;
2851 	err = btf_distill_func_proto(&env->log, desc_btf,
2852 				     func_proto, func_name,
2853 				     &desc->func_model);
2854 	if (!err)
2855 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2856 		     kfunc_desc_cmp_by_id_off, NULL);
2857 	return err;
2858 }
2859 
2860 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2861 {
2862 	const struct bpf_kfunc_desc *d0 = a;
2863 	const struct bpf_kfunc_desc *d1 = b;
2864 
2865 	if (d0->imm != d1->imm)
2866 		return d0->imm < d1->imm ? -1 : 1;
2867 	if (d0->offset != d1->offset)
2868 		return d0->offset < d1->offset ? -1 : 1;
2869 	return 0;
2870 }
2871 
2872 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2873 {
2874 	struct bpf_kfunc_desc_tab *tab;
2875 
2876 	tab = prog->aux->kfunc_tab;
2877 	if (!tab)
2878 		return;
2879 
2880 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2881 	     kfunc_desc_cmp_by_imm_off, NULL);
2882 }
2883 
2884 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2885 {
2886 	return !!prog->aux->kfunc_tab;
2887 }
2888 
2889 const struct btf_func_model *
2890 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2891 			 const struct bpf_insn *insn)
2892 {
2893 	const struct bpf_kfunc_desc desc = {
2894 		.imm = insn->imm,
2895 		.offset = insn->off,
2896 	};
2897 	const struct bpf_kfunc_desc *res;
2898 	struct bpf_kfunc_desc_tab *tab;
2899 
2900 	tab = prog->aux->kfunc_tab;
2901 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2902 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2903 
2904 	return res ? &res->func_model : NULL;
2905 }
2906 
2907 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2908 {
2909 	struct bpf_subprog_info *subprog = env->subprog_info;
2910 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2911 	struct bpf_insn *insn = env->prog->insnsi;
2912 
2913 	/* Add entry function. */
2914 	ret = add_subprog(env, 0);
2915 	if (ret)
2916 		return ret;
2917 
2918 	for (i = 0; i < insn_cnt; i++, insn++) {
2919 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2920 		    !bpf_pseudo_kfunc_call(insn))
2921 			continue;
2922 
2923 		if (!env->bpf_capable) {
2924 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2925 			return -EPERM;
2926 		}
2927 
2928 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2929 			ret = add_subprog(env, i + insn->imm + 1);
2930 		else
2931 			ret = add_kfunc_call(env, insn->imm, insn->off);
2932 
2933 		if (ret < 0)
2934 			return ret;
2935 	}
2936 
2937 	ret = bpf_find_exception_callback_insn_off(env);
2938 	if (ret < 0)
2939 		return ret;
2940 	ex_cb_insn = ret;
2941 
2942 	/* If ex_cb_insn > 0, this means that the main program has a subprog
2943 	 * marked using BTF decl tag to serve as the exception callback.
2944 	 */
2945 	if (ex_cb_insn) {
2946 		ret = add_subprog(env, ex_cb_insn);
2947 		if (ret < 0)
2948 			return ret;
2949 		for (i = 1; i < env->subprog_cnt; i++) {
2950 			if (env->subprog_info[i].start != ex_cb_insn)
2951 				continue;
2952 			env->exception_callback_subprog = i;
2953 			mark_subprog_exc_cb(env, i);
2954 			break;
2955 		}
2956 	}
2957 
2958 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2959 	 * logic. 'subprog_cnt' should not be increased.
2960 	 */
2961 	subprog[env->subprog_cnt].start = insn_cnt;
2962 
2963 	if (env->log.level & BPF_LOG_LEVEL2)
2964 		for (i = 0; i < env->subprog_cnt; i++)
2965 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2966 
2967 	return 0;
2968 }
2969 
2970 static int check_subprogs(struct bpf_verifier_env *env)
2971 {
2972 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2973 	struct bpf_subprog_info *subprog = env->subprog_info;
2974 	struct bpf_insn *insn = env->prog->insnsi;
2975 	int insn_cnt = env->prog->len;
2976 
2977 	/* now check that all jumps are within the same subprog */
2978 	subprog_start = subprog[cur_subprog].start;
2979 	subprog_end = subprog[cur_subprog + 1].start;
2980 	for (i = 0; i < insn_cnt; i++) {
2981 		u8 code = insn[i].code;
2982 
2983 		if (code == (BPF_JMP | BPF_CALL) &&
2984 		    insn[i].src_reg == 0 &&
2985 		    insn[i].imm == BPF_FUNC_tail_call)
2986 			subprog[cur_subprog].has_tail_call = true;
2987 		if (BPF_CLASS(code) == BPF_LD &&
2988 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2989 			subprog[cur_subprog].has_ld_abs = true;
2990 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2991 			goto next;
2992 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2993 			goto next;
2994 		if (code == (BPF_JMP32 | BPF_JA))
2995 			off = i + insn[i].imm + 1;
2996 		else
2997 			off = i + insn[i].off + 1;
2998 		if (off < subprog_start || off >= subprog_end) {
2999 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3000 			return -EINVAL;
3001 		}
3002 next:
3003 		if (i == subprog_end - 1) {
3004 			/* to avoid fall-through from one subprog into another
3005 			 * the last insn of the subprog should be either exit
3006 			 * or unconditional jump back or bpf_throw call
3007 			 */
3008 			if (code != (BPF_JMP | BPF_EXIT) &&
3009 			    code != (BPF_JMP32 | BPF_JA) &&
3010 			    code != (BPF_JMP | BPF_JA)) {
3011 				verbose(env, "last insn is not an exit or jmp\n");
3012 				return -EINVAL;
3013 			}
3014 			subprog_start = subprog_end;
3015 			cur_subprog++;
3016 			if (cur_subprog < env->subprog_cnt)
3017 				subprog_end = subprog[cur_subprog + 1].start;
3018 		}
3019 	}
3020 	return 0;
3021 }
3022 
3023 /* Parentage chain of this register (or stack slot) should take care of all
3024  * issues like callee-saved registers, stack slot allocation time, etc.
3025  */
3026 static int mark_reg_read(struct bpf_verifier_env *env,
3027 			 const struct bpf_reg_state *state,
3028 			 struct bpf_reg_state *parent, u8 flag)
3029 {
3030 	bool writes = parent == state->parent; /* Observe write marks */
3031 	int cnt = 0;
3032 
3033 	while (parent) {
3034 		/* if read wasn't screened by an earlier write ... */
3035 		if (writes && state->live & REG_LIVE_WRITTEN)
3036 			break;
3037 		if (parent->live & REG_LIVE_DONE) {
3038 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3039 				reg_type_str(env, parent->type),
3040 				parent->var_off.value, parent->off);
3041 			return -EFAULT;
3042 		}
3043 		/* The first condition is more likely to be true than the
3044 		 * second, checked it first.
3045 		 */
3046 		if ((parent->live & REG_LIVE_READ) == flag ||
3047 		    parent->live & REG_LIVE_READ64)
3048 			/* The parentage chain never changes and
3049 			 * this parent was already marked as LIVE_READ.
3050 			 * There is no need to keep walking the chain again and
3051 			 * keep re-marking all parents as LIVE_READ.
3052 			 * This case happens when the same register is read
3053 			 * multiple times without writes into it in-between.
3054 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3055 			 * then no need to set the weak REG_LIVE_READ32.
3056 			 */
3057 			break;
3058 		/* ... then we depend on parent's value */
3059 		parent->live |= flag;
3060 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3061 		if (flag == REG_LIVE_READ64)
3062 			parent->live &= ~REG_LIVE_READ32;
3063 		state = parent;
3064 		parent = state->parent;
3065 		writes = true;
3066 		cnt++;
3067 	}
3068 
3069 	if (env->longest_mark_read_walk < cnt)
3070 		env->longest_mark_read_walk = cnt;
3071 	return 0;
3072 }
3073 
3074 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3075 {
3076 	struct bpf_func_state *state = func(env, reg);
3077 	int spi, ret;
3078 
3079 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3080 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3081 	 * check_kfunc_call.
3082 	 */
3083 	if (reg->type == CONST_PTR_TO_DYNPTR)
3084 		return 0;
3085 	spi = dynptr_get_spi(env, reg);
3086 	if (spi < 0)
3087 		return spi;
3088 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3089 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3090 	 * read.
3091 	 */
3092 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3093 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3094 	if (ret)
3095 		return ret;
3096 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3097 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3098 }
3099 
3100 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3101 			  int spi, int nr_slots)
3102 {
3103 	struct bpf_func_state *state = func(env, reg);
3104 	int err, i;
3105 
3106 	for (i = 0; i < nr_slots; i++) {
3107 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3108 
3109 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3110 		if (err)
3111 			return err;
3112 
3113 		mark_stack_slot_scratched(env, spi - i);
3114 	}
3115 
3116 	return 0;
3117 }
3118 
3119 /* This function is supposed to be used by the following 32-bit optimization
3120  * code only. It returns TRUE if the source or destination register operates
3121  * on 64-bit, otherwise return FALSE.
3122  */
3123 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3124 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3125 {
3126 	u8 code, class, op;
3127 
3128 	code = insn->code;
3129 	class = BPF_CLASS(code);
3130 	op = BPF_OP(code);
3131 	if (class == BPF_JMP) {
3132 		/* BPF_EXIT for "main" will reach here. Return TRUE
3133 		 * conservatively.
3134 		 */
3135 		if (op == BPF_EXIT)
3136 			return true;
3137 		if (op == BPF_CALL) {
3138 			/* BPF to BPF call will reach here because of marking
3139 			 * caller saved clobber with DST_OP_NO_MARK for which we
3140 			 * don't care the register def because they are anyway
3141 			 * marked as NOT_INIT already.
3142 			 */
3143 			if (insn->src_reg == BPF_PSEUDO_CALL)
3144 				return false;
3145 			/* Helper call will reach here because of arg type
3146 			 * check, conservatively return TRUE.
3147 			 */
3148 			if (t == SRC_OP)
3149 				return true;
3150 
3151 			return false;
3152 		}
3153 	}
3154 
3155 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3156 		return false;
3157 
3158 	if (class == BPF_ALU64 || class == BPF_JMP ||
3159 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3160 		return true;
3161 
3162 	if (class == BPF_ALU || class == BPF_JMP32)
3163 		return false;
3164 
3165 	if (class == BPF_LDX) {
3166 		if (t != SRC_OP)
3167 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3168 		/* LDX source must be ptr. */
3169 		return true;
3170 	}
3171 
3172 	if (class == BPF_STX) {
3173 		/* BPF_STX (including atomic variants) has multiple source
3174 		 * operands, one of which is a ptr. Check whether the caller is
3175 		 * asking about it.
3176 		 */
3177 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3178 			return true;
3179 		return BPF_SIZE(code) == BPF_DW;
3180 	}
3181 
3182 	if (class == BPF_LD) {
3183 		u8 mode = BPF_MODE(code);
3184 
3185 		/* LD_IMM64 */
3186 		if (mode == BPF_IMM)
3187 			return true;
3188 
3189 		/* Both LD_IND and LD_ABS return 32-bit data. */
3190 		if (t != SRC_OP)
3191 			return  false;
3192 
3193 		/* Implicit ctx ptr. */
3194 		if (regno == BPF_REG_6)
3195 			return true;
3196 
3197 		/* Explicit source could be any width. */
3198 		return true;
3199 	}
3200 
3201 	if (class == BPF_ST)
3202 		/* The only source register for BPF_ST is a ptr. */
3203 		return true;
3204 
3205 	/* Conservatively return true at default. */
3206 	return true;
3207 }
3208 
3209 /* Return the regno defined by the insn, or -1. */
3210 static int insn_def_regno(const struct bpf_insn *insn)
3211 {
3212 	switch (BPF_CLASS(insn->code)) {
3213 	case BPF_JMP:
3214 	case BPF_JMP32:
3215 	case BPF_ST:
3216 		return -1;
3217 	case BPF_STX:
3218 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3219 		    (insn->imm & BPF_FETCH)) {
3220 			if (insn->imm == BPF_CMPXCHG)
3221 				return BPF_REG_0;
3222 			else
3223 				return insn->src_reg;
3224 		} else {
3225 			return -1;
3226 		}
3227 	default:
3228 		return insn->dst_reg;
3229 	}
3230 }
3231 
3232 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3233 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3234 {
3235 	int dst_reg = insn_def_regno(insn);
3236 
3237 	if (dst_reg == -1)
3238 		return false;
3239 
3240 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3241 }
3242 
3243 static void mark_insn_zext(struct bpf_verifier_env *env,
3244 			   struct bpf_reg_state *reg)
3245 {
3246 	s32 def_idx = reg->subreg_def;
3247 
3248 	if (def_idx == DEF_NOT_SUBREG)
3249 		return;
3250 
3251 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3252 	/* The dst will be zero extended, so won't be sub-register anymore. */
3253 	reg->subreg_def = DEF_NOT_SUBREG;
3254 }
3255 
3256 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3257 			   enum reg_arg_type t)
3258 {
3259 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3260 	struct bpf_reg_state *reg;
3261 	bool rw64;
3262 
3263 	if (regno >= MAX_BPF_REG) {
3264 		verbose(env, "R%d is invalid\n", regno);
3265 		return -EINVAL;
3266 	}
3267 
3268 	mark_reg_scratched(env, regno);
3269 
3270 	reg = &regs[regno];
3271 	rw64 = is_reg64(env, insn, regno, reg, t);
3272 	if (t == SRC_OP) {
3273 		/* check whether register used as source operand can be read */
3274 		if (reg->type == NOT_INIT) {
3275 			verbose(env, "R%d !read_ok\n", regno);
3276 			return -EACCES;
3277 		}
3278 		/* We don't need to worry about FP liveness because it's read-only */
3279 		if (regno == BPF_REG_FP)
3280 			return 0;
3281 
3282 		if (rw64)
3283 			mark_insn_zext(env, reg);
3284 
3285 		return mark_reg_read(env, reg, reg->parent,
3286 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3287 	} else {
3288 		/* check whether register used as dest operand can be written to */
3289 		if (regno == BPF_REG_FP) {
3290 			verbose(env, "frame pointer is read only\n");
3291 			return -EACCES;
3292 		}
3293 		reg->live |= REG_LIVE_WRITTEN;
3294 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3295 		if (t == DST_OP)
3296 			mark_reg_unknown(env, regs, regno);
3297 	}
3298 	return 0;
3299 }
3300 
3301 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3302 			 enum reg_arg_type t)
3303 {
3304 	struct bpf_verifier_state *vstate = env->cur_state;
3305 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3306 
3307 	return __check_reg_arg(env, state->regs, regno, t);
3308 }
3309 
3310 static int insn_stack_access_flags(int frameno, int spi)
3311 {
3312 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3313 }
3314 
3315 static int insn_stack_access_spi(int insn_flags)
3316 {
3317 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3318 }
3319 
3320 static int insn_stack_access_frameno(int insn_flags)
3321 {
3322 	return insn_flags & INSN_F_FRAMENO_MASK;
3323 }
3324 
3325 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3326 {
3327 	env->insn_aux_data[idx].jmp_point = true;
3328 }
3329 
3330 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3331 {
3332 	return env->insn_aux_data[insn_idx].jmp_point;
3333 }
3334 
3335 /* for any branch, call, exit record the history of jmps in the given state */
3336 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3337 			    int insn_flags)
3338 {
3339 	u32 cnt = cur->jmp_history_cnt;
3340 	struct bpf_jmp_history_entry *p;
3341 	size_t alloc_size;
3342 
3343 	/* combine instruction flags if we already recorded this instruction */
3344 	if (env->cur_hist_ent) {
3345 		/* atomic instructions push insn_flags twice, for READ and
3346 		 * WRITE sides, but they should agree on stack slot
3347 		 */
3348 		WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3349 			  (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3350 			  "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3351 			  env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3352 		env->cur_hist_ent->flags |= insn_flags;
3353 		return 0;
3354 	}
3355 
3356 	cnt++;
3357 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3358 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3359 	if (!p)
3360 		return -ENOMEM;
3361 	cur->jmp_history = p;
3362 
3363 	p = &cur->jmp_history[cnt - 1];
3364 	p->idx = env->insn_idx;
3365 	p->prev_idx = env->prev_insn_idx;
3366 	p->flags = insn_flags;
3367 	cur->jmp_history_cnt = cnt;
3368 	env->cur_hist_ent = p;
3369 
3370 	return 0;
3371 }
3372 
3373 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3374 						        u32 hist_end, int insn_idx)
3375 {
3376 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3377 		return &st->jmp_history[hist_end - 1];
3378 	return NULL;
3379 }
3380 
3381 /* Backtrack one insn at a time. If idx is not at the top of recorded
3382  * history then previous instruction came from straight line execution.
3383  * Return -ENOENT if we exhausted all instructions within given state.
3384  *
3385  * It's legal to have a bit of a looping with the same starting and ending
3386  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3387  * instruction index is the same as state's first_idx doesn't mean we are
3388  * done. If there is still some jump history left, we should keep going. We
3389  * need to take into account that we might have a jump history between given
3390  * state's parent and itself, due to checkpointing. In this case, we'll have
3391  * history entry recording a jump from last instruction of parent state and
3392  * first instruction of given state.
3393  */
3394 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3395 			     u32 *history)
3396 {
3397 	u32 cnt = *history;
3398 
3399 	if (i == st->first_insn_idx) {
3400 		if (cnt == 0)
3401 			return -ENOENT;
3402 		if (cnt == 1 && st->jmp_history[0].idx == i)
3403 			return -ENOENT;
3404 	}
3405 
3406 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3407 		i = st->jmp_history[cnt - 1].prev_idx;
3408 		(*history)--;
3409 	} else {
3410 		i--;
3411 	}
3412 	return i;
3413 }
3414 
3415 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3416 {
3417 	const struct btf_type *func;
3418 	struct btf *desc_btf;
3419 
3420 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3421 		return NULL;
3422 
3423 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3424 	if (IS_ERR(desc_btf))
3425 		return "<error>";
3426 
3427 	func = btf_type_by_id(desc_btf, insn->imm);
3428 	return btf_name_by_offset(desc_btf, func->name_off);
3429 }
3430 
3431 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3432 {
3433 	bt->frame = frame;
3434 }
3435 
3436 static inline void bt_reset(struct backtrack_state *bt)
3437 {
3438 	struct bpf_verifier_env *env = bt->env;
3439 
3440 	memset(bt, 0, sizeof(*bt));
3441 	bt->env = env;
3442 }
3443 
3444 static inline u32 bt_empty(struct backtrack_state *bt)
3445 {
3446 	u64 mask = 0;
3447 	int i;
3448 
3449 	for (i = 0; i <= bt->frame; i++)
3450 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3451 
3452 	return mask == 0;
3453 }
3454 
3455 static inline int bt_subprog_enter(struct backtrack_state *bt)
3456 {
3457 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3458 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3459 		WARN_ONCE(1, "verifier backtracking bug");
3460 		return -EFAULT;
3461 	}
3462 	bt->frame++;
3463 	return 0;
3464 }
3465 
3466 static inline int bt_subprog_exit(struct backtrack_state *bt)
3467 {
3468 	if (bt->frame == 0) {
3469 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3470 		WARN_ONCE(1, "verifier backtracking bug");
3471 		return -EFAULT;
3472 	}
3473 	bt->frame--;
3474 	return 0;
3475 }
3476 
3477 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3478 {
3479 	bt->reg_masks[frame] |= 1 << reg;
3480 }
3481 
3482 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3483 {
3484 	bt->reg_masks[frame] &= ~(1 << reg);
3485 }
3486 
3487 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3488 {
3489 	bt_set_frame_reg(bt, bt->frame, reg);
3490 }
3491 
3492 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3493 {
3494 	bt_clear_frame_reg(bt, bt->frame, reg);
3495 }
3496 
3497 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3498 {
3499 	bt->stack_masks[frame] |= 1ull << slot;
3500 }
3501 
3502 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3503 {
3504 	bt->stack_masks[frame] &= ~(1ull << slot);
3505 }
3506 
3507 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3508 {
3509 	return bt->reg_masks[frame];
3510 }
3511 
3512 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3513 {
3514 	return bt->reg_masks[bt->frame];
3515 }
3516 
3517 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3518 {
3519 	return bt->stack_masks[frame];
3520 }
3521 
3522 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3523 {
3524 	return bt->stack_masks[bt->frame];
3525 }
3526 
3527 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3528 {
3529 	return bt->reg_masks[bt->frame] & (1 << reg);
3530 }
3531 
3532 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3533 {
3534 	return bt->stack_masks[frame] & (1ull << slot);
3535 }
3536 
3537 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3538 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3539 {
3540 	DECLARE_BITMAP(mask, 64);
3541 	bool first = true;
3542 	int i, n;
3543 
3544 	buf[0] = '\0';
3545 
3546 	bitmap_from_u64(mask, reg_mask);
3547 	for_each_set_bit(i, mask, 32) {
3548 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3549 		first = false;
3550 		buf += n;
3551 		buf_sz -= n;
3552 		if (buf_sz < 0)
3553 			break;
3554 	}
3555 }
3556 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3557 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3558 {
3559 	DECLARE_BITMAP(mask, 64);
3560 	bool first = true;
3561 	int i, n;
3562 
3563 	buf[0] = '\0';
3564 
3565 	bitmap_from_u64(mask, stack_mask);
3566 	for_each_set_bit(i, mask, 64) {
3567 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3568 		first = false;
3569 		buf += n;
3570 		buf_sz -= n;
3571 		if (buf_sz < 0)
3572 			break;
3573 	}
3574 }
3575 
3576 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3577 
3578 /* For given verifier state backtrack_insn() is called from the last insn to
3579  * the first insn. Its purpose is to compute a bitmask of registers and
3580  * stack slots that needs precision in the parent verifier state.
3581  *
3582  * @idx is an index of the instruction we are currently processing;
3583  * @subseq_idx is an index of the subsequent instruction that:
3584  *   - *would be* executed next, if jump history is viewed in forward order;
3585  *   - *was* processed previously during backtracking.
3586  */
3587 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3588 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
3589 {
3590 	const struct bpf_insn_cbs cbs = {
3591 		.cb_call	= disasm_kfunc_name,
3592 		.cb_print	= verbose,
3593 		.private_data	= env,
3594 	};
3595 	struct bpf_insn *insn = env->prog->insnsi + idx;
3596 	u8 class = BPF_CLASS(insn->code);
3597 	u8 opcode = BPF_OP(insn->code);
3598 	u8 mode = BPF_MODE(insn->code);
3599 	u32 dreg = insn->dst_reg;
3600 	u32 sreg = insn->src_reg;
3601 	u32 spi, i, fr;
3602 
3603 	if (insn->code == 0)
3604 		return 0;
3605 	if (env->log.level & BPF_LOG_LEVEL2) {
3606 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3607 		verbose(env, "mark_precise: frame%d: regs=%s ",
3608 			bt->frame, env->tmp_str_buf);
3609 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3610 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3611 		verbose(env, "%d: ", idx);
3612 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3613 	}
3614 
3615 	if (class == BPF_ALU || class == BPF_ALU64) {
3616 		if (!bt_is_reg_set(bt, dreg))
3617 			return 0;
3618 		if (opcode == BPF_END || opcode == BPF_NEG) {
3619 			/* sreg is reserved and unused
3620 			 * dreg still need precision before this insn
3621 			 */
3622 			return 0;
3623 		} else if (opcode == BPF_MOV) {
3624 			if (BPF_SRC(insn->code) == BPF_X) {
3625 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3626 				 * dreg needs precision after this insn
3627 				 * sreg needs precision before this insn
3628 				 */
3629 				bt_clear_reg(bt, dreg);
3630 				if (sreg != BPF_REG_FP)
3631 					bt_set_reg(bt, sreg);
3632 			} else {
3633 				/* dreg = K
3634 				 * dreg needs precision after this insn.
3635 				 * Corresponding register is already marked
3636 				 * as precise=true in this verifier state.
3637 				 * No further markings in parent are necessary
3638 				 */
3639 				bt_clear_reg(bt, dreg);
3640 			}
3641 		} else {
3642 			if (BPF_SRC(insn->code) == BPF_X) {
3643 				/* dreg += sreg
3644 				 * both dreg and sreg need precision
3645 				 * before this insn
3646 				 */
3647 				if (sreg != BPF_REG_FP)
3648 					bt_set_reg(bt, sreg);
3649 			} /* else dreg += K
3650 			   * dreg still needs precision before this insn
3651 			   */
3652 		}
3653 	} else if (class == BPF_LDX) {
3654 		if (!bt_is_reg_set(bt, dreg))
3655 			return 0;
3656 		bt_clear_reg(bt, dreg);
3657 
3658 		/* scalars can only be spilled into stack w/o losing precision.
3659 		 * Load from any other memory can be zero extended.
3660 		 * The desire to keep that precision is already indicated
3661 		 * by 'precise' mark in corresponding register of this state.
3662 		 * No further tracking necessary.
3663 		 */
3664 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3665 			return 0;
3666 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3667 		 * that [fp - off] slot contains scalar that needs to be
3668 		 * tracked with precision
3669 		 */
3670 		spi = insn_stack_access_spi(hist->flags);
3671 		fr = insn_stack_access_frameno(hist->flags);
3672 		bt_set_frame_slot(bt, fr, spi);
3673 	} else if (class == BPF_STX || class == BPF_ST) {
3674 		if (bt_is_reg_set(bt, dreg))
3675 			/* stx & st shouldn't be using _scalar_ dst_reg
3676 			 * to access memory. It means backtracking
3677 			 * encountered a case of pointer subtraction.
3678 			 */
3679 			return -ENOTSUPP;
3680 		/* scalars can only be spilled into stack */
3681 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3682 			return 0;
3683 		spi = insn_stack_access_spi(hist->flags);
3684 		fr = insn_stack_access_frameno(hist->flags);
3685 		if (!bt_is_frame_slot_set(bt, fr, spi))
3686 			return 0;
3687 		bt_clear_frame_slot(bt, fr, spi);
3688 		if (class == BPF_STX)
3689 			bt_set_reg(bt, sreg);
3690 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3691 		if (bpf_pseudo_call(insn)) {
3692 			int subprog_insn_idx, subprog;
3693 
3694 			subprog_insn_idx = idx + insn->imm + 1;
3695 			subprog = find_subprog(env, subprog_insn_idx);
3696 			if (subprog < 0)
3697 				return -EFAULT;
3698 
3699 			if (subprog_is_global(env, subprog)) {
3700 				/* check that jump history doesn't have any
3701 				 * extra instructions from subprog; the next
3702 				 * instruction after call to global subprog
3703 				 * should be literally next instruction in
3704 				 * caller program
3705 				 */
3706 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3707 				/* r1-r5 are invalidated after subprog call,
3708 				 * so for global func call it shouldn't be set
3709 				 * anymore
3710 				 */
3711 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3712 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3713 					WARN_ONCE(1, "verifier backtracking bug");
3714 					return -EFAULT;
3715 				}
3716 				/* global subprog always sets R0 */
3717 				bt_clear_reg(bt, BPF_REG_0);
3718 				return 0;
3719 			} else {
3720 				/* static subprog call instruction, which
3721 				 * means that we are exiting current subprog,
3722 				 * so only r1-r5 could be still requested as
3723 				 * precise, r0 and r6-r10 or any stack slot in
3724 				 * the current frame should be zero by now
3725 				 */
3726 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3727 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3728 					WARN_ONCE(1, "verifier backtracking bug");
3729 					return -EFAULT;
3730 				}
3731 				/* we are now tracking register spills correctly,
3732 				 * so any instance of leftover slots is a bug
3733 				 */
3734 				if (bt_stack_mask(bt) != 0) {
3735 					verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3736 					WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
3737 					return -EFAULT;
3738 				}
3739 				/* propagate r1-r5 to the caller */
3740 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3741 					if (bt_is_reg_set(bt, i)) {
3742 						bt_clear_reg(bt, i);
3743 						bt_set_frame_reg(bt, bt->frame - 1, i);
3744 					}
3745 				}
3746 				if (bt_subprog_exit(bt))
3747 					return -EFAULT;
3748 				return 0;
3749 			}
3750 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3751 			/* exit from callback subprog to callback-calling helper or
3752 			 * kfunc call. Use idx/subseq_idx check to discern it from
3753 			 * straight line code backtracking.
3754 			 * Unlike the subprog call handling above, we shouldn't
3755 			 * propagate precision of r1-r5 (if any requested), as they are
3756 			 * not actually arguments passed directly to callback subprogs
3757 			 */
3758 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3759 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3760 				WARN_ONCE(1, "verifier backtracking bug");
3761 				return -EFAULT;
3762 			}
3763 			if (bt_stack_mask(bt) != 0) {
3764 				verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3765 				WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
3766 				return -EFAULT;
3767 			}
3768 			/* clear r1-r5 in callback subprog's mask */
3769 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3770 				bt_clear_reg(bt, i);
3771 			if (bt_subprog_exit(bt))
3772 				return -EFAULT;
3773 			return 0;
3774 		} else if (opcode == BPF_CALL) {
3775 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3776 			 * catch this error later. Make backtracking conservative
3777 			 * with ENOTSUPP.
3778 			 */
3779 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3780 				return -ENOTSUPP;
3781 			/* regular helper call sets R0 */
3782 			bt_clear_reg(bt, BPF_REG_0);
3783 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3784 				/* if backtracing was looking for registers R1-R5
3785 				 * they should have been found already.
3786 				 */
3787 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3788 				WARN_ONCE(1, "verifier backtracking bug");
3789 				return -EFAULT;
3790 			}
3791 		} else if (opcode == BPF_EXIT) {
3792 			bool r0_precise;
3793 
3794 			/* Backtracking to a nested function call, 'idx' is a part of
3795 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3796 			 * In case of a regular function call, instructions giving
3797 			 * precision to registers R1-R5 should have been found already.
3798 			 * In case of a callback, it is ok to have R1-R5 marked for
3799 			 * backtracking, as these registers are set by the function
3800 			 * invoking callback.
3801 			 */
3802 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3803 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3804 					bt_clear_reg(bt, i);
3805 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3806 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3807 				WARN_ONCE(1, "verifier backtracking bug");
3808 				return -EFAULT;
3809 			}
3810 
3811 			/* BPF_EXIT in subprog or callback always returns
3812 			 * right after the call instruction, so by checking
3813 			 * whether the instruction at subseq_idx-1 is subprog
3814 			 * call or not we can distinguish actual exit from
3815 			 * *subprog* from exit from *callback*. In the former
3816 			 * case, we need to propagate r0 precision, if
3817 			 * necessary. In the former we never do that.
3818 			 */
3819 			r0_precise = subseq_idx - 1 >= 0 &&
3820 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3821 				     bt_is_reg_set(bt, BPF_REG_0);
3822 
3823 			bt_clear_reg(bt, BPF_REG_0);
3824 			if (bt_subprog_enter(bt))
3825 				return -EFAULT;
3826 
3827 			if (r0_precise)
3828 				bt_set_reg(bt, BPF_REG_0);
3829 			/* r6-r9 and stack slots will stay set in caller frame
3830 			 * bitmasks until we return back from callee(s)
3831 			 */
3832 			return 0;
3833 		} else if (BPF_SRC(insn->code) == BPF_X) {
3834 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3835 				return 0;
3836 			/* dreg <cond> sreg
3837 			 * Both dreg and sreg need precision before
3838 			 * this insn. If only sreg was marked precise
3839 			 * before it would be equally necessary to
3840 			 * propagate it to dreg.
3841 			 */
3842 			bt_set_reg(bt, dreg);
3843 			bt_set_reg(bt, sreg);
3844 			 /* else dreg <cond> K
3845 			  * Only dreg still needs precision before
3846 			  * this insn, so for the K-based conditional
3847 			  * there is nothing new to be marked.
3848 			  */
3849 		}
3850 	} else if (class == BPF_LD) {
3851 		if (!bt_is_reg_set(bt, dreg))
3852 			return 0;
3853 		bt_clear_reg(bt, dreg);
3854 		/* It's ld_imm64 or ld_abs or ld_ind.
3855 		 * For ld_imm64 no further tracking of precision
3856 		 * into parent is necessary
3857 		 */
3858 		if (mode == BPF_IND || mode == BPF_ABS)
3859 			/* to be analyzed */
3860 			return -ENOTSUPP;
3861 	}
3862 	return 0;
3863 }
3864 
3865 /* the scalar precision tracking algorithm:
3866  * . at the start all registers have precise=false.
3867  * . scalar ranges are tracked as normal through alu and jmp insns.
3868  * . once precise value of the scalar register is used in:
3869  *   .  ptr + scalar alu
3870  *   . if (scalar cond K|scalar)
3871  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3872  *   backtrack through the verifier states and mark all registers and
3873  *   stack slots with spilled constants that these scalar regisers
3874  *   should be precise.
3875  * . during state pruning two registers (or spilled stack slots)
3876  *   are equivalent if both are not precise.
3877  *
3878  * Note the verifier cannot simply walk register parentage chain,
3879  * since many different registers and stack slots could have been
3880  * used to compute single precise scalar.
3881  *
3882  * The approach of starting with precise=true for all registers and then
3883  * backtrack to mark a register as not precise when the verifier detects
3884  * that program doesn't care about specific value (e.g., when helper
3885  * takes register as ARG_ANYTHING parameter) is not safe.
3886  *
3887  * It's ok to walk single parentage chain of the verifier states.
3888  * It's possible that this backtracking will go all the way till 1st insn.
3889  * All other branches will be explored for needing precision later.
3890  *
3891  * The backtracking needs to deal with cases like:
3892  *   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)
3893  * r9 -= r8
3894  * r5 = r9
3895  * if r5 > 0x79f goto pc+7
3896  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3897  * r5 += 1
3898  * ...
3899  * call bpf_perf_event_output#25
3900  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3901  *
3902  * and this case:
3903  * r6 = 1
3904  * call foo // uses callee's r6 inside to compute r0
3905  * r0 += r6
3906  * if r0 == 0 goto
3907  *
3908  * to track above reg_mask/stack_mask needs to be independent for each frame.
3909  *
3910  * Also if parent's curframe > frame where backtracking started,
3911  * the verifier need to mark registers in both frames, otherwise callees
3912  * may incorrectly prune callers. This is similar to
3913  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3914  *
3915  * For now backtracking falls back into conservative marking.
3916  */
3917 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3918 				     struct bpf_verifier_state *st)
3919 {
3920 	struct bpf_func_state *func;
3921 	struct bpf_reg_state *reg;
3922 	int i, j;
3923 
3924 	if (env->log.level & BPF_LOG_LEVEL2) {
3925 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3926 			st->curframe);
3927 	}
3928 
3929 	/* big hammer: mark all scalars precise in this path.
3930 	 * pop_stack may still get !precise scalars.
3931 	 * We also skip current state and go straight to first parent state,
3932 	 * because precision markings in current non-checkpointed state are
3933 	 * not needed. See why in the comment in __mark_chain_precision below.
3934 	 */
3935 	for (st = st->parent; st; st = st->parent) {
3936 		for (i = 0; i <= st->curframe; i++) {
3937 			func = st->frame[i];
3938 			for (j = 0; j < BPF_REG_FP; j++) {
3939 				reg = &func->regs[j];
3940 				if (reg->type != SCALAR_VALUE || reg->precise)
3941 					continue;
3942 				reg->precise = true;
3943 				if (env->log.level & BPF_LOG_LEVEL2) {
3944 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3945 						i, j);
3946 				}
3947 			}
3948 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3949 				if (!is_spilled_reg(&func->stack[j]))
3950 					continue;
3951 				reg = &func->stack[j].spilled_ptr;
3952 				if (reg->type != SCALAR_VALUE || reg->precise)
3953 					continue;
3954 				reg->precise = true;
3955 				if (env->log.level & BPF_LOG_LEVEL2) {
3956 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3957 						i, -(j + 1) * 8);
3958 				}
3959 			}
3960 		}
3961 	}
3962 }
3963 
3964 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3965 {
3966 	struct bpf_func_state *func;
3967 	struct bpf_reg_state *reg;
3968 	int i, j;
3969 
3970 	for (i = 0; i <= st->curframe; i++) {
3971 		func = st->frame[i];
3972 		for (j = 0; j < BPF_REG_FP; j++) {
3973 			reg = &func->regs[j];
3974 			if (reg->type != SCALAR_VALUE)
3975 				continue;
3976 			reg->precise = false;
3977 		}
3978 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3979 			if (!is_spilled_reg(&func->stack[j]))
3980 				continue;
3981 			reg = &func->stack[j].spilled_ptr;
3982 			if (reg->type != SCALAR_VALUE)
3983 				continue;
3984 			reg->precise = false;
3985 		}
3986 	}
3987 }
3988 
3989 static bool idset_contains(struct bpf_idset *s, u32 id)
3990 {
3991 	u32 i;
3992 
3993 	for (i = 0; i < s->count; ++i)
3994 		if (s->ids[i] == id)
3995 			return true;
3996 
3997 	return false;
3998 }
3999 
4000 static int idset_push(struct bpf_idset *s, u32 id)
4001 {
4002 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4003 		return -EFAULT;
4004 	s->ids[s->count++] = id;
4005 	return 0;
4006 }
4007 
4008 static void idset_reset(struct bpf_idset *s)
4009 {
4010 	s->count = 0;
4011 }
4012 
4013 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4014  * Mark all registers with these IDs as precise.
4015  */
4016 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4017 {
4018 	struct bpf_idset *precise_ids = &env->idset_scratch;
4019 	struct backtrack_state *bt = &env->bt;
4020 	struct bpf_func_state *func;
4021 	struct bpf_reg_state *reg;
4022 	DECLARE_BITMAP(mask, 64);
4023 	int i, fr;
4024 
4025 	idset_reset(precise_ids);
4026 
4027 	for (fr = bt->frame; fr >= 0; fr--) {
4028 		func = st->frame[fr];
4029 
4030 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4031 		for_each_set_bit(i, mask, 32) {
4032 			reg = &func->regs[i];
4033 			if (!reg->id || reg->type != SCALAR_VALUE)
4034 				continue;
4035 			if (idset_push(precise_ids, reg->id))
4036 				return -EFAULT;
4037 		}
4038 
4039 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4040 		for_each_set_bit(i, mask, 64) {
4041 			if (i >= func->allocated_stack / BPF_REG_SIZE)
4042 				break;
4043 			if (!is_spilled_scalar_reg(&func->stack[i]))
4044 				continue;
4045 			reg = &func->stack[i].spilled_ptr;
4046 			if (!reg->id)
4047 				continue;
4048 			if (idset_push(precise_ids, reg->id))
4049 				return -EFAULT;
4050 		}
4051 	}
4052 
4053 	for (fr = 0; fr <= st->curframe; ++fr) {
4054 		func = st->frame[fr];
4055 
4056 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4057 			reg = &func->regs[i];
4058 			if (!reg->id)
4059 				continue;
4060 			if (!idset_contains(precise_ids, reg->id))
4061 				continue;
4062 			bt_set_frame_reg(bt, fr, i);
4063 		}
4064 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4065 			if (!is_spilled_scalar_reg(&func->stack[i]))
4066 				continue;
4067 			reg = &func->stack[i].spilled_ptr;
4068 			if (!reg->id)
4069 				continue;
4070 			if (!idset_contains(precise_ids, reg->id))
4071 				continue;
4072 			bt_set_frame_slot(bt, fr, i);
4073 		}
4074 	}
4075 
4076 	return 0;
4077 }
4078 
4079 /*
4080  * __mark_chain_precision() backtracks BPF program instruction sequence and
4081  * chain of verifier states making sure that register *regno* (if regno >= 0)
4082  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4083  * SCALARS, as well as any other registers and slots that contribute to
4084  * a tracked state of given registers/stack slots, depending on specific BPF
4085  * assembly instructions (see backtrack_insns() for exact instruction handling
4086  * logic). This backtracking relies on recorded jmp_history and is able to
4087  * traverse entire chain of parent states. This process ends only when all the
4088  * necessary registers/slots and their transitive dependencies are marked as
4089  * precise.
4090  *
4091  * One important and subtle aspect is that precise marks *do not matter* in
4092  * the currently verified state (current state). It is important to understand
4093  * why this is the case.
4094  *
4095  * First, note that current state is the state that is not yet "checkpointed",
4096  * i.e., it is not yet put into env->explored_states, and it has no children
4097  * states as well. It's ephemeral, and can end up either a) being discarded if
4098  * compatible explored state is found at some point or BPF_EXIT instruction is
4099  * reached or b) checkpointed and put into env->explored_states, branching out
4100  * into one or more children states.
4101  *
4102  * In the former case, precise markings in current state are completely
4103  * ignored by state comparison code (see regsafe() for details). Only
4104  * checkpointed ("old") state precise markings are important, and if old
4105  * state's register/slot is precise, regsafe() assumes current state's
4106  * register/slot as precise and checks value ranges exactly and precisely. If
4107  * states turn out to be compatible, current state's necessary precise
4108  * markings and any required parent states' precise markings are enforced
4109  * after the fact with propagate_precision() logic, after the fact. But it's
4110  * important to realize that in this case, even after marking current state
4111  * registers/slots as precise, we immediately discard current state. So what
4112  * actually matters is any of the precise markings propagated into current
4113  * state's parent states, which are always checkpointed (due to b) case above).
4114  * As such, for scenario a) it doesn't matter if current state has precise
4115  * markings set or not.
4116  *
4117  * Now, for the scenario b), checkpointing and forking into child(ren)
4118  * state(s). Note that before current state gets to checkpointing step, any
4119  * processed instruction always assumes precise SCALAR register/slot
4120  * knowledge: if precise value or range is useful to prune jump branch, BPF
4121  * verifier takes this opportunity enthusiastically. Similarly, when
4122  * register's value is used to calculate offset or memory address, exact
4123  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4124  * what we mentioned above about state comparison ignoring precise markings
4125  * during state comparison, BPF verifier ignores and also assumes precise
4126  * markings *at will* during instruction verification process. But as verifier
4127  * assumes precision, it also propagates any precision dependencies across
4128  * parent states, which are not yet finalized, so can be further restricted
4129  * based on new knowledge gained from restrictions enforced by their children
4130  * states. This is so that once those parent states are finalized, i.e., when
4131  * they have no more active children state, state comparison logic in
4132  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4133  * required for correctness.
4134  *
4135  * To build a bit more intuition, note also that once a state is checkpointed,
4136  * the path we took to get to that state is not important. This is crucial
4137  * property for state pruning. When state is checkpointed and finalized at
4138  * some instruction index, it can be correctly and safely used to "short
4139  * circuit" any *compatible* state that reaches exactly the same instruction
4140  * index. I.e., if we jumped to that instruction from a completely different
4141  * code path than original finalized state was derived from, it doesn't
4142  * matter, current state can be discarded because from that instruction
4143  * forward having a compatible state will ensure we will safely reach the
4144  * exit. States describe preconditions for further exploration, but completely
4145  * forget the history of how we got here.
4146  *
4147  * This also means that even if we needed precise SCALAR range to get to
4148  * finalized state, but from that point forward *that same* SCALAR register is
4149  * never used in a precise context (i.e., it's precise value is not needed for
4150  * correctness), it's correct and safe to mark such register as "imprecise"
4151  * (i.e., precise marking set to false). This is what we rely on when we do
4152  * not set precise marking in current state. If no child state requires
4153  * precision for any given SCALAR register, it's safe to dictate that it can
4154  * be imprecise. If any child state does require this register to be precise,
4155  * we'll mark it precise later retroactively during precise markings
4156  * propagation from child state to parent states.
4157  *
4158  * Skipping precise marking setting in current state is a mild version of
4159  * relying on the above observation. But we can utilize this property even
4160  * more aggressively by proactively forgetting any precise marking in the
4161  * current state (which we inherited from the parent state), right before we
4162  * checkpoint it and branch off into new child state. This is done by
4163  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4164  * finalized states which help in short circuiting more future states.
4165  */
4166 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4167 {
4168 	struct backtrack_state *bt = &env->bt;
4169 	struct bpf_verifier_state *st = env->cur_state;
4170 	int first_idx = st->first_insn_idx;
4171 	int last_idx = env->insn_idx;
4172 	int subseq_idx = -1;
4173 	struct bpf_func_state *func;
4174 	struct bpf_reg_state *reg;
4175 	bool skip_first = true;
4176 	int i, fr, err;
4177 
4178 	if (!env->bpf_capable)
4179 		return 0;
4180 
4181 	/* set frame number from which we are starting to backtrack */
4182 	bt_init(bt, env->cur_state->curframe);
4183 
4184 	/* Do sanity checks against current state of register and/or stack
4185 	 * slot, but don't set precise flag in current state, as precision
4186 	 * tracking in the current state is unnecessary.
4187 	 */
4188 	func = st->frame[bt->frame];
4189 	if (regno >= 0) {
4190 		reg = &func->regs[regno];
4191 		if (reg->type != SCALAR_VALUE) {
4192 			WARN_ONCE(1, "backtracing misuse");
4193 			return -EFAULT;
4194 		}
4195 		bt_set_reg(bt, regno);
4196 	}
4197 
4198 	if (bt_empty(bt))
4199 		return 0;
4200 
4201 	for (;;) {
4202 		DECLARE_BITMAP(mask, 64);
4203 		u32 history = st->jmp_history_cnt;
4204 		struct bpf_jmp_history_entry *hist;
4205 
4206 		if (env->log.level & BPF_LOG_LEVEL2) {
4207 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4208 				bt->frame, last_idx, first_idx, subseq_idx);
4209 		}
4210 
4211 		/* If some register with scalar ID is marked as precise,
4212 		 * make sure that all registers sharing this ID are also precise.
4213 		 * This is needed to estimate effect of find_equal_scalars().
4214 		 * Do this at the last instruction of each state,
4215 		 * bpf_reg_state::id fields are valid for these instructions.
4216 		 *
4217 		 * Allows to track precision in situation like below:
4218 		 *
4219 		 *     r2 = unknown value
4220 		 *     ...
4221 		 *   --- state #0 ---
4222 		 *     ...
4223 		 *     r1 = r2                 // r1 and r2 now share the same ID
4224 		 *     ...
4225 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4226 		 *     ...
4227 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4228 		 *     ...
4229 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4230 		 *     r3 = r10
4231 		 *     r3 += r1                // need to mark both r1 and r2
4232 		 */
4233 		if (mark_precise_scalar_ids(env, st))
4234 			return -EFAULT;
4235 
4236 		if (last_idx < 0) {
4237 			/* we are at the entry into subprog, which
4238 			 * is expected for global funcs, but only if
4239 			 * requested precise registers are R1-R5
4240 			 * (which are global func's input arguments)
4241 			 */
4242 			if (st->curframe == 0 &&
4243 			    st->frame[0]->subprogno > 0 &&
4244 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4245 			    bt_stack_mask(bt) == 0 &&
4246 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4247 				bitmap_from_u64(mask, bt_reg_mask(bt));
4248 				for_each_set_bit(i, mask, 32) {
4249 					reg = &st->frame[0]->regs[i];
4250 					bt_clear_reg(bt, i);
4251 					if (reg->type == SCALAR_VALUE)
4252 						reg->precise = true;
4253 				}
4254 				return 0;
4255 			}
4256 
4257 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4258 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4259 			WARN_ONCE(1, "verifier backtracking bug");
4260 			return -EFAULT;
4261 		}
4262 
4263 		for (i = last_idx;;) {
4264 			if (skip_first) {
4265 				err = 0;
4266 				skip_first = false;
4267 			} else {
4268 				hist = get_jmp_hist_entry(st, history, i);
4269 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4270 			}
4271 			if (err == -ENOTSUPP) {
4272 				mark_all_scalars_precise(env, env->cur_state);
4273 				bt_reset(bt);
4274 				return 0;
4275 			} else if (err) {
4276 				return err;
4277 			}
4278 			if (bt_empty(bt))
4279 				/* Found assignment(s) into tracked register in this state.
4280 				 * Since this state is already marked, just return.
4281 				 * Nothing to be tracked further in the parent state.
4282 				 */
4283 				return 0;
4284 			subseq_idx = i;
4285 			i = get_prev_insn_idx(st, i, &history);
4286 			if (i == -ENOENT)
4287 				break;
4288 			if (i >= env->prog->len) {
4289 				/* This can happen if backtracking reached insn 0
4290 				 * and there are still reg_mask or stack_mask
4291 				 * to backtrack.
4292 				 * It means the backtracking missed the spot where
4293 				 * particular register was initialized with a constant.
4294 				 */
4295 				verbose(env, "BUG backtracking idx %d\n", i);
4296 				WARN_ONCE(1, "verifier backtracking bug");
4297 				return -EFAULT;
4298 			}
4299 		}
4300 		st = st->parent;
4301 		if (!st)
4302 			break;
4303 
4304 		for (fr = bt->frame; fr >= 0; fr--) {
4305 			func = st->frame[fr];
4306 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4307 			for_each_set_bit(i, mask, 32) {
4308 				reg = &func->regs[i];
4309 				if (reg->type != SCALAR_VALUE) {
4310 					bt_clear_frame_reg(bt, fr, i);
4311 					continue;
4312 				}
4313 				if (reg->precise)
4314 					bt_clear_frame_reg(bt, fr, i);
4315 				else
4316 					reg->precise = true;
4317 			}
4318 
4319 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4320 			for_each_set_bit(i, mask, 64) {
4321 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4322 					verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4323 						i, func->allocated_stack / BPF_REG_SIZE);
4324 					WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4325 					return -EFAULT;
4326 				}
4327 
4328 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4329 					bt_clear_frame_slot(bt, fr, i);
4330 					continue;
4331 				}
4332 				reg = &func->stack[i].spilled_ptr;
4333 				if (reg->precise)
4334 					bt_clear_frame_slot(bt, fr, i);
4335 				else
4336 					reg->precise = true;
4337 			}
4338 			if (env->log.level & BPF_LOG_LEVEL2) {
4339 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4340 					     bt_frame_reg_mask(bt, fr));
4341 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4342 					fr, env->tmp_str_buf);
4343 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4344 					       bt_frame_stack_mask(bt, fr));
4345 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4346 				print_verifier_state(env, func, true);
4347 			}
4348 		}
4349 
4350 		if (bt_empty(bt))
4351 			return 0;
4352 
4353 		subseq_idx = first_idx;
4354 		last_idx = st->last_insn_idx;
4355 		first_idx = st->first_insn_idx;
4356 	}
4357 
4358 	/* if we still have requested precise regs or slots, we missed
4359 	 * something (e.g., stack access through non-r10 register), so
4360 	 * fallback to marking all precise
4361 	 */
4362 	if (!bt_empty(bt)) {
4363 		mark_all_scalars_precise(env, env->cur_state);
4364 		bt_reset(bt);
4365 	}
4366 
4367 	return 0;
4368 }
4369 
4370 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4371 {
4372 	return __mark_chain_precision(env, regno);
4373 }
4374 
4375 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4376  * desired reg and stack masks across all relevant frames
4377  */
4378 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4379 {
4380 	return __mark_chain_precision(env, -1);
4381 }
4382 
4383 static bool is_spillable_regtype(enum bpf_reg_type type)
4384 {
4385 	switch (base_type(type)) {
4386 	case PTR_TO_MAP_VALUE:
4387 	case PTR_TO_STACK:
4388 	case PTR_TO_CTX:
4389 	case PTR_TO_PACKET:
4390 	case PTR_TO_PACKET_META:
4391 	case PTR_TO_PACKET_END:
4392 	case PTR_TO_FLOW_KEYS:
4393 	case CONST_PTR_TO_MAP:
4394 	case PTR_TO_SOCKET:
4395 	case PTR_TO_SOCK_COMMON:
4396 	case PTR_TO_TCP_SOCK:
4397 	case PTR_TO_XDP_SOCK:
4398 	case PTR_TO_BTF_ID:
4399 	case PTR_TO_BUF:
4400 	case PTR_TO_MEM:
4401 	case PTR_TO_FUNC:
4402 	case PTR_TO_MAP_KEY:
4403 	case PTR_TO_ARENA:
4404 		return true;
4405 	default:
4406 		return false;
4407 	}
4408 }
4409 
4410 /* Does this register contain a constant zero? */
4411 static bool register_is_null(struct bpf_reg_state *reg)
4412 {
4413 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4414 }
4415 
4416 /* check if register is a constant scalar value */
4417 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4418 {
4419 	return reg->type == SCALAR_VALUE &&
4420 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4421 }
4422 
4423 /* assuming is_reg_const() is true, return constant value of a register */
4424 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4425 {
4426 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4427 }
4428 
4429 static bool __is_pointer_value(bool allow_ptr_leaks,
4430 			       const struct bpf_reg_state *reg)
4431 {
4432 	if (allow_ptr_leaks)
4433 		return false;
4434 
4435 	return reg->type != SCALAR_VALUE;
4436 }
4437 
4438 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4439 					struct bpf_reg_state *src_reg)
4440 {
4441 	if (src_reg->type == SCALAR_VALUE && !src_reg->id &&
4442 	    !tnum_is_const(src_reg->var_off))
4443 		/* Ensure that src_reg has a valid ID that will be copied to
4444 		 * dst_reg and then will be used by find_equal_scalars() to
4445 		 * propagate min/max range.
4446 		 */
4447 		src_reg->id = ++env->id_gen;
4448 }
4449 
4450 /* Copy src state preserving dst->parent and dst->live fields */
4451 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4452 {
4453 	struct bpf_reg_state *parent = dst->parent;
4454 	enum bpf_reg_liveness live = dst->live;
4455 
4456 	*dst = *src;
4457 	dst->parent = parent;
4458 	dst->live = live;
4459 }
4460 
4461 static void save_register_state(struct bpf_verifier_env *env,
4462 				struct bpf_func_state *state,
4463 				int spi, struct bpf_reg_state *reg,
4464 				int size)
4465 {
4466 	int i;
4467 
4468 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4469 	if (size == BPF_REG_SIZE)
4470 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4471 
4472 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4473 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4474 
4475 	/* size < 8 bytes spill */
4476 	for (; i; i--)
4477 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4478 }
4479 
4480 static bool is_bpf_st_mem(struct bpf_insn *insn)
4481 {
4482 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4483 }
4484 
4485 static int get_reg_width(struct bpf_reg_state *reg)
4486 {
4487 	return fls64(reg->umax_value);
4488 }
4489 
4490 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4491  * stack boundary and alignment are checked in check_mem_access()
4492  */
4493 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4494 				       /* stack frame we're writing to */
4495 				       struct bpf_func_state *state,
4496 				       int off, int size, int value_regno,
4497 				       int insn_idx)
4498 {
4499 	struct bpf_func_state *cur; /* state of the current function */
4500 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4501 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4502 	struct bpf_reg_state *reg = NULL;
4503 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
4504 
4505 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4506 	 * so it's aligned access and [off, off + size) are within stack limits
4507 	 */
4508 	if (!env->allow_ptr_leaks &&
4509 	    is_spilled_reg(&state->stack[spi]) &&
4510 	    size != BPF_REG_SIZE) {
4511 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4512 		return -EACCES;
4513 	}
4514 
4515 	cur = env->cur_state->frame[env->cur_state->curframe];
4516 	if (value_regno >= 0)
4517 		reg = &cur->regs[value_regno];
4518 	if (!env->bypass_spec_v4) {
4519 		bool sanitize = reg && is_spillable_regtype(reg->type);
4520 
4521 		for (i = 0; i < size; i++) {
4522 			u8 type = state->stack[spi].slot_type[i];
4523 
4524 			if (type != STACK_MISC && type != STACK_ZERO) {
4525 				sanitize = true;
4526 				break;
4527 			}
4528 		}
4529 
4530 		if (sanitize)
4531 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4532 	}
4533 
4534 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4535 	if (err)
4536 		return err;
4537 
4538 	mark_stack_slot_scratched(env, spi);
4539 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
4540 		bool reg_value_fits;
4541 
4542 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
4543 		/* Make sure that reg had an ID to build a relation on spill. */
4544 		if (reg_value_fits)
4545 			assign_scalar_id_before_mov(env, reg);
4546 		save_register_state(env, state, spi, reg, size);
4547 		/* Break the relation on a narrowing spill. */
4548 		if (!reg_value_fits)
4549 			state->stack[spi].spilled_ptr.id = 0;
4550 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4551 		   env->bpf_capable) {
4552 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
4553 
4554 		memset(tmp_reg, 0, sizeof(*tmp_reg));
4555 		__mark_reg_known(tmp_reg, insn->imm);
4556 		tmp_reg->type = SCALAR_VALUE;
4557 		save_register_state(env, state, spi, tmp_reg, size);
4558 	} else if (reg && is_spillable_regtype(reg->type)) {
4559 		/* register containing pointer is being spilled into stack */
4560 		if (size != BPF_REG_SIZE) {
4561 			verbose_linfo(env, insn_idx, "; ");
4562 			verbose(env, "invalid size of register spill\n");
4563 			return -EACCES;
4564 		}
4565 		if (state != cur && reg->type == PTR_TO_STACK) {
4566 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4567 			return -EINVAL;
4568 		}
4569 		save_register_state(env, state, spi, reg, size);
4570 	} else {
4571 		u8 type = STACK_MISC;
4572 
4573 		/* regular write of data into stack destroys any spilled ptr */
4574 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4575 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4576 		if (is_stack_slot_special(&state->stack[spi]))
4577 			for (i = 0; i < BPF_REG_SIZE; i++)
4578 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4579 
4580 		/* only mark the slot as written if all 8 bytes were written
4581 		 * otherwise read propagation may incorrectly stop too soon
4582 		 * when stack slots are partially written.
4583 		 * This heuristic means that read propagation will be
4584 		 * conservative, since it will add reg_live_read marks
4585 		 * to stack slots all the way to first state when programs
4586 		 * writes+reads less than 8 bytes
4587 		 */
4588 		if (size == BPF_REG_SIZE)
4589 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4590 
4591 		/* when we zero initialize stack slots mark them as such */
4592 		if ((reg && register_is_null(reg)) ||
4593 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4594 			/* STACK_ZERO case happened because register spill
4595 			 * wasn't properly aligned at the stack slot boundary,
4596 			 * so it's not a register spill anymore; force
4597 			 * originating register to be precise to make
4598 			 * STACK_ZERO correct for subsequent states
4599 			 */
4600 			err = mark_chain_precision(env, value_regno);
4601 			if (err)
4602 				return err;
4603 			type = STACK_ZERO;
4604 		}
4605 
4606 		/* Mark slots affected by this stack write. */
4607 		for (i = 0; i < size; i++)
4608 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4609 		insn_flags = 0; /* not a register spill */
4610 	}
4611 
4612 	if (insn_flags)
4613 		return push_jmp_history(env, env->cur_state, insn_flags);
4614 	return 0;
4615 }
4616 
4617 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4618  * known to contain a variable offset.
4619  * This function checks whether the write is permitted and conservatively
4620  * tracks the effects of the write, considering that each stack slot in the
4621  * dynamic range is potentially written to.
4622  *
4623  * 'off' includes 'regno->off'.
4624  * 'value_regno' can be -1, meaning that an unknown value is being written to
4625  * the stack.
4626  *
4627  * Spilled pointers in range are not marked as written because we don't know
4628  * what's going to be actually written. This means that read propagation for
4629  * future reads cannot be terminated by this write.
4630  *
4631  * For privileged programs, uninitialized stack slots are considered
4632  * initialized by this write (even though we don't know exactly what offsets
4633  * are going to be written to). The idea is that we don't want the verifier to
4634  * reject future reads that access slots written to through variable offsets.
4635  */
4636 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4637 				     /* func where register points to */
4638 				     struct bpf_func_state *state,
4639 				     int ptr_regno, int off, int size,
4640 				     int value_regno, int insn_idx)
4641 {
4642 	struct bpf_func_state *cur; /* state of the current function */
4643 	int min_off, max_off;
4644 	int i, err;
4645 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4646 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4647 	bool writing_zero = false;
4648 	/* set if the fact that we're writing a zero is used to let any
4649 	 * stack slots remain STACK_ZERO
4650 	 */
4651 	bool zero_used = false;
4652 
4653 	cur = env->cur_state->frame[env->cur_state->curframe];
4654 	ptr_reg = &cur->regs[ptr_regno];
4655 	min_off = ptr_reg->smin_value + off;
4656 	max_off = ptr_reg->smax_value + off + size;
4657 	if (value_regno >= 0)
4658 		value_reg = &cur->regs[value_regno];
4659 	if ((value_reg && register_is_null(value_reg)) ||
4660 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4661 		writing_zero = true;
4662 
4663 	for (i = min_off; i < max_off; i++) {
4664 		int spi;
4665 
4666 		spi = __get_spi(i);
4667 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4668 		if (err)
4669 			return err;
4670 	}
4671 
4672 	/* Variable offset writes destroy any spilled pointers in range. */
4673 	for (i = min_off; i < max_off; i++) {
4674 		u8 new_type, *stype;
4675 		int slot, spi;
4676 
4677 		slot = -i - 1;
4678 		spi = slot / BPF_REG_SIZE;
4679 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4680 		mark_stack_slot_scratched(env, spi);
4681 
4682 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4683 			/* Reject the write if range we may write to has not
4684 			 * been initialized beforehand. If we didn't reject
4685 			 * here, the ptr status would be erased below (even
4686 			 * though not all slots are actually overwritten),
4687 			 * possibly opening the door to leaks.
4688 			 *
4689 			 * We do however catch STACK_INVALID case below, and
4690 			 * only allow reading possibly uninitialized memory
4691 			 * later for CAP_PERFMON, as the write may not happen to
4692 			 * that slot.
4693 			 */
4694 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4695 				insn_idx, i);
4696 			return -EINVAL;
4697 		}
4698 
4699 		/* If writing_zero and the spi slot contains a spill of value 0,
4700 		 * maintain the spill type.
4701 		 */
4702 		if (writing_zero && *stype == STACK_SPILL &&
4703 		    is_spilled_scalar_reg(&state->stack[spi])) {
4704 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
4705 
4706 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
4707 				zero_used = true;
4708 				continue;
4709 			}
4710 		}
4711 
4712 		/* Erase all other spilled pointers. */
4713 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4714 
4715 		/* Update the slot type. */
4716 		new_type = STACK_MISC;
4717 		if (writing_zero && *stype == STACK_ZERO) {
4718 			new_type = STACK_ZERO;
4719 			zero_used = true;
4720 		}
4721 		/* If the slot is STACK_INVALID, we check whether it's OK to
4722 		 * pretend that it will be initialized by this write. The slot
4723 		 * might not actually be written to, and so if we mark it as
4724 		 * initialized future reads might leak uninitialized memory.
4725 		 * For privileged programs, we will accept such reads to slots
4726 		 * that may or may not be written because, if we're reject
4727 		 * them, the error would be too confusing.
4728 		 */
4729 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4730 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4731 					insn_idx, i);
4732 			return -EINVAL;
4733 		}
4734 		*stype = new_type;
4735 	}
4736 	if (zero_used) {
4737 		/* backtracking doesn't work for STACK_ZERO yet. */
4738 		err = mark_chain_precision(env, value_regno);
4739 		if (err)
4740 			return err;
4741 	}
4742 	return 0;
4743 }
4744 
4745 /* When register 'dst_regno' is assigned some values from stack[min_off,
4746  * max_off), we set the register's type according to the types of the
4747  * respective stack slots. If all the stack values are known to be zeros, then
4748  * so is the destination reg. Otherwise, the register is considered to be
4749  * SCALAR. This function does not deal with register filling; the caller must
4750  * ensure that all spilled registers in the stack range have been marked as
4751  * read.
4752  */
4753 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4754 				/* func where src register points to */
4755 				struct bpf_func_state *ptr_state,
4756 				int min_off, int max_off, int dst_regno)
4757 {
4758 	struct bpf_verifier_state *vstate = env->cur_state;
4759 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4760 	int i, slot, spi;
4761 	u8 *stype;
4762 	int zeros = 0;
4763 
4764 	for (i = min_off; i < max_off; i++) {
4765 		slot = -i - 1;
4766 		spi = slot / BPF_REG_SIZE;
4767 		mark_stack_slot_scratched(env, spi);
4768 		stype = ptr_state->stack[spi].slot_type;
4769 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4770 			break;
4771 		zeros++;
4772 	}
4773 	if (zeros == max_off - min_off) {
4774 		/* Any access_size read into register is zero extended,
4775 		 * so the whole register == const_zero.
4776 		 */
4777 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
4778 	} else {
4779 		/* have read misc data from the stack */
4780 		mark_reg_unknown(env, state->regs, dst_regno);
4781 	}
4782 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4783 }
4784 
4785 /* Read the stack at 'off' and put the results into the register indicated by
4786  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4787  * spilled reg.
4788  *
4789  * 'dst_regno' can be -1, meaning that the read value is not going to a
4790  * register.
4791  *
4792  * The access is assumed to be within the current stack bounds.
4793  */
4794 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4795 				      /* func where src register points to */
4796 				      struct bpf_func_state *reg_state,
4797 				      int off, int size, int dst_regno)
4798 {
4799 	struct bpf_verifier_state *vstate = env->cur_state;
4800 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4801 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4802 	struct bpf_reg_state *reg;
4803 	u8 *stype, type;
4804 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
4805 
4806 	stype = reg_state->stack[spi].slot_type;
4807 	reg = &reg_state->stack[spi].spilled_ptr;
4808 
4809 	mark_stack_slot_scratched(env, spi);
4810 
4811 	if (is_spilled_reg(&reg_state->stack[spi])) {
4812 		u8 spill_size = 1;
4813 
4814 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4815 			spill_size++;
4816 
4817 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4818 			if (reg->type != SCALAR_VALUE) {
4819 				verbose_linfo(env, env->insn_idx, "; ");
4820 				verbose(env, "invalid size of register fill\n");
4821 				return -EACCES;
4822 			}
4823 
4824 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4825 			if (dst_regno < 0)
4826 				return 0;
4827 
4828 			if (size <= spill_size &&
4829 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
4830 				/* The earlier check_reg_arg() has decided the
4831 				 * subreg_def for this insn.  Save it first.
4832 				 */
4833 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4834 
4835 				copy_register_state(&state->regs[dst_regno], reg);
4836 				state->regs[dst_regno].subreg_def = subreg_def;
4837 
4838 				/* Break the relation on a narrowing fill.
4839 				 * coerce_reg_to_size will adjust the boundaries.
4840 				 */
4841 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
4842 					state->regs[dst_regno].id = 0;
4843 			} else {
4844 				int spill_cnt = 0, zero_cnt = 0;
4845 
4846 				for (i = 0; i < size; i++) {
4847 					type = stype[(slot - i) % BPF_REG_SIZE];
4848 					if (type == STACK_SPILL) {
4849 						spill_cnt++;
4850 						continue;
4851 					}
4852 					if (type == STACK_MISC)
4853 						continue;
4854 					if (type == STACK_ZERO) {
4855 						zero_cnt++;
4856 						continue;
4857 					}
4858 					if (type == STACK_INVALID && env->allow_uninit_stack)
4859 						continue;
4860 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4861 						off, i, size);
4862 					return -EACCES;
4863 				}
4864 
4865 				if (spill_cnt == size &&
4866 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4867 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4868 					/* this IS register fill, so keep insn_flags */
4869 				} else if (zero_cnt == size) {
4870 					/* similarly to mark_reg_stack_read(), preserve zeroes */
4871 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4872 					insn_flags = 0; /* not restoring original register state */
4873 				} else {
4874 					mark_reg_unknown(env, state->regs, dst_regno);
4875 					insn_flags = 0; /* not restoring original register state */
4876 				}
4877 			}
4878 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4879 		} else if (dst_regno >= 0) {
4880 			/* restore register state from stack */
4881 			copy_register_state(&state->regs[dst_regno], reg);
4882 			/* mark reg as written since spilled pointer state likely
4883 			 * has its liveness marks cleared by is_state_visited()
4884 			 * which resets stack/reg liveness for state transitions
4885 			 */
4886 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4887 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4888 			/* If dst_regno==-1, the caller is asking us whether
4889 			 * it is acceptable to use this value as a SCALAR_VALUE
4890 			 * (e.g. for XADD).
4891 			 * We must not allow unprivileged callers to do that
4892 			 * with spilled pointers.
4893 			 */
4894 			verbose(env, "leaking pointer from stack off %d\n",
4895 				off);
4896 			return -EACCES;
4897 		}
4898 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4899 	} else {
4900 		for (i = 0; i < size; i++) {
4901 			type = stype[(slot - i) % BPF_REG_SIZE];
4902 			if (type == STACK_MISC)
4903 				continue;
4904 			if (type == STACK_ZERO)
4905 				continue;
4906 			if (type == STACK_INVALID && env->allow_uninit_stack)
4907 				continue;
4908 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4909 				off, i, size);
4910 			return -EACCES;
4911 		}
4912 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4913 		if (dst_regno >= 0)
4914 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4915 		insn_flags = 0; /* we are not restoring spilled register */
4916 	}
4917 	if (insn_flags)
4918 		return push_jmp_history(env, env->cur_state, insn_flags);
4919 	return 0;
4920 }
4921 
4922 enum bpf_access_src {
4923 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4924 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4925 };
4926 
4927 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4928 					 int regno, int off, int access_size,
4929 					 bool zero_size_allowed,
4930 					 enum bpf_access_src type,
4931 					 struct bpf_call_arg_meta *meta);
4932 
4933 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4934 {
4935 	return cur_regs(env) + regno;
4936 }
4937 
4938 /* Read the stack at 'ptr_regno + off' and put the result into the register
4939  * 'dst_regno'.
4940  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4941  * but not its variable offset.
4942  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4943  *
4944  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4945  * filling registers (i.e. reads of spilled register cannot be detected when
4946  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4947  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4948  * offset; for a fixed offset check_stack_read_fixed_off should be used
4949  * instead.
4950  */
4951 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4952 				    int ptr_regno, int off, int size, int dst_regno)
4953 {
4954 	/* The state of the source register. */
4955 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4956 	struct bpf_func_state *ptr_state = func(env, reg);
4957 	int err;
4958 	int min_off, max_off;
4959 
4960 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4961 	 */
4962 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4963 					    false, ACCESS_DIRECT, NULL);
4964 	if (err)
4965 		return err;
4966 
4967 	min_off = reg->smin_value + off;
4968 	max_off = reg->smax_value + off;
4969 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4970 	return 0;
4971 }
4972 
4973 /* check_stack_read dispatches to check_stack_read_fixed_off or
4974  * check_stack_read_var_off.
4975  *
4976  * The caller must ensure that the offset falls within the allocated stack
4977  * bounds.
4978  *
4979  * 'dst_regno' is a register which will receive the value from the stack. It
4980  * can be -1, meaning that the read value is not going to a register.
4981  */
4982 static int check_stack_read(struct bpf_verifier_env *env,
4983 			    int ptr_regno, int off, int size,
4984 			    int dst_regno)
4985 {
4986 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4987 	struct bpf_func_state *state = func(env, reg);
4988 	int err;
4989 	/* Some accesses are only permitted with a static offset. */
4990 	bool var_off = !tnum_is_const(reg->var_off);
4991 
4992 	/* The offset is required to be static when reads don't go to a
4993 	 * register, in order to not leak pointers (see
4994 	 * check_stack_read_fixed_off).
4995 	 */
4996 	if (dst_regno < 0 && var_off) {
4997 		char tn_buf[48];
4998 
4999 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5000 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5001 			tn_buf, off, size);
5002 		return -EACCES;
5003 	}
5004 	/* Variable offset is prohibited for unprivileged mode for simplicity
5005 	 * since it requires corresponding support in Spectre masking for stack
5006 	 * ALU. See also retrieve_ptr_limit(). The check in
5007 	 * check_stack_access_for_ptr_arithmetic() called by
5008 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5009 	 * with variable offsets, therefore no check is required here. Further,
5010 	 * just checking it here would be insufficient as speculative stack
5011 	 * writes could still lead to unsafe speculative behaviour.
5012 	 */
5013 	if (!var_off) {
5014 		off += reg->var_off.value;
5015 		err = check_stack_read_fixed_off(env, state, off, size,
5016 						 dst_regno);
5017 	} else {
5018 		/* Variable offset stack reads need more conservative handling
5019 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5020 		 * branch.
5021 		 */
5022 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5023 					       dst_regno);
5024 	}
5025 	return err;
5026 }
5027 
5028 
5029 /* check_stack_write dispatches to check_stack_write_fixed_off or
5030  * check_stack_write_var_off.
5031  *
5032  * 'ptr_regno' is the register used as a pointer into the stack.
5033  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5034  * 'value_regno' is the register whose value we're writing to the stack. It can
5035  * be -1, meaning that we're not writing from a register.
5036  *
5037  * The caller must ensure that the offset falls within the maximum stack size.
5038  */
5039 static int check_stack_write(struct bpf_verifier_env *env,
5040 			     int ptr_regno, int off, int size,
5041 			     int value_regno, int insn_idx)
5042 {
5043 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5044 	struct bpf_func_state *state = func(env, reg);
5045 	int err;
5046 
5047 	if (tnum_is_const(reg->var_off)) {
5048 		off += reg->var_off.value;
5049 		err = check_stack_write_fixed_off(env, state, off, size,
5050 						  value_regno, insn_idx);
5051 	} else {
5052 		/* Variable offset stack reads need more conservative handling
5053 		 * than fixed offset ones.
5054 		 */
5055 		err = check_stack_write_var_off(env, state,
5056 						ptr_regno, off, size,
5057 						value_regno, insn_idx);
5058 	}
5059 	return err;
5060 }
5061 
5062 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5063 				 int off, int size, enum bpf_access_type type)
5064 {
5065 	struct bpf_reg_state *regs = cur_regs(env);
5066 	struct bpf_map *map = regs[regno].map_ptr;
5067 	u32 cap = bpf_map_flags_to_cap(map);
5068 
5069 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5070 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5071 			map->value_size, off, size);
5072 		return -EACCES;
5073 	}
5074 
5075 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5076 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5077 			map->value_size, off, size);
5078 		return -EACCES;
5079 	}
5080 
5081 	return 0;
5082 }
5083 
5084 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5085 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5086 			      int off, int size, u32 mem_size,
5087 			      bool zero_size_allowed)
5088 {
5089 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5090 	struct bpf_reg_state *reg;
5091 
5092 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5093 		return 0;
5094 
5095 	reg = &cur_regs(env)[regno];
5096 	switch (reg->type) {
5097 	case PTR_TO_MAP_KEY:
5098 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5099 			mem_size, off, size);
5100 		break;
5101 	case PTR_TO_MAP_VALUE:
5102 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5103 			mem_size, off, size);
5104 		break;
5105 	case PTR_TO_PACKET:
5106 	case PTR_TO_PACKET_META:
5107 	case PTR_TO_PACKET_END:
5108 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5109 			off, size, regno, reg->id, off, mem_size);
5110 		break;
5111 	case PTR_TO_MEM:
5112 	default:
5113 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5114 			mem_size, off, size);
5115 	}
5116 
5117 	return -EACCES;
5118 }
5119 
5120 /* check read/write into a memory region with possible variable offset */
5121 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5122 				   int off, int size, u32 mem_size,
5123 				   bool zero_size_allowed)
5124 {
5125 	struct bpf_verifier_state *vstate = env->cur_state;
5126 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5127 	struct bpf_reg_state *reg = &state->regs[regno];
5128 	int err;
5129 
5130 	/* We may have adjusted the register pointing to memory region, so we
5131 	 * need to try adding each of min_value and max_value to off
5132 	 * to make sure our theoretical access will be safe.
5133 	 *
5134 	 * The minimum value is only important with signed
5135 	 * comparisons where we can't assume the floor of a
5136 	 * value is 0.  If we are using signed variables for our
5137 	 * index'es we need to make sure that whatever we use
5138 	 * will have a set floor within our range.
5139 	 */
5140 	if (reg->smin_value < 0 &&
5141 	    (reg->smin_value == S64_MIN ||
5142 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5143 	      reg->smin_value + off < 0)) {
5144 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5145 			regno);
5146 		return -EACCES;
5147 	}
5148 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5149 				 mem_size, zero_size_allowed);
5150 	if (err) {
5151 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5152 			regno);
5153 		return err;
5154 	}
5155 
5156 	/* If we haven't set a max value then we need to bail since we can't be
5157 	 * sure we won't do bad things.
5158 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5159 	 */
5160 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5161 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5162 			regno);
5163 		return -EACCES;
5164 	}
5165 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5166 				 mem_size, zero_size_allowed);
5167 	if (err) {
5168 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5169 			regno);
5170 		return err;
5171 	}
5172 
5173 	return 0;
5174 }
5175 
5176 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5177 			       const struct bpf_reg_state *reg, int regno,
5178 			       bool fixed_off_ok)
5179 {
5180 	/* Access to this pointer-typed register or passing it to a helper
5181 	 * is only allowed in its original, unmodified form.
5182 	 */
5183 
5184 	if (reg->off < 0) {
5185 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5186 			reg_type_str(env, reg->type), regno, reg->off);
5187 		return -EACCES;
5188 	}
5189 
5190 	if (!fixed_off_ok && reg->off) {
5191 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5192 			reg_type_str(env, reg->type), regno, reg->off);
5193 		return -EACCES;
5194 	}
5195 
5196 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5197 		char tn_buf[48];
5198 
5199 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5200 		verbose(env, "variable %s access var_off=%s disallowed\n",
5201 			reg_type_str(env, reg->type), tn_buf);
5202 		return -EACCES;
5203 	}
5204 
5205 	return 0;
5206 }
5207 
5208 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5209 		             const struct bpf_reg_state *reg, int regno)
5210 {
5211 	return __check_ptr_off_reg(env, reg, regno, false);
5212 }
5213 
5214 static int map_kptr_match_type(struct bpf_verifier_env *env,
5215 			       struct btf_field *kptr_field,
5216 			       struct bpf_reg_state *reg, u32 regno)
5217 {
5218 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5219 	int perm_flags;
5220 	const char *reg_name = "";
5221 
5222 	if (btf_is_kernel(reg->btf)) {
5223 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5224 
5225 		/* Only unreferenced case accepts untrusted pointers */
5226 		if (kptr_field->type == BPF_KPTR_UNREF)
5227 			perm_flags |= PTR_UNTRUSTED;
5228 	} else {
5229 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5230 		if (kptr_field->type == BPF_KPTR_PERCPU)
5231 			perm_flags |= MEM_PERCPU;
5232 	}
5233 
5234 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5235 		goto bad_type;
5236 
5237 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5238 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5239 
5240 	/* For ref_ptr case, release function check should ensure we get one
5241 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5242 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5243 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5244 	 * reg->off and reg->ref_obj_id are not needed here.
5245 	 */
5246 	if (__check_ptr_off_reg(env, reg, regno, true))
5247 		return -EACCES;
5248 
5249 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5250 	 * we also need to take into account the reg->off.
5251 	 *
5252 	 * We want to support cases like:
5253 	 *
5254 	 * struct foo {
5255 	 *         struct bar br;
5256 	 *         struct baz bz;
5257 	 * };
5258 	 *
5259 	 * struct foo *v;
5260 	 * v = func();	      // PTR_TO_BTF_ID
5261 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5262 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5263 	 *                    // first member type of struct after comparison fails
5264 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5265 	 *                    // to match type
5266 	 *
5267 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5268 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5269 	 * the struct to match type against first member of struct, i.e. reject
5270 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5271 	 * strict mode to true for type match.
5272 	 */
5273 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5274 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5275 				  kptr_field->type != BPF_KPTR_UNREF))
5276 		goto bad_type;
5277 	return 0;
5278 bad_type:
5279 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5280 		reg_type_str(env, reg->type), reg_name);
5281 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5282 	if (kptr_field->type == BPF_KPTR_UNREF)
5283 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5284 			targ_name);
5285 	else
5286 		verbose(env, "\n");
5287 	return -EINVAL;
5288 }
5289 
5290 static bool in_sleepable(struct bpf_verifier_env *env)
5291 {
5292 	return env->prog->sleepable ||
5293 	       (env->cur_state && env->cur_state->in_sleepable);
5294 }
5295 
5296 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5297  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5298  */
5299 static bool in_rcu_cs(struct bpf_verifier_env *env)
5300 {
5301 	return env->cur_state->active_rcu_lock ||
5302 	       env->cur_state->active_lock.ptr ||
5303 	       !in_sleepable(env);
5304 }
5305 
5306 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5307 BTF_SET_START(rcu_protected_types)
5308 BTF_ID(struct, prog_test_ref_kfunc)
5309 #ifdef CONFIG_CGROUPS
5310 BTF_ID(struct, cgroup)
5311 #endif
5312 #ifdef CONFIG_BPF_JIT
5313 BTF_ID(struct, bpf_cpumask)
5314 #endif
5315 BTF_ID(struct, task_struct)
5316 BTF_ID(struct, bpf_crypto_ctx)
5317 BTF_SET_END(rcu_protected_types)
5318 
5319 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5320 {
5321 	if (!btf_is_kernel(btf))
5322 		return true;
5323 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5324 }
5325 
5326 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5327 {
5328 	struct btf_struct_meta *meta;
5329 
5330 	if (btf_is_kernel(kptr_field->kptr.btf))
5331 		return NULL;
5332 
5333 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5334 				    kptr_field->kptr.btf_id);
5335 
5336 	return meta ? meta->record : NULL;
5337 }
5338 
5339 static bool rcu_safe_kptr(const struct btf_field *field)
5340 {
5341 	const struct btf_field_kptr *kptr = &field->kptr;
5342 
5343 	return field->type == BPF_KPTR_PERCPU ||
5344 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5345 }
5346 
5347 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5348 {
5349 	struct btf_record *rec;
5350 	u32 ret;
5351 
5352 	ret = PTR_MAYBE_NULL;
5353 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5354 		ret |= MEM_RCU;
5355 		if (kptr_field->type == BPF_KPTR_PERCPU)
5356 			ret |= MEM_PERCPU;
5357 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5358 			ret |= MEM_ALLOC;
5359 
5360 		rec = kptr_pointee_btf_record(kptr_field);
5361 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5362 			ret |= NON_OWN_REF;
5363 	} else {
5364 		ret |= PTR_UNTRUSTED;
5365 	}
5366 
5367 	return ret;
5368 }
5369 
5370 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5371 				 int value_regno, int insn_idx,
5372 				 struct btf_field *kptr_field)
5373 {
5374 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5375 	int class = BPF_CLASS(insn->code);
5376 	struct bpf_reg_state *val_reg;
5377 
5378 	/* Things we already checked for in check_map_access and caller:
5379 	 *  - Reject cases where variable offset may touch kptr
5380 	 *  - size of access (must be BPF_DW)
5381 	 *  - tnum_is_const(reg->var_off)
5382 	 *  - kptr_field->offset == off + reg->var_off.value
5383 	 */
5384 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5385 	if (BPF_MODE(insn->code) != BPF_MEM) {
5386 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5387 		return -EACCES;
5388 	}
5389 
5390 	/* We only allow loading referenced kptr, since it will be marked as
5391 	 * untrusted, similar to unreferenced kptr.
5392 	 */
5393 	if (class != BPF_LDX &&
5394 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5395 		verbose(env, "store to referenced kptr disallowed\n");
5396 		return -EACCES;
5397 	}
5398 
5399 	if (class == BPF_LDX) {
5400 		val_reg = reg_state(env, value_regno);
5401 		/* We can simply mark the value_regno receiving the pointer
5402 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5403 		 */
5404 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5405 				kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5406 	} else if (class == BPF_STX) {
5407 		val_reg = reg_state(env, value_regno);
5408 		if (!register_is_null(val_reg) &&
5409 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5410 			return -EACCES;
5411 	} else if (class == BPF_ST) {
5412 		if (insn->imm) {
5413 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5414 				kptr_field->offset);
5415 			return -EACCES;
5416 		}
5417 	} else {
5418 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5419 		return -EACCES;
5420 	}
5421 	return 0;
5422 }
5423 
5424 /* check read/write into a map element with possible variable offset */
5425 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5426 			    int off, int size, bool zero_size_allowed,
5427 			    enum bpf_access_src src)
5428 {
5429 	struct bpf_verifier_state *vstate = env->cur_state;
5430 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5431 	struct bpf_reg_state *reg = &state->regs[regno];
5432 	struct bpf_map *map = reg->map_ptr;
5433 	struct btf_record *rec;
5434 	int err, i;
5435 
5436 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5437 				      zero_size_allowed);
5438 	if (err)
5439 		return err;
5440 
5441 	if (IS_ERR_OR_NULL(map->record))
5442 		return 0;
5443 	rec = map->record;
5444 	for (i = 0; i < rec->cnt; i++) {
5445 		struct btf_field *field = &rec->fields[i];
5446 		u32 p = field->offset;
5447 
5448 		/* If any part of a field  can be touched by load/store, reject
5449 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5450 		 * it is sufficient to check x1 < y2 && y1 < x2.
5451 		 */
5452 		if (reg->smin_value + off < p + field->size &&
5453 		    p < reg->umax_value + off + size) {
5454 			switch (field->type) {
5455 			case BPF_KPTR_UNREF:
5456 			case BPF_KPTR_REF:
5457 			case BPF_KPTR_PERCPU:
5458 				if (src != ACCESS_DIRECT) {
5459 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5460 					return -EACCES;
5461 				}
5462 				if (!tnum_is_const(reg->var_off)) {
5463 					verbose(env, "kptr access cannot have variable offset\n");
5464 					return -EACCES;
5465 				}
5466 				if (p != off + reg->var_off.value) {
5467 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5468 						p, off + reg->var_off.value);
5469 					return -EACCES;
5470 				}
5471 				if (size != bpf_size_to_bytes(BPF_DW)) {
5472 					verbose(env, "kptr access size must be BPF_DW\n");
5473 					return -EACCES;
5474 				}
5475 				break;
5476 			default:
5477 				verbose(env, "%s cannot be accessed directly by load/store\n",
5478 					btf_field_type_name(field->type));
5479 				return -EACCES;
5480 			}
5481 		}
5482 	}
5483 	return 0;
5484 }
5485 
5486 #define MAX_PACKET_OFF 0xffff
5487 
5488 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5489 				       const struct bpf_call_arg_meta *meta,
5490 				       enum bpf_access_type t)
5491 {
5492 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5493 
5494 	switch (prog_type) {
5495 	/* Program types only with direct read access go here! */
5496 	case BPF_PROG_TYPE_LWT_IN:
5497 	case BPF_PROG_TYPE_LWT_OUT:
5498 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5499 	case BPF_PROG_TYPE_SK_REUSEPORT:
5500 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5501 	case BPF_PROG_TYPE_CGROUP_SKB:
5502 		if (t == BPF_WRITE)
5503 			return false;
5504 		fallthrough;
5505 
5506 	/* Program types with direct read + write access go here! */
5507 	case BPF_PROG_TYPE_SCHED_CLS:
5508 	case BPF_PROG_TYPE_SCHED_ACT:
5509 	case BPF_PROG_TYPE_XDP:
5510 	case BPF_PROG_TYPE_LWT_XMIT:
5511 	case BPF_PROG_TYPE_SK_SKB:
5512 	case BPF_PROG_TYPE_SK_MSG:
5513 		if (meta)
5514 			return meta->pkt_access;
5515 
5516 		env->seen_direct_write = true;
5517 		return true;
5518 
5519 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5520 		if (t == BPF_WRITE)
5521 			env->seen_direct_write = true;
5522 
5523 		return true;
5524 
5525 	default:
5526 		return false;
5527 	}
5528 }
5529 
5530 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5531 			       int size, bool zero_size_allowed)
5532 {
5533 	struct bpf_reg_state *regs = cur_regs(env);
5534 	struct bpf_reg_state *reg = &regs[regno];
5535 	int err;
5536 
5537 	/* We may have added a variable offset to the packet pointer; but any
5538 	 * reg->range we have comes after that.  We are only checking the fixed
5539 	 * offset.
5540 	 */
5541 
5542 	/* We don't allow negative numbers, because we aren't tracking enough
5543 	 * detail to prove they're safe.
5544 	 */
5545 	if (reg->smin_value < 0) {
5546 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5547 			regno);
5548 		return -EACCES;
5549 	}
5550 
5551 	err = reg->range < 0 ? -EINVAL :
5552 	      __check_mem_access(env, regno, off, size, reg->range,
5553 				 zero_size_allowed);
5554 	if (err) {
5555 		verbose(env, "R%d offset is outside of the packet\n", regno);
5556 		return err;
5557 	}
5558 
5559 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5560 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5561 	 * otherwise find_good_pkt_pointers would have refused to set range info
5562 	 * that __check_mem_access would have rejected this pkt access.
5563 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5564 	 */
5565 	env->prog->aux->max_pkt_offset =
5566 		max_t(u32, env->prog->aux->max_pkt_offset,
5567 		      off + reg->umax_value + size - 1);
5568 
5569 	return err;
5570 }
5571 
5572 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5573 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5574 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5575 			    struct btf **btf, u32 *btf_id)
5576 {
5577 	struct bpf_insn_access_aux info = {
5578 		.reg_type = *reg_type,
5579 		.log = &env->log,
5580 	};
5581 
5582 	if (env->ops->is_valid_access &&
5583 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5584 		/* A non zero info.ctx_field_size indicates that this field is a
5585 		 * candidate for later verifier transformation to load the whole
5586 		 * field and then apply a mask when accessed with a narrower
5587 		 * access than actual ctx access size. A zero info.ctx_field_size
5588 		 * will only allow for whole field access and rejects any other
5589 		 * type of narrower access.
5590 		 */
5591 		*reg_type = info.reg_type;
5592 
5593 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5594 			*btf = info.btf;
5595 			*btf_id = info.btf_id;
5596 		} else {
5597 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5598 		}
5599 		/* remember the offset of last byte accessed in ctx */
5600 		if (env->prog->aux->max_ctx_offset < off + size)
5601 			env->prog->aux->max_ctx_offset = off + size;
5602 		return 0;
5603 	}
5604 
5605 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5606 	return -EACCES;
5607 }
5608 
5609 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5610 				  int size)
5611 {
5612 	if (size < 0 || off < 0 ||
5613 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5614 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5615 			off, size);
5616 		return -EACCES;
5617 	}
5618 	return 0;
5619 }
5620 
5621 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5622 			     u32 regno, int off, int size,
5623 			     enum bpf_access_type t)
5624 {
5625 	struct bpf_reg_state *regs = cur_regs(env);
5626 	struct bpf_reg_state *reg = &regs[regno];
5627 	struct bpf_insn_access_aux info = {};
5628 	bool valid;
5629 
5630 	if (reg->smin_value < 0) {
5631 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5632 			regno);
5633 		return -EACCES;
5634 	}
5635 
5636 	switch (reg->type) {
5637 	case PTR_TO_SOCK_COMMON:
5638 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5639 		break;
5640 	case PTR_TO_SOCKET:
5641 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5642 		break;
5643 	case PTR_TO_TCP_SOCK:
5644 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5645 		break;
5646 	case PTR_TO_XDP_SOCK:
5647 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5648 		break;
5649 	default:
5650 		valid = false;
5651 	}
5652 
5653 
5654 	if (valid) {
5655 		env->insn_aux_data[insn_idx].ctx_field_size =
5656 			info.ctx_field_size;
5657 		return 0;
5658 	}
5659 
5660 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5661 		regno, reg_type_str(env, reg->type), off, size);
5662 
5663 	return -EACCES;
5664 }
5665 
5666 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5667 {
5668 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5669 }
5670 
5671 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5672 {
5673 	const struct bpf_reg_state *reg = reg_state(env, regno);
5674 
5675 	return reg->type == PTR_TO_CTX;
5676 }
5677 
5678 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5679 {
5680 	const struct bpf_reg_state *reg = reg_state(env, regno);
5681 
5682 	return type_is_sk_pointer(reg->type);
5683 }
5684 
5685 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5686 {
5687 	const struct bpf_reg_state *reg = reg_state(env, regno);
5688 
5689 	return type_is_pkt_pointer(reg->type);
5690 }
5691 
5692 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5693 {
5694 	const struct bpf_reg_state *reg = reg_state(env, regno);
5695 
5696 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5697 	return reg->type == PTR_TO_FLOW_KEYS;
5698 }
5699 
5700 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
5701 {
5702 	const struct bpf_reg_state *reg = reg_state(env, regno);
5703 
5704 	return reg->type == PTR_TO_ARENA;
5705 }
5706 
5707 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5708 #ifdef CONFIG_NET
5709 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5710 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5711 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5712 #endif
5713 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5714 };
5715 
5716 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5717 {
5718 	/* A referenced register is always trusted. */
5719 	if (reg->ref_obj_id)
5720 		return true;
5721 
5722 	/* Types listed in the reg2btf_ids are always trusted */
5723 	if (reg2btf_ids[base_type(reg->type)] &&
5724 	    !bpf_type_has_unsafe_modifiers(reg->type))
5725 		return true;
5726 
5727 	/* If a register is not referenced, it is trusted if it has the
5728 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5729 	 * other type modifiers may be safe, but we elect to take an opt-in
5730 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5731 	 * not.
5732 	 *
5733 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5734 	 * for whether a register is trusted.
5735 	 */
5736 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5737 	       !bpf_type_has_unsafe_modifiers(reg->type);
5738 }
5739 
5740 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5741 {
5742 	return reg->type & MEM_RCU;
5743 }
5744 
5745 static void clear_trusted_flags(enum bpf_type_flag *flag)
5746 {
5747 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5748 }
5749 
5750 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5751 				   const struct bpf_reg_state *reg,
5752 				   int off, int size, bool strict)
5753 {
5754 	struct tnum reg_off;
5755 	int ip_align;
5756 
5757 	/* Byte size accesses are always allowed. */
5758 	if (!strict || size == 1)
5759 		return 0;
5760 
5761 	/* For platforms that do not have a Kconfig enabling
5762 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5763 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5764 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5765 	 * to this code only in strict mode where we want to emulate
5766 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5767 	 * unconditional IP align value of '2'.
5768 	 */
5769 	ip_align = 2;
5770 
5771 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5772 	if (!tnum_is_aligned(reg_off, size)) {
5773 		char tn_buf[48];
5774 
5775 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5776 		verbose(env,
5777 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5778 			ip_align, tn_buf, reg->off, off, size);
5779 		return -EACCES;
5780 	}
5781 
5782 	return 0;
5783 }
5784 
5785 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5786 				       const struct bpf_reg_state *reg,
5787 				       const char *pointer_desc,
5788 				       int off, int size, bool strict)
5789 {
5790 	struct tnum reg_off;
5791 
5792 	/* Byte size accesses are always allowed. */
5793 	if (!strict || size == 1)
5794 		return 0;
5795 
5796 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5797 	if (!tnum_is_aligned(reg_off, size)) {
5798 		char tn_buf[48];
5799 
5800 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5801 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5802 			pointer_desc, tn_buf, reg->off, off, size);
5803 		return -EACCES;
5804 	}
5805 
5806 	return 0;
5807 }
5808 
5809 static int check_ptr_alignment(struct bpf_verifier_env *env,
5810 			       const struct bpf_reg_state *reg, int off,
5811 			       int size, bool strict_alignment_once)
5812 {
5813 	bool strict = env->strict_alignment || strict_alignment_once;
5814 	const char *pointer_desc = "";
5815 
5816 	switch (reg->type) {
5817 	case PTR_TO_PACKET:
5818 	case PTR_TO_PACKET_META:
5819 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5820 		 * right in front, treat it the very same way.
5821 		 */
5822 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5823 	case PTR_TO_FLOW_KEYS:
5824 		pointer_desc = "flow keys ";
5825 		break;
5826 	case PTR_TO_MAP_KEY:
5827 		pointer_desc = "key ";
5828 		break;
5829 	case PTR_TO_MAP_VALUE:
5830 		pointer_desc = "value ";
5831 		break;
5832 	case PTR_TO_CTX:
5833 		pointer_desc = "context ";
5834 		break;
5835 	case PTR_TO_STACK:
5836 		pointer_desc = "stack ";
5837 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5838 		 * and check_stack_read_fixed_off() relies on stack accesses being
5839 		 * aligned.
5840 		 */
5841 		strict = true;
5842 		break;
5843 	case PTR_TO_SOCKET:
5844 		pointer_desc = "sock ";
5845 		break;
5846 	case PTR_TO_SOCK_COMMON:
5847 		pointer_desc = "sock_common ";
5848 		break;
5849 	case PTR_TO_TCP_SOCK:
5850 		pointer_desc = "tcp_sock ";
5851 		break;
5852 	case PTR_TO_XDP_SOCK:
5853 		pointer_desc = "xdp_sock ";
5854 		break;
5855 	case PTR_TO_ARENA:
5856 		return 0;
5857 	default:
5858 		break;
5859 	}
5860 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5861 					   strict);
5862 }
5863 
5864 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5865 {
5866 	if (env->prog->jit_requested)
5867 		return round_up(stack_depth, 16);
5868 
5869 	/* round up to 32-bytes, since this is granularity
5870 	 * of interpreter stack size
5871 	 */
5872 	return round_up(max_t(u32, stack_depth, 1), 32);
5873 }
5874 
5875 /* starting from main bpf function walk all instructions of the function
5876  * and recursively walk all callees that given function can call.
5877  * Ignore jump and exit insns.
5878  * Since recursion is prevented by check_cfg() this algorithm
5879  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5880  */
5881 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5882 {
5883 	struct bpf_subprog_info *subprog = env->subprog_info;
5884 	struct bpf_insn *insn = env->prog->insnsi;
5885 	int depth = 0, frame = 0, i, subprog_end;
5886 	bool tail_call_reachable = false;
5887 	int ret_insn[MAX_CALL_FRAMES];
5888 	int ret_prog[MAX_CALL_FRAMES];
5889 	int j;
5890 
5891 	i = subprog[idx].start;
5892 process_func:
5893 	/* protect against potential stack overflow that might happen when
5894 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5895 	 * depth for such case down to 256 so that the worst case scenario
5896 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5897 	 * 8k).
5898 	 *
5899 	 * To get the idea what might happen, see an example:
5900 	 * func1 -> sub rsp, 128
5901 	 *  subfunc1 -> sub rsp, 256
5902 	 *  tailcall1 -> add rsp, 256
5903 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5904 	 *   subfunc2 -> sub rsp, 64
5905 	 *   subfunc22 -> sub rsp, 128
5906 	 *   tailcall2 -> add rsp, 128
5907 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5908 	 *
5909 	 * tailcall will unwind the current stack frame but it will not get rid
5910 	 * of caller's stack as shown on the example above.
5911 	 */
5912 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5913 		verbose(env,
5914 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5915 			depth);
5916 		return -EACCES;
5917 	}
5918 	depth += round_up_stack_depth(env, subprog[idx].stack_depth);
5919 	if (depth > MAX_BPF_STACK) {
5920 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5921 			frame + 1, depth);
5922 		return -EACCES;
5923 	}
5924 continue_func:
5925 	subprog_end = subprog[idx + 1].start;
5926 	for (; i < subprog_end; i++) {
5927 		int next_insn, sidx;
5928 
5929 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5930 			bool err = false;
5931 
5932 			if (!is_bpf_throw_kfunc(insn + i))
5933 				continue;
5934 			if (subprog[idx].is_cb)
5935 				err = true;
5936 			for (int c = 0; c < frame && !err; c++) {
5937 				if (subprog[ret_prog[c]].is_cb) {
5938 					err = true;
5939 					break;
5940 				}
5941 			}
5942 			if (!err)
5943 				continue;
5944 			verbose(env,
5945 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5946 				i, idx);
5947 			return -EINVAL;
5948 		}
5949 
5950 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5951 			continue;
5952 		/* remember insn and function to return to */
5953 		ret_insn[frame] = i + 1;
5954 		ret_prog[frame] = idx;
5955 
5956 		/* find the callee */
5957 		next_insn = i + insn[i].imm + 1;
5958 		sidx = find_subprog(env, next_insn);
5959 		if (sidx < 0) {
5960 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5961 				  next_insn);
5962 			return -EFAULT;
5963 		}
5964 		if (subprog[sidx].is_async_cb) {
5965 			if (subprog[sidx].has_tail_call) {
5966 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5967 				return -EFAULT;
5968 			}
5969 			/* async callbacks don't increase bpf prog stack size unless called directly */
5970 			if (!bpf_pseudo_call(insn + i))
5971 				continue;
5972 			if (subprog[sidx].is_exception_cb) {
5973 				verbose(env, "insn %d cannot call exception cb directly\n", i);
5974 				return -EINVAL;
5975 			}
5976 		}
5977 		i = next_insn;
5978 		idx = sidx;
5979 
5980 		if (subprog[idx].has_tail_call)
5981 			tail_call_reachable = true;
5982 
5983 		frame++;
5984 		if (frame >= MAX_CALL_FRAMES) {
5985 			verbose(env, "the call stack of %d frames is too deep !\n",
5986 				frame);
5987 			return -E2BIG;
5988 		}
5989 		goto process_func;
5990 	}
5991 	/* if tail call got detected across bpf2bpf calls then mark each of the
5992 	 * currently present subprog frames as tail call reachable subprogs;
5993 	 * this info will be utilized by JIT so that we will be preserving the
5994 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5995 	 */
5996 	if (tail_call_reachable)
5997 		for (j = 0; j < frame; j++) {
5998 			if (subprog[ret_prog[j]].is_exception_cb) {
5999 				verbose(env, "cannot tail call within exception cb\n");
6000 				return -EINVAL;
6001 			}
6002 			subprog[ret_prog[j]].tail_call_reachable = true;
6003 		}
6004 	if (subprog[0].tail_call_reachable)
6005 		env->prog->aux->tail_call_reachable = true;
6006 
6007 	/* end of for() loop means the last insn of the 'subprog'
6008 	 * was reached. Doesn't matter whether it was JA or EXIT
6009 	 */
6010 	if (frame == 0)
6011 		return 0;
6012 	depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6013 	frame--;
6014 	i = ret_insn[frame];
6015 	idx = ret_prog[frame];
6016 	goto continue_func;
6017 }
6018 
6019 static int check_max_stack_depth(struct bpf_verifier_env *env)
6020 {
6021 	struct bpf_subprog_info *si = env->subprog_info;
6022 	int ret;
6023 
6024 	for (int i = 0; i < env->subprog_cnt; i++) {
6025 		if (!i || si[i].is_async_cb) {
6026 			ret = check_max_stack_depth_subprog(env, i);
6027 			if (ret < 0)
6028 				return ret;
6029 		}
6030 		continue;
6031 	}
6032 	return 0;
6033 }
6034 
6035 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6036 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6037 				  const struct bpf_insn *insn, int idx)
6038 {
6039 	int start = idx + insn->imm + 1, subprog;
6040 
6041 	subprog = find_subprog(env, start);
6042 	if (subprog < 0) {
6043 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6044 			  start);
6045 		return -EFAULT;
6046 	}
6047 	return env->subprog_info[subprog].stack_depth;
6048 }
6049 #endif
6050 
6051 static int __check_buffer_access(struct bpf_verifier_env *env,
6052 				 const char *buf_info,
6053 				 const struct bpf_reg_state *reg,
6054 				 int regno, int off, int size)
6055 {
6056 	if (off < 0) {
6057 		verbose(env,
6058 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6059 			regno, buf_info, off, size);
6060 		return -EACCES;
6061 	}
6062 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6063 		char tn_buf[48];
6064 
6065 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6066 		verbose(env,
6067 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6068 			regno, off, tn_buf);
6069 		return -EACCES;
6070 	}
6071 
6072 	return 0;
6073 }
6074 
6075 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6076 				  const struct bpf_reg_state *reg,
6077 				  int regno, int off, int size)
6078 {
6079 	int err;
6080 
6081 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6082 	if (err)
6083 		return err;
6084 
6085 	if (off + size > env->prog->aux->max_tp_access)
6086 		env->prog->aux->max_tp_access = off + size;
6087 
6088 	return 0;
6089 }
6090 
6091 static int check_buffer_access(struct bpf_verifier_env *env,
6092 			       const struct bpf_reg_state *reg,
6093 			       int regno, int off, int size,
6094 			       bool zero_size_allowed,
6095 			       u32 *max_access)
6096 {
6097 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6098 	int err;
6099 
6100 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6101 	if (err)
6102 		return err;
6103 
6104 	if (off + size > *max_access)
6105 		*max_access = off + size;
6106 
6107 	return 0;
6108 }
6109 
6110 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6111 static void zext_32_to_64(struct bpf_reg_state *reg)
6112 {
6113 	reg->var_off = tnum_subreg(reg->var_off);
6114 	__reg_assign_32_into_64(reg);
6115 }
6116 
6117 /* truncate register to smaller size (in bytes)
6118  * must be called with size < BPF_REG_SIZE
6119  */
6120 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6121 {
6122 	u64 mask;
6123 
6124 	/* clear high bits in bit representation */
6125 	reg->var_off = tnum_cast(reg->var_off, size);
6126 
6127 	/* fix arithmetic bounds */
6128 	mask = ((u64)1 << (size * 8)) - 1;
6129 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6130 		reg->umin_value &= mask;
6131 		reg->umax_value &= mask;
6132 	} else {
6133 		reg->umin_value = 0;
6134 		reg->umax_value = mask;
6135 	}
6136 	reg->smin_value = reg->umin_value;
6137 	reg->smax_value = reg->umax_value;
6138 
6139 	/* If size is smaller than 32bit register the 32bit register
6140 	 * values are also truncated so we push 64-bit bounds into
6141 	 * 32-bit bounds. Above were truncated < 32-bits already.
6142 	 */
6143 	if (size < 4)
6144 		__mark_reg32_unbounded(reg);
6145 
6146 	reg_bounds_sync(reg);
6147 }
6148 
6149 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6150 {
6151 	if (size == 1) {
6152 		reg->smin_value = reg->s32_min_value = S8_MIN;
6153 		reg->smax_value = reg->s32_max_value = S8_MAX;
6154 	} else if (size == 2) {
6155 		reg->smin_value = reg->s32_min_value = S16_MIN;
6156 		reg->smax_value = reg->s32_max_value = S16_MAX;
6157 	} else {
6158 		/* size == 4 */
6159 		reg->smin_value = reg->s32_min_value = S32_MIN;
6160 		reg->smax_value = reg->s32_max_value = S32_MAX;
6161 	}
6162 	reg->umin_value = reg->u32_min_value = 0;
6163 	reg->umax_value = U64_MAX;
6164 	reg->u32_max_value = U32_MAX;
6165 	reg->var_off = tnum_unknown;
6166 }
6167 
6168 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6169 {
6170 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6171 	u64 top_smax_value, top_smin_value;
6172 	u64 num_bits = size * 8;
6173 
6174 	if (tnum_is_const(reg->var_off)) {
6175 		u64_cval = reg->var_off.value;
6176 		if (size == 1)
6177 			reg->var_off = tnum_const((s8)u64_cval);
6178 		else if (size == 2)
6179 			reg->var_off = tnum_const((s16)u64_cval);
6180 		else
6181 			/* size == 4 */
6182 			reg->var_off = tnum_const((s32)u64_cval);
6183 
6184 		u64_cval = reg->var_off.value;
6185 		reg->smax_value = reg->smin_value = u64_cval;
6186 		reg->umax_value = reg->umin_value = u64_cval;
6187 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6188 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6189 		return;
6190 	}
6191 
6192 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6193 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6194 
6195 	if (top_smax_value != top_smin_value)
6196 		goto out;
6197 
6198 	/* find the s64_min and s64_min after sign extension */
6199 	if (size == 1) {
6200 		init_s64_max = (s8)reg->smax_value;
6201 		init_s64_min = (s8)reg->smin_value;
6202 	} else if (size == 2) {
6203 		init_s64_max = (s16)reg->smax_value;
6204 		init_s64_min = (s16)reg->smin_value;
6205 	} else {
6206 		init_s64_max = (s32)reg->smax_value;
6207 		init_s64_min = (s32)reg->smin_value;
6208 	}
6209 
6210 	s64_max = max(init_s64_max, init_s64_min);
6211 	s64_min = min(init_s64_max, init_s64_min);
6212 
6213 	/* both of s64_max/s64_min positive or negative */
6214 	if ((s64_max >= 0) == (s64_min >= 0)) {
6215 		reg->smin_value = reg->s32_min_value = s64_min;
6216 		reg->smax_value = reg->s32_max_value = s64_max;
6217 		reg->umin_value = reg->u32_min_value = s64_min;
6218 		reg->umax_value = reg->u32_max_value = s64_max;
6219 		reg->var_off = tnum_range(s64_min, s64_max);
6220 		return;
6221 	}
6222 
6223 out:
6224 	set_sext64_default_val(reg, size);
6225 }
6226 
6227 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6228 {
6229 	if (size == 1) {
6230 		reg->s32_min_value = S8_MIN;
6231 		reg->s32_max_value = S8_MAX;
6232 	} else {
6233 		/* size == 2 */
6234 		reg->s32_min_value = S16_MIN;
6235 		reg->s32_max_value = S16_MAX;
6236 	}
6237 	reg->u32_min_value = 0;
6238 	reg->u32_max_value = U32_MAX;
6239 }
6240 
6241 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6242 {
6243 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6244 	u32 top_smax_value, top_smin_value;
6245 	u32 num_bits = size * 8;
6246 
6247 	if (tnum_is_const(reg->var_off)) {
6248 		u32_val = reg->var_off.value;
6249 		if (size == 1)
6250 			reg->var_off = tnum_const((s8)u32_val);
6251 		else
6252 			reg->var_off = tnum_const((s16)u32_val);
6253 
6254 		u32_val = reg->var_off.value;
6255 		reg->s32_min_value = reg->s32_max_value = u32_val;
6256 		reg->u32_min_value = reg->u32_max_value = u32_val;
6257 		return;
6258 	}
6259 
6260 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6261 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6262 
6263 	if (top_smax_value != top_smin_value)
6264 		goto out;
6265 
6266 	/* find the s32_min and s32_min after sign extension */
6267 	if (size == 1) {
6268 		init_s32_max = (s8)reg->s32_max_value;
6269 		init_s32_min = (s8)reg->s32_min_value;
6270 	} else {
6271 		/* size == 2 */
6272 		init_s32_max = (s16)reg->s32_max_value;
6273 		init_s32_min = (s16)reg->s32_min_value;
6274 	}
6275 	s32_max = max(init_s32_max, init_s32_min);
6276 	s32_min = min(init_s32_max, init_s32_min);
6277 
6278 	if ((s32_min >= 0) == (s32_max >= 0)) {
6279 		reg->s32_min_value = s32_min;
6280 		reg->s32_max_value = s32_max;
6281 		reg->u32_min_value = (u32)s32_min;
6282 		reg->u32_max_value = (u32)s32_max;
6283 		return;
6284 	}
6285 
6286 out:
6287 	set_sext32_default_val(reg, size);
6288 }
6289 
6290 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6291 {
6292 	/* A map is considered read-only if the following condition are true:
6293 	 *
6294 	 * 1) BPF program side cannot change any of the map content. The
6295 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6296 	 *    and was set at map creation time.
6297 	 * 2) The map value(s) have been initialized from user space by a
6298 	 *    loader and then "frozen", such that no new map update/delete
6299 	 *    operations from syscall side are possible for the rest of
6300 	 *    the map's lifetime from that point onwards.
6301 	 * 3) Any parallel/pending map update/delete operations from syscall
6302 	 *    side have been completed. Only after that point, it's safe to
6303 	 *    assume that map value(s) are immutable.
6304 	 */
6305 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6306 	       READ_ONCE(map->frozen) &&
6307 	       !bpf_map_write_active(map);
6308 }
6309 
6310 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6311 			       bool is_ldsx)
6312 {
6313 	void *ptr;
6314 	u64 addr;
6315 	int err;
6316 
6317 	err = map->ops->map_direct_value_addr(map, &addr, off);
6318 	if (err)
6319 		return err;
6320 	ptr = (void *)(long)addr + off;
6321 
6322 	switch (size) {
6323 	case sizeof(u8):
6324 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6325 		break;
6326 	case sizeof(u16):
6327 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6328 		break;
6329 	case sizeof(u32):
6330 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6331 		break;
6332 	case sizeof(u64):
6333 		*val = *(u64 *)ptr;
6334 		break;
6335 	default:
6336 		return -EINVAL;
6337 	}
6338 	return 0;
6339 }
6340 
6341 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6342 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6343 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6344 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6345 
6346 /*
6347  * Allow list few fields as RCU trusted or full trusted.
6348  * This logic doesn't allow mix tagging and will be removed once GCC supports
6349  * btf_type_tag.
6350  */
6351 
6352 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6353 BTF_TYPE_SAFE_RCU(struct task_struct) {
6354 	const cpumask_t *cpus_ptr;
6355 	struct css_set __rcu *cgroups;
6356 	struct task_struct __rcu *real_parent;
6357 	struct task_struct *group_leader;
6358 };
6359 
6360 BTF_TYPE_SAFE_RCU(struct cgroup) {
6361 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6362 	struct kernfs_node *kn;
6363 };
6364 
6365 BTF_TYPE_SAFE_RCU(struct css_set) {
6366 	struct cgroup *dfl_cgrp;
6367 };
6368 
6369 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6370 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6371 	struct file __rcu *exe_file;
6372 };
6373 
6374 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6375  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6376  */
6377 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6378 	struct sock *sk;
6379 };
6380 
6381 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6382 	struct sock *sk;
6383 };
6384 
6385 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6386 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6387 	struct seq_file *seq;
6388 };
6389 
6390 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6391 	struct bpf_iter_meta *meta;
6392 	struct task_struct *task;
6393 };
6394 
6395 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6396 	struct file *file;
6397 };
6398 
6399 BTF_TYPE_SAFE_TRUSTED(struct file) {
6400 	struct inode *f_inode;
6401 };
6402 
6403 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6404 	/* no negative dentry-s in places where bpf can see it */
6405 	struct inode *d_inode;
6406 };
6407 
6408 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6409 	struct sock *sk;
6410 };
6411 
6412 static bool type_is_rcu(struct bpf_verifier_env *env,
6413 			struct bpf_reg_state *reg,
6414 			const char *field_name, u32 btf_id)
6415 {
6416 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6417 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6418 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6419 
6420 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6421 }
6422 
6423 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6424 				struct bpf_reg_state *reg,
6425 				const char *field_name, u32 btf_id)
6426 {
6427 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6428 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6429 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6430 
6431 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6432 }
6433 
6434 static bool type_is_trusted(struct bpf_verifier_env *env,
6435 			    struct bpf_reg_state *reg,
6436 			    const char *field_name, u32 btf_id)
6437 {
6438 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6439 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6440 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6441 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6442 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6443 
6444 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6445 }
6446 
6447 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6448 				    struct bpf_reg_state *reg,
6449 				    const char *field_name, u32 btf_id)
6450 {
6451 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6452 
6453 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6454 					  "__safe_trusted_or_null");
6455 }
6456 
6457 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6458 				   struct bpf_reg_state *regs,
6459 				   int regno, int off, int size,
6460 				   enum bpf_access_type atype,
6461 				   int value_regno)
6462 {
6463 	struct bpf_reg_state *reg = regs + regno;
6464 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6465 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6466 	const char *field_name = NULL;
6467 	enum bpf_type_flag flag = 0;
6468 	u32 btf_id = 0;
6469 	int ret;
6470 
6471 	if (!env->allow_ptr_leaks) {
6472 		verbose(env,
6473 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6474 			tname);
6475 		return -EPERM;
6476 	}
6477 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6478 		verbose(env,
6479 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6480 			tname);
6481 		return -EINVAL;
6482 	}
6483 	if (off < 0) {
6484 		verbose(env,
6485 			"R%d is ptr_%s invalid negative access: off=%d\n",
6486 			regno, tname, off);
6487 		return -EACCES;
6488 	}
6489 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6490 		char tn_buf[48];
6491 
6492 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6493 		verbose(env,
6494 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6495 			regno, tname, off, tn_buf);
6496 		return -EACCES;
6497 	}
6498 
6499 	if (reg->type & MEM_USER) {
6500 		verbose(env,
6501 			"R%d is ptr_%s access user memory: off=%d\n",
6502 			regno, tname, off);
6503 		return -EACCES;
6504 	}
6505 
6506 	if (reg->type & MEM_PERCPU) {
6507 		verbose(env,
6508 			"R%d is ptr_%s access percpu memory: off=%d\n",
6509 			regno, tname, off);
6510 		return -EACCES;
6511 	}
6512 
6513 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6514 		if (!btf_is_kernel(reg->btf)) {
6515 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6516 			return -EFAULT;
6517 		}
6518 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6519 	} else {
6520 		/* Writes are permitted with default btf_struct_access for
6521 		 * program allocated objects (which always have ref_obj_id > 0),
6522 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6523 		 */
6524 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6525 			verbose(env, "only read is supported\n");
6526 			return -EACCES;
6527 		}
6528 
6529 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6530 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6531 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6532 			return -EFAULT;
6533 		}
6534 
6535 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6536 	}
6537 
6538 	if (ret < 0)
6539 		return ret;
6540 
6541 	if (ret != PTR_TO_BTF_ID) {
6542 		/* just mark; */
6543 
6544 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6545 		/* If this is an untrusted pointer, all pointers formed by walking it
6546 		 * also inherit the untrusted flag.
6547 		 */
6548 		flag = PTR_UNTRUSTED;
6549 
6550 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6551 		/* By default any pointer obtained from walking a trusted pointer is no
6552 		 * longer trusted, unless the field being accessed has explicitly been
6553 		 * marked as inheriting its parent's state of trust (either full or RCU).
6554 		 * For example:
6555 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6556 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6557 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6558 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6559 		 *
6560 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6561 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6562 		 */
6563 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6564 			flag |= PTR_TRUSTED;
6565 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6566 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6567 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6568 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6569 				/* ignore __rcu tag and mark it MEM_RCU */
6570 				flag |= MEM_RCU;
6571 			} else if (flag & MEM_RCU ||
6572 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6573 				/* __rcu tagged pointers can be NULL */
6574 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6575 
6576 				/* We always trust them */
6577 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6578 				    flag & PTR_UNTRUSTED)
6579 					flag &= ~PTR_UNTRUSTED;
6580 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6581 				/* keep as-is */
6582 			} else {
6583 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6584 				clear_trusted_flags(&flag);
6585 			}
6586 		} else {
6587 			/*
6588 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6589 			 * aggressively mark as untrusted otherwise such
6590 			 * pointers will be plain PTR_TO_BTF_ID without flags
6591 			 * and will be allowed to be passed into helpers for
6592 			 * compat reasons.
6593 			 */
6594 			flag = PTR_UNTRUSTED;
6595 		}
6596 	} else {
6597 		/* Old compat. Deprecated */
6598 		clear_trusted_flags(&flag);
6599 	}
6600 
6601 	if (atype == BPF_READ && value_regno >= 0)
6602 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6603 
6604 	return 0;
6605 }
6606 
6607 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6608 				   struct bpf_reg_state *regs,
6609 				   int regno, int off, int size,
6610 				   enum bpf_access_type atype,
6611 				   int value_regno)
6612 {
6613 	struct bpf_reg_state *reg = regs + regno;
6614 	struct bpf_map *map = reg->map_ptr;
6615 	struct bpf_reg_state map_reg;
6616 	enum bpf_type_flag flag = 0;
6617 	const struct btf_type *t;
6618 	const char *tname;
6619 	u32 btf_id;
6620 	int ret;
6621 
6622 	if (!btf_vmlinux) {
6623 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6624 		return -ENOTSUPP;
6625 	}
6626 
6627 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6628 		verbose(env, "map_ptr access not supported for map type %d\n",
6629 			map->map_type);
6630 		return -ENOTSUPP;
6631 	}
6632 
6633 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6634 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6635 
6636 	if (!env->allow_ptr_leaks) {
6637 		verbose(env,
6638 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6639 			tname);
6640 		return -EPERM;
6641 	}
6642 
6643 	if (off < 0) {
6644 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6645 			regno, tname, off);
6646 		return -EACCES;
6647 	}
6648 
6649 	if (atype != BPF_READ) {
6650 		verbose(env, "only read from %s is supported\n", tname);
6651 		return -EACCES;
6652 	}
6653 
6654 	/* Simulate access to a PTR_TO_BTF_ID */
6655 	memset(&map_reg, 0, sizeof(map_reg));
6656 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6657 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6658 	if (ret < 0)
6659 		return ret;
6660 
6661 	if (value_regno >= 0)
6662 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6663 
6664 	return 0;
6665 }
6666 
6667 /* Check that the stack access at the given offset is within bounds. The
6668  * maximum valid offset is -1.
6669  *
6670  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6671  * -state->allocated_stack for reads.
6672  */
6673 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6674                                           s64 off,
6675                                           struct bpf_func_state *state,
6676                                           enum bpf_access_type t)
6677 {
6678 	int min_valid_off;
6679 
6680 	if (t == BPF_WRITE || env->allow_uninit_stack)
6681 		min_valid_off = -MAX_BPF_STACK;
6682 	else
6683 		min_valid_off = -state->allocated_stack;
6684 
6685 	if (off < min_valid_off || off > -1)
6686 		return -EACCES;
6687 	return 0;
6688 }
6689 
6690 /* Check that the stack access at 'regno + off' falls within the maximum stack
6691  * bounds.
6692  *
6693  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6694  */
6695 static int check_stack_access_within_bounds(
6696 		struct bpf_verifier_env *env,
6697 		int regno, int off, int access_size,
6698 		enum bpf_access_src src, enum bpf_access_type type)
6699 {
6700 	struct bpf_reg_state *regs = cur_regs(env);
6701 	struct bpf_reg_state *reg = regs + regno;
6702 	struct bpf_func_state *state = func(env, reg);
6703 	s64 min_off, max_off;
6704 	int err;
6705 	char *err_extra;
6706 
6707 	if (src == ACCESS_HELPER)
6708 		/* We don't know if helpers are reading or writing (or both). */
6709 		err_extra = " indirect access to";
6710 	else if (type == BPF_READ)
6711 		err_extra = " read from";
6712 	else
6713 		err_extra = " write to";
6714 
6715 	if (tnum_is_const(reg->var_off)) {
6716 		min_off = (s64)reg->var_off.value + off;
6717 		max_off = min_off + access_size;
6718 	} else {
6719 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6720 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6721 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6722 				err_extra, regno);
6723 			return -EACCES;
6724 		}
6725 		min_off = reg->smin_value + off;
6726 		max_off = reg->smax_value + off + access_size;
6727 	}
6728 
6729 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6730 	if (!err && max_off > 0)
6731 		err = -EINVAL; /* out of stack access into non-negative offsets */
6732 	if (!err && access_size < 0)
6733 		/* access_size should not be negative (or overflow an int); others checks
6734 		 * along the way should have prevented such an access.
6735 		 */
6736 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6737 
6738 	if (err) {
6739 		if (tnum_is_const(reg->var_off)) {
6740 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6741 				err_extra, regno, off, access_size);
6742 		} else {
6743 			char tn_buf[48];
6744 
6745 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6746 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
6747 				err_extra, regno, tn_buf, off, access_size);
6748 		}
6749 		return err;
6750 	}
6751 
6752 	/* Note that there is no stack access with offset zero, so the needed stack
6753 	 * size is -min_off, not -min_off+1.
6754 	 */
6755 	return grow_stack_state(env, state, -min_off /* size */);
6756 }
6757 
6758 /* check whether memory at (regno + off) is accessible for t = (read | write)
6759  * if t==write, value_regno is a register which value is stored into memory
6760  * if t==read, value_regno is a register which will receive the value from memory
6761  * if t==write && value_regno==-1, some unknown value is stored into memory
6762  * if t==read && value_regno==-1, don't care what we read from memory
6763  */
6764 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6765 			    int off, int bpf_size, enum bpf_access_type t,
6766 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6767 {
6768 	struct bpf_reg_state *regs = cur_regs(env);
6769 	struct bpf_reg_state *reg = regs + regno;
6770 	int size, err = 0;
6771 
6772 	size = bpf_size_to_bytes(bpf_size);
6773 	if (size < 0)
6774 		return size;
6775 
6776 	/* alignment checks will add in reg->off themselves */
6777 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6778 	if (err)
6779 		return err;
6780 
6781 	/* for access checks, reg->off is just part of off */
6782 	off += reg->off;
6783 
6784 	if (reg->type == PTR_TO_MAP_KEY) {
6785 		if (t == BPF_WRITE) {
6786 			verbose(env, "write to change key R%d not allowed\n", regno);
6787 			return -EACCES;
6788 		}
6789 
6790 		err = check_mem_region_access(env, regno, off, size,
6791 					      reg->map_ptr->key_size, false);
6792 		if (err)
6793 			return err;
6794 		if (value_regno >= 0)
6795 			mark_reg_unknown(env, regs, value_regno);
6796 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6797 		struct btf_field *kptr_field = NULL;
6798 
6799 		if (t == BPF_WRITE && value_regno >= 0 &&
6800 		    is_pointer_value(env, value_regno)) {
6801 			verbose(env, "R%d leaks addr into map\n", value_regno);
6802 			return -EACCES;
6803 		}
6804 		err = check_map_access_type(env, regno, off, size, t);
6805 		if (err)
6806 			return err;
6807 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6808 		if (err)
6809 			return err;
6810 		if (tnum_is_const(reg->var_off))
6811 			kptr_field = btf_record_find(reg->map_ptr->record,
6812 						     off + reg->var_off.value, BPF_KPTR);
6813 		if (kptr_field) {
6814 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6815 		} else if (t == BPF_READ && value_regno >= 0) {
6816 			struct bpf_map *map = reg->map_ptr;
6817 
6818 			/* if map is read-only, track its contents as scalars */
6819 			if (tnum_is_const(reg->var_off) &&
6820 			    bpf_map_is_rdonly(map) &&
6821 			    map->ops->map_direct_value_addr) {
6822 				int map_off = off + reg->var_off.value;
6823 				u64 val = 0;
6824 
6825 				err = bpf_map_direct_read(map, map_off, size,
6826 							  &val, is_ldsx);
6827 				if (err)
6828 					return err;
6829 
6830 				regs[value_regno].type = SCALAR_VALUE;
6831 				__mark_reg_known(&regs[value_regno], val);
6832 			} else {
6833 				mark_reg_unknown(env, regs, value_regno);
6834 			}
6835 		}
6836 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6837 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6838 
6839 		if (type_may_be_null(reg->type)) {
6840 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6841 				reg_type_str(env, reg->type));
6842 			return -EACCES;
6843 		}
6844 
6845 		if (t == BPF_WRITE && rdonly_mem) {
6846 			verbose(env, "R%d cannot write into %s\n",
6847 				regno, reg_type_str(env, reg->type));
6848 			return -EACCES;
6849 		}
6850 
6851 		if (t == BPF_WRITE && value_regno >= 0 &&
6852 		    is_pointer_value(env, value_regno)) {
6853 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6854 			return -EACCES;
6855 		}
6856 
6857 		err = check_mem_region_access(env, regno, off, size,
6858 					      reg->mem_size, false);
6859 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6860 			mark_reg_unknown(env, regs, value_regno);
6861 	} else if (reg->type == PTR_TO_CTX) {
6862 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6863 		struct btf *btf = NULL;
6864 		u32 btf_id = 0;
6865 
6866 		if (t == BPF_WRITE && value_regno >= 0 &&
6867 		    is_pointer_value(env, value_regno)) {
6868 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6869 			return -EACCES;
6870 		}
6871 
6872 		err = check_ptr_off_reg(env, reg, regno);
6873 		if (err < 0)
6874 			return err;
6875 
6876 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6877 				       &btf_id);
6878 		if (err)
6879 			verbose_linfo(env, insn_idx, "; ");
6880 		if (!err && t == BPF_READ && value_regno >= 0) {
6881 			/* ctx access returns either a scalar, or a
6882 			 * PTR_TO_PACKET[_META,_END]. In the latter
6883 			 * case, we know the offset is zero.
6884 			 */
6885 			if (reg_type == SCALAR_VALUE) {
6886 				mark_reg_unknown(env, regs, value_regno);
6887 			} else {
6888 				mark_reg_known_zero(env, regs,
6889 						    value_regno);
6890 				if (type_may_be_null(reg_type))
6891 					regs[value_regno].id = ++env->id_gen;
6892 				/* A load of ctx field could have different
6893 				 * actual load size with the one encoded in the
6894 				 * insn. When the dst is PTR, it is for sure not
6895 				 * a sub-register.
6896 				 */
6897 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6898 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6899 					regs[value_regno].btf = btf;
6900 					regs[value_regno].btf_id = btf_id;
6901 				}
6902 			}
6903 			regs[value_regno].type = reg_type;
6904 		}
6905 
6906 	} else if (reg->type == PTR_TO_STACK) {
6907 		/* Basic bounds checks. */
6908 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6909 		if (err)
6910 			return err;
6911 
6912 		if (t == BPF_READ)
6913 			err = check_stack_read(env, regno, off, size,
6914 					       value_regno);
6915 		else
6916 			err = check_stack_write(env, regno, off, size,
6917 						value_regno, insn_idx);
6918 	} else if (reg_is_pkt_pointer(reg)) {
6919 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6920 			verbose(env, "cannot write into packet\n");
6921 			return -EACCES;
6922 		}
6923 		if (t == BPF_WRITE && value_regno >= 0 &&
6924 		    is_pointer_value(env, value_regno)) {
6925 			verbose(env, "R%d leaks addr into packet\n",
6926 				value_regno);
6927 			return -EACCES;
6928 		}
6929 		err = check_packet_access(env, regno, off, size, false);
6930 		if (!err && t == BPF_READ && value_regno >= 0)
6931 			mark_reg_unknown(env, regs, value_regno);
6932 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6933 		if (t == BPF_WRITE && value_regno >= 0 &&
6934 		    is_pointer_value(env, value_regno)) {
6935 			verbose(env, "R%d leaks addr into flow keys\n",
6936 				value_regno);
6937 			return -EACCES;
6938 		}
6939 
6940 		err = check_flow_keys_access(env, off, size);
6941 		if (!err && t == BPF_READ && value_regno >= 0)
6942 			mark_reg_unknown(env, regs, value_regno);
6943 	} else if (type_is_sk_pointer(reg->type)) {
6944 		if (t == BPF_WRITE) {
6945 			verbose(env, "R%d cannot write into %s\n",
6946 				regno, reg_type_str(env, reg->type));
6947 			return -EACCES;
6948 		}
6949 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6950 		if (!err && value_regno >= 0)
6951 			mark_reg_unknown(env, regs, value_regno);
6952 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6953 		err = check_tp_buffer_access(env, reg, regno, off, size);
6954 		if (!err && t == BPF_READ && value_regno >= 0)
6955 			mark_reg_unknown(env, regs, value_regno);
6956 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6957 		   !type_may_be_null(reg->type)) {
6958 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6959 					      value_regno);
6960 	} else if (reg->type == CONST_PTR_TO_MAP) {
6961 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6962 					      value_regno);
6963 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6964 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6965 		u32 *max_access;
6966 
6967 		if (rdonly_mem) {
6968 			if (t == BPF_WRITE) {
6969 				verbose(env, "R%d cannot write into %s\n",
6970 					regno, reg_type_str(env, reg->type));
6971 				return -EACCES;
6972 			}
6973 			max_access = &env->prog->aux->max_rdonly_access;
6974 		} else {
6975 			max_access = &env->prog->aux->max_rdwr_access;
6976 		}
6977 
6978 		err = check_buffer_access(env, reg, regno, off, size, false,
6979 					  max_access);
6980 
6981 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6982 			mark_reg_unknown(env, regs, value_regno);
6983 	} else if (reg->type == PTR_TO_ARENA) {
6984 		if (t == BPF_READ && value_regno >= 0)
6985 			mark_reg_unknown(env, regs, value_regno);
6986 	} else {
6987 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6988 			reg_type_str(env, reg->type));
6989 		return -EACCES;
6990 	}
6991 
6992 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6993 	    regs[value_regno].type == SCALAR_VALUE) {
6994 		if (!is_ldsx)
6995 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6996 			coerce_reg_to_size(&regs[value_regno], size);
6997 		else
6998 			coerce_reg_to_size_sx(&regs[value_regno], size);
6999 	}
7000 	return err;
7001 }
7002 
7003 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7004 			     bool allow_trust_mismatch);
7005 
7006 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
7007 {
7008 	int load_reg;
7009 	int err;
7010 
7011 	switch (insn->imm) {
7012 	case BPF_ADD:
7013 	case BPF_ADD | BPF_FETCH:
7014 	case BPF_AND:
7015 	case BPF_AND | BPF_FETCH:
7016 	case BPF_OR:
7017 	case BPF_OR | BPF_FETCH:
7018 	case BPF_XOR:
7019 	case BPF_XOR | BPF_FETCH:
7020 	case BPF_XCHG:
7021 	case BPF_CMPXCHG:
7022 		break;
7023 	default:
7024 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
7025 		return -EINVAL;
7026 	}
7027 
7028 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7029 		verbose(env, "invalid atomic operand size\n");
7030 		return -EINVAL;
7031 	}
7032 
7033 	/* check src1 operand */
7034 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7035 	if (err)
7036 		return err;
7037 
7038 	/* check src2 operand */
7039 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7040 	if (err)
7041 		return err;
7042 
7043 	if (insn->imm == BPF_CMPXCHG) {
7044 		/* Check comparison of R0 with memory location */
7045 		const u32 aux_reg = BPF_REG_0;
7046 
7047 		err = check_reg_arg(env, aux_reg, SRC_OP);
7048 		if (err)
7049 			return err;
7050 
7051 		if (is_pointer_value(env, aux_reg)) {
7052 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7053 			return -EACCES;
7054 		}
7055 	}
7056 
7057 	if (is_pointer_value(env, insn->src_reg)) {
7058 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7059 		return -EACCES;
7060 	}
7061 
7062 	if (is_ctx_reg(env, insn->dst_reg) ||
7063 	    is_pkt_reg(env, insn->dst_reg) ||
7064 	    is_flow_key_reg(env, insn->dst_reg) ||
7065 	    is_sk_reg(env, insn->dst_reg) ||
7066 	    (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) {
7067 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7068 			insn->dst_reg,
7069 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7070 		return -EACCES;
7071 	}
7072 
7073 	if (insn->imm & BPF_FETCH) {
7074 		if (insn->imm == BPF_CMPXCHG)
7075 			load_reg = BPF_REG_0;
7076 		else
7077 			load_reg = insn->src_reg;
7078 
7079 		/* check and record load of old value */
7080 		err = check_reg_arg(env, load_reg, DST_OP);
7081 		if (err)
7082 			return err;
7083 	} else {
7084 		/* This instruction accesses a memory location but doesn't
7085 		 * actually load it into a register.
7086 		 */
7087 		load_reg = -1;
7088 	}
7089 
7090 	/* Check whether we can read the memory, with second call for fetch
7091 	 * case to simulate the register fill.
7092 	 */
7093 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7094 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7095 	if (!err && load_reg >= 0)
7096 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7097 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7098 				       true, false);
7099 	if (err)
7100 		return err;
7101 
7102 	if (is_arena_reg(env, insn->dst_reg)) {
7103 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7104 		if (err)
7105 			return err;
7106 	}
7107 	/* Check whether we can write into the same memory. */
7108 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7109 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7110 	if (err)
7111 		return err;
7112 	return 0;
7113 }
7114 
7115 /* When register 'regno' is used to read the stack (either directly or through
7116  * a helper function) make sure that it's within stack boundary and, depending
7117  * on the access type and privileges, that all elements of the stack are
7118  * initialized.
7119  *
7120  * 'off' includes 'regno->off', but not its dynamic part (if any).
7121  *
7122  * All registers that have been spilled on the stack in the slots within the
7123  * read offsets are marked as read.
7124  */
7125 static int check_stack_range_initialized(
7126 		struct bpf_verifier_env *env, int regno, int off,
7127 		int access_size, bool zero_size_allowed,
7128 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7129 {
7130 	struct bpf_reg_state *reg = reg_state(env, regno);
7131 	struct bpf_func_state *state = func(env, reg);
7132 	int err, min_off, max_off, i, j, slot, spi;
7133 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7134 	enum bpf_access_type bounds_check_type;
7135 	/* Some accesses can write anything into the stack, others are
7136 	 * read-only.
7137 	 */
7138 	bool clobber = false;
7139 
7140 	if (access_size == 0 && !zero_size_allowed) {
7141 		verbose(env, "invalid zero-sized read\n");
7142 		return -EACCES;
7143 	}
7144 
7145 	if (type == ACCESS_HELPER) {
7146 		/* The bounds checks for writes are more permissive than for
7147 		 * reads. However, if raw_mode is not set, we'll do extra
7148 		 * checks below.
7149 		 */
7150 		bounds_check_type = BPF_WRITE;
7151 		clobber = true;
7152 	} else {
7153 		bounds_check_type = BPF_READ;
7154 	}
7155 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7156 					       type, bounds_check_type);
7157 	if (err)
7158 		return err;
7159 
7160 
7161 	if (tnum_is_const(reg->var_off)) {
7162 		min_off = max_off = reg->var_off.value + off;
7163 	} else {
7164 		/* Variable offset is prohibited for unprivileged mode for
7165 		 * simplicity since it requires corresponding support in
7166 		 * Spectre masking for stack ALU.
7167 		 * See also retrieve_ptr_limit().
7168 		 */
7169 		if (!env->bypass_spec_v1) {
7170 			char tn_buf[48];
7171 
7172 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7173 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7174 				regno, err_extra, tn_buf);
7175 			return -EACCES;
7176 		}
7177 		/* Only initialized buffer on stack is allowed to be accessed
7178 		 * with variable offset. With uninitialized buffer it's hard to
7179 		 * guarantee that whole memory is marked as initialized on
7180 		 * helper return since specific bounds are unknown what may
7181 		 * cause uninitialized stack leaking.
7182 		 */
7183 		if (meta && meta->raw_mode)
7184 			meta = NULL;
7185 
7186 		min_off = reg->smin_value + off;
7187 		max_off = reg->smax_value + off;
7188 	}
7189 
7190 	if (meta && meta->raw_mode) {
7191 		/* Ensure we won't be overwriting dynptrs when simulating byte
7192 		 * by byte access in check_helper_call using meta.access_size.
7193 		 * This would be a problem if we have a helper in the future
7194 		 * which takes:
7195 		 *
7196 		 *	helper(uninit_mem, len, dynptr)
7197 		 *
7198 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7199 		 * may end up writing to dynptr itself when touching memory from
7200 		 * arg 1. This can be relaxed on a case by case basis for known
7201 		 * safe cases, but reject due to the possibilitiy of aliasing by
7202 		 * default.
7203 		 */
7204 		for (i = min_off; i < max_off + access_size; i++) {
7205 			int stack_off = -i - 1;
7206 
7207 			spi = __get_spi(i);
7208 			/* raw_mode may write past allocated_stack */
7209 			if (state->allocated_stack <= stack_off)
7210 				continue;
7211 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7212 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7213 				return -EACCES;
7214 			}
7215 		}
7216 		meta->access_size = access_size;
7217 		meta->regno = regno;
7218 		return 0;
7219 	}
7220 
7221 	for (i = min_off; i < max_off + access_size; i++) {
7222 		u8 *stype;
7223 
7224 		slot = -i - 1;
7225 		spi = slot / BPF_REG_SIZE;
7226 		if (state->allocated_stack <= slot) {
7227 			verbose(env, "verifier bug: allocated_stack too small");
7228 			return -EFAULT;
7229 		}
7230 
7231 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7232 		if (*stype == STACK_MISC)
7233 			goto mark;
7234 		if ((*stype == STACK_ZERO) ||
7235 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7236 			if (clobber) {
7237 				/* helper can write anything into the stack */
7238 				*stype = STACK_MISC;
7239 			}
7240 			goto mark;
7241 		}
7242 
7243 		if (is_spilled_reg(&state->stack[spi]) &&
7244 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7245 		     env->allow_ptr_leaks)) {
7246 			if (clobber) {
7247 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7248 				for (j = 0; j < BPF_REG_SIZE; j++)
7249 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7250 			}
7251 			goto mark;
7252 		}
7253 
7254 		if (tnum_is_const(reg->var_off)) {
7255 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7256 				err_extra, regno, min_off, i - min_off, access_size);
7257 		} else {
7258 			char tn_buf[48];
7259 
7260 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7261 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7262 				err_extra, regno, tn_buf, i - min_off, access_size);
7263 		}
7264 		return -EACCES;
7265 mark:
7266 		/* reading any byte out of 8-byte 'spill_slot' will cause
7267 		 * the whole slot to be marked as 'read'
7268 		 */
7269 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7270 			      state->stack[spi].spilled_ptr.parent,
7271 			      REG_LIVE_READ64);
7272 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7273 		 * be sure that whether stack slot is written to or not. Hence,
7274 		 * we must still conservatively propagate reads upwards even if
7275 		 * helper may write to the entire memory range.
7276 		 */
7277 	}
7278 	return 0;
7279 }
7280 
7281 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7282 				   int access_size, bool zero_size_allowed,
7283 				   struct bpf_call_arg_meta *meta)
7284 {
7285 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7286 	u32 *max_access;
7287 
7288 	switch (base_type(reg->type)) {
7289 	case PTR_TO_PACKET:
7290 	case PTR_TO_PACKET_META:
7291 		return check_packet_access(env, regno, reg->off, access_size,
7292 					   zero_size_allowed);
7293 	case PTR_TO_MAP_KEY:
7294 		if (meta && meta->raw_mode) {
7295 			verbose(env, "R%d cannot write into %s\n", regno,
7296 				reg_type_str(env, reg->type));
7297 			return -EACCES;
7298 		}
7299 		return check_mem_region_access(env, regno, reg->off, access_size,
7300 					       reg->map_ptr->key_size, false);
7301 	case PTR_TO_MAP_VALUE:
7302 		if (check_map_access_type(env, regno, reg->off, access_size,
7303 					  meta && meta->raw_mode ? BPF_WRITE :
7304 					  BPF_READ))
7305 			return -EACCES;
7306 		return check_map_access(env, regno, reg->off, access_size,
7307 					zero_size_allowed, ACCESS_HELPER);
7308 	case PTR_TO_MEM:
7309 		if (type_is_rdonly_mem(reg->type)) {
7310 			if (meta && meta->raw_mode) {
7311 				verbose(env, "R%d cannot write into %s\n", regno,
7312 					reg_type_str(env, reg->type));
7313 				return -EACCES;
7314 			}
7315 		}
7316 		return check_mem_region_access(env, regno, reg->off,
7317 					       access_size, reg->mem_size,
7318 					       zero_size_allowed);
7319 	case PTR_TO_BUF:
7320 		if (type_is_rdonly_mem(reg->type)) {
7321 			if (meta && meta->raw_mode) {
7322 				verbose(env, "R%d cannot write into %s\n", regno,
7323 					reg_type_str(env, reg->type));
7324 				return -EACCES;
7325 			}
7326 
7327 			max_access = &env->prog->aux->max_rdonly_access;
7328 		} else {
7329 			max_access = &env->prog->aux->max_rdwr_access;
7330 		}
7331 		return check_buffer_access(env, reg, regno, reg->off,
7332 					   access_size, zero_size_allowed,
7333 					   max_access);
7334 	case PTR_TO_STACK:
7335 		return check_stack_range_initialized(
7336 				env,
7337 				regno, reg->off, access_size,
7338 				zero_size_allowed, ACCESS_HELPER, meta);
7339 	case PTR_TO_BTF_ID:
7340 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7341 					       access_size, BPF_READ, -1);
7342 	case PTR_TO_CTX:
7343 		/* in case the function doesn't know how to access the context,
7344 		 * (because we are in a program of type SYSCALL for example), we
7345 		 * can not statically check its size.
7346 		 * Dynamically check it now.
7347 		 */
7348 		if (!env->ops->convert_ctx_access) {
7349 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7350 			int offset = access_size - 1;
7351 
7352 			/* Allow zero-byte read from PTR_TO_CTX */
7353 			if (access_size == 0)
7354 				return zero_size_allowed ? 0 : -EACCES;
7355 
7356 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7357 						atype, -1, false, false);
7358 		}
7359 
7360 		fallthrough;
7361 	default: /* scalar_value or invalid ptr */
7362 		/* Allow zero-byte read from NULL, regardless of pointer type */
7363 		if (zero_size_allowed && access_size == 0 &&
7364 		    register_is_null(reg))
7365 			return 0;
7366 
7367 		verbose(env, "R%d type=%s ", regno,
7368 			reg_type_str(env, reg->type));
7369 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7370 		return -EACCES;
7371 	}
7372 }
7373 
7374 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7375  * size.
7376  *
7377  * @regno is the register containing the access size. regno-1 is the register
7378  * containing the pointer.
7379  */
7380 static int check_mem_size_reg(struct bpf_verifier_env *env,
7381 			      struct bpf_reg_state *reg, u32 regno,
7382 			      bool zero_size_allowed,
7383 			      struct bpf_call_arg_meta *meta)
7384 {
7385 	int err;
7386 
7387 	/* This is used to refine r0 return value bounds for helpers
7388 	 * that enforce this value as an upper bound on return values.
7389 	 * See do_refine_retval_range() for helpers that can refine
7390 	 * the return value. C type of helper is u32 so we pull register
7391 	 * bound from umax_value however, if negative verifier errors
7392 	 * out. Only upper bounds can be learned because retval is an
7393 	 * int type and negative retvals are allowed.
7394 	 */
7395 	meta->msize_max_value = reg->umax_value;
7396 
7397 	/* The register is SCALAR_VALUE; the access check
7398 	 * happens using its boundaries.
7399 	 */
7400 	if (!tnum_is_const(reg->var_off))
7401 		/* For unprivileged variable accesses, disable raw
7402 		 * mode so that the program is required to
7403 		 * initialize all the memory that the helper could
7404 		 * just partially fill up.
7405 		 */
7406 		meta = NULL;
7407 
7408 	if (reg->smin_value < 0) {
7409 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7410 			regno);
7411 		return -EACCES;
7412 	}
7413 
7414 	if (reg->umin_value == 0 && !zero_size_allowed) {
7415 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7416 			regno, reg->umin_value, reg->umax_value);
7417 		return -EACCES;
7418 	}
7419 
7420 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7421 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7422 			regno);
7423 		return -EACCES;
7424 	}
7425 	err = check_helper_mem_access(env, regno - 1,
7426 				      reg->umax_value,
7427 				      zero_size_allowed, meta);
7428 	if (!err)
7429 		err = mark_chain_precision(env, regno);
7430 	return err;
7431 }
7432 
7433 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7434 			 u32 regno, u32 mem_size)
7435 {
7436 	bool may_be_null = type_may_be_null(reg->type);
7437 	struct bpf_reg_state saved_reg;
7438 	struct bpf_call_arg_meta meta;
7439 	int err;
7440 
7441 	if (register_is_null(reg))
7442 		return 0;
7443 
7444 	memset(&meta, 0, sizeof(meta));
7445 	/* Assuming that the register contains a value check if the memory
7446 	 * access is safe. Temporarily save and restore the register's state as
7447 	 * the conversion shouldn't be visible to a caller.
7448 	 */
7449 	if (may_be_null) {
7450 		saved_reg = *reg;
7451 		mark_ptr_not_null_reg(reg);
7452 	}
7453 
7454 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7455 	/* Check access for BPF_WRITE */
7456 	meta.raw_mode = true;
7457 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7458 
7459 	if (may_be_null)
7460 		*reg = saved_reg;
7461 
7462 	return err;
7463 }
7464 
7465 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7466 				    u32 regno)
7467 {
7468 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7469 	bool may_be_null = type_may_be_null(mem_reg->type);
7470 	struct bpf_reg_state saved_reg;
7471 	struct bpf_call_arg_meta meta;
7472 	int err;
7473 
7474 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7475 
7476 	memset(&meta, 0, sizeof(meta));
7477 
7478 	if (may_be_null) {
7479 		saved_reg = *mem_reg;
7480 		mark_ptr_not_null_reg(mem_reg);
7481 	}
7482 
7483 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7484 	/* Check access for BPF_WRITE */
7485 	meta.raw_mode = true;
7486 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7487 
7488 	if (may_be_null)
7489 		*mem_reg = saved_reg;
7490 	return err;
7491 }
7492 
7493 /* Implementation details:
7494  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7495  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7496  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7497  * Two separate bpf_obj_new will also have different reg->id.
7498  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7499  * clears reg->id after value_or_null->value transition, since the verifier only
7500  * cares about the range of access to valid map value pointer and doesn't care
7501  * about actual address of the map element.
7502  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7503  * reg->id > 0 after value_or_null->value transition. By doing so
7504  * two bpf_map_lookups will be considered two different pointers that
7505  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7506  * returned from bpf_obj_new.
7507  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7508  * dead-locks.
7509  * Since only one bpf_spin_lock is allowed the checks are simpler than
7510  * reg_is_refcounted() logic. The verifier needs to remember only
7511  * one spin_lock instead of array of acquired_refs.
7512  * cur_state->active_lock remembers which map value element or allocated
7513  * object got locked and clears it after bpf_spin_unlock.
7514  */
7515 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7516 			     bool is_lock)
7517 {
7518 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7519 	struct bpf_verifier_state *cur = env->cur_state;
7520 	bool is_const = tnum_is_const(reg->var_off);
7521 	u64 val = reg->var_off.value;
7522 	struct bpf_map *map = NULL;
7523 	struct btf *btf = NULL;
7524 	struct btf_record *rec;
7525 
7526 	if (!is_const) {
7527 		verbose(env,
7528 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7529 			regno);
7530 		return -EINVAL;
7531 	}
7532 	if (reg->type == PTR_TO_MAP_VALUE) {
7533 		map = reg->map_ptr;
7534 		if (!map->btf) {
7535 			verbose(env,
7536 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7537 				map->name);
7538 			return -EINVAL;
7539 		}
7540 	} else {
7541 		btf = reg->btf;
7542 	}
7543 
7544 	rec = reg_btf_record(reg);
7545 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7546 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7547 			map ? map->name : "kptr");
7548 		return -EINVAL;
7549 	}
7550 	if (rec->spin_lock_off != val + reg->off) {
7551 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7552 			val + reg->off, rec->spin_lock_off);
7553 		return -EINVAL;
7554 	}
7555 	if (is_lock) {
7556 		if (cur->active_lock.ptr) {
7557 			verbose(env,
7558 				"Locking two bpf_spin_locks are not allowed\n");
7559 			return -EINVAL;
7560 		}
7561 		if (map)
7562 			cur->active_lock.ptr = map;
7563 		else
7564 			cur->active_lock.ptr = btf;
7565 		cur->active_lock.id = reg->id;
7566 	} else {
7567 		void *ptr;
7568 
7569 		if (map)
7570 			ptr = map;
7571 		else
7572 			ptr = btf;
7573 
7574 		if (!cur->active_lock.ptr) {
7575 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7576 			return -EINVAL;
7577 		}
7578 		if (cur->active_lock.ptr != ptr ||
7579 		    cur->active_lock.id != reg->id) {
7580 			verbose(env, "bpf_spin_unlock of different lock\n");
7581 			return -EINVAL;
7582 		}
7583 
7584 		invalidate_non_owning_refs(env);
7585 
7586 		cur->active_lock.ptr = NULL;
7587 		cur->active_lock.id = 0;
7588 	}
7589 	return 0;
7590 }
7591 
7592 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7593 			      struct bpf_call_arg_meta *meta)
7594 {
7595 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7596 	bool is_const = tnum_is_const(reg->var_off);
7597 	struct bpf_map *map = reg->map_ptr;
7598 	u64 val = reg->var_off.value;
7599 
7600 	if (!is_const) {
7601 		verbose(env,
7602 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7603 			regno);
7604 		return -EINVAL;
7605 	}
7606 	if (!map->btf) {
7607 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7608 			map->name);
7609 		return -EINVAL;
7610 	}
7611 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7612 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7613 		return -EINVAL;
7614 	}
7615 	if (map->record->timer_off != val + reg->off) {
7616 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7617 			val + reg->off, map->record->timer_off);
7618 		return -EINVAL;
7619 	}
7620 	if (meta->map_ptr) {
7621 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7622 		return -EFAULT;
7623 	}
7624 	meta->map_uid = reg->map_uid;
7625 	meta->map_ptr = map;
7626 	return 0;
7627 }
7628 
7629 static int process_wq_func(struct bpf_verifier_env *env, int regno,
7630 			   struct bpf_kfunc_call_arg_meta *meta)
7631 {
7632 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7633 	struct bpf_map *map = reg->map_ptr;
7634 	u64 val = reg->var_off.value;
7635 
7636 	if (map->record->wq_off != val + reg->off) {
7637 		verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
7638 			val + reg->off, map->record->wq_off);
7639 		return -EINVAL;
7640 	}
7641 	meta->map.uid = reg->map_uid;
7642 	meta->map.ptr = map;
7643 	return 0;
7644 }
7645 
7646 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7647 			     struct bpf_call_arg_meta *meta)
7648 {
7649 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7650 	struct bpf_map *map_ptr = reg->map_ptr;
7651 	struct btf_field *kptr_field;
7652 	u32 kptr_off;
7653 
7654 	if (!tnum_is_const(reg->var_off)) {
7655 		verbose(env,
7656 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7657 			regno);
7658 		return -EINVAL;
7659 	}
7660 	if (!map_ptr->btf) {
7661 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7662 			map_ptr->name);
7663 		return -EINVAL;
7664 	}
7665 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7666 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7667 		return -EINVAL;
7668 	}
7669 
7670 	meta->map_ptr = map_ptr;
7671 	kptr_off = reg->off + reg->var_off.value;
7672 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7673 	if (!kptr_field) {
7674 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7675 		return -EACCES;
7676 	}
7677 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7678 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7679 		return -EACCES;
7680 	}
7681 	meta->kptr_field = kptr_field;
7682 	return 0;
7683 }
7684 
7685 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7686  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7687  *
7688  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7689  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7690  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7691  *
7692  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7693  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7694  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7695  * mutate the view of the dynptr and also possibly destroy it. In the latter
7696  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7697  * memory that dynptr points to.
7698  *
7699  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7700  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7701  * readonly dynptr view yet, hence only the first case is tracked and checked.
7702  *
7703  * This is consistent with how C applies the const modifier to a struct object,
7704  * where the pointer itself inside bpf_dynptr becomes const but not what it
7705  * points to.
7706  *
7707  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7708  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7709  */
7710 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7711 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7712 {
7713 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7714 	int err;
7715 
7716 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7717 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7718 	 */
7719 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7720 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7721 		return -EFAULT;
7722 	}
7723 
7724 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7725 	 *		 constructing a mutable bpf_dynptr object.
7726 	 *
7727 	 *		 Currently, this is only possible with PTR_TO_STACK
7728 	 *		 pointing to a region of at least 16 bytes which doesn't
7729 	 *		 contain an existing bpf_dynptr.
7730 	 *
7731 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7732 	 *		 mutated or destroyed. However, the memory it points to
7733 	 *		 may be mutated.
7734 	 *
7735 	 *  None       - Points to a initialized dynptr that can be mutated and
7736 	 *		 destroyed, including mutation of the memory it points
7737 	 *		 to.
7738 	 */
7739 	if (arg_type & MEM_UNINIT) {
7740 		int i;
7741 
7742 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7743 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7744 			return -EINVAL;
7745 		}
7746 
7747 		/* we write BPF_DW bits (8 bytes) at a time */
7748 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7749 			err = check_mem_access(env, insn_idx, regno,
7750 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7751 			if (err)
7752 				return err;
7753 		}
7754 
7755 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7756 	} else /* MEM_RDONLY and None case from above */ {
7757 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7758 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7759 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7760 			return -EINVAL;
7761 		}
7762 
7763 		if (!is_dynptr_reg_valid_init(env, reg)) {
7764 			verbose(env,
7765 				"Expected an initialized dynptr as arg #%d\n",
7766 				regno);
7767 			return -EINVAL;
7768 		}
7769 
7770 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7771 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7772 			verbose(env,
7773 				"Expected a dynptr of type %s as arg #%d\n",
7774 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7775 			return -EINVAL;
7776 		}
7777 
7778 		err = mark_dynptr_read(env, reg);
7779 	}
7780 	return err;
7781 }
7782 
7783 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7784 {
7785 	struct bpf_func_state *state = func(env, reg);
7786 
7787 	return state->stack[spi].spilled_ptr.ref_obj_id;
7788 }
7789 
7790 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7791 {
7792 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7793 }
7794 
7795 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7796 {
7797 	return meta->kfunc_flags & KF_ITER_NEW;
7798 }
7799 
7800 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7801 {
7802 	return meta->kfunc_flags & KF_ITER_NEXT;
7803 }
7804 
7805 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7806 {
7807 	return meta->kfunc_flags & KF_ITER_DESTROY;
7808 }
7809 
7810 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7811 {
7812 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7813 	 * kfunc is iter state pointer
7814 	 */
7815 	return arg == 0 && is_iter_kfunc(meta);
7816 }
7817 
7818 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7819 			    struct bpf_kfunc_call_arg_meta *meta)
7820 {
7821 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7822 	const struct btf_type *t;
7823 	const struct btf_param *arg;
7824 	int spi, err, i, nr_slots;
7825 	u32 btf_id;
7826 
7827 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7828 	arg = &btf_params(meta->func_proto)[0];
7829 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7830 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7831 	nr_slots = t->size / BPF_REG_SIZE;
7832 
7833 	if (is_iter_new_kfunc(meta)) {
7834 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7835 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7836 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7837 				iter_type_str(meta->btf, btf_id), regno);
7838 			return -EINVAL;
7839 		}
7840 
7841 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7842 			err = check_mem_access(env, insn_idx, regno,
7843 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7844 			if (err)
7845 				return err;
7846 		}
7847 
7848 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7849 		if (err)
7850 			return err;
7851 	} else {
7852 		/* iter_next() or iter_destroy() expect initialized iter state*/
7853 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7854 		switch (err) {
7855 		case 0:
7856 			break;
7857 		case -EINVAL:
7858 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7859 				iter_type_str(meta->btf, btf_id), regno);
7860 			return err;
7861 		case -EPROTO:
7862 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7863 			return err;
7864 		default:
7865 			return err;
7866 		}
7867 
7868 		spi = iter_get_spi(env, reg, nr_slots);
7869 		if (spi < 0)
7870 			return spi;
7871 
7872 		err = mark_iter_read(env, reg, spi, nr_slots);
7873 		if (err)
7874 			return err;
7875 
7876 		/* remember meta->iter info for process_iter_next_call() */
7877 		meta->iter.spi = spi;
7878 		meta->iter.frameno = reg->frameno;
7879 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7880 
7881 		if (is_iter_destroy_kfunc(meta)) {
7882 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7883 			if (err)
7884 				return err;
7885 		}
7886 	}
7887 
7888 	return 0;
7889 }
7890 
7891 /* Look for a previous loop entry at insn_idx: nearest parent state
7892  * stopped at insn_idx with callsites matching those in cur->frame.
7893  */
7894 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7895 						  struct bpf_verifier_state *cur,
7896 						  int insn_idx)
7897 {
7898 	struct bpf_verifier_state_list *sl;
7899 	struct bpf_verifier_state *st;
7900 
7901 	/* Explored states are pushed in stack order, most recent states come first */
7902 	sl = *explored_state(env, insn_idx);
7903 	for (; sl; sl = sl->next) {
7904 		/* If st->branches != 0 state is a part of current DFS verification path,
7905 		 * hence cur & st for a loop.
7906 		 */
7907 		st = &sl->state;
7908 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7909 		    st->dfs_depth < cur->dfs_depth)
7910 			return st;
7911 	}
7912 
7913 	return NULL;
7914 }
7915 
7916 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7917 static bool regs_exact(const struct bpf_reg_state *rold,
7918 		       const struct bpf_reg_state *rcur,
7919 		       struct bpf_idmap *idmap);
7920 
7921 static void maybe_widen_reg(struct bpf_verifier_env *env,
7922 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7923 			    struct bpf_idmap *idmap)
7924 {
7925 	if (rold->type != SCALAR_VALUE)
7926 		return;
7927 	if (rold->type != rcur->type)
7928 		return;
7929 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7930 		return;
7931 	__mark_reg_unknown(env, rcur);
7932 }
7933 
7934 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7935 				   struct bpf_verifier_state *old,
7936 				   struct bpf_verifier_state *cur)
7937 {
7938 	struct bpf_func_state *fold, *fcur;
7939 	int i, fr;
7940 
7941 	reset_idmap_scratch(env);
7942 	for (fr = old->curframe; fr >= 0; fr--) {
7943 		fold = old->frame[fr];
7944 		fcur = cur->frame[fr];
7945 
7946 		for (i = 0; i < MAX_BPF_REG; i++)
7947 			maybe_widen_reg(env,
7948 					&fold->regs[i],
7949 					&fcur->regs[i],
7950 					&env->idmap_scratch);
7951 
7952 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7953 			if (!is_spilled_reg(&fold->stack[i]) ||
7954 			    !is_spilled_reg(&fcur->stack[i]))
7955 				continue;
7956 
7957 			maybe_widen_reg(env,
7958 					&fold->stack[i].spilled_ptr,
7959 					&fcur->stack[i].spilled_ptr,
7960 					&env->idmap_scratch);
7961 		}
7962 	}
7963 	return 0;
7964 }
7965 
7966 /* process_iter_next_call() is called when verifier gets to iterator's next
7967  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7968  * to it as just "iter_next()" in comments below.
7969  *
7970  * BPF verifier relies on a crucial contract for any iter_next()
7971  * implementation: it should *eventually* return NULL, and once that happens
7972  * it should keep returning NULL. That is, once iterator exhausts elements to
7973  * iterate, it should never reset or spuriously return new elements.
7974  *
7975  * With the assumption of such contract, process_iter_next_call() simulates
7976  * a fork in the verifier state to validate loop logic correctness and safety
7977  * without having to simulate infinite amount of iterations.
7978  *
7979  * In current state, we first assume that iter_next() returned NULL and
7980  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7981  * conditions we should not form an infinite loop and should eventually reach
7982  * exit.
7983  *
7984  * Besides that, we also fork current state and enqueue it for later
7985  * verification. In a forked state we keep iterator state as ACTIVE
7986  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7987  * also bump iteration depth to prevent erroneous infinite loop detection
7988  * later on (see iter_active_depths_differ() comment for details). In this
7989  * state we assume that we'll eventually loop back to another iter_next()
7990  * calls (it could be in exactly same location or in some other instruction,
7991  * it doesn't matter, we don't make any unnecessary assumptions about this,
7992  * everything revolves around iterator state in a stack slot, not which
7993  * instruction is calling iter_next()). When that happens, we either will come
7994  * to iter_next() with equivalent state and can conclude that next iteration
7995  * will proceed in exactly the same way as we just verified, so it's safe to
7996  * assume that loop converges. If not, we'll go on another iteration
7997  * simulation with a different input state, until all possible starting states
7998  * are validated or we reach maximum number of instructions limit.
7999  *
8000  * This way, we will either exhaustively discover all possible input states
8001  * that iterator loop can start with and eventually will converge, or we'll
8002  * effectively regress into bounded loop simulation logic and either reach
8003  * maximum number of instructions if loop is not provably convergent, or there
8004  * is some statically known limit on number of iterations (e.g., if there is
8005  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8006  *
8007  * Iteration convergence logic in is_state_visited() relies on exact
8008  * states comparison, which ignores read and precision marks.
8009  * This is necessary because read and precision marks are not finalized
8010  * while in the loop. Exact comparison might preclude convergence for
8011  * simple programs like below:
8012  *
8013  *     i = 0;
8014  *     while(iter_next(&it))
8015  *       i++;
8016  *
8017  * At each iteration step i++ would produce a new distinct state and
8018  * eventually instruction processing limit would be reached.
8019  *
8020  * To avoid such behavior speculatively forget (widen) range for
8021  * imprecise scalar registers, if those registers were not precise at the
8022  * end of the previous iteration and do not match exactly.
8023  *
8024  * This is a conservative heuristic that allows to verify wide range of programs,
8025  * however it precludes verification of programs that conjure an
8026  * imprecise value on the first loop iteration and use it as precise on a second.
8027  * For example, the following safe program would fail to verify:
8028  *
8029  *     struct bpf_num_iter it;
8030  *     int arr[10];
8031  *     int i = 0, a = 0;
8032  *     bpf_iter_num_new(&it, 0, 10);
8033  *     while (bpf_iter_num_next(&it)) {
8034  *       if (a == 0) {
8035  *         a = 1;
8036  *         i = 7; // Because i changed verifier would forget
8037  *                // it's range on second loop entry.
8038  *       } else {
8039  *         arr[i] = 42; // This would fail to verify.
8040  *       }
8041  *     }
8042  *     bpf_iter_num_destroy(&it);
8043  */
8044 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8045 				  struct bpf_kfunc_call_arg_meta *meta)
8046 {
8047 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8048 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8049 	struct bpf_reg_state *cur_iter, *queued_iter;
8050 	int iter_frameno = meta->iter.frameno;
8051 	int iter_spi = meta->iter.spi;
8052 
8053 	BTF_TYPE_EMIT(struct bpf_iter);
8054 
8055 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8056 
8057 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8058 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8059 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
8060 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8061 		return -EFAULT;
8062 	}
8063 
8064 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8065 		/* Because iter_next() call is a checkpoint is_state_visitied()
8066 		 * should guarantee parent state with same call sites and insn_idx.
8067 		 */
8068 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8069 		    !same_callsites(cur_st->parent, cur_st)) {
8070 			verbose(env, "bug: bad parent state for iter next call");
8071 			return -EFAULT;
8072 		}
8073 		/* Note cur_st->parent in the call below, it is necessary to skip
8074 		 * checkpoint created for cur_st by is_state_visited()
8075 		 * right at this instruction.
8076 		 */
8077 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8078 		/* branch out active iter state */
8079 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8080 		if (!queued_st)
8081 			return -ENOMEM;
8082 
8083 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8084 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8085 		queued_iter->iter.depth++;
8086 		if (prev_st)
8087 			widen_imprecise_scalars(env, prev_st, queued_st);
8088 
8089 		queued_fr = queued_st->frame[queued_st->curframe];
8090 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8091 	}
8092 
8093 	/* switch to DRAINED state, but keep the depth unchanged */
8094 	/* mark current iter state as drained and assume returned NULL */
8095 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8096 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8097 
8098 	return 0;
8099 }
8100 
8101 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8102 {
8103 	return type == ARG_CONST_SIZE ||
8104 	       type == ARG_CONST_SIZE_OR_ZERO;
8105 }
8106 
8107 static bool arg_type_is_release(enum bpf_arg_type type)
8108 {
8109 	return type & OBJ_RELEASE;
8110 }
8111 
8112 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8113 {
8114 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8115 }
8116 
8117 static int int_ptr_type_to_size(enum bpf_arg_type type)
8118 {
8119 	if (type == ARG_PTR_TO_INT)
8120 		return sizeof(u32);
8121 	else if (type == ARG_PTR_TO_LONG)
8122 		return sizeof(u64);
8123 
8124 	return -EINVAL;
8125 }
8126 
8127 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8128 				 const struct bpf_call_arg_meta *meta,
8129 				 enum bpf_arg_type *arg_type)
8130 {
8131 	if (!meta->map_ptr) {
8132 		/* kernel subsystem misconfigured verifier */
8133 		verbose(env, "invalid map_ptr to access map->type\n");
8134 		return -EACCES;
8135 	}
8136 
8137 	switch (meta->map_ptr->map_type) {
8138 	case BPF_MAP_TYPE_SOCKMAP:
8139 	case BPF_MAP_TYPE_SOCKHASH:
8140 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8141 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8142 		} else {
8143 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8144 			return -EINVAL;
8145 		}
8146 		break;
8147 	case BPF_MAP_TYPE_BLOOM_FILTER:
8148 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8149 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8150 		break;
8151 	default:
8152 		break;
8153 	}
8154 	return 0;
8155 }
8156 
8157 struct bpf_reg_types {
8158 	const enum bpf_reg_type types[10];
8159 	u32 *btf_id;
8160 };
8161 
8162 static const struct bpf_reg_types sock_types = {
8163 	.types = {
8164 		PTR_TO_SOCK_COMMON,
8165 		PTR_TO_SOCKET,
8166 		PTR_TO_TCP_SOCK,
8167 		PTR_TO_XDP_SOCK,
8168 	},
8169 };
8170 
8171 #ifdef CONFIG_NET
8172 static const struct bpf_reg_types btf_id_sock_common_types = {
8173 	.types = {
8174 		PTR_TO_SOCK_COMMON,
8175 		PTR_TO_SOCKET,
8176 		PTR_TO_TCP_SOCK,
8177 		PTR_TO_XDP_SOCK,
8178 		PTR_TO_BTF_ID,
8179 		PTR_TO_BTF_ID | PTR_TRUSTED,
8180 	},
8181 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8182 };
8183 #endif
8184 
8185 static const struct bpf_reg_types mem_types = {
8186 	.types = {
8187 		PTR_TO_STACK,
8188 		PTR_TO_PACKET,
8189 		PTR_TO_PACKET_META,
8190 		PTR_TO_MAP_KEY,
8191 		PTR_TO_MAP_VALUE,
8192 		PTR_TO_MEM,
8193 		PTR_TO_MEM | MEM_RINGBUF,
8194 		PTR_TO_BUF,
8195 		PTR_TO_BTF_ID | PTR_TRUSTED,
8196 	},
8197 };
8198 
8199 static const struct bpf_reg_types int_ptr_types = {
8200 	.types = {
8201 		PTR_TO_STACK,
8202 		PTR_TO_PACKET,
8203 		PTR_TO_PACKET_META,
8204 		PTR_TO_MAP_KEY,
8205 		PTR_TO_MAP_VALUE,
8206 	},
8207 };
8208 
8209 static const struct bpf_reg_types spin_lock_types = {
8210 	.types = {
8211 		PTR_TO_MAP_VALUE,
8212 		PTR_TO_BTF_ID | MEM_ALLOC,
8213 	}
8214 };
8215 
8216 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8217 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8218 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8219 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8220 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8221 static const struct bpf_reg_types btf_ptr_types = {
8222 	.types = {
8223 		PTR_TO_BTF_ID,
8224 		PTR_TO_BTF_ID | PTR_TRUSTED,
8225 		PTR_TO_BTF_ID | MEM_RCU,
8226 	},
8227 };
8228 static const struct bpf_reg_types percpu_btf_ptr_types = {
8229 	.types = {
8230 		PTR_TO_BTF_ID | MEM_PERCPU,
8231 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8232 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8233 	}
8234 };
8235 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8236 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8237 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8238 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8239 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8240 static const struct bpf_reg_types dynptr_types = {
8241 	.types = {
8242 		PTR_TO_STACK,
8243 		CONST_PTR_TO_DYNPTR,
8244 	}
8245 };
8246 
8247 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8248 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8249 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8250 	[ARG_CONST_SIZE]		= &scalar_types,
8251 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8252 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8253 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8254 	[ARG_PTR_TO_CTX]		= &context_types,
8255 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8256 #ifdef CONFIG_NET
8257 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8258 #endif
8259 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8260 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8261 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8262 	[ARG_PTR_TO_MEM]		= &mem_types,
8263 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8264 	[ARG_PTR_TO_INT]		= &int_ptr_types,
8265 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
8266 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8267 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8268 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8269 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8270 	[ARG_PTR_TO_TIMER]		= &timer_types,
8271 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8272 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8273 };
8274 
8275 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8276 			  enum bpf_arg_type arg_type,
8277 			  const u32 *arg_btf_id,
8278 			  struct bpf_call_arg_meta *meta)
8279 {
8280 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8281 	enum bpf_reg_type expected, type = reg->type;
8282 	const struct bpf_reg_types *compatible;
8283 	int i, j;
8284 
8285 	compatible = compatible_reg_types[base_type(arg_type)];
8286 	if (!compatible) {
8287 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8288 		return -EFAULT;
8289 	}
8290 
8291 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8292 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8293 	 *
8294 	 * Same for MAYBE_NULL:
8295 	 *
8296 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8297 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8298 	 *
8299 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8300 	 *
8301 	 * Therefore we fold these flags depending on the arg_type before comparison.
8302 	 */
8303 	if (arg_type & MEM_RDONLY)
8304 		type &= ~MEM_RDONLY;
8305 	if (arg_type & PTR_MAYBE_NULL)
8306 		type &= ~PTR_MAYBE_NULL;
8307 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8308 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8309 
8310 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
8311 		type &= ~MEM_ALLOC;
8312 		type &= ~MEM_PERCPU;
8313 	}
8314 
8315 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8316 		expected = compatible->types[i];
8317 		if (expected == NOT_INIT)
8318 			break;
8319 
8320 		if (type == expected)
8321 			goto found;
8322 	}
8323 
8324 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8325 	for (j = 0; j + 1 < i; j++)
8326 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8327 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8328 	return -EACCES;
8329 
8330 found:
8331 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8332 		return 0;
8333 
8334 	if (compatible == &mem_types) {
8335 		if (!(arg_type & MEM_RDONLY)) {
8336 			verbose(env,
8337 				"%s() may write into memory pointed by R%d type=%s\n",
8338 				func_id_name(meta->func_id),
8339 				regno, reg_type_str(env, reg->type));
8340 			return -EACCES;
8341 		}
8342 		return 0;
8343 	}
8344 
8345 	switch ((int)reg->type) {
8346 	case PTR_TO_BTF_ID:
8347 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8348 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
8349 	case PTR_TO_BTF_ID | MEM_RCU:
8350 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8351 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8352 	{
8353 		/* For bpf_sk_release, it needs to match against first member
8354 		 * 'struct sock_common', hence make an exception for it. This
8355 		 * allows bpf_sk_release to work for multiple socket types.
8356 		 */
8357 		bool strict_type_match = arg_type_is_release(arg_type) &&
8358 					 meta->func_id != BPF_FUNC_sk_release;
8359 
8360 		if (type_may_be_null(reg->type) &&
8361 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8362 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8363 			return -EACCES;
8364 		}
8365 
8366 		if (!arg_btf_id) {
8367 			if (!compatible->btf_id) {
8368 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8369 				return -EFAULT;
8370 			}
8371 			arg_btf_id = compatible->btf_id;
8372 		}
8373 
8374 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8375 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8376 				return -EACCES;
8377 		} else {
8378 			if (arg_btf_id == BPF_PTR_POISON) {
8379 				verbose(env, "verifier internal error:");
8380 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8381 					regno);
8382 				return -EACCES;
8383 			}
8384 
8385 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8386 						  btf_vmlinux, *arg_btf_id,
8387 						  strict_type_match)) {
8388 				verbose(env, "R%d is of type %s but %s is expected\n",
8389 					regno, btf_type_name(reg->btf, reg->btf_id),
8390 					btf_type_name(btf_vmlinux, *arg_btf_id));
8391 				return -EACCES;
8392 			}
8393 		}
8394 		break;
8395 	}
8396 	case PTR_TO_BTF_ID | MEM_ALLOC:
8397 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8398 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8399 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8400 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8401 			return -EFAULT;
8402 		}
8403 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8404 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8405 				return -EACCES;
8406 		}
8407 		break;
8408 	case PTR_TO_BTF_ID | MEM_PERCPU:
8409 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8410 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8411 		/* Handled by helper specific checks */
8412 		break;
8413 	default:
8414 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8415 		return -EFAULT;
8416 	}
8417 	return 0;
8418 }
8419 
8420 static struct btf_field *
8421 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8422 {
8423 	struct btf_field *field;
8424 	struct btf_record *rec;
8425 
8426 	rec = reg_btf_record(reg);
8427 	if (!rec)
8428 		return NULL;
8429 
8430 	field = btf_record_find(rec, off, fields);
8431 	if (!field)
8432 		return NULL;
8433 
8434 	return field;
8435 }
8436 
8437 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8438 				  const struct bpf_reg_state *reg, int regno,
8439 				  enum bpf_arg_type arg_type)
8440 {
8441 	u32 type = reg->type;
8442 
8443 	/* When referenced register is passed to release function, its fixed
8444 	 * offset must be 0.
8445 	 *
8446 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8447 	 * meta->release_regno.
8448 	 */
8449 	if (arg_type_is_release(arg_type)) {
8450 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8451 		 * may not directly point to the object being released, but to
8452 		 * dynptr pointing to such object, which might be at some offset
8453 		 * on the stack. In that case, we simply to fallback to the
8454 		 * default handling.
8455 		 */
8456 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8457 			return 0;
8458 
8459 		/* Doing check_ptr_off_reg check for the offset will catch this
8460 		 * because fixed_off_ok is false, but checking here allows us
8461 		 * to give the user a better error message.
8462 		 */
8463 		if (reg->off) {
8464 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8465 				regno);
8466 			return -EINVAL;
8467 		}
8468 		return __check_ptr_off_reg(env, reg, regno, false);
8469 	}
8470 
8471 	switch (type) {
8472 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8473 	case PTR_TO_STACK:
8474 	case PTR_TO_PACKET:
8475 	case PTR_TO_PACKET_META:
8476 	case PTR_TO_MAP_KEY:
8477 	case PTR_TO_MAP_VALUE:
8478 	case PTR_TO_MEM:
8479 	case PTR_TO_MEM | MEM_RDONLY:
8480 	case PTR_TO_MEM | MEM_RINGBUF:
8481 	case PTR_TO_BUF:
8482 	case PTR_TO_BUF | MEM_RDONLY:
8483 	case PTR_TO_ARENA:
8484 	case SCALAR_VALUE:
8485 		return 0;
8486 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8487 	 * fixed offset.
8488 	 */
8489 	case PTR_TO_BTF_ID:
8490 	case PTR_TO_BTF_ID | MEM_ALLOC:
8491 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8492 	case PTR_TO_BTF_ID | MEM_RCU:
8493 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8494 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8495 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8496 		 * its fixed offset must be 0. In the other cases, fixed offset
8497 		 * can be non-zero. This was already checked above. So pass
8498 		 * fixed_off_ok as true to allow fixed offset for all other
8499 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8500 		 * still need to do checks instead of returning.
8501 		 */
8502 		return __check_ptr_off_reg(env, reg, regno, true);
8503 	default:
8504 		return __check_ptr_off_reg(env, reg, regno, false);
8505 	}
8506 }
8507 
8508 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8509 						const struct bpf_func_proto *fn,
8510 						struct bpf_reg_state *regs)
8511 {
8512 	struct bpf_reg_state *state = NULL;
8513 	int i;
8514 
8515 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8516 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8517 			if (state) {
8518 				verbose(env, "verifier internal error: multiple dynptr args\n");
8519 				return NULL;
8520 			}
8521 			state = &regs[BPF_REG_1 + i];
8522 		}
8523 
8524 	if (!state)
8525 		verbose(env, "verifier internal error: no dynptr arg found\n");
8526 
8527 	return state;
8528 }
8529 
8530 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8531 {
8532 	struct bpf_func_state *state = func(env, reg);
8533 	int spi;
8534 
8535 	if (reg->type == CONST_PTR_TO_DYNPTR)
8536 		return reg->id;
8537 	spi = dynptr_get_spi(env, reg);
8538 	if (spi < 0)
8539 		return spi;
8540 	return state->stack[spi].spilled_ptr.id;
8541 }
8542 
8543 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8544 {
8545 	struct bpf_func_state *state = func(env, reg);
8546 	int spi;
8547 
8548 	if (reg->type == CONST_PTR_TO_DYNPTR)
8549 		return reg->ref_obj_id;
8550 	spi = dynptr_get_spi(env, reg);
8551 	if (spi < 0)
8552 		return spi;
8553 	return state->stack[spi].spilled_ptr.ref_obj_id;
8554 }
8555 
8556 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8557 					    struct bpf_reg_state *reg)
8558 {
8559 	struct bpf_func_state *state = func(env, reg);
8560 	int spi;
8561 
8562 	if (reg->type == CONST_PTR_TO_DYNPTR)
8563 		return reg->dynptr.type;
8564 
8565 	spi = __get_spi(reg->off);
8566 	if (spi < 0) {
8567 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8568 		return BPF_DYNPTR_TYPE_INVALID;
8569 	}
8570 
8571 	return state->stack[spi].spilled_ptr.dynptr.type;
8572 }
8573 
8574 static int check_reg_const_str(struct bpf_verifier_env *env,
8575 			       struct bpf_reg_state *reg, u32 regno)
8576 {
8577 	struct bpf_map *map = reg->map_ptr;
8578 	int err;
8579 	int map_off;
8580 	u64 map_addr;
8581 	char *str_ptr;
8582 
8583 	if (reg->type != PTR_TO_MAP_VALUE)
8584 		return -EINVAL;
8585 
8586 	if (!bpf_map_is_rdonly(map)) {
8587 		verbose(env, "R%d does not point to a readonly map'\n", regno);
8588 		return -EACCES;
8589 	}
8590 
8591 	if (!tnum_is_const(reg->var_off)) {
8592 		verbose(env, "R%d is not a constant address'\n", regno);
8593 		return -EACCES;
8594 	}
8595 
8596 	if (!map->ops->map_direct_value_addr) {
8597 		verbose(env, "no direct value access support for this map type\n");
8598 		return -EACCES;
8599 	}
8600 
8601 	err = check_map_access(env, regno, reg->off,
8602 			       map->value_size - reg->off, false,
8603 			       ACCESS_HELPER);
8604 	if (err)
8605 		return err;
8606 
8607 	map_off = reg->off + reg->var_off.value;
8608 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8609 	if (err) {
8610 		verbose(env, "direct value access on string failed\n");
8611 		return err;
8612 	}
8613 
8614 	str_ptr = (char *)(long)(map_addr);
8615 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8616 		verbose(env, "string is not zero-terminated\n");
8617 		return -EINVAL;
8618 	}
8619 	return 0;
8620 }
8621 
8622 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8623 			  struct bpf_call_arg_meta *meta,
8624 			  const struct bpf_func_proto *fn,
8625 			  int insn_idx)
8626 {
8627 	u32 regno = BPF_REG_1 + arg;
8628 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8629 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8630 	enum bpf_reg_type type = reg->type;
8631 	u32 *arg_btf_id = NULL;
8632 	int err = 0;
8633 
8634 	if (arg_type == ARG_DONTCARE)
8635 		return 0;
8636 
8637 	err = check_reg_arg(env, regno, SRC_OP);
8638 	if (err)
8639 		return err;
8640 
8641 	if (arg_type == ARG_ANYTHING) {
8642 		if (is_pointer_value(env, regno)) {
8643 			verbose(env, "R%d leaks addr into helper function\n",
8644 				regno);
8645 			return -EACCES;
8646 		}
8647 		return 0;
8648 	}
8649 
8650 	if (type_is_pkt_pointer(type) &&
8651 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8652 		verbose(env, "helper access to the packet is not allowed\n");
8653 		return -EACCES;
8654 	}
8655 
8656 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8657 		err = resolve_map_arg_type(env, meta, &arg_type);
8658 		if (err)
8659 			return err;
8660 	}
8661 
8662 	if (register_is_null(reg) && type_may_be_null(arg_type))
8663 		/* A NULL register has a SCALAR_VALUE type, so skip
8664 		 * type checking.
8665 		 */
8666 		goto skip_type_check;
8667 
8668 	/* arg_btf_id and arg_size are in a union. */
8669 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8670 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8671 		arg_btf_id = fn->arg_btf_id[arg];
8672 
8673 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8674 	if (err)
8675 		return err;
8676 
8677 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8678 	if (err)
8679 		return err;
8680 
8681 skip_type_check:
8682 	if (arg_type_is_release(arg_type)) {
8683 		if (arg_type_is_dynptr(arg_type)) {
8684 			struct bpf_func_state *state = func(env, reg);
8685 			int spi;
8686 
8687 			/* Only dynptr created on stack can be released, thus
8688 			 * the get_spi and stack state checks for spilled_ptr
8689 			 * should only be done before process_dynptr_func for
8690 			 * PTR_TO_STACK.
8691 			 */
8692 			if (reg->type == PTR_TO_STACK) {
8693 				spi = dynptr_get_spi(env, reg);
8694 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8695 					verbose(env, "arg %d is an unacquired reference\n", regno);
8696 					return -EINVAL;
8697 				}
8698 			} else {
8699 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8700 				return -EINVAL;
8701 			}
8702 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8703 			verbose(env, "R%d must be referenced when passed to release function\n",
8704 				regno);
8705 			return -EINVAL;
8706 		}
8707 		if (meta->release_regno) {
8708 			verbose(env, "verifier internal error: more than one release argument\n");
8709 			return -EFAULT;
8710 		}
8711 		meta->release_regno = regno;
8712 	}
8713 
8714 	if (reg->ref_obj_id) {
8715 		if (meta->ref_obj_id) {
8716 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8717 				regno, reg->ref_obj_id,
8718 				meta->ref_obj_id);
8719 			return -EFAULT;
8720 		}
8721 		meta->ref_obj_id = reg->ref_obj_id;
8722 	}
8723 
8724 	switch (base_type(arg_type)) {
8725 	case ARG_CONST_MAP_PTR:
8726 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8727 		if (meta->map_ptr) {
8728 			/* Use map_uid (which is unique id of inner map) to reject:
8729 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8730 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8731 			 * if (inner_map1 && inner_map2) {
8732 			 *     timer = bpf_map_lookup_elem(inner_map1);
8733 			 *     if (timer)
8734 			 *         // mismatch would have been allowed
8735 			 *         bpf_timer_init(timer, inner_map2);
8736 			 * }
8737 			 *
8738 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8739 			 */
8740 			if (meta->map_ptr != reg->map_ptr ||
8741 			    meta->map_uid != reg->map_uid) {
8742 				verbose(env,
8743 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8744 					meta->map_uid, reg->map_uid);
8745 				return -EINVAL;
8746 			}
8747 		}
8748 		meta->map_ptr = reg->map_ptr;
8749 		meta->map_uid = reg->map_uid;
8750 		break;
8751 	case ARG_PTR_TO_MAP_KEY:
8752 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8753 		 * check that [key, key + map->key_size) are within
8754 		 * stack limits and initialized
8755 		 */
8756 		if (!meta->map_ptr) {
8757 			/* in function declaration map_ptr must come before
8758 			 * map_key, so that it's verified and known before
8759 			 * we have to check map_key here. Otherwise it means
8760 			 * that kernel subsystem misconfigured verifier
8761 			 */
8762 			verbose(env, "invalid map_ptr to access map->key\n");
8763 			return -EACCES;
8764 		}
8765 		err = check_helper_mem_access(env, regno,
8766 					      meta->map_ptr->key_size, false,
8767 					      NULL);
8768 		break;
8769 	case ARG_PTR_TO_MAP_VALUE:
8770 		if (type_may_be_null(arg_type) && register_is_null(reg))
8771 			return 0;
8772 
8773 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8774 		 * check [value, value + map->value_size) validity
8775 		 */
8776 		if (!meta->map_ptr) {
8777 			/* kernel subsystem misconfigured verifier */
8778 			verbose(env, "invalid map_ptr to access map->value\n");
8779 			return -EACCES;
8780 		}
8781 		meta->raw_mode = arg_type & MEM_UNINIT;
8782 		err = check_helper_mem_access(env, regno,
8783 					      meta->map_ptr->value_size, false,
8784 					      meta);
8785 		break;
8786 	case ARG_PTR_TO_PERCPU_BTF_ID:
8787 		if (!reg->btf_id) {
8788 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8789 			return -EACCES;
8790 		}
8791 		meta->ret_btf = reg->btf;
8792 		meta->ret_btf_id = reg->btf_id;
8793 		break;
8794 	case ARG_PTR_TO_SPIN_LOCK:
8795 		if (in_rbtree_lock_required_cb(env)) {
8796 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8797 			return -EACCES;
8798 		}
8799 		if (meta->func_id == BPF_FUNC_spin_lock) {
8800 			err = process_spin_lock(env, regno, true);
8801 			if (err)
8802 				return err;
8803 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8804 			err = process_spin_lock(env, regno, false);
8805 			if (err)
8806 				return err;
8807 		} else {
8808 			verbose(env, "verifier internal error\n");
8809 			return -EFAULT;
8810 		}
8811 		break;
8812 	case ARG_PTR_TO_TIMER:
8813 		err = process_timer_func(env, regno, meta);
8814 		if (err)
8815 			return err;
8816 		break;
8817 	case ARG_PTR_TO_FUNC:
8818 		meta->subprogno = reg->subprogno;
8819 		break;
8820 	case ARG_PTR_TO_MEM:
8821 		/* The access to this pointer is only checked when we hit the
8822 		 * next is_mem_size argument below.
8823 		 */
8824 		meta->raw_mode = arg_type & MEM_UNINIT;
8825 		if (arg_type & MEM_FIXED_SIZE) {
8826 			err = check_helper_mem_access(env, regno,
8827 						      fn->arg_size[arg], false,
8828 						      meta);
8829 		}
8830 		break;
8831 	case ARG_CONST_SIZE:
8832 		err = check_mem_size_reg(env, reg, regno, false, meta);
8833 		break;
8834 	case ARG_CONST_SIZE_OR_ZERO:
8835 		err = check_mem_size_reg(env, reg, regno, true, meta);
8836 		break;
8837 	case ARG_PTR_TO_DYNPTR:
8838 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8839 		if (err)
8840 			return err;
8841 		break;
8842 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8843 		if (!tnum_is_const(reg->var_off)) {
8844 			verbose(env, "R%d is not a known constant'\n",
8845 				regno);
8846 			return -EACCES;
8847 		}
8848 		meta->mem_size = reg->var_off.value;
8849 		err = mark_chain_precision(env, regno);
8850 		if (err)
8851 			return err;
8852 		break;
8853 	case ARG_PTR_TO_INT:
8854 	case ARG_PTR_TO_LONG:
8855 	{
8856 		int size = int_ptr_type_to_size(arg_type);
8857 
8858 		err = check_helper_mem_access(env, regno, size, false, meta);
8859 		if (err)
8860 			return err;
8861 		err = check_ptr_alignment(env, reg, 0, size, true);
8862 		break;
8863 	}
8864 	case ARG_PTR_TO_CONST_STR:
8865 	{
8866 		err = check_reg_const_str(env, reg, regno);
8867 		if (err)
8868 			return err;
8869 		break;
8870 	}
8871 	case ARG_PTR_TO_KPTR:
8872 		err = process_kptr_func(env, regno, meta);
8873 		if (err)
8874 			return err;
8875 		break;
8876 	}
8877 
8878 	return err;
8879 }
8880 
8881 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8882 {
8883 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8884 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8885 
8886 	if (func_id != BPF_FUNC_map_update_elem &&
8887 	    func_id != BPF_FUNC_map_delete_elem)
8888 		return false;
8889 
8890 	/* It's not possible to get access to a locked struct sock in these
8891 	 * contexts, so updating is safe.
8892 	 */
8893 	switch (type) {
8894 	case BPF_PROG_TYPE_TRACING:
8895 		if (eatype == BPF_TRACE_ITER)
8896 			return true;
8897 		break;
8898 	case BPF_PROG_TYPE_SOCK_OPS:
8899 		/* map_update allowed only via dedicated helpers with event type checks */
8900 		if (func_id == BPF_FUNC_map_delete_elem)
8901 			return true;
8902 		break;
8903 	case BPF_PROG_TYPE_SOCKET_FILTER:
8904 	case BPF_PROG_TYPE_SCHED_CLS:
8905 	case BPF_PROG_TYPE_SCHED_ACT:
8906 	case BPF_PROG_TYPE_XDP:
8907 	case BPF_PROG_TYPE_SK_REUSEPORT:
8908 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8909 	case BPF_PROG_TYPE_SK_LOOKUP:
8910 		return true;
8911 	default:
8912 		break;
8913 	}
8914 
8915 	verbose(env, "cannot update sockmap in this context\n");
8916 	return false;
8917 }
8918 
8919 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8920 {
8921 	return env->prog->jit_requested &&
8922 	       bpf_jit_supports_subprog_tailcalls();
8923 }
8924 
8925 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8926 					struct bpf_map *map, int func_id)
8927 {
8928 	if (!map)
8929 		return 0;
8930 
8931 	/* We need a two way check, first is from map perspective ... */
8932 	switch (map->map_type) {
8933 	case BPF_MAP_TYPE_PROG_ARRAY:
8934 		if (func_id != BPF_FUNC_tail_call)
8935 			goto error;
8936 		break;
8937 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8938 		if (func_id != BPF_FUNC_perf_event_read &&
8939 		    func_id != BPF_FUNC_perf_event_output &&
8940 		    func_id != BPF_FUNC_skb_output &&
8941 		    func_id != BPF_FUNC_perf_event_read_value &&
8942 		    func_id != BPF_FUNC_xdp_output)
8943 			goto error;
8944 		break;
8945 	case BPF_MAP_TYPE_RINGBUF:
8946 		if (func_id != BPF_FUNC_ringbuf_output &&
8947 		    func_id != BPF_FUNC_ringbuf_reserve &&
8948 		    func_id != BPF_FUNC_ringbuf_query &&
8949 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8950 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8951 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8952 			goto error;
8953 		break;
8954 	case BPF_MAP_TYPE_USER_RINGBUF:
8955 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8956 			goto error;
8957 		break;
8958 	case BPF_MAP_TYPE_STACK_TRACE:
8959 		if (func_id != BPF_FUNC_get_stackid)
8960 			goto error;
8961 		break;
8962 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8963 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8964 		    func_id != BPF_FUNC_current_task_under_cgroup)
8965 			goto error;
8966 		break;
8967 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8968 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8969 		if (func_id != BPF_FUNC_get_local_storage)
8970 			goto error;
8971 		break;
8972 	case BPF_MAP_TYPE_DEVMAP:
8973 	case BPF_MAP_TYPE_DEVMAP_HASH:
8974 		if (func_id != BPF_FUNC_redirect_map &&
8975 		    func_id != BPF_FUNC_map_lookup_elem)
8976 			goto error;
8977 		break;
8978 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8979 	 * appear.
8980 	 */
8981 	case BPF_MAP_TYPE_CPUMAP:
8982 		if (func_id != BPF_FUNC_redirect_map)
8983 			goto error;
8984 		break;
8985 	case BPF_MAP_TYPE_XSKMAP:
8986 		if (func_id != BPF_FUNC_redirect_map &&
8987 		    func_id != BPF_FUNC_map_lookup_elem)
8988 			goto error;
8989 		break;
8990 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8991 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8992 		if (func_id != BPF_FUNC_map_lookup_elem)
8993 			goto error;
8994 		break;
8995 	case BPF_MAP_TYPE_SOCKMAP:
8996 		if (func_id != BPF_FUNC_sk_redirect_map &&
8997 		    func_id != BPF_FUNC_sock_map_update &&
8998 		    func_id != BPF_FUNC_msg_redirect_map &&
8999 		    func_id != BPF_FUNC_sk_select_reuseport &&
9000 		    func_id != BPF_FUNC_map_lookup_elem &&
9001 		    !may_update_sockmap(env, func_id))
9002 			goto error;
9003 		break;
9004 	case BPF_MAP_TYPE_SOCKHASH:
9005 		if (func_id != BPF_FUNC_sk_redirect_hash &&
9006 		    func_id != BPF_FUNC_sock_hash_update &&
9007 		    func_id != BPF_FUNC_msg_redirect_hash &&
9008 		    func_id != BPF_FUNC_sk_select_reuseport &&
9009 		    func_id != BPF_FUNC_map_lookup_elem &&
9010 		    !may_update_sockmap(env, func_id))
9011 			goto error;
9012 		break;
9013 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
9014 		if (func_id != BPF_FUNC_sk_select_reuseport)
9015 			goto error;
9016 		break;
9017 	case BPF_MAP_TYPE_QUEUE:
9018 	case BPF_MAP_TYPE_STACK:
9019 		if (func_id != BPF_FUNC_map_peek_elem &&
9020 		    func_id != BPF_FUNC_map_pop_elem &&
9021 		    func_id != BPF_FUNC_map_push_elem)
9022 			goto error;
9023 		break;
9024 	case BPF_MAP_TYPE_SK_STORAGE:
9025 		if (func_id != BPF_FUNC_sk_storage_get &&
9026 		    func_id != BPF_FUNC_sk_storage_delete &&
9027 		    func_id != BPF_FUNC_kptr_xchg)
9028 			goto error;
9029 		break;
9030 	case BPF_MAP_TYPE_INODE_STORAGE:
9031 		if (func_id != BPF_FUNC_inode_storage_get &&
9032 		    func_id != BPF_FUNC_inode_storage_delete &&
9033 		    func_id != BPF_FUNC_kptr_xchg)
9034 			goto error;
9035 		break;
9036 	case BPF_MAP_TYPE_TASK_STORAGE:
9037 		if (func_id != BPF_FUNC_task_storage_get &&
9038 		    func_id != BPF_FUNC_task_storage_delete &&
9039 		    func_id != BPF_FUNC_kptr_xchg)
9040 			goto error;
9041 		break;
9042 	case BPF_MAP_TYPE_CGRP_STORAGE:
9043 		if (func_id != BPF_FUNC_cgrp_storage_get &&
9044 		    func_id != BPF_FUNC_cgrp_storage_delete &&
9045 		    func_id != BPF_FUNC_kptr_xchg)
9046 			goto error;
9047 		break;
9048 	case BPF_MAP_TYPE_BLOOM_FILTER:
9049 		if (func_id != BPF_FUNC_map_peek_elem &&
9050 		    func_id != BPF_FUNC_map_push_elem)
9051 			goto error;
9052 		break;
9053 	default:
9054 		break;
9055 	}
9056 
9057 	/* ... and second from the function itself. */
9058 	switch (func_id) {
9059 	case BPF_FUNC_tail_call:
9060 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
9061 			goto error;
9062 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
9063 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
9064 			return -EINVAL;
9065 		}
9066 		break;
9067 	case BPF_FUNC_perf_event_read:
9068 	case BPF_FUNC_perf_event_output:
9069 	case BPF_FUNC_perf_event_read_value:
9070 	case BPF_FUNC_skb_output:
9071 	case BPF_FUNC_xdp_output:
9072 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9073 			goto error;
9074 		break;
9075 	case BPF_FUNC_ringbuf_output:
9076 	case BPF_FUNC_ringbuf_reserve:
9077 	case BPF_FUNC_ringbuf_query:
9078 	case BPF_FUNC_ringbuf_reserve_dynptr:
9079 	case BPF_FUNC_ringbuf_submit_dynptr:
9080 	case BPF_FUNC_ringbuf_discard_dynptr:
9081 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9082 			goto error;
9083 		break;
9084 	case BPF_FUNC_user_ringbuf_drain:
9085 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9086 			goto error;
9087 		break;
9088 	case BPF_FUNC_get_stackid:
9089 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9090 			goto error;
9091 		break;
9092 	case BPF_FUNC_current_task_under_cgroup:
9093 	case BPF_FUNC_skb_under_cgroup:
9094 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9095 			goto error;
9096 		break;
9097 	case BPF_FUNC_redirect_map:
9098 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9099 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9100 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
9101 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
9102 			goto error;
9103 		break;
9104 	case BPF_FUNC_sk_redirect_map:
9105 	case BPF_FUNC_msg_redirect_map:
9106 	case BPF_FUNC_sock_map_update:
9107 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9108 			goto error;
9109 		break;
9110 	case BPF_FUNC_sk_redirect_hash:
9111 	case BPF_FUNC_msg_redirect_hash:
9112 	case BPF_FUNC_sock_hash_update:
9113 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9114 			goto error;
9115 		break;
9116 	case BPF_FUNC_get_local_storage:
9117 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9118 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9119 			goto error;
9120 		break;
9121 	case BPF_FUNC_sk_select_reuseport:
9122 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9123 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9124 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
9125 			goto error;
9126 		break;
9127 	case BPF_FUNC_map_pop_elem:
9128 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9129 		    map->map_type != BPF_MAP_TYPE_STACK)
9130 			goto error;
9131 		break;
9132 	case BPF_FUNC_map_peek_elem:
9133 	case BPF_FUNC_map_push_elem:
9134 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9135 		    map->map_type != BPF_MAP_TYPE_STACK &&
9136 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9137 			goto error;
9138 		break;
9139 	case BPF_FUNC_map_lookup_percpu_elem:
9140 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9141 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9142 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9143 			goto error;
9144 		break;
9145 	case BPF_FUNC_sk_storage_get:
9146 	case BPF_FUNC_sk_storage_delete:
9147 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9148 			goto error;
9149 		break;
9150 	case BPF_FUNC_inode_storage_get:
9151 	case BPF_FUNC_inode_storage_delete:
9152 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9153 			goto error;
9154 		break;
9155 	case BPF_FUNC_task_storage_get:
9156 	case BPF_FUNC_task_storage_delete:
9157 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9158 			goto error;
9159 		break;
9160 	case BPF_FUNC_cgrp_storage_get:
9161 	case BPF_FUNC_cgrp_storage_delete:
9162 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9163 			goto error;
9164 		break;
9165 	default:
9166 		break;
9167 	}
9168 
9169 	return 0;
9170 error:
9171 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9172 		map->map_type, func_id_name(func_id), func_id);
9173 	return -EINVAL;
9174 }
9175 
9176 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9177 {
9178 	int count = 0;
9179 
9180 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9181 		count++;
9182 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9183 		count++;
9184 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9185 		count++;
9186 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9187 		count++;
9188 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9189 		count++;
9190 
9191 	/* We only support one arg being in raw mode at the moment,
9192 	 * which is sufficient for the helper functions we have
9193 	 * right now.
9194 	 */
9195 	return count <= 1;
9196 }
9197 
9198 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9199 {
9200 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9201 	bool has_size = fn->arg_size[arg] != 0;
9202 	bool is_next_size = false;
9203 
9204 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9205 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9206 
9207 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9208 		return is_next_size;
9209 
9210 	return has_size == is_next_size || is_next_size == is_fixed;
9211 }
9212 
9213 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9214 {
9215 	/* bpf_xxx(..., buf, len) call will access 'len'
9216 	 * bytes from memory 'buf'. Both arg types need
9217 	 * to be paired, so make sure there's no buggy
9218 	 * helper function specification.
9219 	 */
9220 	if (arg_type_is_mem_size(fn->arg1_type) ||
9221 	    check_args_pair_invalid(fn, 0) ||
9222 	    check_args_pair_invalid(fn, 1) ||
9223 	    check_args_pair_invalid(fn, 2) ||
9224 	    check_args_pair_invalid(fn, 3) ||
9225 	    check_args_pair_invalid(fn, 4))
9226 		return false;
9227 
9228 	return true;
9229 }
9230 
9231 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9232 {
9233 	int i;
9234 
9235 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9236 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9237 			return !!fn->arg_btf_id[i];
9238 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9239 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9240 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9241 		    /* arg_btf_id and arg_size are in a union. */
9242 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9243 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9244 			return false;
9245 	}
9246 
9247 	return true;
9248 }
9249 
9250 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9251 {
9252 	return check_raw_mode_ok(fn) &&
9253 	       check_arg_pair_ok(fn) &&
9254 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9255 }
9256 
9257 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9258  * are now invalid, so turn them into unknown SCALAR_VALUE.
9259  *
9260  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9261  * since these slices point to packet data.
9262  */
9263 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9264 {
9265 	struct bpf_func_state *state;
9266 	struct bpf_reg_state *reg;
9267 
9268 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9269 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9270 			mark_reg_invalid(env, reg);
9271 	}));
9272 }
9273 
9274 enum {
9275 	AT_PKT_END = -1,
9276 	BEYOND_PKT_END = -2,
9277 };
9278 
9279 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9280 {
9281 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9282 	struct bpf_reg_state *reg = &state->regs[regn];
9283 
9284 	if (reg->type != PTR_TO_PACKET)
9285 		/* PTR_TO_PACKET_META is not supported yet */
9286 		return;
9287 
9288 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9289 	 * How far beyond pkt_end it goes is unknown.
9290 	 * if (!range_open) it's the case of pkt >= pkt_end
9291 	 * if (range_open) it's the case of pkt > pkt_end
9292 	 * hence this pointer is at least 1 byte bigger than pkt_end
9293 	 */
9294 	if (range_open)
9295 		reg->range = BEYOND_PKT_END;
9296 	else
9297 		reg->range = AT_PKT_END;
9298 }
9299 
9300 /* The pointer with the specified id has released its reference to kernel
9301  * resources. Identify all copies of the same pointer and clear the reference.
9302  */
9303 static int release_reference(struct bpf_verifier_env *env,
9304 			     int ref_obj_id)
9305 {
9306 	struct bpf_func_state *state;
9307 	struct bpf_reg_state *reg;
9308 	int err;
9309 
9310 	err = release_reference_state(cur_func(env), ref_obj_id);
9311 	if (err)
9312 		return err;
9313 
9314 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9315 		if (reg->ref_obj_id == ref_obj_id)
9316 			mark_reg_invalid(env, reg);
9317 	}));
9318 
9319 	return 0;
9320 }
9321 
9322 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9323 {
9324 	struct bpf_func_state *unused;
9325 	struct bpf_reg_state *reg;
9326 
9327 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9328 		if (type_is_non_owning_ref(reg->type))
9329 			mark_reg_invalid(env, reg);
9330 	}));
9331 }
9332 
9333 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9334 				    struct bpf_reg_state *regs)
9335 {
9336 	int i;
9337 
9338 	/* after the call registers r0 - r5 were scratched */
9339 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9340 		mark_reg_not_init(env, regs, caller_saved[i]);
9341 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9342 	}
9343 }
9344 
9345 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9346 				   struct bpf_func_state *caller,
9347 				   struct bpf_func_state *callee,
9348 				   int insn_idx);
9349 
9350 static int set_callee_state(struct bpf_verifier_env *env,
9351 			    struct bpf_func_state *caller,
9352 			    struct bpf_func_state *callee, int insn_idx);
9353 
9354 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9355 			    set_callee_state_fn set_callee_state_cb,
9356 			    struct bpf_verifier_state *state)
9357 {
9358 	struct bpf_func_state *caller, *callee;
9359 	int err;
9360 
9361 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9362 		verbose(env, "the call stack of %d frames is too deep\n",
9363 			state->curframe + 2);
9364 		return -E2BIG;
9365 	}
9366 
9367 	if (state->frame[state->curframe + 1]) {
9368 		verbose(env, "verifier bug. Frame %d already allocated\n",
9369 			state->curframe + 1);
9370 		return -EFAULT;
9371 	}
9372 
9373 	caller = state->frame[state->curframe];
9374 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9375 	if (!callee)
9376 		return -ENOMEM;
9377 	state->frame[state->curframe + 1] = callee;
9378 
9379 	/* callee cannot access r0, r6 - r9 for reading and has to write
9380 	 * into its own stack before reading from it.
9381 	 * callee can read/write into caller's stack
9382 	 */
9383 	init_func_state(env, callee,
9384 			/* remember the callsite, it will be used by bpf_exit */
9385 			callsite,
9386 			state->curframe + 1 /* frameno within this callchain */,
9387 			subprog /* subprog number within this prog */);
9388 	/* Transfer references to the callee */
9389 	err = copy_reference_state(callee, caller);
9390 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9391 	if (err)
9392 		goto err_out;
9393 
9394 	/* only increment it after check_reg_arg() finished */
9395 	state->curframe++;
9396 
9397 	return 0;
9398 
9399 err_out:
9400 	free_func_state(callee);
9401 	state->frame[state->curframe + 1] = NULL;
9402 	return err;
9403 }
9404 
9405 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9406 				    const struct btf *btf,
9407 				    struct bpf_reg_state *regs)
9408 {
9409 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
9410 	struct bpf_verifier_log *log = &env->log;
9411 	u32 i;
9412 	int ret;
9413 
9414 	ret = btf_prepare_func_args(env, subprog);
9415 	if (ret)
9416 		return ret;
9417 
9418 	/* check that BTF function arguments match actual types that the
9419 	 * verifier sees.
9420 	 */
9421 	for (i = 0; i < sub->arg_cnt; i++) {
9422 		u32 regno = i + 1;
9423 		struct bpf_reg_state *reg = &regs[regno];
9424 		struct bpf_subprog_arg_info *arg = &sub->args[i];
9425 
9426 		if (arg->arg_type == ARG_ANYTHING) {
9427 			if (reg->type != SCALAR_VALUE) {
9428 				bpf_log(log, "R%d is not a scalar\n", regno);
9429 				return -EINVAL;
9430 			}
9431 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
9432 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9433 			if (ret < 0)
9434 				return ret;
9435 			/* If function expects ctx type in BTF check that caller
9436 			 * is passing PTR_TO_CTX.
9437 			 */
9438 			if (reg->type != PTR_TO_CTX) {
9439 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9440 				return -EINVAL;
9441 			}
9442 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9443 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9444 			if (ret < 0)
9445 				return ret;
9446 			if (check_mem_reg(env, reg, regno, arg->mem_size))
9447 				return -EINVAL;
9448 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9449 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9450 				return -EINVAL;
9451 			}
9452 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
9453 			/*
9454 			 * Can pass any value and the kernel won't crash, but
9455 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
9456 			 * else is a bug in the bpf program. Point it out to
9457 			 * the user at the verification time instead of
9458 			 * run-time debug nightmare.
9459 			 */
9460 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
9461 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
9462 				return -EINVAL;
9463 			}
9464 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
9465 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
9466 			if (ret)
9467 				return ret;
9468 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
9469 			struct bpf_call_arg_meta meta;
9470 			int err;
9471 
9472 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
9473 				continue;
9474 
9475 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
9476 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
9477 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
9478 			if (err)
9479 				return err;
9480 		} else {
9481 			bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
9482 				i, arg->arg_type);
9483 			return -EFAULT;
9484 		}
9485 	}
9486 
9487 	return 0;
9488 }
9489 
9490 /* Compare BTF of a function call with given bpf_reg_state.
9491  * Returns:
9492  * EFAULT - there is a verifier bug. Abort verification.
9493  * EINVAL - there is a type mismatch or BTF is not available.
9494  * 0 - BTF matches with what bpf_reg_state expects.
9495  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9496  */
9497 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9498 				  struct bpf_reg_state *regs)
9499 {
9500 	struct bpf_prog *prog = env->prog;
9501 	struct btf *btf = prog->aux->btf;
9502 	u32 btf_id;
9503 	int err;
9504 
9505 	if (!prog->aux->func_info)
9506 		return -EINVAL;
9507 
9508 	btf_id = prog->aux->func_info[subprog].type_id;
9509 	if (!btf_id)
9510 		return -EFAULT;
9511 
9512 	if (prog->aux->func_info_aux[subprog].unreliable)
9513 		return -EINVAL;
9514 
9515 	err = btf_check_func_arg_match(env, subprog, btf, regs);
9516 	/* Compiler optimizations can remove arguments from static functions
9517 	 * or mismatched type can be passed into a global function.
9518 	 * In such cases mark the function as unreliable from BTF point of view.
9519 	 */
9520 	if (err)
9521 		prog->aux->func_info_aux[subprog].unreliable = true;
9522 	return err;
9523 }
9524 
9525 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9526 			      int insn_idx, int subprog,
9527 			      set_callee_state_fn set_callee_state_cb)
9528 {
9529 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9530 	struct bpf_func_state *caller, *callee;
9531 	int err;
9532 
9533 	caller = state->frame[state->curframe];
9534 	err = btf_check_subprog_call(env, subprog, caller->regs);
9535 	if (err == -EFAULT)
9536 		return err;
9537 
9538 	/* set_callee_state is used for direct subprog calls, but we are
9539 	 * interested in validating only BPF helpers that can call subprogs as
9540 	 * callbacks
9541 	 */
9542 	env->subprog_info[subprog].is_cb = true;
9543 	if (bpf_pseudo_kfunc_call(insn) &&
9544 	    !is_callback_calling_kfunc(insn->imm)) {
9545 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9546 			func_id_name(insn->imm), insn->imm);
9547 		return -EFAULT;
9548 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9549 		   !is_callback_calling_function(insn->imm)) { /* helper */
9550 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9551 			func_id_name(insn->imm), insn->imm);
9552 		return -EFAULT;
9553 	}
9554 
9555 	if (is_async_callback_calling_insn(insn)) {
9556 		struct bpf_verifier_state *async_cb;
9557 
9558 		/* there is no real recursion here. timer and workqueue callbacks are async */
9559 		env->subprog_info[subprog].is_async_cb = true;
9560 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9561 					 insn_idx, subprog,
9562 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm));
9563 		if (!async_cb)
9564 			return -EFAULT;
9565 		callee = async_cb->frame[0];
9566 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9567 
9568 		/* Convert bpf_timer_set_callback() args into timer callback args */
9569 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9570 		if (err)
9571 			return err;
9572 
9573 		return 0;
9574 	}
9575 
9576 	/* for callback functions enqueue entry to callback and
9577 	 * proceed with next instruction within current frame.
9578 	 */
9579 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9580 	if (!callback_state)
9581 		return -ENOMEM;
9582 
9583 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9584 			       callback_state);
9585 	if (err)
9586 		return err;
9587 
9588 	callback_state->callback_unroll_depth++;
9589 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9590 	caller->callback_depth = 0;
9591 	return 0;
9592 }
9593 
9594 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9595 			   int *insn_idx)
9596 {
9597 	struct bpf_verifier_state *state = env->cur_state;
9598 	struct bpf_func_state *caller;
9599 	int err, subprog, target_insn;
9600 
9601 	target_insn = *insn_idx + insn->imm + 1;
9602 	subprog = find_subprog(env, target_insn);
9603 	if (subprog < 0) {
9604 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9605 		return -EFAULT;
9606 	}
9607 
9608 	caller = state->frame[state->curframe];
9609 	err = btf_check_subprog_call(env, subprog, caller->regs);
9610 	if (err == -EFAULT)
9611 		return err;
9612 	if (subprog_is_global(env, subprog)) {
9613 		const char *sub_name = subprog_name(env, subprog);
9614 
9615 		/* Only global subprogs cannot be called with a lock held. */
9616 		if (env->cur_state->active_lock.ptr) {
9617 			verbose(env, "global function calls are not allowed while holding a lock,\n"
9618 				     "use static function instead\n");
9619 			return -EINVAL;
9620 		}
9621 
9622 		/* Only global subprogs cannot be called with preemption disabled. */
9623 		if (env->cur_state->active_preempt_lock) {
9624 			verbose(env, "global function calls are not allowed with preemption disabled,\n"
9625 				     "use static function instead\n");
9626 			return -EINVAL;
9627 		}
9628 
9629 		if (err) {
9630 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9631 				subprog, sub_name);
9632 			return err;
9633 		}
9634 
9635 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9636 			subprog, sub_name);
9637 		/* mark global subprog for verifying after main prog */
9638 		subprog_aux(env, subprog)->called = true;
9639 		clear_caller_saved_regs(env, caller->regs);
9640 
9641 		/* All global functions return a 64-bit SCALAR_VALUE */
9642 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9643 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9644 
9645 		/* continue with next insn after call */
9646 		return 0;
9647 	}
9648 
9649 	/* for regular function entry setup new frame and continue
9650 	 * from that frame.
9651 	 */
9652 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9653 	if (err)
9654 		return err;
9655 
9656 	clear_caller_saved_regs(env, caller->regs);
9657 
9658 	/* and go analyze first insn of the callee */
9659 	*insn_idx = env->subprog_info[subprog].start - 1;
9660 
9661 	if (env->log.level & BPF_LOG_LEVEL) {
9662 		verbose(env, "caller:\n");
9663 		print_verifier_state(env, caller, true);
9664 		verbose(env, "callee:\n");
9665 		print_verifier_state(env, state->frame[state->curframe], true);
9666 	}
9667 
9668 	return 0;
9669 }
9670 
9671 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9672 				   struct bpf_func_state *caller,
9673 				   struct bpf_func_state *callee)
9674 {
9675 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9676 	 *      void *callback_ctx, u64 flags);
9677 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9678 	 *      void *callback_ctx);
9679 	 */
9680 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9681 
9682 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9683 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9684 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9685 
9686 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9687 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9688 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9689 
9690 	/* pointer to stack or null */
9691 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9692 
9693 	/* unused */
9694 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9695 	return 0;
9696 }
9697 
9698 static int set_callee_state(struct bpf_verifier_env *env,
9699 			    struct bpf_func_state *caller,
9700 			    struct bpf_func_state *callee, int insn_idx)
9701 {
9702 	int i;
9703 
9704 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9705 	 * pointers, which connects us up to the liveness chain
9706 	 */
9707 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9708 		callee->regs[i] = caller->regs[i];
9709 	return 0;
9710 }
9711 
9712 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9713 				       struct bpf_func_state *caller,
9714 				       struct bpf_func_state *callee,
9715 				       int insn_idx)
9716 {
9717 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9718 	struct bpf_map *map;
9719 	int err;
9720 
9721 	/* valid map_ptr and poison value does not matter */
9722 	map = insn_aux->map_ptr_state.map_ptr;
9723 	if (!map->ops->map_set_for_each_callback_args ||
9724 	    !map->ops->map_for_each_callback) {
9725 		verbose(env, "callback function not allowed for map\n");
9726 		return -ENOTSUPP;
9727 	}
9728 
9729 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9730 	if (err)
9731 		return err;
9732 
9733 	callee->in_callback_fn = true;
9734 	callee->callback_ret_range = retval_range(0, 1);
9735 	return 0;
9736 }
9737 
9738 static int set_loop_callback_state(struct bpf_verifier_env *env,
9739 				   struct bpf_func_state *caller,
9740 				   struct bpf_func_state *callee,
9741 				   int insn_idx)
9742 {
9743 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9744 	 *	    u64 flags);
9745 	 * callback_fn(u32 index, void *callback_ctx);
9746 	 */
9747 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9748 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9749 
9750 	/* unused */
9751 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9752 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9753 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9754 
9755 	callee->in_callback_fn = true;
9756 	callee->callback_ret_range = retval_range(0, 1);
9757 	return 0;
9758 }
9759 
9760 static int set_timer_callback_state(struct bpf_verifier_env *env,
9761 				    struct bpf_func_state *caller,
9762 				    struct bpf_func_state *callee,
9763 				    int insn_idx)
9764 {
9765 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9766 
9767 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9768 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9769 	 */
9770 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9771 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9772 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9773 
9774 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9775 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9776 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9777 
9778 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9779 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9780 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9781 
9782 	/* unused */
9783 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9784 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9785 	callee->in_async_callback_fn = true;
9786 	callee->callback_ret_range = retval_range(0, 1);
9787 	return 0;
9788 }
9789 
9790 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9791 				       struct bpf_func_state *caller,
9792 				       struct bpf_func_state *callee,
9793 				       int insn_idx)
9794 {
9795 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9796 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9797 	 * (callback_fn)(struct task_struct *task,
9798 	 *               struct vm_area_struct *vma, void *callback_ctx);
9799 	 */
9800 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9801 
9802 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9803 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9804 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9805 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9806 
9807 	/* pointer to stack or null */
9808 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9809 
9810 	/* unused */
9811 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9812 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9813 	callee->in_callback_fn = true;
9814 	callee->callback_ret_range = retval_range(0, 1);
9815 	return 0;
9816 }
9817 
9818 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9819 					   struct bpf_func_state *caller,
9820 					   struct bpf_func_state *callee,
9821 					   int insn_idx)
9822 {
9823 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9824 	 *			  callback_ctx, u64 flags);
9825 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9826 	 */
9827 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9828 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9829 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9830 
9831 	/* unused */
9832 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9833 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9834 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9835 
9836 	callee->in_callback_fn = true;
9837 	callee->callback_ret_range = retval_range(0, 1);
9838 	return 0;
9839 }
9840 
9841 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9842 					 struct bpf_func_state *caller,
9843 					 struct bpf_func_state *callee,
9844 					 int insn_idx)
9845 {
9846 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9847 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9848 	 *
9849 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9850 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9851 	 * by this point, so look at 'root'
9852 	 */
9853 	struct btf_field *field;
9854 
9855 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9856 				      BPF_RB_ROOT);
9857 	if (!field || !field->graph_root.value_btf_id)
9858 		return -EFAULT;
9859 
9860 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9861 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9862 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9863 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9864 
9865 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9866 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9867 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9868 	callee->in_callback_fn = true;
9869 	callee->callback_ret_range = retval_range(0, 1);
9870 	return 0;
9871 }
9872 
9873 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9874 
9875 /* Are we currently verifying the callback for a rbtree helper that must
9876  * be called with lock held? If so, no need to complain about unreleased
9877  * lock
9878  */
9879 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9880 {
9881 	struct bpf_verifier_state *state = env->cur_state;
9882 	struct bpf_insn *insn = env->prog->insnsi;
9883 	struct bpf_func_state *callee;
9884 	int kfunc_btf_id;
9885 
9886 	if (!state->curframe)
9887 		return false;
9888 
9889 	callee = state->frame[state->curframe];
9890 
9891 	if (!callee->in_callback_fn)
9892 		return false;
9893 
9894 	kfunc_btf_id = insn[callee->callsite].imm;
9895 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9896 }
9897 
9898 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
9899 {
9900 	return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
9901 }
9902 
9903 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9904 {
9905 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9906 	struct bpf_func_state *caller, *callee;
9907 	struct bpf_reg_state *r0;
9908 	bool in_callback_fn;
9909 	int err;
9910 
9911 	callee = state->frame[state->curframe];
9912 	r0 = &callee->regs[BPF_REG_0];
9913 	if (r0->type == PTR_TO_STACK) {
9914 		/* technically it's ok to return caller's stack pointer
9915 		 * (or caller's caller's pointer) back to the caller,
9916 		 * since these pointers are valid. Only current stack
9917 		 * pointer will be invalid as soon as function exits,
9918 		 * but let's be conservative
9919 		 */
9920 		verbose(env, "cannot return stack pointer to the caller\n");
9921 		return -EINVAL;
9922 	}
9923 
9924 	caller = state->frame[state->curframe - 1];
9925 	if (callee->in_callback_fn) {
9926 		if (r0->type != SCALAR_VALUE) {
9927 			verbose(env, "R0 not a scalar value\n");
9928 			return -EACCES;
9929 		}
9930 
9931 		/* we are going to rely on register's precise value */
9932 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9933 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9934 		if (err)
9935 			return err;
9936 
9937 		/* enforce R0 return value range */
9938 		if (!retval_range_within(callee->callback_ret_range, r0)) {
9939 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
9940 					       "At callback return", "R0");
9941 			return -EINVAL;
9942 		}
9943 		if (!calls_callback(env, callee->callsite)) {
9944 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9945 				*insn_idx, callee->callsite);
9946 			return -EFAULT;
9947 		}
9948 	} else {
9949 		/* return to the caller whatever r0 had in the callee */
9950 		caller->regs[BPF_REG_0] = *r0;
9951 	}
9952 
9953 	/* callback_fn frame should have released its own additions to parent's
9954 	 * reference state at this point, or check_reference_leak would
9955 	 * complain, hence it must be the same as the caller. There is no need
9956 	 * to copy it back.
9957 	 */
9958 	if (!callee->in_callback_fn) {
9959 		/* Transfer references to the caller */
9960 		err = copy_reference_state(caller, callee);
9961 		if (err)
9962 			return err;
9963 	}
9964 
9965 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9966 	 * there function call logic would reschedule callback visit. If iteration
9967 	 * converges is_state_visited() would prune that visit eventually.
9968 	 */
9969 	in_callback_fn = callee->in_callback_fn;
9970 	if (in_callback_fn)
9971 		*insn_idx = callee->callsite;
9972 	else
9973 		*insn_idx = callee->callsite + 1;
9974 
9975 	if (env->log.level & BPF_LOG_LEVEL) {
9976 		verbose(env, "returning from callee:\n");
9977 		print_verifier_state(env, callee, true);
9978 		verbose(env, "to caller at %d:\n", *insn_idx);
9979 		print_verifier_state(env, caller, true);
9980 	}
9981 	/* clear everything in the callee. In case of exceptional exits using
9982 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9983 	free_func_state(callee);
9984 	state->frame[state->curframe--] = NULL;
9985 
9986 	/* for callbacks widen imprecise scalars to make programs like below verify:
9987 	 *
9988 	 *   struct ctx { int i; }
9989 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9990 	 *   ...
9991 	 *   struct ctx = { .i = 0; }
9992 	 *   bpf_loop(100, cb, &ctx, 0);
9993 	 *
9994 	 * This is similar to what is done in process_iter_next_call() for open
9995 	 * coded iterators.
9996 	 */
9997 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9998 	if (prev_st) {
9999 		err = widen_imprecise_scalars(env, prev_st, state);
10000 		if (err)
10001 			return err;
10002 	}
10003 	return 0;
10004 }
10005 
10006 static int do_refine_retval_range(struct bpf_verifier_env *env,
10007 				  struct bpf_reg_state *regs, int ret_type,
10008 				  int func_id,
10009 				  struct bpf_call_arg_meta *meta)
10010 {
10011 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
10012 
10013 	if (ret_type != RET_INTEGER)
10014 		return 0;
10015 
10016 	switch (func_id) {
10017 	case BPF_FUNC_get_stack:
10018 	case BPF_FUNC_get_task_stack:
10019 	case BPF_FUNC_probe_read_str:
10020 	case BPF_FUNC_probe_read_kernel_str:
10021 	case BPF_FUNC_probe_read_user_str:
10022 		ret_reg->smax_value = meta->msize_max_value;
10023 		ret_reg->s32_max_value = meta->msize_max_value;
10024 		ret_reg->smin_value = -MAX_ERRNO;
10025 		ret_reg->s32_min_value = -MAX_ERRNO;
10026 		reg_bounds_sync(ret_reg);
10027 		break;
10028 	case BPF_FUNC_get_smp_processor_id:
10029 		ret_reg->umax_value = nr_cpu_ids - 1;
10030 		ret_reg->u32_max_value = nr_cpu_ids - 1;
10031 		ret_reg->smax_value = nr_cpu_ids - 1;
10032 		ret_reg->s32_max_value = nr_cpu_ids - 1;
10033 		ret_reg->umin_value = 0;
10034 		ret_reg->u32_min_value = 0;
10035 		ret_reg->smin_value = 0;
10036 		ret_reg->s32_min_value = 0;
10037 		reg_bounds_sync(ret_reg);
10038 		break;
10039 	}
10040 
10041 	return reg_bounds_sanity_check(env, ret_reg, "retval");
10042 }
10043 
10044 static int
10045 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10046 		int func_id, int insn_idx)
10047 {
10048 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10049 	struct bpf_map *map = meta->map_ptr;
10050 
10051 	if (func_id != BPF_FUNC_tail_call &&
10052 	    func_id != BPF_FUNC_map_lookup_elem &&
10053 	    func_id != BPF_FUNC_map_update_elem &&
10054 	    func_id != BPF_FUNC_map_delete_elem &&
10055 	    func_id != BPF_FUNC_map_push_elem &&
10056 	    func_id != BPF_FUNC_map_pop_elem &&
10057 	    func_id != BPF_FUNC_map_peek_elem &&
10058 	    func_id != BPF_FUNC_for_each_map_elem &&
10059 	    func_id != BPF_FUNC_redirect_map &&
10060 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
10061 		return 0;
10062 
10063 	if (map == NULL) {
10064 		verbose(env, "kernel subsystem misconfigured verifier\n");
10065 		return -EINVAL;
10066 	}
10067 
10068 	/* In case of read-only, some additional restrictions
10069 	 * need to be applied in order to prevent altering the
10070 	 * state of the map from program side.
10071 	 */
10072 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
10073 	    (func_id == BPF_FUNC_map_delete_elem ||
10074 	     func_id == BPF_FUNC_map_update_elem ||
10075 	     func_id == BPF_FUNC_map_push_elem ||
10076 	     func_id == BPF_FUNC_map_pop_elem)) {
10077 		verbose(env, "write into map forbidden\n");
10078 		return -EACCES;
10079 	}
10080 
10081 	if (!aux->map_ptr_state.map_ptr)
10082 		bpf_map_ptr_store(aux, meta->map_ptr,
10083 				  !meta->map_ptr->bypass_spec_v1, false);
10084 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
10085 		bpf_map_ptr_store(aux, meta->map_ptr,
10086 				  !meta->map_ptr->bypass_spec_v1, true);
10087 	return 0;
10088 }
10089 
10090 static int
10091 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10092 		int func_id, int insn_idx)
10093 {
10094 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10095 	struct bpf_reg_state *regs = cur_regs(env), *reg;
10096 	struct bpf_map *map = meta->map_ptr;
10097 	u64 val, max;
10098 	int err;
10099 
10100 	if (func_id != BPF_FUNC_tail_call)
10101 		return 0;
10102 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
10103 		verbose(env, "kernel subsystem misconfigured verifier\n");
10104 		return -EINVAL;
10105 	}
10106 
10107 	reg = &regs[BPF_REG_3];
10108 	val = reg->var_off.value;
10109 	max = map->max_entries;
10110 
10111 	if (!(is_reg_const(reg, false) && val < max)) {
10112 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10113 		return 0;
10114 	}
10115 
10116 	err = mark_chain_precision(env, BPF_REG_3);
10117 	if (err)
10118 		return err;
10119 	if (bpf_map_key_unseen(aux))
10120 		bpf_map_key_store(aux, val);
10121 	else if (!bpf_map_key_poisoned(aux) &&
10122 		  bpf_map_key_immediate(aux) != val)
10123 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10124 	return 0;
10125 }
10126 
10127 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
10128 {
10129 	struct bpf_func_state *state = cur_func(env);
10130 	bool refs_lingering = false;
10131 	int i;
10132 
10133 	if (!exception_exit && state->frameno && !state->in_callback_fn)
10134 		return 0;
10135 
10136 	for (i = 0; i < state->acquired_refs; i++) {
10137 		if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
10138 			continue;
10139 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10140 			state->refs[i].id, state->refs[i].insn_idx);
10141 		refs_lingering = true;
10142 	}
10143 	return refs_lingering ? -EINVAL : 0;
10144 }
10145 
10146 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10147 				   struct bpf_reg_state *regs)
10148 {
10149 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
10150 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
10151 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
10152 	struct bpf_bprintf_data data = {};
10153 	int err, fmt_map_off, num_args;
10154 	u64 fmt_addr;
10155 	char *fmt;
10156 
10157 	/* data must be an array of u64 */
10158 	if (data_len_reg->var_off.value % 8)
10159 		return -EINVAL;
10160 	num_args = data_len_reg->var_off.value / 8;
10161 
10162 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10163 	 * and map_direct_value_addr is set.
10164 	 */
10165 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10166 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10167 						  fmt_map_off);
10168 	if (err) {
10169 		verbose(env, "verifier bug\n");
10170 		return -EFAULT;
10171 	}
10172 	fmt = (char *)(long)fmt_addr + fmt_map_off;
10173 
10174 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10175 	 * can focus on validating the format specifiers.
10176 	 */
10177 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10178 	if (err < 0)
10179 		verbose(env, "Invalid format string\n");
10180 
10181 	return err;
10182 }
10183 
10184 static int check_get_func_ip(struct bpf_verifier_env *env)
10185 {
10186 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10187 	int func_id = BPF_FUNC_get_func_ip;
10188 
10189 	if (type == BPF_PROG_TYPE_TRACING) {
10190 		if (!bpf_prog_has_trampoline(env->prog)) {
10191 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10192 				func_id_name(func_id), func_id);
10193 			return -ENOTSUPP;
10194 		}
10195 		return 0;
10196 	} else if (type == BPF_PROG_TYPE_KPROBE) {
10197 		return 0;
10198 	}
10199 
10200 	verbose(env, "func %s#%d not supported for program type %d\n",
10201 		func_id_name(func_id), func_id, type);
10202 	return -ENOTSUPP;
10203 }
10204 
10205 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10206 {
10207 	return &env->insn_aux_data[env->insn_idx];
10208 }
10209 
10210 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10211 {
10212 	struct bpf_reg_state *regs = cur_regs(env);
10213 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
10214 	bool reg_is_null = register_is_null(reg);
10215 
10216 	if (reg_is_null)
10217 		mark_chain_precision(env, BPF_REG_4);
10218 
10219 	return reg_is_null;
10220 }
10221 
10222 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10223 {
10224 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10225 
10226 	if (!state->initialized) {
10227 		state->initialized = 1;
10228 		state->fit_for_inline = loop_flag_is_zero(env);
10229 		state->callback_subprogno = subprogno;
10230 		return;
10231 	}
10232 
10233 	if (!state->fit_for_inline)
10234 		return;
10235 
10236 	state->fit_for_inline = (loop_flag_is_zero(env) &&
10237 				 state->callback_subprogno == subprogno);
10238 }
10239 
10240 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10241 			     int *insn_idx_p)
10242 {
10243 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10244 	bool returns_cpu_specific_alloc_ptr = false;
10245 	const struct bpf_func_proto *fn = NULL;
10246 	enum bpf_return_type ret_type;
10247 	enum bpf_type_flag ret_flag;
10248 	struct bpf_reg_state *regs;
10249 	struct bpf_call_arg_meta meta;
10250 	int insn_idx = *insn_idx_p;
10251 	bool changes_data;
10252 	int i, err, func_id;
10253 
10254 	/* find function prototype */
10255 	func_id = insn->imm;
10256 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
10257 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
10258 			func_id);
10259 		return -EINVAL;
10260 	}
10261 
10262 	if (env->ops->get_func_proto)
10263 		fn = env->ops->get_func_proto(func_id, env->prog);
10264 	if (!fn) {
10265 		verbose(env, "program of this type cannot use helper %s#%d\n",
10266 			func_id_name(func_id), func_id);
10267 		return -EINVAL;
10268 	}
10269 
10270 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
10271 	if (!env->prog->gpl_compatible && fn->gpl_only) {
10272 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10273 		return -EINVAL;
10274 	}
10275 
10276 	if (fn->allowed && !fn->allowed(env->prog)) {
10277 		verbose(env, "helper call is not allowed in probe\n");
10278 		return -EINVAL;
10279 	}
10280 
10281 	if (!in_sleepable(env) && fn->might_sleep) {
10282 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
10283 		return -EINVAL;
10284 	}
10285 
10286 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10287 	changes_data = bpf_helper_changes_pkt_data(fn->func);
10288 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10289 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10290 			func_id_name(func_id), func_id);
10291 		return -EINVAL;
10292 	}
10293 
10294 	memset(&meta, 0, sizeof(meta));
10295 	meta.pkt_access = fn->pkt_access;
10296 
10297 	err = check_func_proto(fn, func_id);
10298 	if (err) {
10299 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10300 			func_id_name(func_id), func_id);
10301 		return err;
10302 	}
10303 
10304 	if (env->cur_state->active_rcu_lock) {
10305 		if (fn->might_sleep) {
10306 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10307 				func_id_name(func_id), func_id);
10308 			return -EINVAL;
10309 		}
10310 
10311 		if (in_sleepable(env) && is_storage_get_function(func_id))
10312 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10313 	}
10314 
10315 	if (env->cur_state->active_preempt_lock) {
10316 		if (fn->might_sleep) {
10317 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
10318 				func_id_name(func_id), func_id);
10319 			return -EINVAL;
10320 		}
10321 
10322 		if (in_sleepable(env) && is_storage_get_function(func_id))
10323 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10324 	}
10325 
10326 	meta.func_id = func_id;
10327 	/* check args */
10328 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10329 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10330 		if (err)
10331 			return err;
10332 	}
10333 
10334 	err = record_func_map(env, &meta, func_id, insn_idx);
10335 	if (err)
10336 		return err;
10337 
10338 	err = record_func_key(env, &meta, func_id, insn_idx);
10339 	if (err)
10340 		return err;
10341 
10342 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10343 	 * is inferred from register state.
10344 	 */
10345 	for (i = 0; i < meta.access_size; i++) {
10346 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10347 				       BPF_WRITE, -1, false, false);
10348 		if (err)
10349 			return err;
10350 	}
10351 
10352 	regs = cur_regs(env);
10353 
10354 	if (meta.release_regno) {
10355 		err = -EINVAL;
10356 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10357 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10358 		 * is safe to do directly.
10359 		 */
10360 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10361 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10362 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10363 				return -EFAULT;
10364 			}
10365 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10366 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10367 			u32 ref_obj_id = meta.ref_obj_id;
10368 			bool in_rcu = in_rcu_cs(env);
10369 			struct bpf_func_state *state;
10370 			struct bpf_reg_state *reg;
10371 
10372 			err = release_reference_state(cur_func(env), ref_obj_id);
10373 			if (!err) {
10374 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10375 					if (reg->ref_obj_id == ref_obj_id) {
10376 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10377 							reg->ref_obj_id = 0;
10378 							reg->type &= ~MEM_ALLOC;
10379 							reg->type |= MEM_RCU;
10380 						} else {
10381 							mark_reg_invalid(env, reg);
10382 						}
10383 					}
10384 				}));
10385 			}
10386 		} else if (meta.ref_obj_id) {
10387 			err = release_reference(env, meta.ref_obj_id);
10388 		} else if (register_is_null(&regs[meta.release_regno])) {
10389 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10390 			 * released is NULL, which must be > R0.
10391 			 */
10392 			err = 0;
10393 		}
10394 		if (err) {
10395 			verbose(env, "func %s#%d reference has not been acquired before\n",
10396 				func_id_name(func_id), func_id);
10397 			return err;
10398 		}
10399 	}
10400 
10401 	switch (func_id) {
10402 	case BPF_FUNC_tail_call:
10403 		err = check_reference_leak(env, false);
10404 		if (err) {
10405 			verbose(env, "tail_call would lead to reference leak\n");
10406 			return err;
10407 		}
10408 		break;
10409 	case BPF_FUNC_get_local_storage:
10410 		/* check that flags argument in get_local_storage(map, flags) is 0,
10411 		 * this is required because get_local_storage() can't return an error.
10412 		 */
10413 		if (!register_is_null(&regs[BPF_REG_2])) {
10414 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10415 			return -EINVAL;
10416 		}
10417 		break;
10418 	case BPF_FUNC_for_each_map_elem:
10419 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10420 					 set_map_elem_callback_state);
10421 		break;
10422 	case BPF_FUNC_timer_set_callback:
10423 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10424 					 set_timer_callback_state);
10425 		break;
10426 	case BPF_FUNC_find_vma:
10427 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10428 					 set_find_vma_callback_state);
10429 		break;
10430 	case BPF_FUNC_snprintf:
10431 		err = check_bpf_snprintf_call(env, regs);
10432 		break;
10433 	case BPF_FUNC_loop:
10434 		update_loop_inline_state(env, meta.subprogno);
10435 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10436 		 * is finished, thus mark it precise.
10437 		 */
10438 		err = mark_chain_precision(env, BPF_REG_1);
10439 		if (err)
10440 			return err;
10441 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10442 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10443 						 set_loop_callback_state);
10444 		} else {
10445 			cur_func(env)->callback_depth = 0;
10446 			if (env->log.level & BPF_LOG_LEVEL2)
10447 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10448 					env->cur_state->curframe);
10449 		}
10450 		break;
10451 	case BPF_FUNC_dynptr_from_mem:
10452 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10453 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10454 				reg_type_str(env, regs[BPF_REG_1].type));
10455 			return -EACCES;
10456 		}
10457 		break;
10458 	case BPF_FUNC_set_retval:
10459 		if (prog_type == BPF_PROG_TYPE_LSM &&
10460 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10461 			if (!env->prog->aux->attach_func_proto->type) {
10462 				/* Make sure programs that attach to void
10463 				 * hooks don't try to modify return value.
10464 				 */
10465 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10466 				return -EINVAL;
10467 			}
10468 		}
10469 		break;
10470 	case BPF_FUNC_dynptr_data:
10471 	{
10472 		struct bpf_reg_state *reg;
10473 		int id, ref_obj_id;
10474 
10475 		reg = get_dynptr_arg_reg(env, fn, regs);
10476 		if (!reg)
10477 			return -EFAULT;
10478 
10479 
10480 		if (meta.dynptr_id) {
10481 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10482 			return -EFAULT;
10483 		}
10484 		if (meta.ref_obj_id) {
10485 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10486 			return -EFAULT;
10487 		}
10488 
10489 		id = dynptr_id(env, reg);
10490 		if (id < 0) {
10491 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10492 			return id;
10493 		}
10494 
10495 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10496 		if (ref_obj_id < 0) {
10497 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10498 			return ref_obj_id;
10499 		}
10500 
10501 		meta.dynptr_id = id;
10502 		meta.ref_obj_id = ref_obj_id;
10503 
10504 		break;
10505 	}
10506 	case BPF_FUNC_dynptr_write:
10507 	{
10508 		enum bpf_dynptr_type dynptr_type;
10509 		struct bpf_reg_state *reg;
10510 
10511 		reg = get_dynptr_arg_reg(env, fn, regs);
10512 		if (!reg)
10513 			return -EFAULT;
10514 
10515 		dynptr_type = dynptr_get_type(env, reg);
10516 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10517 			return -EFAULT;
10518 
10519 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10520 			/* this will trigger clear_all_pkt_pointers(), which will
10521 			 * invalidate all dynptr slices associated with the skb
10522 			 */
10523 			changes_data = true;
10524 
10525 		break;
10526 	}
10527 	case BPF_FUNC_per_cpu_ptr:
10528 	case BPF_FUNC_this_cpu_ptr:
10529 	{
10530 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
10531 		const struct btf_type *type;
10532 
10533 		if (reg->type & MEM_RCU) {
10534 			type = btf_type_by_id(reg->btf, reg->btf_id);
10535 			if (!type || !btf_type_is_struct(type)) {
10536 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
10537 				return -EFAULT;
10538 			}
10539 			returns_cpu_specific_alloc_ptr = true;
10540 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10541 		}
10542 		break;
10543 	}
10544 	case BPF_FUNC_user_ringbuf_drain:
10545 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10546 					 set_user_ringbuf_callback_state);
10547 		break;
10548 	}
10549 
10550 	if (err)
10551 		return err;
10552 
10553 	/* reset caller saved regs */
10554 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10555 		mark_reg_not_init(env, regs, caller_saved[i]);
10556 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10557 	}
10558 
10559 	/* helper call returns 64-bit value. */
10560 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10561 
10562 	/* update return register (already marked as written above) */
10563 	ret_type = fn->ret_type;
10564 	ret_flag = type_flag(ret_type);
10565 
10566 	switch (base_type(ret_type)) {
10567 	case RET_INTEGER:
10568 		/* sets type to SCALAR_VALUE */
10569 		mark_reg_unknown(env, regs, BPF_REG_0);
10570 		break;
10571 	case RET_VOID:
10572 		regs[BPF_REG_0].type = NOT_INIT;
10573 		break;
10574 	case RET_PTR_TO_MAP_VALUE:
10575 		/* There is no offset yet applied, variable or fixed */
10576 		mark_reg_known_zero(env, regs, BPF_REG_0);
10577 		/* remember map_ptr, so that check_map_access()
10578 		 * can check 'value_size' boundary of memory access
10579 		 * to map element returned from bpf_map_lookup_elem()
10580 		 */
10581 		if (meta.map_ptr == NULL) {
10582 			verbose(env,
10583 				"kernel subsystem misconfigured verifier\n");
10584 			return -EINVAL;
10585 		}
10586 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10587 		regs[BPF_REG_0].map_uid = meta.map_uid;
10588 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10589 		if (!type_may_be_null(ret_type) &&
10590 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10591 			regs[BPF_REG_0].id = ++env->id_gen;
10592 		}
10593 		break;
10594 	case RET_PTR_TO_SOCKET:
10595 		mark_reg_known_zero(env, regs, BPF_REG_0);
10596 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10597 		break;
10598 	case RET_PTR_TO_SOCK_COMMON:
10599 		mark_reg_known_zero(env, regs, BPF_REG_0);
10600 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10601 		break;
10602 	case RET_PTR_TO_TCP_SOCK:
10603 		mark_reg_known_zero(env, regs, BPF_REG_0);
10604 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10605 		break;
10606 	case RET_PTR_TO_MEM:
10607 		mark_reg_known_zero(env, regs, BPF_REG_0);
10608 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10609 		regs[BPF_REG_0].mem_size = meta.mem_size;
10610 		break;
10611 	case RET_PTR_TO_MEM_OR_BTF_ID:
10612 	{
10613 		const struct btf_type *t;
10614 
10615 		mark_reg_known_zero(env, regs, BPF_REG_0);
10616 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10617 		if (!btf_type_is_struct(t)) {
10618 			u32 tsize;
10619 			const struct btf_type *ret;
10620 			const char *tname;
10621 
10622 			/* resolve the type size of ksym. */
10623 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10624 			if (IS_ERR(ret)) {
10625 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10626 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10627 					tname, PTR_ERR(ret));
10628 				return -EINVAL;
10629 			}
10630 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10631 			regs[BPF_REG_0].mem_size = tsize;
10632 		} else {
10633 			if (returns_cpu_specific_alloc_ptr) {
10634 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10635 			} else {
10636 				/* MEM_RDONLY may be carried from ret_flag, but it
10637 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10638 				 * it will confuse the check of PTR_TO_BTF_ID in
10639 				 * check_mem_access().
10640 				 */
10641 				ret_flag &= ~MEM_RDONLY;
10642 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10643 			}
10644 
10645 			regs[BPF_REG_0].btf = meta.ret_btf;
10646 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10647 		}
10648 		break;
10649 	}
10650 	case RET_PTR_TO_BTF_ID:
10651 	{
10652 		struct btf *ret_btf;
10653 		int ret_btf_id;
10654 
10655 		mark_reg_known_zero(env, regs, BPF_REG_0);
10656 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10657 		if (func_id == BPF_FUNC_kptr_xchg) {
10658 			ret_btf = meta.kptr_field->kptr.btf;
10659 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10660 			if (!btf_is_kernel(ret_btf)) {
10661 				regs[BPF_REG_0].type |= MEM_ALLOC;
10662 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10663 					regs[BPF_REG_0].type |= MEM_PERCPU;
10664 			}
10665 		} else {
10666 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10667 				verbose(env, "verifier internal error:");
10668 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10669 					func_id_name(func_id));
10670 				return -EINVAL;
10671 			}
10672 			ret_btf = btf_vmlinux;
10673 			ret_btf_id = *fn->ret_btf_id;
10674 		}
10675 		if (ret_btf_id == 0) {
10676 			verbose(env, "invalid return type %u of func %s#%d\n",
10677 				base_type(ret_type), func_id_name(func_id),
10678 				func_id);
10679 			return -EINVAL;
10680 		}
10681 		regs[BPF_REG_0].btf = ret_btf;
10682 		regs[BPF_REG_0].btf_id = ret_btf_id;
10683 		break;
10684 	}
10685 	default:
10686 		verbose(env, "unknown return type %u of func %s#%d\n",
10687 			base_type(ret_type), func_id_name(func_id), func_id);
10688 		return -EINVAL;
10689 	}
10690 
10691 	if (type_may_be_null(regs[BPF_REG_0].type))
10692 		regs[BPF_REG_0].id = ++env->id_gen;
10693 
10694 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10695 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10696 			func_id_name(func_id), func_id);
10697 		return -EFAULT;
10698 	}
10699 
10700 	if (is_dynptr_ref_function(func_id))
10701 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10702 
10703 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10704 		/* For release_reference() */
10705 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10706 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10707 		int id = acquire_reference_state(env, insn_idx);
10708 
10709 		if (id < 0)
10710 			return id;
10711 		/* For mark_ptr_or_null_reg() */
10712 		regs[BPF_REG_0].id = id;
10713 		/* For release_reference() */
10714 		regs[BPF_REG_0].ref_obj_id = id;
10715 	}
10716 
10717 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10718 	if (err)
10719 		return err;
10720 
10721 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10722 	if (err)
10723 		return err;
10724 
10725 	if ((func_id == BPF_FUNC_get_stack ||
10726 	     func_id == BPF_FUNC_get_task_stack) &&
10727 	    !env->prog->has_callchain_buf) {
10728 		const char *err_str;
10729 
10730 #ifdef CONFIG_PERF_EVENTS
10731 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10732 		err_str = "cannot get callchain buffer for func %s#%d\n";
10733 #else
10734 		err = -ENOTSUPP;
10735 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10736 #endif
10737 		if (err) {
10738 			verbose(env, err_str, func_id_name(func_id), func_id);
10739 			return err;
10740 		}
10741 
10742 		env->prog->has_callchain_buf = true;
10743 	}
10744 
10745 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10746 		env->prog->call_get_stack = true;
10747 
10748 	if (func_id == BPF_FUNC_get_func_ip) {
10749 		if (check_get_func_ip(env))
10750 			return -ENOTSUPP;
10751 		env->prog->call_get_func_ip = true;
10752 	}
10753 
10754 	if (changes_data)
10755 		clear_all_pkt_pointers(env);
10756 	return 0;
10757 }
10758 
10759 /* mark_btf_func_reg_size() is used when the reg size is determined by
10760  * the BTF func_proto's return value size and argument.
10761  */
10762 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10763 				   size_t reg_size)
10764 {
10765 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10766 
10767 	if (regno == BPF_REG_0) {
10768 		/* Function return value */
10769 		reg->live |= REG_LIVE_WRITTEN;
10770 		reg->subreg_def = reg_size == sizeof(u64) ?
10771 			DEF_NOT_SUBREG : env->insn_idx + 1;
10772 	} else {
10773 		/* Function argument */
10774 		if (reg_size == sizeof(u64)) {
10775 			mark_insn_zext(env, reg);
10776 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10777 		} else {
10778 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10779 		}
10780 	}
10781 }
10782 
10783 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10784 {
10785 	return meta->kfunc_flags & KF_ACQUIRE;
10786 }
10787 
10788 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10789 {
10790 	return meta->kfunc_flags & KF_RELEASE;
10791 }
10792 
10793 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10794 {
10795 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10796 }
10797 
10798 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10799 {
10800 	return meta->kfunc_flags & KF_SLEEPABLE;
10801 }
10802 
10803 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10804 {
10805 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10806 }
10807 
10808 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10809 {
10810 	return meta->kfunc_flags & KF_RCU;
10811 }
10812 
10813 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10814 {
10815 	return meta->kfunc_flags & KF_RCU_PROTECTED;
10816 }
10817 
10818 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10819 				  const struct btf_param *arg,
10820 				  const struct bpf_reg_state *reg)
10821 {
10822 	const struct btf_type *t;
10823 
10824 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10825 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10826 		return false;
10827 
10828 	return btf_param_match_suffix(btf, arg, "__sz");
10829 }
10830 
10831 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10832 					const struct btf_param *arg,
10833 					const struct bpf_reg_state *reg)
10834 {
10835 	const struct btf_type *t;
10836 
10837 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10838 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10839 		return false;
10840 
10841 	return btf_param_match_suffix(btf, arg, "__szk");
10842 }
10843 
10844 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10845 {
10846 	return btf_param_match_suffix(btf, arg, "__opt");
10847 }
10848 
10849 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10850 {
10851 	return btf_param_match_suffix(btf, arg, "__k");
10852 }
10853 
10854 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10855 {
10856 	return btf_param_match_suffix(btf, arg, "__ign");
10857 }
10858 
10859 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
10860 {
10861 	return btf_param_match_suffix(btf, arg, "__map");
10862 }
10863 
10864 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10865 {
10866 	return btf_param_match_suffix(btf, arg, "__alloc");
10867 }
10868 
10869 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10870 {
10871 	return btf_param_match_suffix(btf, arg, "__uninit");
10872 }
10873 
10874 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10875 {
10876 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
10877 }
10878 
10879 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10880 {
10881 	return btf_param_match_suffix(btf, arg, "__nullable");
10882 }
10883 
10884 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
10885 {
10886 	return btf_param_match_suffix(btf, arg, "__str");
10887 }
10888 
10889 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10890 					  const struct btf_param *arg,
10891 					  const char *name)
10892 {
10893 	int len, target_len = strlen(name);
10894 	const char *param_name;
10895 
10896 	param_name = btf_name_by_offset(btf, arg->name_off);
10897 	if (str_is_empty(param_name))
10898 		return false;
10899 	len = strlen(param_name);
10900 	if (len != target_len)
10901 		return false;
10902 	if (strcmp(param_name, name))
10903 		return false;
10904 
10905 	return true;
10906 }
10907 
10908 enum {
10909 	KF_ARG_DYNPTR_ID,
10910 	KF_ARG_LIST_HEAD_ID,
10911 	KF_ARG_LIST_NODE_ID,
10912 	KF_ARG_RB_ROOT_ID,
10913 	KF_ARG_RB_NODE_ID,
10914 	KF_ARG_WORKQUEUE_ID,
10915 };
10916 
10917 BTF_ID_LIST(kf_arg_btf_ids)
10918 BTF_ID(struct, bpf_dynptr_kern)
10919 BTF_ID(struct, bpf_list_head)
10920 BTF_ID(struct, bpf_list_node)
10921 BTF_ID(struct, bpf_rb_root)
10922 BTF_ID(struct, bpf_rb_node)
10923 BTF_ID(struct, bpf_wq)
10924 
10925 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10926 				    const struct btf_param *arg, int type)
10927 {
10928 	const struct btf_type *t;
10929 	u32 res_id;
10930 
10931 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10932 	if (!t)
10933 		return false;
10934 	if (!btf_type_is_ptr(t))
10935 		return false;
10936 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10937 	if (!t)
10938 		return false;
10939 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10940 }
10941 
10942 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10943 {
10944 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10945 }
10946 
10947 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10948 {
10949 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10950 }
10951 
10952 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10953 {
10954 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10955 }
10956 
10957 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10958 {
10959 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10960 }
10961 
10962 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10963 {
10964 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10965 }
10966 
10967 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
10968 {
10969 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
10970 }
10971 
10972 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10973 				  const struct btf_param *arg)
10974 {
10975 	const struct btf_type *t;
10976 
10977 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10978 	if (!t)
10979 		return false;
10980 
10981 	return true;
10982 }
10983 
10984 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10985 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10986 					const struct btf *btf,
10987 					const struct btf_type *t, int rec)
10988 {
10989 	const struct btf_type *member_type;
10990 	const struct btf_member *member;
10991 	u32 i;
10992 
10993 	if (!btf_type_is_struct(t))
10994 		return false;
10995 
10996 	for_each_member(i, t, member) {
10997 		const struct btf_array *array;
10998 
10999 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
11000 		if (btf_type_is_struct(member_type)) {
11001 			if (rec >= 3) {
11002 				verbose(env, "max struct nesting depth exceeded\n");
11003 				return false;
11004 			}
11005 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
11006 				return false;
11007 			continue;
11008 		}
11009 		if (btf_type_is_array(member_type)) {
11010 			array = btf_array(member_type);
11011 			if (!array->nelems)
11012 				return false;
11013 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
11014 			if (!btf_type_is_scalar(member_type))
11015 				return false;
11016 			continue;
11017 		}
11018 		if (!btf_type_is_scalar(member_type))
11019 			return false;
11020 	}
11021 	return true;
11022 }
11023 
11024 enum kfunc_ptr_arg_type {
11025 	KF_ARG_PTR_TO_CTX,
11026 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
11027 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
11028 	KF_ARG_PTR_TO_DYNPTR,
11029 	KF_ARG_PTR_TO_ITER,
11030 	KF_ARG_PTR_TO_LIST_HEAD,
11031 	KF_ARG_PTR_TO_LIST_NODE,
11032 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
11033 	KF_ARG_PTR_TO_MEM,
11034 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
11035 	KF_ARG_PTR_TO_CALLBACK,
11036 	KF_ARG_PTR_TO_RB_ROOT,
11037 	KF_ARG_PTR_TO_RB_NODE,
11038 	KF_ARG_PTR_TO_NULL,
11039 	KF_ARG_PTR_TO_CONST_STR,
11040 	KF_ARG_PTR_TO_MAP,
11041 	KF_ARG_PTR_TO_WORKQUEUE,
11042 };
11043 
11044 enum special_kfunc_type {
11045 	KF_bpf_obj_new_impl,
11046 	KF_bpf_obj_drop_impl,
11047 	KF_bpf_refcount_acquire_impl,
11048 	KF_bpf_list_push_front_impl,
11049 	KF_bpf_list_push_back_impl,
11050 	KF_bpf_list_pop_front,
11051 	KF_bpf_list_pop_back,
11052 	KF_bpf_cast_to_kern_ctx,
11053 	KF_bpf_rdonly_cast,
11054 	KF_bpf_rcu_read_lock,
11055 	KF_bpf_rcu_read_unlock,
11056 	KF_bpf_rbtree_remove,
11057 	KF_bpf_rbtree_add_impl,
11058 	KF_bpf_rbtree_first,
11059 	KF_bpf_dynptr_from_skb,
11060 	KF_bpf_dynptr_from_xdp,
11061 	KF_bpf_dynptr_slice,
11062 	KF_bpf_dynptr_slice_rdwr,
11063 	KF_bpf_dynptr_clone,
11064 	KF_bpf_percpu_obj_new_impl,
11065 	KF_bpf_percpu_obj_drop_impl,
11066 	KF_bpf_throw,
11067 	KF_bpf_wq_set_callback_impl,
11068 	KF_bpf_preempt_disable,
11069 	KF_bpf_preempt_enable,
11070 	KF_bpf_iter_css_task_new,
11071 	KF_bpf_session_cookie,
11072 };
11073 
11074 BTF_SET_START(special_kfunc_set)
11075 BTF_ID(func, bpf_obj_new_impl)
11076 BTF_ID(func, bpf_obj_drop_impl)
11077 BTF_ID(func, bpf_refcount_acquire_impl)
11078 BTF_ID(func, bpf_list_push_front_impl)
11079 BTF_ID(func, bpf_list_push_back_impl)
11080 BTF_ID(func, bpf_list_pop_front)
11081 BTF_ID(func, bpf_list_pop_back)
11082 BTF_ID(func, bpf_cast_to_kern_ctx)
11083 BTF_ID(func, bpf_rdonly_cast)
11084 BTF_ID(func, bpf_rbtree_remove)
11085 BTF_ID(func, bpf_rbtree_add_impl)
11086 BTF_ID(func, bpf_rbtree_first)
11087 BTF_ID(func, bpf_dynptr_from_skb)
11088 BTF_ID(func, bpf_dynptr_from_xdp)
11089 BTF_ID(func, bpf_dynptr_slice)
11090 BTF_ID(func, bpf_dynptr_slice_rdwr)
11091 BTF_ID(func, bpf_dynptr_clone)
11092 BTF_ID(func, bpf_percpu_obj_new_impl)
11093 BTF_ID(func, bpf_percpu_obj_drop_impl)
11094 BTF_ID(func, bpf_throw)
11095 BTF_ID(func, bpf_wq_set_callback_impl)
11096 #ifdef CONFIG_CGROUPS
11097 BTF_ID(func, bpf_iter_css_task_new)
11098 #endif
11099 BTF_SET_END(special_kfunc_set)
11100 
11101 BTF_ID_LIST(special_kfunc_list)
11102 BTF_ID(func, bpf_obj_new_impl)
11103 BTF_ID(func, bpf_obj_drop_impl)
11104 BTF_ID(func, bpf_refcount_acquire_impl)
11105 BTF_ID(func, bpf_list_push_front_impl)
11106 BTF_ID(func, bpf_list_push_back_impl)
11107 BTF_ID(func, bpf_list_pop_front)
11108 BTF_ID(func, bpf_list_pop_back)
11109 BTF_ID(func, bpf_cast_to_kern_ctx)
11110 BTF_ID(func, bpf_rdonly_cast)
11111 BTF_ID(func, bpf_rcu_read_lock)
11112 BTF_ID(func, bpf_rcu_read_unlock)
11113 BTF_ID(func, bpf_rbtree_remove)
11114 BTF_ID(func, bpf_rbtree_add_impl)
11115 BTF_ID(func, bpf_rbtree_first)
11116 BTF_ID(func, bpf_dynptr_from_skb)
11117 BTF_ID(func, bpf_dynptr_from_xdp)
11118 BTF_ID(func, bpf_dynptr_slice)
11119 BTF_ID(func, bpf_dynptr_slice_rdwr)
11120 BTF_ID(func, bpf_dynptr_clone)
11121 BTF_ID(func, bpf_percpu_obj_new_impl)
11122 BTF_ID(func, bpf_percpu_obj_drop_impl)
11123 BTF_ID(func, bpf_throw)
11124 BTF_ID(func, bpf_wq_set_callback_impl)
11125 BTF_ID(func, bpf_preempt_disable)
11126 BTF_ID(func, bpf_preempt_enable)
11127 #ifdef CONFIG_CGROUPS
11128 BTF_ID(func, bpf_iter_css_task_new)
11129 #else
11130 BTF_ID_UNUSED
11131 #endif
11132 #ifdef CONFIG_BPF_EVENTS
11133 BTF_ID(func, bpf_session_cookie)
11134 #else
11135 BTF_ID_UNUSED
11136 #endif
11137 
11138 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
11139 {
11140 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
11141 	    meta->arg_owning_ref) {
11142 		return false;
11143 	}
11144 
11145 	return meta->kfunc_flags & KF_RET_NULL;
11146 }
11147 
11148 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
11149 {
11150 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11151 }
11152 
11153 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11154 {
11155 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11156 }
11157 
11158 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
11159 {
11160 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
11161 }
11162 
11163 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
11164 {
11165 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
11166 }
11167 
11168 static enum kfunc_ptr_arg_type
11169 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
11170 		       struct bpf_kfunc_call_arg_meta *meta,
11171 		       const struct btf_type *t, const struct btf_type *ref_t,
11172 		       const char *ref_tname, const struct btf_param *args,
11173 		       int argno, int nargs)
11174 {
11175 	u32 regno = argno + 1;
11176 	struct bpf_reg_state *regs = cur_regs(env);
11177 	struct bpf_reg_state *reg = &regs[regno];
11178 	bool arg_mem_size = false;
11179 
11180 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11181 		return KF_ARG_PTR_TO_CTX;
11182 
11183 	/* In this function, we verify the kfunc's BTF as per the argument type,
11184 	 * leaving the rest of the verification with respect to the register
11185 	 * type to our caller. When a set of conditions hold in the BTF type of
11186 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11187 	 */
11188 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11189 		return KF_ARG_PTR_TO_CTX;
11190 
11191 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11192 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11193 
11194 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11195 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11196 
11197 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11198 		return KF_ARG_PTR_TO_DYNPTR;
11199 
11200 	if (is_kfunc_arg_iter(meta, argno))
11201 		return KF_ARG_PTR_TO_ITER;
11202 
11203 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11204 		return KF_ARG_PTR_TO_LIST_HEAD;
11205 
11206 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11207 		return KF_ARG_PTR_TO_LIST_NODE;
11208 
11209 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11210 		return KF_ARG_PTR_TO_RB_ROOT;
11211 
11212 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11213 		return KF_ARG_PTR_TO_RB_NODE;
11214 
11215 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11216 		return KF_ARG_PTR_TO_CONST_STR;
11217 
11218 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
11219 		return KF_ARG_PTR_TO_MAP;
11220 
11221 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
11222 		return KF_ARG_PTR_TO_WORKQUEUE;
11223 
11224 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11225 		if (!btf_type_is_struct(ref_t)) {
11226 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11227 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11228 			return -EINVAL;
11229 		}
11230 		return KF_ARG_PTR_TO_BTF_ID;
11231 	}
11232 
11233 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11234 		return KF_ARG_PTR_TO_CALLBACK;
11235 
11236 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11237 		return KF_ARG_PTR_TO_NULL;
11238 
11239 	if (argno + 1 < nargs &&
11240 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
11241 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
11242 		arg_mem_size = true;
11243 
11244 	/* This is the catch all argument type of register types supported by
11245 	 * check_helper_mem_access. However, we only allow when argument type is
11246 	 * pointer to scalar, or struct composed (recursively) of scalars. When
11247 	 * arg_mem_size is true, the pointer can be void *.
11248 	 */
11249 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11250 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11251 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11252 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11253 		return -EINVAL;
11254 	}
11255 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11256 }
11257 
11258 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11259 					struct bpf_reg_state *reg,
11260 					const struct btf_type *ref_t,
11261 					const char *ref_tname, u32 ref_id,
11262 					struct bpf_kfunc_call_arg_meta *meta,
11263 					int argno)
11264 {
11265 	const struct btf_type *reg_ref_t;
11266 	bool strict_type_match = false;
11267 	const struct btf *reg_btf;
11268 	const char *reg_ref_tname;
11269 	u32 reg_ref_id;
11270 
11271 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
11272 		reg_btf = reg->btf;
11273 		reg_ref_id = reg->btf_id;
11274 	} else {
11275 		reg_btf = btf_vmlinux;
11276 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11277 	}
11278 
11279 	/* Enforce strict type matching for calls to kfuncs that are acquiring
11280 	 * or releasing a reference, or are no-cast aliases. We do _not_
11281 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11282 	 * as we want to enable BPF programs to pass types that are bitwise
11283 	 * equivalent without forcing them to explicitly cast with something
11284 	 * like bpf_cast_to_kern_ctx().
11285 	 *
11286 	 * For example, say we had a type like the following:
11287 	 *
11288 	 * struct bpf_cpumask {
11289 	 *	cpumask_t cpumask;
11290 	 *	refcount_t usage;
11291 	 * };
11292 	 *
11293 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11294 	 * to a struct cpumask, so it would be safe to pass a struct
11295 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11296 	 *
11297 	 * The philosophy here is similar to how we allow scalars of different
11298 	 * types to be passed to kfuncs as long as the size is the same. The
11299 	 * only difference here is that we're simply allowing
11300 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11301 	 * resolve types.
11302 	 */
11303 	if (is_kfunc_acquire(meta) ||
11304 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
11305 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11306 		strict_type_match = true;
11307 
11308 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
11309 
11310 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
11311 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11312 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
11313 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11314 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11315 			btf_type_str(reg_ref_t), reg_ref_tname);
11316 		return -EINVAL;
11317 	}
11318 	return 0;
11319 }
11320 
11321 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11322 {
11323 	struct bpf_verifier_state *state = env->cur_state;
11324 	struct btf_record *rec = reg_btf_record(reg);
11325 
11326 	if (!state->active_lock.ptr) {
11327 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11328 		return -EFAULT;
11329 	}
11330 
11331 	if (type_flag(reg->type) & NON_OWN_REF) {
11332 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11333 		return -EFAULT;
11334 	}
11335 
11336 	reg->type |= NON_OWN_REF;
11337 	if (rec->refcount_off >= 0)
11338 		reg->type |= MEM_RCU;
11339 
11340 	return 0;
11341 }
11342 
11343 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11344 {
11345 	struct bpf_func_state *state, *unused;
11346 	struct bpf_reg_state *reg;
11347 	int i;
11348 
11349 	state = cur_func(env);
11350 
11351 	if (!ref_obj_id) {
11352 		verbose(env, "verifier internal error: ref_obj_id is zero for "
11353 			     "owning -> non-owning conversion\n");
11354 		return -EFAULT;
11355 	}
11356 
11357 	for (i = 0; i < state->acquired_refs; i++) {
11358 		if (state->refs[i].id != ref_obj_id)
11359 			continue;
11360 
11361 		/* Clear ref_obj_id here so release_reference doesn't clobber
11362 		 * the whole reg
11363 		 */
11364 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11365 			if (reg->ref_obj_id == ref_obj_id) {
11366 				reg->ref_obj_id = 0;
11367 				ref_set_non_owning(env, reg);
11368 			}
11369 		}));
11370 		return 0;
11371 	}
11372 
11373 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11374 	return -EFAULT;
11375 }
11376 
11377 /* Implementation details:
11378  *
11379  * Each register points to some region of memory, which we define as an
11380  * allocation. Each allocation may embed a bpf_spin_lock which protects any
11381  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11382  * allocation. The lock and the data it protects are colocated in the same
11383  * memory region.
11384  *
11385  * Hence, everytime a register holds a pointer value pointing to such
11386  * allocation, the verifier preserves a unique reg->id for it.
11387  *
11388  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11389  * bpf_spin_lock is called.
11390  *
11391  * To enable this, lock state in the verifier captures two values:
11392  *	active_lock.ptr = Register's type specific pointer
11393  *	active_lock.id  = A unique ID for each register pointer value
11394  *
11395  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11396  * supported register types.
11397  *
11398  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11399  * allocated objects is the reg->btf pointer.
11400  *
11401  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11402  * can establish the provenance of the map value statically for each distinct
11403  * lookup into such maps. They always contain a single map value hence unique
11404  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11405  *
11406  * So, in case of global variables, they use array maps with max_entries = 1,
11407  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11408  * into the same map value as max_entries is 1, as described above).
11409  *
11410  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11411  * outer map pointer (in verifier context), but each lookup into an inner map
11412  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11413  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11414  * will get different reg->id assigned to each lookup, hence different
11415  * active_lock.id.
11416  *
11417  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11418  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11419  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11420  */
11421 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11422 {
11423 	void *ptr;
11424 	u32 id;
11425 
11426 	switch ((int)reg->type) {
11427 	case PTR_TO_MAP_VALUE:
11428 		ptr = reg->map_ptr;
11429 		break;
11430 	case PTR_TO_BTF_ID | MEM_ALLOC:
11431 		ptr = reg->btf;
11432 		break;
11433 	default:
11434 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11435 		return -EFAULT;
11436 	}
11437 	id = reg->id;
11438 
11439 	if (!env->cur_state->active_lock.ptr)
11440 		return -EINVAL;
11441 	if (env->cur_state->active_lock.ptr != ptr ||
11442 	    env->cur_state->active_lock.id != id) {
11443 		verbose(env, "held lock and object are not in the same allocation\n");
11444 		return -EINVAL;
11445 	}
11446 	return 0;
11447 }
11448 
11449 static bool is_bpf_list_api_kfunc(u32 btf_id)
11450 {
11451 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11452 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11453 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11454 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11455 }
11456 
11457 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11458 {
11459 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11460 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11461 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11462 }
11463 
11464 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11465 {
11466 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11467 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11468 }
11469 
11470 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11471 {
11472 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11473 }
11474 
11475 static bool is_async_callback_calling_kfunc(u32 btf_id)
11476 {
11477 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
11478 }
11479 
11480 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11481 {
11482 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11483 	       insn->imm == special_kfunc_list[KF_bpf_throw];
11484 }
11485 
11486 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
11487 {
11488 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
11489 }
11490 
11491 static bool is_callback_calling_kfunc(u32 btf_id)
11492 {
11493 	return is_sync_callback_calling_kfunc(btf_id) ||
11494 	       is_async_callback_calling_kfunc(btf_id);
11495 }
11496 
11497 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11498 {
11499 	return is_bpf_rbtree_api_kfunc(btf_id);
11500 }
11501 
11502 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11503 					  enum btf_field_type head_field_type,
11504 					  u32 kfunc_btf_id)
11505 {
11506 	bool ret;
11507 
11508 	switch (head_field_type) {
11509 	case BPF_LIST_HEAD:
11510 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11511 		break;
11512 	case BPF_RB_ROOT:
11513 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11514 		break;
11515 	default:
11516 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11517 			btf_field_type_name(head_field_type));
11518 		return false;
11519 	}
11520 
11521 	if (!ret)
11522 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11523 			btf_field_type_name(head_field_type));
11524 	return ret;
11525 }
11526 
11527 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11528 					  enum btf_field_type node_field_type,
11529 					  u32 kfunc_btf_id)
11530 {
11531 	bool ret;
11532 
11533 	switch (node_field_type) {
11534 	case BPF_LIST_NODE:
11535 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11536 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11537 		break;
11538 	case BPF_RB_NODE:
11539 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11540 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11541 		break;
11542 	default:
11543 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11544 			btf_field_type_name(node_field_type));
11545 		return false;
11546 	}
11547 
11548 	if (!ret)
11549 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11550 			btf_field_type_name(node_field_type));
11551 	return ret;
11552 }
11553 
11554 static int
11555 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11556 				   struct bpf_reg_state *reg, u32 regno,
11557 				   struct bpf_kfunc_call_arg_meta *meta,
11558 				   enum btf_field_type head_field_type,
11559 				   struct btf_field **head_field)
11560 {
11561 	const char *head_type_name;
11562 	struct btf_field *field;
11563 	struct btf_record *rec;
11564 	u32 head_off;
11565 
11566 	if (meta->btf != btf_vmlinux) {
11567 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11568 		return -EFAULT;
11569 	}
11570 
11571 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11572 		return -EFAULT;
11573 
11574 	head_type_name = btf_field_type_name(head_field_type);
11575 	if (!tnum_is_const(reg->var_off)) {
11576 		verbose(env,
11577 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11578 			regno, head_type_name);
11579 		return -EINVAL;
11580 	}
11581 
11582 	rec = reg_btf_record(reg);
11583 	head_off = reg->off + reg->var_off.value;
11584 	field = btf_record_find(rec, head_off, head_field_type);
11585 	if (!field) {
11586 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11587 		return -EINVAL;
11588 	}
11589 
11590 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11591 	if (check_reg_allocation_locked(env, reg)) {
11592 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11593 			rec->spin_lock_off, head_type_name);
11594 		return -EINVAL;
11595 	}
11596 
11597 	if (*head_field) {
11598 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11599 		return -EFAULT;
11600 	}
11601 	*head_field = field;
11602 	return 0;
11603 }
11604 
11605 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11606 					   struct bpf_reg_state *reg, u32 regno,
11607 					   struct bpf_kfunc_call_arg_meta *meta)
11608 {
11609 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11610 							  &meta->arg_list_head.field);
11611 }
11612 
11613 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11614 					     struct bpf_reg_state *reg, u32 regno,
11615 					     struct bpf_kfunc_call_arg_meta *meta)
11616 {
11617 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11618 							  &meta->arg_rbtree_root.field);
11619 }
11620 
11621 static int
11622 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11623 				   struct bpf_reg_state *reg, u32 regno,
11624 				   struct bpf_kfunc_call_arg_meta *meta,
11625 				   enum btf_field_type head_field_type,
11626 				   enum btf_field_type node_field_type,
11627 				   struct btf_field **node_field)
11628 {
11629 	const char *node_type_name;
11630 	const struct btf_type *et, *t;
11631 	struct btf_field *field;
11632 	u32 node_off;
11633 
11634 	if (meta->btf != btf_vmlinux) {
11635 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11636 		return -EFAULT;
11637 	}
11638 
11639 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11640 		return -EFAULT;
11641 
11642 	node_type_name = btf_field_type_name(node_field_type);
11643 	if (!tnum_is_const(reg->var_off)) {
11644 		verbose(env,
11645 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11646 			regno, node_type_name);
11647 		return -EINVAL;
11648 	}
11649 
11650 	node_off = reg->off + reg->var_off.value;
11651 	field = reg_find_field_offset(reg, node_off, node_field_type);
11652 	if (!field) {
11653 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11654 		return -EINVAL;
11655 	}
11656 
11657 	field = *node_field;
11658 
11659 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11660 	t = btf_type_by_id(reg->btf, reg->btf_id);
11661 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11662 				  field->graph_root.value_btf_id, true)) {
11663 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11664 			"in struct %s, but arg is at offset=%d in struct %s\n",
11665 			btf_field_type_name(head_field_type),
11666 			btf_field_type_name(node_field_type),
11667 			field->graph_root.node_offset,
11668 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11669 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11670 		return -EINVAL;
11671 	}
11672 	meta->arg_btf = reg->btf;
11673 	meta->arg_btf_id = reg->btf_id;
11674 
11675 	if (node_off != field->graph_root.node_offset) {
11676 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11677 			node_off, btf_field_type_name(node_field_type),
11678 			field->graph_root.node_offset,
11679 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11680 		return -EINVAL;
11681 	}
11682 
11683 	return 0;
11684 }
11685 
11686 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11687 					   struct bpf_reg_state *reg, u32 regno,
11688 					   struct bpf_kfunc_call_arg_meta *meta)
11689 {
11690 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11691 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11692 						  &meta->arg_list_head.field);
11693 }
11694 
11695 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11696 					     struct bpf_reg_state *reg, u32 regno,
11697 					     struct bpf_kfunc_call_arg_meta *meta)
11698 {
11699 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11700 						  BPF_RB_ROOT, BPF_RB_NODE,
11701 						  &meta->arg_rbtree_root.field);
11702 }
11703 
11704 /*
11705  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11706  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11707  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11708  * them can only be attached to some specific hook points.
11709  */
11710 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11711 {
11712 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11713 
11714 	switch (prog_type) {
11715 	case BPF_PROG_TYPE_LSM:
11716 		return true;
11717 	case BPF_PROG_TYPE_TRACING:
11718 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11719 			return true;
11720 		fallthrough;
11721 	default:
11722 		return in_sleepable(env);
11723 	}
11724 }
11725 
11726 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11727 			    int insn_idx)
11728 {
11729 	const char *func_name = meta->func_name, *ref_tname;
11730 	const struct btf *btf = meta->btf;
11731 	const struct btf_param *args;
11732 	struct btf_record *rec;
11733 	u32 i, nargs;
11734 	int ret;
11735 
11736 	args = (const struct btf_param *)(meta->func_proto + 1);
11737 	nargs = btf_type_vlen(meta->func_proto);
11738 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11739 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11740 			MAX_BPF_FUNC_REG_ARGS);
11741 		return -EINVAL;
11742 	}
11743 
11744 	/* Check that BTF function arguments match actual types that the
11745 	 * verifier sees.
11746 	 */
11747 	for (i = 0; i < nargs; i++) {
11748 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11749 		const struct btf_type *t, *ref_t, *resolve_ret;
11750 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11751 		u32 regno = i + 1, ref_id, type_size;
11752 		bool is_ret_buf_sz = false;
11753 		int kf_arg_type;
11754 
11755 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11756 
11757 		if (is_kfunc_arg_ignore(btf, &args[i]))
11758 			continue;
11759 
11760 		if (btf_type_is_scalar(t)) {
11761 			if (reg->type != SCALAR_VALUE) {
11762 				verbose(env, "R%d is not a scalar\n", regno);
11763 				return -EINVAL;
11764 			}
11765 
11766 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11767 				if (meta->arg_constant.found) {
11768 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11769 					return -EFAULT;
11770 				}
11771 				if (!tnum_is_const(reg->var_off)) {
11772 					verbose(env, "R%d must be a known constant\n", regno);
11773 					return -EINVAL;
11774 				}
11775 				ret = mark_chain_precision(env, regno);
11776 				if (ret < 0)
11777 					return ret;
11778 				meta->arg_constant.found = true;
11779 				meta->arg_constant.value = reg->var_off.value;
11780 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11781 				meta->r0_rdonly = true;
11782 				is_ret_buf_sz = true;
11783 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11784 				is_ret_buf_sz = true;
11785 			}
11786 
11787 			if (is_ret_buf_sz) {
11788 				if (meta->r0_size) {
11789 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11790 					return -EINVAL;
11791 				}
11792 
11793 				if (!tnum_is_const(reg->var_off)) {
11794 					verbose(env, "R%d is not a const\n", regno);
11795 					return -EINVAL;
11796 				}
11797 
11798 				meta->r0_size = reg->var_off.value;
11799 				ret = mark_chain_precision(env, regno);
11800 				if (ret)
11801 					return ret;
11802 			}
11803 			continue;
11804 		}
11805 
11806 		if (!btf_type_is_ptr(t)) {
11807 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11808 			return -EINVAL;
11809 		}
11810 
11811 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11812 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
11813 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
11814 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11815 			return -EACCES;
11816 		}
11817 
11818 		if (reg->ref_obj_id) {
11819 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11820 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11821 					regno, reg->ref_obj_id,
11822 					meta->ref_obj_id);
11823 				return -EFAULT;
11824 			}
11825 			meta->ref_obj_id = reg->ref_obj_id;
11826 			if (is_kfunc_release(meta))
11827 				meta->release_regno = regno;
11828 		}
11829 
11830 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11831 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11832 
11833 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11834 		if (kf_arg_type < 0)
11835 			return kf_arg_type;
11836 
11837 		switch (kf_arg_type) {
11838 		case KF_ARG_PTR_TO_NULL:
11839 			continue;
11840 		case KF_ARG_PTR_TO_MAP:
11841 			if (!reg->map_ptr) {
11842 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
11843 				return -EINVAL;
11844 			}
11845 			if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) {
11846 				/* Use map_uid (which is unique id of inner map) to reject:
11847 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
11848 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
11849 				 * if (inner_map1 && inner_map2) {
11850 				 *     wq = bpf_map_lookup_elem(inner_map1);
11851 				 *     if (wq)
11852 				 *         // mismatch would have been allowed
11853 				 *         bpf_wq_init(wq, inner_map2);
11854 				 * }
11855 				 *
11856 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
11857 				 */
11858 				if (meta->map.ptr != reg->map_ptr ||
11859 				    meta->map.uid != reg->map_uid) {
11860 					verbose(env,
11861 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
11862 						meta->map.uid, reg->map_uid);
11863 					return -EINVAL;
11864 				}
11865 			}
11866 			meta->map.ptr = reg->map_ptr;
11867 			meta->map.uid = reg->map_uid;
11868 			fallthrough;
11869 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11870 		case KF_ARG_PTR_TO_BTF_ID:
11871 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11872 				break;
11873 
11874 			if (!is_trusted_reg(reg)) {
11875 				if (!is_kfunc_rcu(meta)) {
11876 					verbose(env, "R%d must be referenced or trusted\n", regno);
11877 					return -EINVAL;
11878 				}
11879 				if (!is_rcu_reg(reg)) {
11880 					verbose(env, "R%d must be a rcu pointer\n", regno);
11881 					return -EINVAL;
11882 				}
11883 			}
11884 
11885 			fallthrough;
11886 		case KF_ARG_PTR_TO_CTX:
11887 			/* Trusted arguments have the same offset checks as release arguments */
11888 			arg_type |= OBJ_RELEASE;
11889 			break;
11890 		case KF_ARG_PTR_TO_DYNPTR:
11891 		case KF_ARG_PTR_TO_ITER:
11892 		case KF_ARG_PTR_TO_LIST_HEAD:
11893 		case KF_ARG_PTR_TO_LIST_NODE:
11894 		case KF_ARG_PTR_TO_RB_ROOT:
11895 		case KF_ARG_PTR_TO_RB_NODE:
11896 		case KF_ARG_PTR_TO_MEM:
11897 		case KF_ARG_PTR_TO_MEM_SIZE:
11898 		case KF_ARG_PTR_TO_CALLBACK:
11899 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11900 		case KF_ARG_PTR_TO_CONST_STR:
11901 		case KF_ARG_PTR_TO_WORKQUEUE:
11902 			/* Trusted by default */
11903 			break;
11904 		default:
11905 			WARN_ON_ONCE(1);
11906 			return -EFAULT;
11907 		}
11908 
11909 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11910 			arg_type |= OBJ_RELEASE;
11911 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11912 		if (ret < 0)
11913 			return ret;
11914 
11915 		switch (kf_arg_type) {
11916 		case KF_ARG_PTR_TO_CTX:
11917 			if (reg->type != PTR_TO_CTX) {
11918 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11919 				return -EINVAL;
11920 			}
11921 
11922 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11923 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11924 				if (ret < 0)
11925 					return -EINVAL;
11926 				meta->ret_btf_id  = ret;
11927 			}
11928 			break;
11929 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11930 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11931 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11932 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11933 					return -EINVAL;
11934 				}
11935 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11936 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11937 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11938 					return -EINVAL;
11939 				}
11940 			} else {
11941 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11942 				return -EINVAL;
11943 			}
11944 			if (!reg->ref_obj_id) {
11945 				verbose(env, "allocated object must be referenced\n");
11946 				return -EINVAL;
11947 			}
11948 			if (meta->btf == btf_vmlinux) {
11949 				meta->arg_btf = reg->btf;
11950 				meta->arg_btf_id = reg->btf_id;
11951 			}
11952 			break;
11953 		case KF_ARG_PTR_TO_DYNPTR:
11954 		{
11955 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11956 			int clone_ref_obj_id = 0;
11957 
11958 			if (reg->type != PTR_TO_STACK &&
11959 			    reg->type != CONST_PTR_TO_DYNPTR) {
11960 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11961 				return -EINVAL;
11962 			}
11963 
11964 			if (reg->type == CONST_PTR_TO_DYNPTR)
11965 				dynptr_arg_type |= MEM_RDONLY;
11966 
11967 			if (is_kfunc_arg_uninit(btf, &args[i]))
11968 				dynptr_arg_type |= MEM_UNINIT;
11969 
11970 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11971 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11972 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11973 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11974 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11975 				   (dynptr_arg_type & MEM_UNINIT)) {
11976 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11977 
11978 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11979 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11980 					return -EFAULT;
11981 				}
11982 
11983 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11984 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11985 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11986 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11987 					return -EFAULT;
11988 				}
11989 			}
11990 
11991 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11992 			if (ret < 0)
11993 				return ret;
11994 
11995 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11996 				int id = dynptr_id(env, reg);
11997 
11998 				if (id < 0) {
11999 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
12000 					return id;
12001 				}
12002 				meta->initialized_dynptr.id = id;
12003 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
12004 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
12005 			}
12006 
12007 			break;
12008 		}
12009 		case KF_ARG_PTR_TO_ITER:
12010 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
12011 				if (!check_css_task_iter_allowlist(env)) {
12012 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
12013 					return -EINVAL;
12014 				}
12015 			}
12016 			ret = process_iter_arg(env, regno, insn_idx, meta);
12017 			if (ret < 0)
12018 				return ret;
12019 			break;
12020 		case KF_ARG_PTR_TO_LIST_HEAD:
12021 			if (reg->type != PTR_TO_MAP_VALUE &&
12022 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12023 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12024 				return -EINVAL;
12025 			}
12026 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12027 				verbose(env, "allocated object must be referenced\n");
12028 				return -EINVAL;
12029 			}
12030 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
12031 			if (ret < 0)
12032 				return ret;
12033 			break;
12034 		case KF_ARG_PTR_TO_RB_ROOT:
12035 			if (reg->type != PTR_TO_MAP_VALUE &&
12036 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12037 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12038 				return -EINVAL;
12039 			}
12040 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12041 				verbose(env, "allocated object must be referenced\n");
12042 				return -EINVAL;
12043 			}
12044 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
12045 			if (ret < 0)
12046 				return ret;
12047 			break;
12048 		case KF_ARG_PTR_TO_LIST_NODE:
12049 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12050 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
12051 				return -EINVAL;
12052 			}
12053 			if (!reg->ref_obj_id) {
12054 				verbose(env, "allocated object must be referenced\n");
12055 				return -EINVAL;
12056 			}
12057 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
12058 			if (ret < 0)
12059 				return ret;
12060 			break;
12061 		case KF_ARG_PTR_TO_RB_NODE:
12062 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
12063 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
12064 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
12065 					return -EINVAL;
12066 				}
12067 				if (in_rbtree_lock_required_cb(env)) {
12068 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
12069 					return -EINVAL;
12070 				}
12071 			} else {
12072 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12073 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
12074 					return -EINVAL;
12075 				}
12076 				if (!reg->ref_obj_id) {
12077 					verbose(env, "allocated object must be referenced\n");
12078 					return -EINVAL;
12079 				}
12080 			}
12081 
12082 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
12083 			if (ret < 0)
12084 				return ret;
12085 			break;
12086 		case KF_ARG_PTR_TO_MAP:
12087 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
12088 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
12089 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
12090 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12091 			fallthrough;
12092 		case KF_ARG_PTR_TO_BTF_ID:
12093 			/* Only base_type is checked, further checks are done here */
12094 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
12095 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
12096 			    !reg2btf_ids[base_type(reg->type)]) {
12097 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
12098 				verbose(env, "expected %s or socket\n",
12099 					reg_type_str(env, base_type(reg->type) |
12100 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
12101 				return -EINVAL;
12102 			}
12103 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
12104 			if (ret < 0)
12105 				return ret;
12106 			break;
12107 		case KF_ARG_PTR_TO_MEM:
12108 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
12109 			if (IS_ERR(resolve_ret)) {
12110 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
12111 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
12112 				return -EINVAL;
12113 			}
12114 			ret = check_mem_reg(env, reg, regno, type_size);
12115 			if (ret < 0)
12116 				return ret;
12117 			break;
12118 		case KF_ARG_PTR_TO_MEM_SIZE:
12119 		{
12120 			struct bpf_reg_state *buff_reg = &regs[regno];
12121 			const struct btf_param *buff_arg = &args[i];
12122 			struct bpf_reg_state *size_reg = &regs[regno + 1];
12123 			const struct btf_param *size_arg = &args[i + 1];
12124 
12125 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
12126 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
12127 				if (ret < 0) {
12128 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
12129 					return ret;
12130 				}
12131 			}
12132 
12133 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
12134 				if (meta->arg_constant.found) {
12135 					verbose(env, "verifier internal error: only one constant argument permitted\n");
12136 					return -EFAULT;
12137 				}
12138 				if (!tnum_is_const(size_reg->var_off)) {
12139 					verbose(env, "R%d must be a known constant\n", regno + 1);
12140 					return -EINVAL;
12141 				}
12142 				meta->arg_constant.found = true;
12143 				meta->arg_constant.value = size_reg->var_off.value;
12144 			}
12145 
12146 			/* Skip next '__sz' or '__szk' argument */
12147 			i++;
12148 			break;
12149 		}
12150 		case KF_ARG_PTR_TO_CALLBACK:
12151 			if (reg->type != PTR_TO_FUNC) {
12152 				verbose(env, "arg%d expected pointer to func\n", i);
12153 				return -EINVAL;
12154 			}
12155 			meta->subprogno = reg->subprogno;
12156 			break;
12157 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12158 			if (!type_is_ptr_alloc_obj(reg->type)) {
12159 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
12160 				return -EINVAL;
12161 			}
12162 			if (!type_is_non_owning_ref(reg->type))
12163 				meta->arg_owning_ref = true;
12164 
12165 			rec = reg_btf_record(reg);
12166 			if (!rec) {
12167 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
12168 				return -EFAULT;
12169 			}
12170 
12171 			if (rec->refcount_off < 0) {
12172 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
12173 				return -EINVAL;
12174 			}
12175 
12176 			meta->arg_btf = reg->btf;
12177 			meta->arg_btf_id = reg->btf_id;
12178 			break;
12179 		case KF_ARG_PTR_TO_CONST_STR:
12180 			if (reg->type != PTR_TO_MAP_VALUE) {
12181 				verbose(env, "arg#%d doesn't point to a const string\n", i);
12182 				return -EINVAL;
12183 			}
12184 			ret = check_reg_const_str(env, reg, regno);
12185 			if (ret)
12186 				return ret;
12187 			break;
12188 		case KF_ARG_PTR_TO_WORKQUEUE:
12189 			if (reg->type != PTR_TO_MAP_VALUE) {
12190 				verbose(env, "arg#%d doesn't point to a map value\n", i);
12191 				return -EINVAL;
12192 			}
12193 			ret = process_wq_func(env, regno, meta);
12194 			if (ret < 0)
12195 				return ret;
12196 			break;
12197 		}
12198 	}
12199 
12200 	if (is_kfunc_release(meta) && !meta->release_regno) {
12201 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
12202 			func_name);
12203 		return -EINVAL;
12204 	}
12205 
12206 	return 0;
12207 }
12208 
12209 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
12210 			    struct bpf_insn *insn,
12211 			    struct bpf_kfunc_call_arg_meta *meta,
12212 			    const char **kfunc_name)
12213 {
12214 	const struct btf_type *func, *func_proto;
12215 	u32 func_id, *kfunc_flags;
12216 	const char *func_name;
12217 	struct btf *desc_btf;
12218 
12219 	if (kfunc_name)
12220 		*kfunc_name = NULL;
12221 
12222 	if (!insn->imm)
12223 		return -EINVAL;
12224 
12225 	desc_btf = find_kfunc_desc_btf(env, insn->off);
12226 	if (IS_ERR(desc_btf))
12227 		return PTR_ERR(desc_btf);
12228 
12229 	func_id = insn->imm;
12230 	func = btf_type_by_id(desc_btf, func_id);
12231 	func_name = btf_name_by_offset(desc_btf, func->name_off);
12232 	if (kfunc_name)
12233 		*kfunc_name = func_name;
12234 	func_proto = btf_type_by_id(desc_btf, func->type);
12235 
12236 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
12237 	if (!kfunc_flags) {
12238 		return -EACCES;
12239 	}
12240 
12241 	memset(meta, 0, sizeof(*meta));
12242 	meta->btf = desc_btf;
12243 	meta->func_id = func_id;
12244 	meta->kfunc_flags = *kfunc_flags;
12245 	meta->func_proto = func_proto;
12246 	meta->func_name = func_name;
12247 
12248 	return 0;
12249 }
12250 
12251 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12252 
12253 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12254 			    int *insn_idx_p)
12255 {
12256 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
12257 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
12258 	struct bpf_reg_state *regs = cur_regs(env);
12259 	const char *func_name, *ptr_type_name;
12260 	const struct btf_type *t, *ptr_type;
12261 	struct bpf_kfunc_call_arg_meta meta;
12262 	struct bpf_insn_aux_data *insn_aux;
12263 	int err, insn_idx = *insn_idx_p;
12264 	const struct btf_param *args;
12265 	const struct btf_type *ret_t;
12266 	struct btf *desc_btf;
12267 
12268 	/* skip for now, but return error when we find this in fixup_kfunc_call */
12269 	if (!insn->imm)
12270 		return 0;
12271 
12272 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
12273 	if (err == -EACCES && func_name)
12274 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
12275 	if (err)
12276 		return err;
12277 	desc_btf = meta.btf;
12278 	insn_aux = &env->insn_aux_data[insn_idx];
12279 
12280 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
12281 
12282 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12283 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12284 		return -EACCES;
12285 	}
12286 
12287 	sleepable = is_kfunc_sleepable(&meta);
12288 	if (sleepable && !in_sleepable(env)) {
12289 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12290 		return -EACCES;
12291 	}
12292 
12293 	/* Check the arguments */
12294 	err = check_kfunc_args(env, &meta, insn_idx);
12295 	if (err < 0)
12296 		return err;
12297 
12298 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12299 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12300 					 set_rbtree_add_callback_state);
12301 		if (err) {
12302 			verbose(env, "kfunc %s#%d failed callback verification\n",
12303 				func_name, meta.func_id);
12304 			return err;
12305 		}
12306 	}
12307 
12308 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
12309 		meta.r0_size = sizeof(u64);
12310 		meta.r0_rdonly = false;
12311 	}
12312 
12313 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
12314 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12315 					 set_timer_callback_state);
12316 		if (err) {
12317 			verbose(env, "kfunc %s#%d failed callback verification\n",
12318 				func_name, meta.func_id);
12319 			return err;
12320 		}
12321 	}
12322 
12323 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12324 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
12325 
12326 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
12327 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
12328 
12329 	if (env->cur_state->active_rcu_lock) {
12330 		struct bpf_func_state *state;
12331 		struct bpf_reg_state *reg;
12332 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
12333 
12334 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12335 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12336 			return -EACCES;
12337 		}
12338 
12339 		if (rcu_lock) {
12340 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12341 			return -EINVAL;
12342 		} else if (rcu_unlock) {
12343 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
12344 				if (reg->type & MEM_RCU) {
12345 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
12346 					reg->type |= PTR_UNTRUSTED;
12347 				}
12348 			}));
12349 			env->cur_state->active_rcu_lock = false;
12350 		} else if (sleepable) {
12351 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12352 			return -EACCES;
12353 		}
12354 	} else if (rcu_lock) {
12355 		env->cur_state->active_rcu_lock = true;
12356 	} else if (rcu_unlock) {
12357 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12358 		return -EINVAL;
12359 	}
12360 
12361 	if (env->cur_state->active_preempt_lock) {
12362 		if (preempt_disable) {
12363 			env->cur_state->active_preempt_lock++;
12364 		} else if (preempt_enable) {
12365 			env->cur_state->active_preempt_lock--;
12366 		} else if (sleepable) {
12367 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
12368 			return -EACCES;
12369 		}
12370 	} else if (preempt_disable) {
12371 		env->cur_state->active_preempt_lock++;
12372 	} else if (preempt_enable) {
12373 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
12374 		return -EINVAL;
12375 	}
12376 
12377 	/* In case of release function, we get register number of refcounted
12378 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
12379 	 */
12380 	if (meta.release_regno) {
12381 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
12382 		if (err) {
12383 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12384 				func_name, meta.func_id);
12385 			return err;
12386 		}
12387 	}
12388 
12389 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12390 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12391 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12392 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
12393 		insn_aux->insert_off = regs[BPF_REG_2].off;
12394 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
12395 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12396 		if (err) {
12397 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
12398 				func_name, meta.func_id);
12399 			return err;
12400 		}
12401 
12402 		err = release_reference(env, release_ref_obj_id);
12403 		if (err) {
12404 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12405 				func_name, meta.func_id);
12406 			return err;
12407 		}
12408 	}
12409 
12410 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12411 		if (!bpf_jit_supports_exceptions()) {
12412 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
12413 				func_name, meta.func_id);
12414 			return -ENOTSUPP;
12415 		}
12416 		env->seen_exception = true;
12417 
12418 		/* In the case of the default callback, the cookie value passed
12419 		 * to bpf_throw becomes the return value of the program.
12420 		 */
12421 		if (!env->exception_callback_subprog) {
12422 			err = check_return_code(env, BPF_REG_1, "R1");
12423 			if (err < 0)
12424 				return err;
12425 		}
12426 	}
12427 
12428 	for (i = 0; i < CALLER_SAVED_REGS; i++)
12429 		mark_reg_not_init(env, regs, caller_saved[i]);
12430 
12431 	/* Check return type */
12432 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12433 
12434 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12435 		/* Only exception is bpf_obj_new_impl */
12436 		if (meta.btf != btf_vmlinux ||
12437 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12438 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12439 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12440 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12441 			return -EINVAL;
12442 		}
12443 	}
12444 
12445 	if (btf_type_is_scalar(t)) {
12446 		mark_reg_unknown(env, regs, BPF_REG_0);
12447 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12448 	} else if (btf_type_is_ptr(t)) {
12449 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12450 
12451 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12452 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12453 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12454 				struct btf_struct_meta *struct_meta;
12455 				struct btf *ret_btf;
12456 				u32 ret_btf_id;
12457 
12458 				if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12459 					return -ENOMEM;
12460 
12461 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12462 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12463 					return -EINVAL;
12464 				}
12465 
12466 				ret_btf = env->prog->aux->btf;
12467 				ret_btf_id = meta.arg_constant.value;
12468 
12469 				/* This may be NULL due to user not supplying a BTF */
12470 				if (!ret_btf) {
12471 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12472 					return -EINVAL;
12473 				}
12474 
12475 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12476 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
12477 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12478 					return -EINVAL;
12479 				}
12480 
12481 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12482 					if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12483 						verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12484 							ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12485 						return -EINVAL;
12486 					}
12487 
12488 					if (!bpf_global_percpu_ma_set) {
12489 						mutex_lock(&bpf_percpu_ma_lock);
12490 						if (!bpf_global_percpu_ma_set) {
12491 							/* Charge memory allocated with bpf_global_percpu_ma to
12492 							 * root memcg. The obj_cgroup for root memcg is NULL.
12493 							 */
12494 							err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12495 							if (!err)
12496 								bpf_global_percpu_ma_set = true;
12497 						}
12498 						mutex_unlock(&bpf_percpu_ma_lock);
12499 						if (err)
12500 							return err;
12501 					}
12502 
12503 					mutex_lock(&bpf_percpu_ma_lock);
12504 					err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12505 					mutex_unlock(&bpf_percpu_ma_lock);
12506 					if (err)
12507 						return err;
12508 				}
12509 
12510 				struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12511 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12512 					if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12513 						verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12514 						return -EINVAL;
12515 					}
12516 
12517 					if (struct_meta) {
12518 						verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12519 						return -EINVAL;
12520 					}
12521 				}
12522 
12523 				mark_reg_known_zero(env, regs, BPF_REG_0);
12524 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12525 				regs[BPF_REG_0].btf = ret_btf;
12526 				regs[BPF_REG_0].btf_id = ret_btf_id;
12527 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12528 					regs[BPF_REG_0].type |= MEM_PERCPU;
12529 
12530 				insn_aux->obj_new_size = ret_t->size;
12531 				insn_aux->kptr_struct_meta = struct_meta;
12532 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12533 				mark_reg_known_zero(env, regs, BPF_REG_0);
12534 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12535 				regs[BPF_REG_0].btf = meta.arg_btf;
12536 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12537 
12538 				insn_aux->kptr_struct_meta =
12539 					btf_find_struct_meta(meta.arg_btf,
12540 							     meta.arg_btf_id);
12541 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12542 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12543 				struct btf_field *field = meta.arg_list_head.field;
12544 
12545 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12546 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12547 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12548 				struct btf_field *field = meta.arg_rbtree_root.field;
12549 
12550 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12551 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12552 				mark_reg_known_zero(env, regs, BPF_REG_0);
12553 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12554 				regs[BPF_REG_0].btf = desc_btf;
12555 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12556 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12557 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12558 				if (!ret_t || !btf_type_is_struct(ret_t)) {
12559 					verbose(env,
12560 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12561 					return -EINVAL;
12562 				}
12563 
12564 				mark_reg_known_zero(env, regs, BPF_REG_0);
12565 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12566 				regs[BPF_REG_0].btf = desc_btf;
12567 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12568 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12569 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12570 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12571 
12572 				mark_reg_known_zero(env, regs, BPF_REG_0);
12573 
12574 				if (!meta.arg_constant.found) {
12575 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12576 					return -EFAULT;
12577 				}
12578 
12579 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12580 
12581 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12582 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12583 
12584 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12585 					regs[BPF_REG_0].type |= MEM_RDONLY;
12586 				} else {
12587 					/* this will set env->seen_direct_write to true */
12588 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12589 						verbose(env, "the prog does not allow writes to packet data\n");
12590 						return -EINVAL;
12591 					}
12592 				}
12593 
12594 				if (!meta.initialized_dynptr.id) {
12595 					verbose(env, "verifier internal error: no dynptr id\n");
12596 					return -EFAULT;
12597 				}
12598 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12599 
12600 				/* we don't need to set BPF_REG_0's ref obj id
12601 				 * because packet slices are not refcounted (see
12602 				 * dynptr_type_refcounted)
12603 				 */
12604 			} else {
12605 				verbose(env, "kernel function %s unhandled dynamic return type\n",
12606 					meta.func_name);
12607 				return -EFAULT;
12608 			}
12609 		} else if (btf_type_is_void(ptr_type)) {
12610 			/* kfunc returning 'void *' is equivalent to returning scalar */
12611 			mark_reg_unknown(env, regs, BPF_REG_0);
12612 		} else if (!__btf_type_is_struct(ptr_type)) {
12613 			if (!meta.r0_size) {
12614 				__u32 sz;
12615 
12616 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12617 					meta.r0_size = sz;
12618 					meta.r0_rdonly = true;
12619 				}
12620 			}
12621 			if (!meta.r0_size) {
12622 				ptr_type_name = btf_name_by_offset(desc_btf,
12623 								   ptr_type->name_off);
12624 				verbose(env,
12625 					"kernel function %s returns pointer type %s %s is not supported\n",
12626 					func_name,
12627 					btf_type_str(ptr_type),
12628 					ptr_type_name);
12629 				return -EINVAL;
12630 			}
12631 
12632 			mark_reg_known_zero(env, regs, BPF_REG_0);
12633 			regs[BPF_REG_0].type = PTR_TO_MEM;
12634 			regs[BPF_REG_0].mem_size = meta.r0_size;
12635 
12636 			if (meta.r0_rdonly)
12637 				regs[BPF_REG_0].type |= MEM_RDONLY;
12638 
12639 			/* Ensures we don't access the memory after a release_reference() */
12640 			if (meta.ref_obj_id)
12641 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12642 		} else {
12643 			mark_reg_known_zero(env, regs, BPF_REG_0);
12644 			regs[BPF_REG_0].btf = desc_btf;
12645 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12646 			regs[BPF_REG_0].btf_id = ptr_type_id;
12647 		}
12648 
12649 		if (is_kfunc_ret_null(&meta)) {
12650 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12651 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12652 			regs[BPF_REG_0].id = ++env->id_gen;
12653 		}
12654 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12655 		if (is_kfunc_acquire(&meta)) {
12656 			int id = acquire_reference_state(env, insn_idx);
12657 
12658 			if (id < 0)
12659 				return id;
12660 			if (is_kfunc_ret_null(&meta))
12661 				regs[BPF_REG_0].id = id;
12662 			regs[BPF_REG_0].ref_obj_id = id;
12663 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12664 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12665 		}
12666 
12667 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12668 			regs[BPF_REG_0].id = ++env->id_gen;
12669 	} else if (btf_type_is_void(t)) {
12670 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12671 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12672 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12673 				insn_aux->kptr_struct_meta =
12674 					btf_find_struct_meta(meta.arg_btf,
12675 							     meta.arg_btf_id);
12676 			}
12677 		}
12678 	}
12679 
12680 	nargs = btf_type_vlen(meta.func_proto);
12681 	args = (const struct btf_param *)(meta.func_proto + 1);
12682 	for (i = 0; i < nargs; i++) {
12683 		u32 regno = i + 1;
12684 
12685 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12686 		if (btf_type_is_ptr(t))
12687 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12688 		else
12689 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12690 			mark_btf_func_reg_size(env, regno, t->size);
12691 	}
12692 
12693 	if (is_iter_next_kfunc(&meta)) {
12694 		err = process_iter_next_call(env, insn_idx, &meta);
12695 		if (err)
12696 			return err;
12697 	}
12698 
12699 	return 0;
12700 }
12701 
12702 static bool signed_add_overflows(s64 a, s64 b)
12703 {
12704 	/* Do the add in u64, where overflow is well-defined */
12705 	s64 res = (s64)((u64)a + (u64)b);
12706 
12707 	if (b < 0)
12708 		return res > a;
12709 	return res < a;
12710 }
12711 
12712 static bool signed_add32_overflows(s32 a, s32 b)
12713 {
12714 	/* Do the add in u32, where overflow is well-defined */
12715 	s32 res = (s32)((u32)a + (u32)b);
12716 
12717 	if (b < 0)
12718 		return res > a;
12719 	return res < a;
12720 }
12721 
12722 static bool signed_sub_overflows(s64 a, s64 b)
12723 {
12724 	/* Do the sub in u64, where overflow is well-defined */
12725 	s64 res = (s64)((u64)a - (u64)b);
12726 
12727 	if (b < 0)
12728 		return res < a;
12729 	return res > a;
12730 }
12731 
12732 static bool signed_sub32_overflows(s32 a, s32 b)
12733 {
12734 	/* Do the sub in u32, where overflow is well-defined */
12735 	s32 res = (s32)((u32)a - (u32)b);
12736 
12737 	if (b < 0)
12738 		return res < a;
12739 	return res > a;
12740 }
12741 
12742 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12743 				  const struct bpf_reg_state *reg,
12744 				  enum bpf_reg_type type)
12745 {
12746 	bool known = tnum_is_const(reg->var_off);
12747 	s64 val = reg->var_off.value;
12748 	s64 smin = reg->smin_value;
12749 
12750 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12751 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12752 			reg_type_str(env, type), val);
12753 		return false;
12754 	}
12755 
12756 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12757 		verbose(env, "%s pointer offset %d is not allowed\n",
12758 			reg_type_str(env, type), reg->off);
12759 		return false;
12760 	}
12761 
12762 	if (smin == S64_MIN) {
12763 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12764 			reg_type_str(env, type));
12765 		return false;
12766 	}
12767 
12768 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12769 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12770 			smin, reg_type_str(env, type));
12771 		return false;
12772 	}
12773 
12774 	return true;
12775 }
12776 
12777 enum {
12778 	REASON_BOUNDS	= -1,
12779 	REASON_TYPE	= -2,
12780 	REASON_PATHS	= -3,
12781 	REASON_LIMIT	= -4,
12782 	REASON_STACK	= -5,
12783 };
12784 
12785 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12786 			      u32 *alu_limit, bool mask_to_left)
12787 {
12788 	u32 max = 0, ptr_limit = 0;
12789 
12790 	switch (ptr_reg->type) {
12791 	case PTR_TO_STACK:
12792 		/* Offset 0 is out-of-bounds, but acceptable start for the
12793 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12794 		 * offset where we would need to deal with min/max bounds is
12795 		 * currently prohibited for unprivileged.
12796 		 */
12797 		max = MAX_BPF_STACK + mask_to_left;
12798 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12799 		break;
12800 	case PTR_TO_MAP_VALUE:
12801 		max = ptr_reg->map_ptr->value_size;
12802 		ptr_limit = (mask_to_left ?
12803 			     ptr_reg->smin_value :
12804 			     ptr_reg->umax_value) + ptr_reg->off;
12805 		break;
12806 	default:
12807 		return REASON_TYPE;
12808 	}
12809 
12810 	if (ptr_limit >= max)
12811 		return REASON_LIMIT;
12812 	*alu_limit = ptr_limit;
12813 	return 0;
12814 }
12815 
12816 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12817 				    const struct bpf_insn *insn)
12818 {
12819 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12820 }
12821 
12822 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12823 				       u32 alu_state, u32 alu_limit)
12824 {
12825 	/* If we arrived here from different branches with different
12826 	 * state or limits to sanitize, then this won't work.
12827 	 */
12828 	if (aux->alu_state &&
12829 	    (aux->alu_state != alu_state ||
12830 	     aux->alu_limit != alu_limit))
12831 		return REASON_PATHS;
12832 
12833 	/* Corresponding fixup done in do_misc_fixups(). */
12834 	aux->alu_state = alu_state;
12835 	aux->alu_limit = alu_limit;
12836 	return 0;
12837 }
12838 
12839 static int sanitize_val_alu(struct bpf_verifier_env *env,
12840 			    struct bpf_insn *insn)
12841 {
12842 	struct bpf_insn_aux_data *aux = cur_aux(env);
12843 
12844 	if (can_skip_alu_sanitation(env, insn))
12845 		return 0;
12846 
12847 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12848 }
12849 
12850 static bool sanitize_needed(u8 opcode)
12851 {
12852 	return opcode == BPF_ADD || opcode == BPF_SUB;
12853 }
12854 
12855 struct bpf_sanitize_info {
12856 	struct bpf_insn_aux_data aux;
12857 	bool mask_to_left;
12858 };
12859 
12860 static struct bpf_verifier_state *
12861 sanitize_speculative_path(struct bpf_verifier_env *env,
12862 			  const struct bpf_insn *insn,
12863 			  u32 next_idx, u32 curr_idx)
12864 {
12865 	struct bpf_verifier_state *branch;
12866 	struct bpf_reg_state *regs;
12867 
12868 	branch = push_stack(env, next_idx, curr_idx, true);
12869 	if (branch && insn) {
12870 		regs = branch->frame[branch->curframe]->regs;
12871 		if (BPF_SRC(insn->code) == BPF_K) {
12872 			mark_reg_unknown(env, regs, insn->dst_reg);
12873 		} else if (BPF_SRC(insn->code) == BPF_X) {
12874 			mark_reg_unknown(env, regs, insn->dst_reg);
12875 			mark_reg_unknown(env, regs, insn->src_reg);
12876 		}
12877 	}
12878 	return branch;
12879 }
12880 
12881 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12882 			    struct bpf_insn *insn,
12883 			    const struct bpf_reg_state *ptr_reg,
12884 			    const struct bpf_reg_state *off_reg,
12885 			    struct bpf_reg_state *dst_reg,
12886 			    struct bpf_sanitize_info *info,
12887 			    const bool commit_window)
12888 {
12889 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12890 	struct bpf_verifier_state *vstate = env->cur_state;
12891 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12892 	bool off_is_neg = off_reg->smin_value < 0;
12893 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12894 	u8 opcode = BPF_OP(insn->code);
12895 	u32 alu_state, alu_limit;
12896 	struct bpf_reg_state tmp;
12897 	bool ret;
12898 	int err;
12899 
12900 	if (can_skip_alu_sanitation(env, insn))
12901 		return 0;
12902 
12903 	/* We already marked aux for masking from non-speculative
12904 	 * paths, thus we got here in the first place. We only care
12905 	 * to explore bad access from here.
12906 	 */
12907 	if (vstate->speculative)
12908 		goto do_sim;
12909 
12910 	if (!commit_window) {
12911 		if (!tnum_is_const(off_reg->var_off) &&
12912 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12913 			return REASON_BOUNDS;
12914 
12915 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12916 				     (opcode == BPF_SUB && !off_is_neg);
12917 	}
12918 
12919 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12920 	if (err < 0)
12921 		return err;
12922 
12923 	if (commit_window) {
12924 		/* In commit phase we narrow the masking window based on
12925 		 * the observed pointer move after the simulated operation.
12926 		 */
12927 		alu_state = info->aux.alu_state;
12928 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12929 	} else {
12930 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12931 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12932 		alu_state |= ptr_is_dst_reg ?
12933 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12934 
12935 		/* Limit pruning on unknown scalars to enable deep search for
12936 		 * potential masking differences from other program paths.
12937 		 */
12938 		if (!off_is_imm)
12939 			env->explore_alu_limits = true;
12940 	}
12941 
12942 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12943 	if (err < 0)
12944 		return err;
12945 do_sim:
12946 	/* If we're in commit phase, we're done here given we already
12947 	 * pushed the truncated dst_reg into the speculative verification
12948 	 * stack.
12949 	 *
12950 	 * Also, when register is a known constant, we rewrite register-based
12951 	 * operation to immediate-based, and thus do not need masking (and as
12952 	 * a consequence, do not need to simulate the zero-truncation either).
12953 	 */
12954 	if (commit_window || off_is_imm)
12955 		return 0;
12956 
12957 	/* Simulate and find potential out-of-bounds access under
12958 	 * speculative execution from truncation as a result of
12959 	 * masking when off was not within expected range. If off
12960 	 * sits in dst, then we temporarily need to move ptr there
12961 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12962 	 * for cases where we use K-based arithmetic in one direction
12963 	 * and truncated reg-based in the other in order to explore
12964 	 * bad access.
12965 	 */
12966 	if (!ptr_is_dst_reg) {
12967 		tmp = *dst_reg;
12968 		copy_register_state(dst_reg, ptr_reg);
12969 	}
12970 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12971 					env->insn_idx);
12972 	if (!ptr_is_dst_reg && ret)
12973 		*dst_reg = tmp;
12974 	return !ret ? REASON_STACK : 0;
12975 }
12976 
12977 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12978 {
12979 	struct bpf_verifier_state *vstate = env->cur_state;
12980 
12981 	/* If we simulate paths under speculation, we don't update the
12982 	 * insn as 'seen' such that when we verify unreachable paths in
12983 	 * the non-speculative domain, sanitize_dead_code() can still
12984 	 * rewrite/sanitize them.
12985 	 */
12986 	if (!vstate->speculative)
12987 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12988 }
12989 
12990 static int sanitize_err(struct bpf_verifier_env *env,
12991 			const struct bpf_insn *insn, int reason,
12992 			const struct bpf_reg_state *off_reg,
12993 			const struct bpf_reg_state *dst_reg)
12994 {
12995 	static const char *err = "pointer arithmetic with it prohibited for !root";
12996 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12997 	u32 dst = insn->dst_reg, src = insn->src_reg;
12998 
12999 	switch (reason) {
13000 	case REASON_BOUNDS:
13001 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
13002 			off_reg == dst_reg ? dst : src, err);
13003 		break;
13004 	case REASON_TYPE:
13005 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
13006 			off_reg == dst_reg ? src : dst, err);
13007 		break;
13008 	case REASON_PATHS:
13009 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
13010 			dst, op, err);
13011 		break;
13012 	case REASON_LIMIT:
13013 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
13014 			dst, op, err);
13015 		break;
13016 	case REASON_STACK:
13017 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
13018 			dst, err);
13019 		break;
13020 	default:
13021 		verbose(env, "verifier internal error: unknown reason (%d)\n",
13022 			reason);
13023 		break;
13024 	}
13025 
13026 	return -EACCES;
13027 }
13028 
13029 /* check that stack access falls within stack limits and that 'reg' doesn't
13030  * have a variable offset.
13031  *
13032  * Variable offset is prohibited for unprivileged mode for simplicity since it
13033  * requires corresponding support in Spectre masking for stack ALU.  See also
13034  * retrieve_ptr_limit().
13035  *
13036  *
13037  * 'off' includes 'reg->off'.
13038  */
13039 static int check_stack_access_for_ptr_arithmetic(
13040 				struct bpf_verifier_env *env,
13041 				int regno,
13042 				const struct bpf_reg_state *reg,
13043 				int off)
13044 {
13045 	if (!tnum_is_const(reg->var_off)) {
13046 		char tn_buf[48];
13047 
13048 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
13049 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
13050 			regno, tn_buf, off);
13051 		return -EACCES;
13052 	}
13053 
13054 	if (off >= 0 || off < -MAX_BPF_STACK) {
13055 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
13056 			"prohibited for !root; off=%d\n", regno, off);
13057 		return -EACCES;
13058 	}
13059 
13060 	return 0;
13061 }
13062 
13063 static int sanitize_check_bounds(struct bpf_verifier_env *env,
13064 				 const struct bpf_insn *insn,
13065 				 const struct bpf_reg_state *dst_reg)
13066 {
13067 	u32 dst = insn->dst_reg;
13068 
13069 	/* For unprivileged we require that resulting offset must be in bounds
13070 	 * in order to be able to sanitize access later on.
13071 	 */
13072 	if (env->bypass_spec_v1)
13073 		return 0;
13074 
13075 	switch (dst_reg->type) {
13076 	case PTR_TO_STACK:
13077 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
13078 					dst_reg->off + dst_reg->var_off.value))
13079 			return -EACCES;
13080 		break;
13081 	case PTR_TO_MAP_VALUE:
13082 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
13083 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
13084 				"prohibited for !root\n", dst);
13085 			return -EACCES;
13086 		}
13087 		break;
13088 	default:
13089 		break;
13090 	}
13091 
13092 	return 0;
13093 }
13094 
13095 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
13096  * Caller should also handle BPF_MOV case separately.
13097  * If we return -EACCES, caller may want to try again treating pointer as a
13098  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
13099  */
13100 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
13101 				   struct bpf_insn *insn,
13102 				   const struct bpf_reg_state *ptr_reg,
13103 				   const struct bpf_reg_state *off_reg)
13104 {
13105 	struct bpf_verifier_state *vstate = env->cur_state;
13106 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13107 	struct bpf_reg_state *regs = state->regs, *dst_reg;
13108 	bool known = tnum_is_const(off_reg->var_off);
13109 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
13110 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
13111 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
13112 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
13113 	struct bpf_sanitize_info info = {};
13114 	u8 opcode = BPF_OP(insn->code);
13115 	u32 dst = insn->dst_reg;
13116 	int ret;
13117 
13118 	dst_reg = &regs[dst];
13119 
13120 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
13121 	    smin_val > smax_val || umin_val > umax_val) {
13122 		/* Taint dst register if offset had invalid bounds derived from
13123 		 * e.g. dead branches.
13124 		 */
13125 		__mark_reg_unknown(env, dst_reg);
13126 		return 0;
13127 	}
13128 
13129 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
13130 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
13131 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13132 			__mark_reg_unknown(env, dst_reg);
13133 			return 0;
13134 		}
13135 
13136 		verbose(env,
13137 			"R%d 32-bit pointer arithmetic prohibited\n",
13138 			dst);
13139 		return -EACCES;
13140 	}
13141 
13142 	if (ptr_reg->type & PTR_MAYBE_NULL) {
13143 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
13144 			dst, reg_type_str(env, ptr_reg->type));
13145 		return -EACCES;
13146 	}
13147 
13148 	switch (base_type(ptr_reg->type)) {
13149 	case PTR_TO_CTX:
13150 	case PTR_TO_MAP_VALUE:
13151 	case PTR_TO_MAP_KEY:
13152 	case PTR_TO_STACK:
13153 	case PTR_TO_PACKET_META:
13154 	case PTR_TO_PACKET:
13155 	case PTR_TO_TP_BUFFER:
13156 	case PTR_TO_BTF_ID:
13157 	case PTR_TO_MEM:
13158 	case PTR_TO_BUF:
13159 	case PTR_TO_FUNC:
13160 	case CONST_PTR_TO_DYNPTR:
13161 		break;
13162 	case PTR_TO_FLOW_KEYS:
13163 		if (known)
13164 			break;
13165 		fallthrough;
13166 	case CONST_PTR_TO_MAP:
13167 		/* smin_val represents the known value */
13168 		if (known && smin_val == 0 && opcode == BPF_ADD)
13169 			break;
13170 		fallthrough;
13171 	default:
13172 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
13173 			dst, reg_type_str(env, ptr_reg->type));
13174 		return -EACCES;
13175 	}
13176 
13177 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
13178 	 * The id may be overwritten later if we create a new variable offset.
13179 	 */
13180 	dst_reg->type = ptr_reg->type;
13181 	dst_reg->id = ptr_reg->id;
13182 
13183 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
13184 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
13185 		return -EINVAL;
13186 
13187 	/* pointer types do not carry 32-bit bounds at the moment. */
13188 	__mark_reg32_unbounded(dst_reg);
13189 
13190 	if (sanitize_needed(opcode)) {
13191 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
13192 				       &info, false);
13193 		if (ret < 0)
13194 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13195 	}
13196 
13197 	switch (opcode) {
13198 	case BPF_ADD:
13199 		/* We can take a fixed offset as long as it doesn't overflow
13200 		 * the s32 'off' field
13201 		 */
13202 		if (known && (ptr_reg->off + smin_val ==
13203 			      (s64)(s32)(ptr_reg->off + smin_val))) {
13204 			/* pointer += K.  Accumulate it into fixed offset */
13205 			dst_reg->smin_value = smin_ptr;
13206 			dst_reg->smax_value = smax_ptr;
13207 			dst_reg->umin_value = umin_ptr;
13208 			dst_reg->umax_value = umax_ptr;
13209 			dst_reg->var_off = ptr_reg->var_off;
13210 			dst_reg->off = ptr_reg->off + smin_val;
13211 			dst_reg->raw = ptr_reg->raw;
13212 			break;
13213 		}
13214 		/* A new variable offset is created.  Note that off_reg->off
13215 		 * == 0, since it's a scalar.
13216 		 * dst_reg gets the pointer type and since some positive
13217 		 * integer value was added to the pointer, give it a new 'id'
13218 		 * if it's a PTR_TO_PACKET.
13219 		 * this creates a new 'base' pointer, off_reg (variable) gets
13220 		 * added into the variable offset, and we copy the fixed offset
13221 		 * from ptr_reg.
13222 		 */
13223 		if (signed_add_overflows(smin_ptr, smin_val) ||
13224 		    signed_add_overflows(smax_ptr, smax_val)) {
13225 			dst_reg->smin_value = S64_MIN;
13226 			dst_reg->smax_value = S64_MAX;
13227 		} else {
13228 			dst_reg->smin_value = smin_ptr + smin_val;
13229 			dst_reg->smax_value = smax_ptr + smax_val;
13230 		}
13231 		if (umin_ptr + umin_val < umin_ptr ||
13232 		    umax_ptr + umax_val < umax_ptr) {
13233 			dst_reg->umin_value = 0;
13234 			dst_reg->umax_value = U64_MAX;
13235 		} else {
13236 			dst_reg->umin_value = umin_ptr + umin_val;
13237 			dst_reg->umax_value = umax_ptr + umax_val;
13238 		}
13239 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
13240 		dst_reg->off = ptr_reg->off;
13241 		dst_reg->raw = ptr_reg->raw;
13242 		if (reg_is_pkt_pointer(ptr_reg)) {
13243 			dst_reg->id = ++env->id_gen;
13244 			/* something was added to pkt_ptr, set range to zero */
13245 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13246 		}
13247 		break;
13248 	case BPF_SUB:
13249 		if (dst_reg == off_reg) {
13250 			/* scalar -= pointer.  Creates an unknown scalar */
13251 			verbose(env, "R%d tried to subtract pointer from scalar\n",
13252 				dst);
13253 			return -EACCES;
13254 		}
13255 		/* We don't allow subtraction from FP, because (according to
13256 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
13257 		 * be able to deal with it.
13258 		 */
13259 		if (ptr_reg->type == PTR_TO_STACK) {
13260 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
13261 				dst);
13262 			return -EACCES;
13263 		}
13264 		if (known && (ptr_reg->off - smin_val ==
13265 			      (s64)(s32)(ptr_reg->off - smin_val))) {
13266 			/* pointer -= K.  Subtract it from fixed offset */
13267 			dst_reg->smin_value = smin_ptr;
13268 			dst_reg->smax_value = smax_ptr;
13269 			dst_reg->umin_value = umin_ptr;
13270 			dst_reg->umax_value = umax_ptr;
13271 			dst_reg->var_off = ptr_reg->var_off;
13272 			dst_reg->id = ptr_reg->id;
13273 			dst_reg->off = ptr_reg->off - smin_val;
13274 			dst_reg->raw = ptr_reg->raw;
13275 			break;
13276 		}
13277 		/* A new variable offset is created.  If the subtrahend is known
13278 		 * nonnegative, then any reg->range we had before is still good.
13279 		 */
13280 		if (signed_sub_overflows(smin_ptr, smax_val) ||
13281 		    signed_sub_overflows(smax_ptr, smin_val)) {
13282 			/* Overflow possible, we know nothing */
13283 			dst_reg->smin_value = S64_MIN;
13284 			dst_reg->smax_value = S64_MAX;
13285 		} else {
13286 			dst_reg->smin_value = smin_ptr - smax_val;
13287 			dst_reg->smax_value = smax_ptr - smin_val;
13288 		}
13289 		if (umin_ptr < umax_val) {
13290 			/* Overflow possible, we know nothing */
13291 			dst_reg->umin_value = 0;
13292 			dst_reg->umax_value = U64_MAX;
13293 		} else {
13294 			/* Cannot overflow (as long as bounds are consistent) */
13295 			dst_reg->umin_value = umin_ptr - umax_val;
13296 			dst_reg->umax_value = umax_ptr - umin_val;
13297 		}
13298 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13299 		dst_reg->off = ptr_reg->off;
13300 		dst_reg->raw = ptr_reg->raw;
13301 		if (reg_is_pkt_pointer(ptr_reg)) {
13302 			dst_reg->id = ++env->id_gen;
13303 			/* something was added to pkt_ptr, set range to zero */
13304 			if (smin_val < 0)
13305 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13306 		}
13307 		break;
13308 	case BPF_AND:
13309 	case BPF_OR:
13310 	case BPF_XOR:
13311 		/* bitwise ops on pointers are troublesome, prohibit. */
13312 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13313 			dst, bpf_alu_string[opcode >> 4]);
13314 		return -EACCES;
13315 	default:
13316 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
13317 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13318 			dst, bpf_alu_string[opcode >> 4]);
13319 		return -EACCES;
13320 	}
13321 
13322 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
13323 		return -EINVAL;
13324 	reg_bounds_sync(dst_reg);
13325 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13326 		return -EACCES;
13327 	if (sanitize_needed(opcode)) {
13328 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13329 				       &info, true);
13330 		if (ret < 0)
13331 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13332 	}
13333 
13334 	return 0;
13335 }
13336 
13337 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13338 				 struct bpf_reg_state *src_reg)
13339 {
13340 	s32 smin_val = src_reg->s32_min_value;
13341 	s32 smax_val = src_reg->s32_max_value;
13342 	u32 umin_val = src_reg->u32_min_value;
13343 	u32 umax_val = src_reg->u32_max_value;
13344 
13345 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
13346 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
13347 		dst_reg->s32_min_value = S32_MIN;
13348 		dst_reg->s32_max_value = S32_MAX;
13349 	} else {
13350 		dst_reg->s32_min_value += smin_val;
13351 		dst_reg->s32_max_value += smax_val;
13352 	}
13353 	if (dst_reg->u32_min_value + umin_val < umin_val ||
13354 	    dst_reg->u32_max_value + umax_val < umax_val) {
13355 		dst_reg->u32_min_value = 0;
13356 		dst_reg->u32_max_value = U32_MAX;
13357 	} else {
13358 		dst_reg->u32_min_value += umin_val;
13359 		dst_reg->u32_max_value += umax_val;
13360 	}
13361 }
13362 
13363 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13364 			       struct bpf_reg_state *src_reg)
13365 {
13366 	s64 smin_val = src_reg->smin_value;
13367 	s64 smax_val = src_reg->smax_value;
13368 	u64 umin_val = src_reg->umin_value;
13369 	u64 umax_val = src_reg->umax_value;
13370 
13371 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
13372 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
13373 		dst_reg->smin_value = S64_MIN;
13374 		dst_reg->smax_value = S64_MAX;
13375 	} else {
13376 		dst_reg->smin_value += smin_val;
13377 		dst_reg->smax_value += smax_val;
13378 	}
13379 	if (dst_reg->umin_value + umin_val < umin_val ||
13380 	    dst_reg->umax_value + umax_val < umax_val) {
13381 		dst_reg->umin_value = 0;
13382 		dst_reg->umax_value = U64_MAX;
13383 	} else {
13384 		dst_reg->umin_value += umin_val;
13385 		dst_reg->umax_value += umax_val;
13386 	}
13387 }
13388 
13389 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13390 				 struct bpf_reg_state *src_reg)
13391 {
13392 	s32 smin_val = src_reg->s32_min_value;
13393 	s32 smax_val = src_reg->s32_max_value;
13394 	u32 umin_val = src_reg->u32_min_value;
13395 	u32 umax_val = src_reg->u32_max_value;
13396 
13397 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
13398 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
13399 		/* Overflow possible, we know nothing */
13400 		dst_reg->s32_min_value = S32_MIN;
13401 		dst_reg->s32_max_value = S32_MAX;
13402 	} else {
13403 		dst_reg->s32_min_value -= smax_val;
13404 		dst_reg->s32_max_value -= smin_val;
13405 	}
13406 	if (dst_reg->u32_min_value < umax_val) {
13407 		/* Overflow possible, we know nothing */
13408 		dst_reg->u32_min_value = 0;
13409 		dst_reg->u32_max_value = U32_MAX;
13410 	} else {
13411 		/* Cannot overflow (as long as bounds are consistent) */
13412 		dst_reg->u32_min_value -= umax_val;
13413 		dst_reg->u32_max_value -= umin_val;
13414 	}
13415 }
13416 
13417 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13418 			       struct bpf_reg_state *src_reg)
13419 {
13420 	s64 smin_val = src_reg->smin_value;
13421 	s64 smax_val = src_reg->smax_value;
13422 	u64 umin_val = src_reg->umin_value;
13423 	u64 umax_val = src_reg->umax_value;
13424 
13425 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
13426 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
13427 		/* Overflow possible, we know nothing */
13428 		dst_reg->smin_value = S64_MIN;
13429 		dst_reg->smax_value = S64_MAX;
13430 	} else {
13431 		dst_reg->smin_value -= smax_val;
13432 		dst_reg->smax_value -= smin_val;
13433 	}
13434 	if (dst_reg->umin_value < umax_val) {
13435 		/* Overflow possible, we know nothing */
13436 		dst_reg->umin_value = 0;
13437 		dst_reg->umax_value = U64_MAX;
13438 	} else {
13439 		/* Cannot overflow (as long as bounds are consistent) */
13440 		dst_reg->umin_value -= umax_val;
13441 		dst_reg->umax_value -= umin_val;
13442 	}
13443 }
13444 
13445 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13446 				 struct bpf_reg_state *src_reg)
13447 {
13448 	s32 smin_val = src_reg->s32_min_value;
13449 	u32 umin_val = src_reg->u32_min_value;
13450 	u32 umax_val = src_reg->u32_max_value;
13451 
13452 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13453 		/* Ain't nobody got time to multiply that sign */
13454 		__mark_reg32_unbounded(dst_reg);
13455 		return;
13456 	}
13457 	/* Both values are positive, so we can work with unsigned and
13458 	 * copy the result to signed (unless it exceeds S32_MAX).
13459 	 */
13460 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13461 		/* Potential overflow, we know nothing */
13462 		__mark_reg32_unbounded(dst_reg);
13463 		return;
13464 	}
13465 	dst_reg->u32_min_value *= umin_val;
13466 	dst_reg->u32_max_value *= umax_val;
13467 	if (dst_reg->u32_max_value > S32_MAX) {
13468 		/* Overflow possible, we know nothing */
13469 		dst_reg->s32_min_value = S32_MIN;
13470 		dst_reg->s32_max_value = S32_MAX;
13471 	} else {
13472 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13473 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13474 	}
13475 }
13476 
13477 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13478 			       struct bpf_reg_state *src_reg)
13479 {
13480 	s64 smin_val = src_reg->smin_value;
13481 	u64 umin_val = src_reg->umin_value;
13482 	u64 umax_val = src_reg->umax_value;
13483 
13484 	if (smin_val < 0 || dst_reg->smin_value < 0) {
13485 		/* Ain't nobody got time to multiply that sign */
13486 		__mark_reg64_unbounded(dst_reg);
13487 		return;
13488 	}
13489 	/* Both values are positive, so we can work with unsigned and
13490 	 * copy the result to signed (unless it exceeds S64_MAX).
13491 	 */
13492 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13493 		/* Potential overflow, we know nothing */
13494 		__mark_reg64_unbounded(dst_reg);
13495 		return;
13496 	}
13497 	dst_reg->umin_value *= umin_val;
13498 	dst_reg->umax_value *= umax_val;
13499 	if (dst_reg->umax_value > S64_MAX) {
13500 		/* Overflow possible, we know nothing */
13501 		dst_reg->smin_value = S64_MIN;
13502 		dst_reg->smax_value = S64_MAX;
13503 	} else {
13504 		dst_reg->smin_value = dst_reg->umin_value;
13505 		dst_reg->smax_value = dst_reg->umax_value;
13506 	}
13507 }
13508 
13509 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13510 				 struct bpf_reg_state *src_reg)
13511 {
13512 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13513 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13514 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13515 	u32 umax_val = src_reg->u32_max_value;
13516 
13517 	if (src_known && dst_known) {
13518 		__mark_reg32_known(dst_reg, var32_off.value);
13519 		return;
13520 	}
13521 
13522 	/* We get our minimum from the var_off, since that's inherently
13523 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13524 	 */
13525 	dst_reg->u32_min_value = var32_off.value;
13526 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13527 
13528 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
13529 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13530 	 */
13531 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13532 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13533 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13534 	} else {
13535 		dst_reg->s32_min_value = S32_MIN;
13536 		dst_reg->s32_max_value = S32_MAX;
13537 	}
13538 }
13539 
13540 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13541 			       struct bpf_reg_state *src_reg)
13542 {
13543 	bool src_known = tnum_is_const(src_reg->var_off);
13544 	bool dst_known = tnum_is_const(dst_reg->var_off);
13545 	u64 umax_val = src_reg->umax_value;
13546 
13547 	if (src_known && dst_known) {
13548 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13549 		return;
13550 	}
13551 
13552 	/* We get our minimum from the var_off, since that's inherently
13553 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13554 	 */
13555 	dst_reg->umin_value = dst_reg->var_off.value;
13556 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13557 
13558 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
13559 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13560 	 */
13561 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13562 		dst_reg->smin_value = dst_reg->umin_value;
13563 		dst_reg->smax_value = dst_reg->umax_value;
13564 	} else {
13565 		dst_reg->smin_value = S64_MIN;
13566 		dst_reg->smax_value = S64_MAX;
13567 	}
13568 	/* We may learn something more from the var_off */
13569 	__update_reg_bounds(dst_reg);
13570 }
13571 
13572 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13573 				struct bpf_reg_state *src_reg)
13574 {
13575 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13576 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13577 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13578 	u32 umin_val = src_reg->u32_min_value;
13579 
13580 	if (src_known && dst_known) {
13581 		__mark_reg32_known(dst_reg, var32_off.value);
13582 		return;
13583 	}
13584 
13585 	/* We get our maximum from the var_off, and our minimum is the
13586 	 * maximum of the operands' minima
13587 	 */
13588 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13589 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13590 
13591 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
13592 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13593 	 */
13594 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13595 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13596 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13597 	} else {
13598 		dst_reg->s32_min_value = S32_MIN;
13599 		dst_reg->s32_max_value = S32_MAX;
13600 	}
13601 }
13602 
13603 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13604 			      struct bpf_reg_state *src_reg)
13605 {
13606 	bool src_known = tnum_is_const(src_reg->var_off);
13607 	bool dst_known = tnum_is_const(dst_reg->var_off);
13608 	u64 umin_val = src_reg->umin_value;
13609 
13610 	if (src_known && dst_known) {
13611 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13612 		return;
13613 	}
13614 
13615 	/* We get our maximum from the var_off, and our minimum is the
13616 	 * maximum of the operands' minima
13617 	 */
13618 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13619 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13620 
13621 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
13622 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13623 	 */
13624 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13625 		dst_reg->smin_value = dst_reg->umin_value;
13626 		dst_reg->smax_value = dst_reg->umax_value;
13627 	} else {
13628 		dst_reg->smin_value = S64_MIN;
13629 		dst_reg->smax_value = S64_MAX;
13630 	}
13631 	/* We may learn something more from the var_off */
13632 	__update_reg_bounds(dst_reg);
13633 }
13634 
13635 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13636 				 struct bpf_reg_state *src_reg)
13637 {
13638 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13639 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13640 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13641 
13642 	if (src_known && dst_known) {
13643 		__mark_reg32_known(dst_reg, var32_off.value);
13644 		return;
13645 	}
13646 
13647 	/* We get both minimum and maximum from the var32_off. */
13648 	dst_reg->u32_min_value = var32_off.value;
13649 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13650 
13651 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
13652 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13653 	 */
13654 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13655 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13656 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13657 	} else {
13658 		dst_reg->s32_min_value = S32_MIN;
13659 		dst_reg->s32_max_value = S32_MAX;
13660 	}
13661 }
13662 
13663 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13664 			       struct bpf_reg_state *src_reg)
13665 {
13666 	bool src_known = tnum_is_const(src_reg->var_off);
13667 	bool dst_known = tnum_is_const(dst_reg->var_off);
13668 
13669 	if (src_known && dst_known) {
13670 		/* dst_reg->var_off.value has been updated earlier */
13671 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13672 		return;
13673 	}
13674 
13675 	/* We get both minimum and maximum from the var_off. */
13676 	dst_reg->umin_value = dst_reg->var_off.value;
13677 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13678 
13679 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
13680 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13681 	 */
13682 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13683 		dst_reg->smin_value = dst_reg->umin_value;
13684 		dst_reg->smax_value = dst_reg->umax_value;
13685 	} else {
13686 		dst_reg->smin_value = S64_MIN;
13687 		dst_reg->smax_value = S64_MAX;
13688 	}
13689 
13690 	__update_reg_bounds(dst_reg);
13691 }
13692 
13693 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13694 				   u64 umin_val, u64 umax_val)
13695 {
13696 	/* We lose all sign bit information (except what we can pick
13697 	 * up from var_off)
13698 	 */
13699 	dst_reg->s32_min_value = S32_MIN;
13700 	dst_reg->s32_max_value = S32_MAX;
13701 	/* If we might shift our top bit out, then we know nothing */
13702 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13703 		dst_reg->u32_min_value = 0;
13704 		dst_reg->u32_max_value = U32_MAX;
13705 	} else {
13706 		dst_reg->u32_min_value <<= umin_val;
13707 		dst_reg->u32_max_value <<= umax_val;
13708 	}
13709 }
13710 
13711 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13712 				 struct bpf_reg_state *src_reg)
13713 {
13714 	u32 umax_val = src_reg->u32_max_value;
13715 	u32 umin_val = src_reg->u32_min_value;
13716 	/* u32 alu operation will zext upper bits */
13717 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13718 
13719 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13720 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13721 	/* Not required but being careful mark reg64 bounds as unknown so
13722 	 * that we are forced to pick them up from tnum and zext later and
13723 	 * if some path skips this step we are still safe.
13724 	 */
13725 	__mark_reg64_unbounded(dst_reg);
13726 	__update_reg32_bounds(dst_reg);
13727 }
13728 
13729 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13730 				   u64 umin_val, u64 umax_val)
13731 {
13732 	/* Special case <<32 because it is a common compiler pattern to sign
13733 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13734 	 * positive we know this shift will also be positive so we can track
13735 	 * bounds correctly. Otherwise we lose all sign bit information except
13736 	 * what we can pick up from var_off. Perhaps we can generalize this
13737 	 * later to shifts of any length.
13738 	 */
13739 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13740 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13741 	else
13742 		dst_reg->smax_value = S64_MAX;
13743 
13744 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13745 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13746 	else
13747 		dst_reg->smin_value = S64_MIN;
13748 
13749 	/* If we might shift our top bit out, then we know nothing */
13750 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13751 		dst_reg->umin_value = 0;
13752 		dst_reg->umax_value = U64_MAX;
13753 	} else {
13754 		dst_reg->umin_value <<= umin_val;
13755 		dst_reg->umax_value <<= umax_val;
13756 	}
13757 }
13758 
13759 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13760 			       struct bpf_reg_state *src_reg)
13761 {
13762 	u64 umax_val = src_reg->umax_value;
13763 	u64 umin_val = src_reg->umin_value;
13764 
13765 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13766 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13767 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13768 
13769 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13770 	/* We may learn something more from the var_off */
13771 	__update_reg_bounds(dst_reg);
13772 }
13773 
13774 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13775 				 struct bpf_reg_state *src_reg)
13776 {
13777 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13778 	u32 umax_val = src_reg->u32_max_value;
13779 	u32 umin_val = src_reg->u32_min_value;
13780 
13781 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13782 	 * be negative, then either:
13783 	 * 1) src_reg might be zero, so the sign bit of the result is
13784 	 *    unknown, so we lose our signed bounds
13785 	 * 2) it's known negative, thus the unsigned bounds capture the
13786 	 *    signed bounds
13787 	 * 3) the signed bounds cross zero, so they tell us nothing
13788 	 *    about the result
13789 	 * If the value in dst_reg is known nonnegative, then again the
13790 	 * unsigned bounds capture the signed bounds.
13791 	 * Thus, in all cases it suffices to blow away our signed bounds
13792 	 * and rely on inferring new ones from the unsigned bounds and
13793 	 * var_off of the result.
13794 	 */
13795 	dst_reg->s32_min_value = S32_MIN;
13796 	dst_reg->s32_max_value = S32_MAX;
13797 
13798 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13799 	dst_reg->u32_min_value >>= umax_val;
13800 	dst_reg->u32_max_value >>= umin_val;
13801 
13802 	__mark_reg64_unbounded(dst_reg);
13803 	__update_reg32_bounds(dst_reg);
13804 }
13805 
13806 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13807 			       struct bpf_reg_state *src_reg)
13808 {
13809 	u64 umax_val = src_reg->umax_value;
13810 	u64 umin_val = src_reg->umin_value;
13811 
13812 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13813 	 * be negative, then either:
13814 	 * 1) src_reg might be zero, so the sign bit of the result is
13815 	 *    unknown, so we lose our signed bounds
13816 	 * 2) it's known negative, thus the unsigned bounds capture the
13817 	 *    signed bounds
13818 	 * 3) the signed bounds cross zero, so they tell us nothing
13819 	 *    about the result
13820 	 * If the value in dst_reg is known nonnegative, then again the
13821 	 * unsigned bounds capture the signed bounds.
13822 	 * Thus, in all cases it suffices to blow away our signed bounds
13823 	 * and rely on inferring new ones from the unsigned bounds and
13824 	 * var_off of the result.
13825 	 */
13826 	dst_reg->smin_value = S64_MIN;
13827 	dst_reg->smax_value = S64_MAX;
13828 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13829 	dst_reg->umin_value >>= umax_val;
13830 	dst_reg->umax_value >>= umin_val;
13831 
13832 	/* Its not easy to operate on alu32 bounds here because it depends
13833 	 * on bits being shifted in. Take easy way out and mark unbounded
13834 	 * so we can recalculate later from tnum.
13835 	 */
13836 	__mark_reg32_unbounded(dst_reg);
13837 	__update_reg_bounds(dst_reg);
13838 }
13839 
13840 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13841 				  struct bpf_reg_state *src_reg)
13842 {
13843 	u64 umin_val = src_reg->u32_min_value;
13844 
13845 	/* Upon reaching here, src_known is true and
13846 	 * umax_val is equal to umin_val.
13847 	 */
13848 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13849 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13850 
13851 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13852 
13853 	/* blow away the dst_reg umin_value/umax_value and rely on
13854 	 * dst_reg var_off to refine the result.
13855 	 */
13856 	dst_reg->u32_min_value = 0;
13857 	dst_reg->u32_max_value = U32_MAX;
13858 
13859 	__mark_reg64_unbounded(dst_reg);
13860 	__update_reg32_bounds(dst_reg);
13861 }
13862 
13863 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13864 				struct bpf_reg_state *src_reg)
13865 {
13866 	u64 umin_val = src_reg->umin_value;
13867 
13868 	/* Upon reaching here, src_known is true and umax_val is equal
13869 	 * to umin_val.
13870 	 */
13871 	dst_reg->smin_value >>= umin_val;
13872 	dst_reg->smax_value >>= umin_val;
13873 
13874 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13875 
13876 	/* blow away the dst_reg umin_value/umax_value and rely on
13877 	 * dst_reg var_off to refine the result.
13878 	 */
13879 	dst_reg->umin_value = 0;
13880 	dst_reg->umax_value = U64_MAX;
13881 
13882 	/* Its not easy to operate on alu32 bounds here because it depends
13883 	 * on bits being shifted in from upper 32-bits. Take easy way out
13884 	 * and mark unbounded so we can recalculate later from tnum.
13885 	 */
13886 	__mark_reg32_unbounded(dst_reg);
13887 	__update_reg_bounds(dst_reg);
13888 }
13889 
13890 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
13891 					     const struct bpf_reg_state *src_reg)
13892 {
13893 	bool src_is_const = false;
13894 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13895 
13896 	if (insn_bitness == 32) {
13897 		if (tnum_subreg_is_const(src_reg->var_off)
13898 		    && src_reg->s32_min_value == src_reg->s32_max_value
13899 		    && src_reg->u32_min_value == src_reg->u32_max_value)
13900 			src_is_const = true;
13901 	} else {
13902 		if (tnum_is_const(src_reg->var_off)
13903 		    && src_reg->smin_value == src_reg->smax_value
13904 		    && src_reg->umin_value == src_reg->umax_value)
13905 			src_is_const = true;
13906 	}
13907 
13908 	switch (BPF_OP(insn->code)) {
13909 	case BPF_ADD:
13910 	case BPF_SUB:
13911 	case BPF_AND:
13912 	case BPF_XOR:
13913 	case BPF_OR:
13914 	case BPF_MUL:
13915 		return true;
13916 
13917 	/* Shift operators range is only computable if shift dimension operand
13918 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
13919 	 * includes shifts by a negative number.
13920 	 */
13921 	case BPF_LSH:
13922 	case BPF_RSH:
13923 	case BPF_ARSH:
13924 		return (src_is_const && src_reg->umax_value < insn_bitness);
13925 	default:
13926 		return false;
13927 	}
13928 }
13929 
13930 /* WARNING: This function does calculations on 64-bit values, but the actual
13931  * execution may occur on 32-bit values. Therefore, things like bitshifts
13932  * need extra checks in the 32-bit case.
13933  */
13934 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13935 				      struct bpf_insn *insn,
13936 				      struct bpf_reg_state *dst_reg,
13937 				      struct bpf_reg_state src_reg)
13938 {
13939 	u8 opcode = BPF_OP(insn->code);
13940 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13941 	int ret;
13942 
13943 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
13944 		__mark_reg_unknown(env, dst_reg);
13945 		return 0;
13946 	}
13947 
13948 	if (sanitize_needed(opcode)) {
13949 		ret = sanitize_val_alu(env, insn);
13950 		if (ret < 0)
13951 			return sanitize_err(env, insn, ret, NULL, NULL);
13952 	}
13953 
13954 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13955 	 * There are two classes of instructions: The first class we track both
13956 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13957 	 * greatest amount of precision when alu operations are mixed with jmp32
13958 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13959 	 * and BPF_OR. This is possible because these ops have fairly easy to
13960 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13961 	 * See alu32 verifier tests for examples. The second class of
13962 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13963 	 * with regards to tracking sign/unsigned bounds because the bits may
13964 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13965 	 * the reg unbounded in the subreg bound space and use the resulting
13966 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13967 	 */
13968 	switch (opcode) {
13969 	case BPF_ADD:
13970 		scalar32_min_max_add(dst_reg, &src_reg);
13971 		scalar_min_max_add(dst_reg, &src_reg);
13972 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13973 		break;
13974 	case BPF_SUB:
13975 		scalar32_min_max_sub(dst_reg, &src_reg);
13976 		scalar_min_max_sub(dst_reg, &src_reg);
13977 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13978 		break;
13979 	case BPF_MUL:
13980 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13981 		scalar32_min_max_mul(dst_reg, &src_reg);
13982 		scalar_min_max_mul(dst_reg, &src_reg);
13983 		break;
13984 	case BPF_AND:
13985 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13986 		scalar32_min_max_and(dst_reg, &src_reg);
13987 		scalar_min_max_and(dst_reg, &src_reg);
13988 		break;
13989 	case BPF_OR:
13990 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13991 		scalar32_min_max_or(dst_reg, &src_reg);
13992 		scalar_min_max_or(dst_reg, &src_reg);
13993 		break;
13994 	case BPF_XOR:
13995 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13996 		scalar32_min_max_xor(dst_reg, &src_reg);
13997 		scalar_min_max_xor(dst_reg, &src_reg);
13998 		break;
13999 	case BPF_LSH:
14000 		if (alu32)
14001 			scalar32_min_max_lsh(dst_reg, &src_reg);
14002 		else
14003 			scalar_min_max_lsh(dst_reg, &src_reg);
14004 		break;
14005 	case BPF_RSH:
14006 		if (alu32)
14007 			scalar32_min_max_rsh(dst_reg, &src_reg);
14008 		else
14009 			scalar_min_max_rsh(dst_reg, &src_reg);
14010 		break;
14011 	case BPF_ARSH:
14012 		if (alu32)
14013 			scalar32_min_max_arsh(dst_reg, &src_reg);
14014 		else
14015 			scalar_min_max_arsh(dst_reg, &src_reg);
14016 		break;
14017 	default:
14018 		break;
14019 	}
14020 
14021 	/* ALU32 ops are zero extended into 64bit register */
14022 	if (alu32)
14023 		zext_32_to_64(dst_reg);
14024 	reg_bounds_sync(dst_reg);
14025 	return 0;
14026 }
14027 
14028 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
14029  * and var_off.
14030  */
14031 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
14032 				   struct bpf_insn *insn)
14033 {
14034 	struct bpf_verifier_state *vstate = env->cur_state;
14035 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14036 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
14037 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
14038 	u8 opcode = BPF_OP(insn->code);
14039 	int err;
14040 
14041 	dst_reg = &regs[insn->dst_reg];
14042 	src_reg = NULL;
14043 
14044 	if (dst_reg->type == PTR_TO_ARENA) {
14045 		struct bpf_insn_aux_data *aux = cur_aux(env);
14046 
14047 		if (BPF_CLASS(insn->code) == BPF_ALU64)
14048 			/*
14049 			 * 32-bit operations zero upper bits automatically.
14050 			 * 64-bit operations need to be converted to 32.
14051 			 */
14052 			aux->needs_zext = true;
14053 
14054 		/* Any arithmetic operations are allowed on arena pointers */
14055 		return 0;
14056 	}
14057 
14058 	if (dst_reg->type != SCALAR_VALUE)
14059 		ptr_reg = dst_reg;
14060 	else
14061 		/* Make sure ID is cleared otherwise dst_reg min/max could be
14062 		 * incorrectly propagated into other registers by find_equal_scalars()
14063 		 */
14064 		dst_reg->id = 0;
14065 	if (BPF_SRC(insn->code) == BPF_X) {
14066 		src_reg = &regs[insn->src_reg];
14067 		if (src_reg->type != SCALAR_VALUE) {
14068 			if (dst_reg->type != SCALAR_VALUE) {
14069 				/* Combining two pointers by any ALU op yields
14070 				 * an arbitrary scalar. Disallow all math except
14071 				 * pointer subtraction
14072 				 */
14073 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14074 					mark_reg_unknown(env, regs, insn->dst_reg);
14075 					return 0;
14076 				}
14077 				verbose(env, "R%d pointer %s pointer prohibited\n",
14078 					insn->dst_reg,
14079 					bpf_alu_string[opcode >> 4]);
14080 				return -EACCES;
14081 			} else {
14082 				/* scalar += pointer
14083 				 * This is legal, but we have to reverse our
14084 				 * src/dest handling in computing the range
14085 				 */
14086 				err = mark_chain_precision(env, insn->dst_reg);
14087 				if (err)
14088 					return err;
14089 				return adjust_ptr_min_max_vals(env, insn,
14090 							       src_reg, dst_reg);
14091 			}
14092 		} else if (ptr_reg) {
14093 			/* pointer += scalar */
14094 			err = mark_chain_precision(env, insn->src_reg);
14095 			if (err)
14096 				return err;
14097 			return adjust_ptr_min_max_vals(env, insn,
14098 						       dst_reg, src_reg);
14099 		} else if (dst_reg->precise) {
14100 			/* if dst_reg is precise, src_reg should be precise as well */
14101 			err = mark_chain_precision(env, insn->src_reg);
14102 			if (err)
14103 				return err;
14104 		}
14105 	} else {
14106 		/* Pretend the src is a reg with a known value, since we only
14107 		 * need to be able to read from this state.
14108 		 */
14109 		off_reg.type = SCALAR_VALUE;
14110 		__mark_reg_known(&off_reg, insn->imm);
14111 		src_reg = &off_reg;
14112 		if (ptr_reg) /* pointer += K */
14113 			return adjust_ptr_min_max_vals(env, insn,
14114 						       ptr_reg, src_reg);
14115 	}
14116 
14117 	/* Got here implies adding two SCALAR_VALUEs */
14118 	if (WARN_ON_ONCE(ptr_reg)) {
14119 		print_verifier_state(env, state, true);
14120 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
14121 		return -EINVAL;
14122 	}
14123 	if (WARN_ON(!src_reg)) {
14124 		print_verifier_state(env, state, true);
14125 		verbose(env, "verifier internal error: no src_reg\n");
14126 		return -EINVAL;
14127 	}
14128 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
14129 }
14130 
14131 /* check validity of 32-bit and 64-bit arithmetic operations */
14132 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
14133 {
14134 	struct bpf_reg_state *regs = cur_regs(env);
14135 	u8 opcode = BPF_OP(insn->code);
14136 	int err;
14137 
14138 	if (opcode == BPF_END || opcode == BPF_NEG) {
14139 		if (opcode == BPF_NEG) {
14140 			if (BPF_SRC(insn->code) != BPF_K ||
14141 			    insn->src_reg != BPF_REG_0 ||
14142 			    insn->off != 0 || insn->imm != 0) {
14143 				verbose(env, "BPF_NEG uses reserved fields\n");
14144 				return -EINVAL;
14145 			}
14146 		} else {
14147 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
14148 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
14149 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
14150 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
14151 				verbose(env, "BPF_END uses reserved fields\n");
14152 				return -EINVAL;
14153 			}
14154 		}
14155 
14156 		/* check src operand */
14157 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14158 		if (err)
14159 			return err;
14160 
14161 		if (is_pointer_value(env, insn->dst_reg)) {
14162 			verbose(env, "R%d pointer arithmetic prohibited\n",
14163 				insn->dst_reg);
14164 			return -EACCES;
14165 		}
14166 
14167 		/* check dest operand */
14168 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
14169 		if (err)
14170 			return err;
14171 
14172 	} else if (opcode == BPF_MOV) {
14173 
14174 		if (BPF_SRC(insn->code) == BPF_X) {
14175 			if (BPF_CLASS(insn->code) == BPF_ALU) {
14176 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
14177 				    insn->imm) {
14178 					verbose(env, "BPF_MOV uses reserved fields\n");
14179 					return -EINVAL;
14180 				}
14181 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
14182 				if (insn->imm != 1 && insn->imm != 1u << 16) {
14183 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
14184 					return -EINVAL;
14185 				}
14186 				if (!env->prog->aux->arena) {
14187 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
14188 					return -EINVAL;
14189 				}
14190 			} else {
14191 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
14192 				     insn->off != 32) || insn->imm) {
14193 					verbose(env, "BPF_MOV uses reserved fields\n");
14194 					return -EINVAL;
14195 				}
14196 			}
14197 
14198 			/* check src operand */
14199 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14200 			if (err)
14201 				return err;
14202 		} else {
14203 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
14204 				verbose(env, "BPF_MOV uses reserved fields\n");
14205 				return -EINVAL;
14206 			}
14207 		}
14208 
14209 		/* check dest operand, mark as required later */
14210 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14211 		if (err)
14212 			return err;
14213 
14214 		if (BPF_SRC(insn->code) == BPF_X) {
14215 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
14216 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
14217 
14218 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14219 				if (insn->imm) {
14220 					/* off == BPF_ADDR_SPACE_CAST */
14221 					mark_reg_unknown(env, regs, insn->dst_reg);
14222 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
14223 						dst_reg->type = PTR_TO_ARENA;
14224 						/* PTR_TO_ARENA is 32-bit */
14225 						dst_reg->subreg_def = env->insn_idx + 1;
14226 					}
14227 				} else if (insn->off == 0) {
14228 					/* case: R1 = R2
14229 					 * copy register state to dest reg
14230 					 */
14231 					assign_scalar_id_before_mov(env, src_reg);
14232 					copy_register_state(dst_reg, src_reg);
14233 					dst_reg->live |= REG_LIVE_WRITTEN;
14234 					dst_reg->subreg_def = DEF_NOT_SUBREG;
14235 				} else {
14236 					/* case: R1 = (s8, s16 s32)R2 */
14237 					if (is_pointer_value(env, insn->src_reg)) {
14238 						verbose(env,
14239 							"R%d sign-extension part of pointer\n",
14240 							insn->src_reg);
14241 						return -EACCES;
14242 					} else if (src_reg->type == SCALAR_VALUE) {
14243 						bool no_sext;
14244 
14245 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14246 						if (no_sext)
14247 							assign_scalar_id_before_mov(env, src_reg);
14248 						copy_register_state(dst_reg, src_reg);
14249 						if (!no_sext)
14250 							dst_reg->id = 0;
14251 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
14252 						dst_reg->live |= REG_LIVE_WRITTEN;
14253 						dst_reg->subreg_def = DEF_NOT_SUBREG;
14254 					} else {
14255 						mark_reg_unknown(env, regs, insn->dst_reg);
14256 					}
14257 				}
14258 			} else {
14259 				/* R1 = (u32) R2 */
14260 				if (is_pointer_value(env, insn->src_reg)) {
14261 					verbose(env,
14262 						"R%d partial copy of pointer\n",
14263 						insn->src_reg);
14264 					return -EACCES;
14265 				} else if (src_reg->type == SCALAR_VALUE) {
14266 					if (insn->off == 0) {
14267 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
14268 
14269 						if (is_src_reg_u32)
14270 							assign_scalar_id_before_mov(env, src_reg);
14271 						copy_register_state(dst_reg, src_reg);
14272 						/* Make sure ID is cleared if src_reg is not in u32
14273 						 * range otherwise dst_reg min/max could be incorrectly
14274 						 * propagated into src_reg by find_equal_scalars()
14275 						 */
14276 						if (!is_src_reg_u32)
14277 							dst_reg->id = 0;
14278 						dst_reg->live |= REG_LIVE_WRITTEN;
14279 						dst_reg->subreg_def = env->insn_idx + 1;
14280 					} else {
14281 						/* case: W1 = (s8, s16)W2 */
14282 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14283 
14284 						if (no_sext)
14285 							assign_scalar_id_before_mov(env, src_reg);
14286 						copy_register_state(dst_reg, src_reg);
14287 						if (!no_sext)
14288 							dst_reg->id = 0;
14289 						dst_reg->live |= REG_LIVE_WRITTEN;
14290 						dst_reg->subreg_def = env->insn_idx + 1;
14291 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
14292 					}
14293 				} else {
14294 					mark_reg_unknown(env, regs,
14295 							 insn->dst_reg);
14296 				}
14297 				zext_32_to_64(dst_reg);
14298 				reg_bounds_sync(dst_reg);
14299 			}
14300 		} else {
14301 			/* case: R = imm
14302 			 * remember the value we stored into this reg
14303 			 */
14304 			/* clear any state __mark_reg_known doesn't set */
14305 			mark_reg_unknown(env, regs, insn->dst_reg);
14306 			regs[insn->dst_reg].type = SCALAR_VALUE;
14307 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14308 				__mark_reg_known(regs + insn->dst_reg,
14309 						 insn->imm);
14310 			} else {
14311 				__mark_reg_known(regs + insn->dst_reg,
14312 						 (u32)insn->imm);
14313 			}
14314 		}
14315 
14316 	} else if (opcode > BPF_END) {
14317 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14318 		return -EINVAL;
14319 
14320 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
14321 
14322 		if (BPF_SRC(insn->code) == BPF_X) {
14323 			if (insn->imm != 0 || insn->off > 1 ||
14324 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14325 				verbose(env, "BPF_ALU uses reserved fields\n");
14326 				return -EINVAL;
14327 			}
14328 			/* check src1 operand */
14329 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14330 			if (err)
14331 				return err;
14332 		} else {
14333 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14334 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14335 				verbose(env, "BPF_ALU uses reserved fields\n");
14336 				return -EINVAL;
14337 			}
14338 		}
14339 
14340 		/* check src2 operand */
14341 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14342 		if (err)
14343 			return err;
14344 
14345 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14346 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14347 			verbose(env, "div by zero\n");
14348 			return -EINVAL;
14349 		}
14350 
14351 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14352 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14353 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14354 
14355 			if (insn->imm < 0 || insn->imm >= size) {
14356 				verbose(env, "invalid shift %d\n", insn->imm);
14357 				return -EINVAL;
14358 			}
14359 		}
14360 
14361 		/* check dest operand */
14362 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14363 		err = err ?: adjust_reg_min_max_vals(env, insn);
14364 		if (err)
14365 			return err;
14366 	}
14367 
14368 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
14369 }
14370 
14371 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14372 				   struct bpf_reg_state *dst_reg,
14373 				   enum bpf_reg_type type,
14374 				   bool range_right_open)
14375 {
14376 	struct bpf_func_state *state;
14377 	struct bpf_reg_state *reg;
14378 	int new_range;
14379 
14380 	if (dst_reg->off < 0 ||
14381 	    (dst_reg->off == 0 && range_right_open))
14382 		/* This doesn't give us any range */
14383 		return;
14384 
14385 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
14386 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14387 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
14388 		 * than pkt_end, but that's because it's also less than pkt.
14389 		 */
14390 		return;
14391 
14392 	new_range = dst_reg->off;
14393 	if (range_right_open)
14394 		new_range++;
14395 
14396 	/* Examples for register markings:
14397 	 *
14398 	 * pkt_data in dst register:
14399 	 *
14400 	 *   r2 = r3;
14401 	 *   r2 += 8;
14402 	 *   if (r2 > pkt_end) goto <handle exception>
14403 	 *   <access okay>
14404 	 *
14405 	 *   r2 = r3;
14406 	 *   r2 += 8;
14407 	 *   if (r2 < pkt_end) goto <access okay>
14408 	 *   <handle exception>
14409 	 *
14410 	 *   Where:
14411 	 *     r2 == dst_reg, pkt_end == src_reg
14412 	 *     r2=pkt(id=n,off=8,r=0)
14413 	 *     r3=pkt(id=n,off=0,r=0)
14414 	 *
14415 	 * pkt_data in src register:
14416 	 *
14417 	 *   r2 = r3;
14418 	 *   r2 += 8;
14419 	 *   if (pkt_end >= r2) goto <access okay>
14420 	 *   <handle exception>
14421 	 *
14422 	 *   r2 = r3;
14423 	 *   r2 += 8;
14424 	 *   if (pkt_end <= r2) goto <handle exception>
14425 	 *   <access okay>
14426 	 *
14427 	 *   Where:
14428 	 *     pkt_end == dst_reg, r2 == src_reg
14429 	 *     r2=pkt(id=n,off=8,r=0)
14430 	 *     r3=pkt(id=n,off=0,r=0)
14431 	 *
14432 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14433 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14434 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
14435 	 * the check.
14436 	 */
14437 
14438 	/* If our ids match, then we must have the same max_value.  And we
14439 	 * don't care about the other reg's fixed offset, since if it's too big
14440 	 * the range won't allow anything.
14441 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14442 	 */
14443 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14444 		if (reg->type == type && reg->id == dst_reg->id)
14445 			/* keep the maximum range already checked */
14446 			reg->range = max(reg->range, new_range);
14447 	}));
14448 }
14449 
14450 /*
14451  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14452  */
14453 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14454 				  u8 opcode, bool is_jmp32)
14455 {
14456 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14457 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14458 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14459 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14460 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14461 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14462 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14463 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14464 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14465 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14466 
14467 	switch (opcode) {
14468 	case BPF_JEQ:
14469 		/* constants, umin/umax and smin/smax checks would be
14470 		 * redundant in this case because they all should match
14471 		 */
14472 		if (tnum_is_const(t1) && tnum_is_const(t2))
14473 			return t1.value == t2.value;
14474 		/* non-overlapping ranges */
14475 		if (umin1 > umax2 || umax1 < umin2)
14476 			return 0;
14477 		if (smin1 > smax2 || smax1 < smin2)
14478 			return 0;
14479 		if (!is_jmp32) {
14480 			/* if 64-bit ranges are inconclusive, see if we can
14481 			 * utilize 32-bit subrange knowledge to eliminate
14482 			 * branches that can't be taken a priori
14483 			 */
14484 			if (reg1->u32_min_value > reg2->u32_max_value ||
14485 			    reg1->u32_max_value < reg2->u32_min_value)
14486 				return 0;
14487 			if (reg1->s32_min_value > reg2->s32_max_value ||
14488 			    reg1->s32_max_value < reg2->s32_min_value)
14489 				return 0;
14490 		}
14491 		break;
14492 	case BPF_JNE:
14493 		/* constants, umin/umax and smin/smax checks would be
14494 		 * redundant in this case because they all should match
14495 		 */
14496 		if (tnum_is_const(t1) && tnum_is_const(t2))
14497 			return t1.value != t2.value;
14498 		/* non-overlapping ranges */
14499 		if (umin1 > umax2 || umax1 < umin2)
14500 			return 1;
14501 		if (smin1 > smax2 || smax1 < smin2)
14502 			return 1;
14503 		if (!is_jmp32) {
14504 			/* if 64-bit ranges are inconclusive, see if we can
14505 			 * utilize 32-bit subrange knowledge to eliminate
14506 			 * branches that can't be taken a priori
14507 			 */
14508 			if (reg1->u32_min_value > reg2->u32_max_value ||
14509 			    reg1->u32_max_value < reg2->u32_min_value)
14510 				return 1;
14511 			if (reg1->s32_min_value > reg2->s32_max_value ||
14512 			    reg1->s32_max_value < reg2->s32_min_value)
14513 				return 1;
14514 		}
14515 		break;
14516 	case BPF_JSET:
14517 		if (!is_reg_const(reg2, is_jmp32)) {
14518 			swap(reg1, reg2);
14519 			swap(t1, t2);
14520 		}
14521 		if (!is_reg_const(reg2, is_jmp32))
14522 			return -1;
14523 		if ((~t1.mask & t1.value) & t2.value)
14524 			return 1;
14525 		if (!((t1.mask | t1.value) & t2.value))
14526 			return 0;
14527 		break;
14528 	case BPF_JGT:
14529 		if (umin1 > umax2)
14530 			return 1;
14531 		else if (umax1 <= umin2)
14532 			return 0;
14533 		break;
14534 	case BPF_JSGT:
14535 		if (smin1 > smax2)
14536 			return 1;
14537 		else if (smax1 <= smin2)
14538 			return 0;
14539 		break;
14540 	case BPF_JLT:
14541 		if (umax1 < umin2)
14542 			return 1;
14543 		else if (umin1 >= umax2)
14544 			return 0;
14545 		break;
14546 	case BPF_JSLT:
14547 		if (smax1 < smin2)
14548 			return 1;
14549 		else if (smin1 >= smax2)
14550 			return 0;
14551 		break;
14552 	case BPF_JGE:
14553 		if (umin1 >= umax2)
14554 			return 1;
14555 		else if (umax1 < umin2)
14556 			return 0;
14557 		break;
14558 	case BPF_JSGE:
14559 		if (smin1 >= smax2)
14560 			return 1;
14561 		else if (smax1 < smin2)
14562 			return 0;
14563 		break;
14564 	case BPF_JLE:
14565 		if (umax1 <= umin2)
14566 			return 1;
14567 		else if (umin1 > umax2)
14568 			return 0;
14569 		break;
14570 	case BPF_JSLE:
14571 		if (smax1 <= smin2)
14572 			return 1;
14573 		else if (smin1 > smax2)
14574 			return 0;
14575 		break;
14576 	}
14577 
14578 	return -1;
14579 }
14580 
14581 static int flip_opcode(u32 opcode)
14582 {
14583 	/* How can we transform "a <op> b" into "b <op> a"? */
14584 	static const u8 opcode_flip[16] = {
14585 		/* these stay the same */
14586 		[BPF_JEQ  >> 4] = BPF_JEQ,
14587 		[BPF_JNE  >> 4] = BPF_JNE,
14588 		[BPF_JSET >> 4] = BPF_JSET,
14589 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14590 		[BPF_JGE  >> 4] = BPF_JLE,
14591 		[BPF_JGT  >> 4] = BPF_JLT,
14592 		[BPF_JLE  >> 4] = BPF_JGE,
14593 		[BPF_JLT  >> 4] = BPF_JGT,
14594 		[BPF_JSGE >> 4] = BPF_JSLE,
14595 		[BPF_JSGT >> 4] = BPF_JSLT,
14596 		[BPF_JSLE >> 4] = BPF_JSGE,
14597 		[BPF_JSLT >> 4] = BPF_JSGT
14598 	};
14599 	return opcode_flip[opcode >> 4];
14600 }
14601 
14602 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14603 				   struct bpf_reg_state *src_reg,
14604 				   u8 opcode)
14605 {
14606 	struct bpf_reg_state *pkt;
14607 
14608 	if (src_reg->type == PTR_TO_PACKET_END) {
14609 		pkt = dst_reg;
14610 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14611 		pkt = src_reg;
14612 		opcode = flip_opcode(opcode);
14613 	} else {
14614 		return -1;
14615 	}
14616 
14617 	if (pkt->range >= 0)
14618 		return -1;
14619 
14620 	switch (opcode) {
14621 	case BPF_JLE:
14622 		/* pkt <= pkt_end */
14623 		fallthrough;
14624 	case BPF_JGT:
14625 		/* pkt > pkt_end */
14626 		if (pkt->range == BEYOND_PKT_END)
14627 			/* pkt has at last one extra byte beyond pkt_end */
14628 			return opcode == BPF_JGT;
14629 		break;
14630 	case BPF_JLT:
14631 		/* pkt < pkt_end */
14632 		fallthrough;
14633 	case BPF_JGE:
14634 		/* pkt >= pkt_end */
14635 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14636 			return opcode == BPF_JGE;
14637 		break;
14638 	}
14639 	return -1;
14640 }
14641 
14642 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14643  * and return:
14644  *  1 - branch will be taken and "goto target" will be executed
14645  *  0 - branch will not be taken and fall-through to next insn
14646  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14647  *      range [0,10]
14648  */
14649 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14650 			   u8 opcode, bool is_jmp32)
14651 {
14652 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14653 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14654 
14655 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14656 		u64 val;
14657 
14658 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
14659 		if (!is_reg_const(reg2, is_jmp32)) {
14660 			opcode = flip_opcode(opcode);
14661 			swap(reg1, reg2);
14662 		}
14663 		/* and ensure that reg2 is a constant */
14664 		if (!is_reg_const(reg2, is_jmp32))
14665 			return -1;
14666 
14667 		if (!reg_not_null(reg1))
14668 			return -1;
14669 
14670 		/* If pointer is valid tests against zero will fail so we can
14671 		 * use this to direct branch taken.
14672 		 */
14673 		val = reg_const_value(reg2, is_jmp32);
14674 		if (val != 0)
14675 			return -1;
14676 
14677 		switch (opcode) {
14678 		case BPF_JEQ:
14679 			return 0;
14680 		case BPF_JNE:
14681 			return 1;
14682 		default:
14683 			return -1;
14684 		}
14685 	}
14686 
14687 	/* now deal with two scalars, but not necessarily constants */
14688 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14689 }
14690 
14691 /* Opcode that corresponds to a *false* branch condition.
14692  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14693  */
14694 static u8 rev_opcode(u8 opcode)
14695 {
14696 	switch (opcode) {
14697 	case BPF_JEQ:		return BPF_JNE;
14698 	case BPF_JNE:		return BPF_JEQ;
14699 	/* JSET doesn't have it's reverse opcode in BPF, so add
14700 	 * BPF_X flag to denote the reverse of that operation
14701 	 */
14702 	case BPF_JSET:		return BPF_JSET | BPF_X;
14703 	case BPF_JSET | BPF_X:	return BPF_JSET;
14704 	case BPF_JGE:		return BPF_JLT;
14705 	case BPF_JGT:		return BPF_JLE;
14706 	case BPF_JLE:		return BPF_JGT;
14707 	case BPF_JLT:		return BPF_JGE;
14708 	case BPF_JSGE:		return BPF_JSLT;
14709 	case BPF_JSGT:		return BPF_JSLE;
14710 	case BPF_JSLE:		return BPF_JSGT;
14711 	case BPF_JSLT:		return BPF_JSGE;
14712 	default:		return 0;
14713 	}
14714 }
14715 
14716 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
14717 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14718 				u8 opcode, bool is_jmp32)
14719 {
14720 	struct tnum t;
14721 	u64 val;
14722 
14723 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
14724 	switch (opcode) {
14725 	case BPF_JGE:
14726 	case BPF_JGT:
14727 	case BPF_JSGE:
14728 	case BPF_JSGT:
14729 		opcode = flip_opcode(opcode);
14730 		swap(reg1, reg2);
14731 		break;
14732 	default:
14733 		break;
14734 	}
14735 
14736 	switch (opcode) {
14737 	case BPF_JEQ:
14738 		if (is_jmp32) {
14739 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14740 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14741 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14742 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14743 			reg2->u32_min_value = reg1->u32_min_value;
14744 			reg2->u32_max_value = reg1->u32_max_value;
14745 			reg2->s32_min_value = reg1->s32_min_value;
14746 			reg2->s32_max_value = reg1->s32_max_value;
14747 
14748 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14749 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14750 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14751 		} else {
14752 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14753 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14754 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14755 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14756 			reg2->umin_value = reg1->umin_value;
14757 			reg2->umax_value = reg1->umax_value;
14758 			reg2->smin_value = reg1->smin_value;
14759 			reg2->smax_value = reg1->smax_value;
14760 
14761 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14762 			reg2->var_off = reg1->var_off;
14763 		}
14764 		break;
14765 	case BPF_JNE:
14766 		if (!is_reg_const(reg2, is_jmp32))
14767 			swap(reg1, reg2);
14768 		if (!is_reg_const(reg2, is_jmp32))
14769 			break;
14770 
14771 		/* try to recompute the bound of reg1 if reg2 is a const and
14772 		 * is exactly the edge of reg1.
14773 		 */
14774 		val = reg_const_value(reg2, is_jmp32);
14775 		if (is_jmp32) {
14776 			/* u32_min_value is not equal to 0xffffffff at this point,
14777 			 * because otherwise u32_max_value is 0xffffffff as well,
14778 			 * in such a case both reg1 and reg2 would be constants,
14779 			 * jump would be predicted and reg_set_min_max() won't
14780 			 * be called.
14781 			 *
14782 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
14783 			 * below.
14784 			 */
14785 			if (reg1->u32_min_value == (u32)val)
14786 				reg1->u32_min_value++;
14787 			if (reg1->u32_max_value == (u32)val)
14788 				reg1->u32_max_value--;
14789 			if (reg1->s32_min_value == (s32)val)
14790 				reg1->s32_min_value++;
14791 			if (reg1->s32_max_value == (s32)val)
14792 				reg1->s32_max_value--;
14793 		} else {
14794 			if (reg1->umin_value == (u64)val)
14795 				reg1->umin_value++;
14796 			if (reg1->umax_value == (u64)val)
14797 				reg1->umax_value--;
14798 			if (reg1->smin_value == (s64)val)
14799 				reg1->smin_value++;
14800 			if (reg1->smax_value == (s64)val)
14801 				reg1->smax_value--;
14802 		}
14803 		break;
14804 	case BPF_JSET:
14805 		if (!is_reg_const(reg2, is_jmp32))
14806 			swap(reg1, reg2);
14807 		if (!is_reg_const(reg2, is_jmp32))
14808 			break;
14809 		val = reg_const_value(reg2, is_jmp32);
14810 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14811 		 * requires single bit to learn something useful. E.g., if we
14812 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14813 		 * are actually set? We can learn something definite only if
14814 		 * it's a single-bit value to begin with.
14815 		 *
14816 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14817 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14818 		 * bit 1 is set, which we can readily use in adjustments.
14819 		 */
14820 		if (!is_power_of_2(val))
14821 			break;
14822 		if (is_jmp32) {
14823 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14824 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14825 		} else {
14826 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
14827 		}
14828 		break;
14829 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
14830 		if (!is_reg_const(reg2, is_jmp32))
14831 			swap(reg1, reg2);
14832 		if (!is_reg_const(reg2, is_jmp32))
14833 			break;
14834 		val = reg_const_value(reg2, is_jmp32);
14835 		if (is_jmp32) {
14836 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
14837 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14838 		} else {
14839 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
14840 		}
14841 		break;
14842 	case BPF_JLE:
14843 		if (is_jmp32) {
14844 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14845 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14846 		} else {
14847 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14848 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
14849 		}
14850 		break;
14851 	case BPF_JLT:
14852 		if (is_jmp32) {
14853 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
14854 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
14855 		} else {
14856 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
14857 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
14858 		}
14859 		break;
14860 	case BPF_JSLE:
14861 		if (is_jmp32) {
14862 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14863 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14864 		} else {
14865 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14866 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
14867 		}
14868 		break;
14869 	case BPF_JSLT:
14870 		if (is_jmp32) {
14871 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
14872 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
14873 		} else {
14874 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
14875 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
14876 		}
14877 		break;
14878 	default:
14879 		return;
14880 	}
14881 }
14882 
14883 /* Adjusts the register min/max values in the case that the dst_reg and
14884  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
14885  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
14886  * Technically we can do similar adjustments for pointers to the same object,
14887  * but we don't support that right now.
14888  */
14889 static int reg_set_min_max(struct bpf_verifier_env *env,
14890 			   struct bpf_reg_state *true_reg1,
14891 			   struct bpf_reg_state *true_reg2,
14892 			   struct bpf_reg_state *false_reg1,
14893 			   struct bpf_reg_state *false_reg2,
14894 			   u8 opcode, bool is_jmp32)
14895 {
14896 	int err;
14897 
14898 	/* If either register is a pointer, we can't learn anything about its
14899 	 * variable offset from the compare (unless they were a pointer into
14900 	 * the same object, but we don't bother with that).
14901 	 */
14902 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
14903 		return 0;
14904 
14905 	/* fallthrough (FALSE) branch */
14906 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
14907 	reg_bounds_sync(false_reg1);
14908 	reg_bounds_sync(false_reg2);
14909 
14910 	/* jump (TRUE) branch */
14911 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
14912 	reg_bounds_sync(true_reg1);
14913 	reg_bounds_sync(true_reg2);
14914 
14915 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
14916 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
14917 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
14918 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
14919 	return err;
14920 }
14921 
14922 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14923 				 struct bpf_reg_state *reg, u32 id,
14924 				 bool is_null)
14925 {
14926 	if (type_may_be_null(reg->type) && reg->id == id &&
14927 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14928 		/* Old offset (both fixed and variable parts) should have been
14929 		 * known-zero, because we don't allow pointer arithmetic on
14930 		 * pointers that might be NULL. If we see this happening, don't
14931 		 * convert the register.
14932 		 *
14933 		 * But in some cases, some helpers that return local kptrs
14934 		 * advance offset for the returned pointer. In those cases, it
14935 		 * is fine to expect to see reg->off.
14936 		 */
14937 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14938 			return;
14939 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14940 		    WARN_ON_ONCE(reg->off))
14941 			return;
14942 
14943 		if (is_null) {
14944 			reg->type = SCALAR_VALUE;
14945 			/* We don't need id and ref_obj_id from this point
14946 			 * onwards anymore, thus we should better reset it,
14947 			 * so that state pruning has chances to take effect.
14948 			 */
14949 			reg->id = 0;
14950 			reg->ref_obj_id = 0;
14951 
14952 			return;
14953 		}
14954 
14955 		mark_ptr_not_null_reg(reg);
14956 
14957 		if (!reg_may_point_to_spin_lock(reg)) {
14958 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14959 			 * in release_reference().
14960 			 *
14961 			 * reg->id is still used by spin_lock ptr. Other
14962 			 * than spin_lock ptr type, reg->id can be reset.
14963 			 */
14964 			reg->id = 0;
14965 		}
14966 	}
14967 }
14968 
14969 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14970  * be folded together at some point.
14971  */
14972 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14973 				  bool is_null)
14974 {
14975 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14976 	struct bpf_reg_state *regs = state->regs, *reg;
14977 	u32 ref_obj_id = regs[regno].ref_obj_id;
14978 	u32 id = regs[regno].id;
14979 
14980 	if (ref_obj_id && ref_obj_id == id && is_null)
14981 		/* regs[regno] is in the " == NULL" branch.
14982 		 * No one could have freed the reference state before
14983 		 * doing the NULL check.
14984 		 */
14985 		WARN_ON_ONCE(release_reference_state(state, id));
14986 
14987 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14988 		mark_ptr_or_null_reg(state, reg, id, is_null);
14989 	}));
14990 }
14991 
14992 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14993 				   struct bpf_reg_state *dst_reg,
14994 				   struct bpf_reg_state *src_reg,
14995 				   struct bpf_verifier_state *this_branch,
14996 				   struct bpf_verifier_state *other_branch)
14997 {
14998 	if (BPF_SRC(insn->code) != BPF_X)
14999 		return false;
15000 
15001 	/* Pointers are always 64-bit. */
15002 	if (BPF_CLASS(insn->code) == BPF_JMP32)
15003 		return false;
15004 
15005 	switch (BPF_OP(insn->code)) {
15006 	case BPF_JGT:
15007 		if ((dst_reg->type == PTR_TO_PACKET &&
15008 		     src_reg->type == PTR_TO_PACKET_END) ||
15009 		    (dst_reg->type == PTR_TO_PACKET_META &&
15010 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15011 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
15012 			find_good_pkt_pointers(this_branch, dst_reg,
15013 					       dst_reg->type, false);
15014 			mark_pkt_end(other_branch, insn->dst_reg, true);
15015 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15016 			    src_reg->type == PTR_TO_PACKET) ||
15017 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15018 			    src_reg->type == PTR_TO_PACKET_META)) {
15019 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
15020 			find_good_pkt_pointers(other_branch, src_reg,
15021 					       src_reg->type, true);
15022 			mark_pkt_end(this_branch, insn->src_reg, false);
15023 		} else {
15024 			return false;
15025 		}
15026 		break;
15027 	case BPF_JLT:
15028 		if ((dst_reg->type == PTR_TO_PACKET &&
15029 		     src_reg->type == PTR_TO_PACKET_END) ||
15030 		    (dst_reg->type == PTR_TO_PACKET_META &&
15031 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15032 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
15033 			find_good_pkt_pointers(other_branch, dst_reg,
15034 					       dst_reg->type, true);
15035 			mark_pkt_end(this_branch, insn->dst_reg, false);
15036 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15037 			    src_reg->type == PTR_TO_PACKET) ||
15038 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15039 			    src_reg->type == PTR_TO_PACKET_META)) {
15040 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
15041 			find_good_pkt_pointers(this_branch, src_reg,
15042 					       src_reg->type, false);
15043 			mark_pkt_end(other_branch, insn->src_reg, true);
15044 		} else {
15045 			return false;
15046 		}
15047 		break;
15048 	case BPF_JGE:
15049 		if ((dst_reg->type == PTR_TO_PACKET &&
15050 		     src_reg->type == PTR_TO_PACKET_END) ||
15051 		    (dst_reg->type == PTR_TO_PACKET_META &&
15052 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15053 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
15054 			find_good_pkt_pointers(this_branch, dst_reg,
15055 					       dst_reg->type, true);
15056 			mark_pkt_end(other_branch, insn->dst_reg, false);
15057 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15058 			    src_reg->type == PTR_TO_PACKET) ||
15059 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15060 			    src_reg->type == PTR_TO_PACKET_META)) {
15061 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
15062 			find_good_pkt_pointers(other_branch, src_reg,
15063 					       src_reg->type, false);
15064 			mark_pkt_end(this_branch, insn->src_reg, true);
15065 		} else {
15066 			return false;
15067 		}
15068 		break;
15069 	case BPF_JLE:
15070 		if ((dst_reg->type == PTR_TO_PACKET &&
15071 		     src_reg->type == PTR_TO_PACKET_END) ||
15072 		    (dst_reg->type == PTR_TO_PACKET_META &&
15073 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15074 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
15075 			find_good_pkt_pointers(other_branch, dst_reg,
15076 					       dst_reg->type, false);
15077 			mark_pkt_end(this_branch, insn->dst_reg, true);
15078 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15079 			    src_reg->type == PTR_TO_PACKET) ||
15080 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15081 			    src_reg->type == PTR_TO_PACKET_META)) {
15082 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
15083 			find_good_pkt_pointers(this_branch, src_reg,
15084 					       src_reg->type, true);
15085 			mark_pkt_end(other_branch, insn->src_reg, false);
15086 		} else {
15087 			return false;
15088 		}
15089 		break;
15090 	default:
15091 		return false;
15092 	}
15093 
15094 	return true;
15095 }
15096 
15097 static void find_equal_scalars(struct bpf_verifier_state *vstate,
15098 			       struct bpf_reg_state *known_reg)
15099 {
15100 	struct bpf_func_state *state;
15101 	struct bpf_reg_state *reg;
15102 
15103 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15104 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
15105 			copy_register_state(reg, known_reg);
15106 	}));
15107 }
15108 
15109 static int check_cond_jmp_op(struct bpf_verifier_env *env,
15110 			     struct bpf_insn *insn, int *insn_idx)
15111 {
15112 	struct bpf_verifier_state *this_branch = env->cur_state;
15113 	struct bpf_verifier_state *other_branch;
15114 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
15115 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
15116 	struct bpf_reg_state *eq_branch_regs;
15117 	u8 opcode = BPF_OP(insn->code);
15118 	bool is_jmp32;
15119 	int pred = -1;
15120 	int err;
15121 
15122 	/* Only conditional jumps are expected to reach here. */
15123 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
15124 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
15125 		return -EINVAL;
15126 	}
15127 
15128 	if (opcode == BPF_JCOND) {
15129 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
15130 		int idx = *insn_idx;
15131 
15132 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
15133 		    insn->src_reg != BPF_MAY_GOTO ||
15134 		    insn->dst_reg || insn->imm || insn->off == 0) {
15135 			verbose(env, "invalid may_goto off %d imm %d\n",
15136 				insn->off, insn->imm);
15137 			return -EINVAL;
15138 		}
15139 		prev_st = find_prev_entry(env, cur_st->parent, idx);
15140 
15141 		/* branch out 'fallthrough' insn as a new state to explore */
15142 		queued_st = push_stack(env, idx + 1, idx, false);
15143 		if (!queued_st)
15144 			return -ENOMEM;
15145 
15146 		queued_st->may_goto_depth++;
15147 		if (prev_st)
15148 			widen_imprecise_scalars(env, prev_st, queued_st);
15149 		*insn_idx += insn->off;
15150 		return 0;
15151 	}
15152 
15153 	/* check src2 operand */
15154 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15155 	if (err)
15156 		return err;
15157 
15158 	dst_reg = &regs[insn->dst_reg];
15159 	if (BPF_SRC(insn->code) == BPF_X) {
15160 		if (insn->imm != 0) {
15161 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15162 			return -EINVAL;
15163 		}
15164 
15165 		/* check src1 operand */
15166 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15167 		if (err)
15168 			return err;
15169 
15170 		src_reg = &regs[insn->src_reg];
15171 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
15172 		    is_pointer_value(env, insn->src_reg)) {
15173 			verbose(env, "R%d pointer comparison prohibited\n",
15174 				insn->src_reg);
15175 			return -EACCES;
15176 		}
15177 	} else {
15178 		if (insn->src_reg != BPF_REG_0) {
15179 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15180 			return -EINVAL;
15181 		}
15182 		src_reg = &env->fake_reg[0];
15183 		memset(src_reg, 0, sizeof(*src_reg));
15184 		src_reg->type = SCALAR_VALUE;
15185 		__mark_reg_known(src_reg, insn->imm);
15186 	}
15187 
15188 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
15189 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
15190 	if (pred >= 0) {
15191 		/* If we get here with a dst_reg pointer type it is because
15192 		 * above is_branch_taken() special cased the 0 comparison.
15193 		 */
15194 		if (!__is_pointer_value(false, dst_reg))
15195 			err = mark_chain_precision(env, insn->dst_reg);
15196 		if (BPF_SRC(insn->code) == BPF_X && !err &&
15197 		    !__is_pointer_value(false, src_reg))
15198 			err = mark_chain_precision(env, insn->src_reg);
15199 		if (err)
15200 			return err;
15201 	}
15202 
15203 	if (pred == 1) {
15204 		/* Only follow the goto, ignore fall-through. If needed, push
15205 		 * the fall-through branch for simulation under speculative
15206 		 * execution.
15207 		 */
15208 		if (!env->bypass_spec_v1 &&
15209 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
15210 					       *insn_idx))
15211 			return -EFAULT;
15212 		if (env->log.level & BPF_LOG_LEVEL)
15213 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
15214 		*insn_idx += insn->off;
15215 		return 0;
15216 	} else if (pred == 0) {
15217 		/* Only follow the fall-through branch, since that's where the
15218 		 * program will go. If needed, push the goto branch for
15219 		 * simulation under speculative execution.
15220 		 */
15221 		if (!env->bypass_spec_v1 &&
15222 		    !sanitize_speculative_path(env, insn,
15223 					       *insn_idx + insn->off + 1,
15224 					       *insn_idx))
15225 			return -EFAULT;
15226 		if (env->log.level & BPF_LOG_LEVEL)
15227 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
15228 		return 0;
15229 	}
15230 
15231 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
15232 				  false);
15233 	if (!other_branch)
15234 		return -EFAULT;
15235 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
15236 
15237 	if (BPF_SRC(insn->code) == BPF_X) {
15238 		err = reg_set_min_max(env,
15239 				      &other_branch_regs[insn->dst_reg],
15240 				      &other_branch_regs[insn->src_reg],
15241 				      dst_reg, src_reg, opcode, is_jmp32);
15242 	} else /* BPF_SRC(insn->code) == BPF_K */ {
15243 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
15244 		 * so that these are two different memory locations. The
15245 		 * src_reg is not used beyond here in context of K.
15246 		 */
15247 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
15248 		       sizeof(env->fake_reg[0]));
15249 		err = reg_set_min_max(env,
15250 				      &other_branch_regs[insn->dst_reg],
15251 				      &env->fake_reg[0],
15252 				      dst_reg, &env->fake_reg[1],
15253 				      opcode, is_jmp32);
15254 	}
15255 	if (err)
15256 		return err;
15257 
15258 	if (BPF_SRC(insn->code) == BPF_X &&
15259 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
15260 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
15261 		find_equal_scalars(this_branch, src_reg);
15262 		find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
15263 	}
15264 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
15265 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
15266 		find_equal_scalars(this_branch, dst_reg);
15267 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
15268 	}
15269 
15270 	/* if one pointer register is compared to another pointer
15271 	 * register check if PTR_MAYBE_NULL could be lifted.
15272 	 * E.g. register A - maybe null
15273 	 *      register B - not null
15274 	 * for JNE A, B, ... - A is not null in the false branch;
15275 	 * for JEQ A, B, ... - A is not null in the true branch.
15276 	 *
15277 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
15278 	 * not need to be null checked by the BPF program, i.e.,
15279 	 * could be null even without PTR_MAYBE_NULL marking, so
15280 	 * only propagate nullness when neither reg is that type.
15281 	 */
15282 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
15283 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
15284 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
15285 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
15286 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
15287 		eq_branch_regs = NULL;
15288 		switch (opcode) {
15289 		case BPF_JEQ:
15290 			eq_branch_regs = other_branch_regs;
15291 			break;
15292 		case BPF_JNE:
15293 			eq_branch_regs = regs;
15294 			break;
15295 		default:
15296 			/* do nothing */
15297 			break;
15298 		}
15299 		if (eq_branch_regs) {
15300 			if (type_may_be_null(src_reg->type))
15301 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
15302 			else
15303 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
15304 		}
15305 	}
15306 
15307 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
15308 	 * NOTE: these optimizations below are related with pointer comparison
15309 	 *       which will never be JMP32.
15310 	 */
15311 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
15312 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
15313 	    type_may_be_null(dst_reg->type)) {
15314 		/* Mark all identical registers in each branch as either
15315 		 * safe or unknown depending R == 0 or R != 0 conditional.
15316 		 */
15317 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
15318 				      opcode == BPF_JNE);
15319 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
15320 				      opcode == BPF_JEQ);
15321 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
15322 					   this_branch, other_branch) &&
15323 		   is_pointer_value(env, insn->dst_reg)) {
15324 		verbose(env, "R%d pointer comparison prohibited\n",
15325 			insn->dst_reg);
15326 		return -EACCES;
15327 	}
15328 	if (env->log.level & BPF_LOG_LEVEL)
15329 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
15330 	return 0;
15331 }
15332 
15333 /* verify BPF_LD_IMM64 instruction */
15334 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
15335 {
15336 	struct bpf_insn_aux_data *aux = cur_aux(env);
15337 	struct bpf_reg_state *regs = cur_regs(env);
15338 	struct bpf_reg_state *dst_reg;
15339 	struct bpf_map *map;
15340 	int err;
15341 
15342 	if (BPF_SIZE(insn->code) != BPF_DW) {
15343 		verbose(env, "invalid BPF_LD_IMM insn\n");
15344 		return -EINVAL;
15345 	}
15346 	if (insn->off != 0) {
15347 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
15348 		return -EINVAL;
15349 	}
15350 
15351 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
15352 	if (err)
15353 		return err;
15354 
15355 	dst_reg = &regs[insn->dst_reg];
15356 	if (insn->src_reg == 0) {
15357 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15358 
15359 		dst_reg->type = SCALAR_VALUE;
15360 		__mark_reg_known(&regs[insn->dst_reg], imm);
15361 		return 0;
15362 	}
15363 
15364 	/* All special src_reg cases are listed below. From this point onwards
15365 	 * we either succeed and assign a corresponding dst_reg->type after
15366 	 * zeroing the offset, or fail and reject the program.
15367 	 */
15368 	mark_reg_known_zero(env, regs, insn->dst_reg);
15369 
15370 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15371 		dst_reg->type = aux->btf_var.reg_type;
15372 		switch (base_type(dst_reg->type)) {
15373 		case PTR_TO_MEM:
15374 			dst_reg->mem_size = aux->btf_var.mem_size;
15375 			break;
15376 		case PTR_TO_BTF_ID:
15377 			dst_reg->btf = aux->btf_var.btf;
15378 			dst_reg->btf_id = aux->btf_var.btf_id;
15379 			break;
15380 		default:
15381 			verbose(env, "bpf verifier is misconfigured\n");
15382 			return -EFAULT;
15383 		}
15384 		return 0;
15385 	}
15386 
15387 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
15388 		struct bpf_prog_aux *aux = env->prog->aux;
15389 		u32 subprogno = find_subprog(env,
15390 					     env->insn_idx + insn->imm + 1);
15391 
15392 		if (!aux->func_info) {
15393 			verbose(env, "missing btf func_info\n");
15394 			return -EINVAL;
15395 		}
15396 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15397 			verbose(env, "callback function not static\n");
15398 			return -EINVAL;
15399 		}
15400 
15401 		dst_reg->type = PTR_TO_FUNC;
15402 		dst_reg->subprogno = subprogno;
15403 		return 0;
15404 	}
15405 
15406 	map = env->used_maps[aux->map_index];
15407 	dst_reg->map_ptr = map;
15408 
15409 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15410 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15411 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
15412 			__mark_reg_unknown(env, dst_reg);
15413 			return 0;
15414 		}
15415 		dst_reg->type = PTR_TO_MAP_VALUE;
15416 		dst_reg->off = aux->map_off;
15417 		WARN_ON_ONCE(map->max_entries != 1);
15418 		/* We want reg->id to be same (0) as map_value is not distinct */
15419 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15420 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15421 		dst_reg->type = CONST_PTR_TO_MAP;
15422 	} else {
15423 		verbose(env, "bpf verifier is misconfigured\n");
15424 		return -EINVAL;
15425 	}
15426 
15427 	return 0;
15428 }
15429 
15430 static bool may_access_skb(enum bpf_prog_type type)
15431 {
15432 	switch (type) {
15433 	case BPF_PROG_TYPE_SOCKET_FILTER:
15434 	case BPF_PROG_TYPE_SCHED_CLS:
15435 	case BPF_PROG_TYPE_SCHED_ACT:
15436 		return true;
15437 	default:
15438 		return false;
15439 	}
15440 }
15441 
15442 /* verify safety of LD_ABS|LD_IND instructions:
15443  * - they can only appear in the programs where ctx == skb
15444  * - since they are wrappers of function calls, they scratch R1-R5 registers,
15445  *   preserve R6-R9, and store return value into R0
15446  *
15447  * Implicit input:
15448  *   ctx == skb == R6 == CTX
15449  *
15450  * Explicit input:
15451  *   SRC == any register
15452  *   IMM == 32-bit immediate
15453  *
15454  * Output:
15455  *   R0 - 8/16/32-bit skb data converted to cpu endianness
15456  */
15457 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15458 {
15459 	struct bpf_reg_state *regs = cur_regs(env);
15460 	static const int ctx_reg = BPF_REG_6;
15461 	u8 mode = BPF_MODE(insn->code);
15462 	int i, err;
15463 
15464 	if (!may_access_skb(resolve_prog_type(env->prog))) {
15465 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15466 		return -EINVAL;
15467 	}
15468 
15469 	if (!env->ops->gen_ld_abs) {
15470 		verbose(env, "bpf verifier is misconfigured\n");
15471 		return -EINVAL;
15472 	}
15473 
15474 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15475 	    BPF_SIZE(insn->code) == BPF_DW ||
15476 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15477 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15478 		return -EINVAL;
15479 	}
15480 
15481 	/* check whether implicit source operand (register R6) is readable */
15482 	err = check_reg_arg(env, ctx_reg, SRC_OP);
15483 	if (err)
15484 		return err;
15485 
15486 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15487 	 * gen_ld_abs() may terminate the program at runtime, leading to
15488 	 * reference leak.
15489 	 */
15490 	err = check_reference_leak(env, false);
15491 	if (err) {
15492 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15493 		return err;
15494 	}
15495 
15496 	if (env->cur_state->active_lock.ptr) {
15497 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15498 		return -EINVAL;
15499 	}
15500 
15501 	if (env->cur_state->active_rcu_lock) {
15502 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15503 		return -EINVAL;
15504 	}
15505 
15506 	if (env->cur_state->active_preempt_lock) {
15507 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_preempt_disable-ed region\n");
15508 		return -EINVAL;
15509 	}
15510 
15511 	if (regs[ctx_reg].type != PTR_TO_CTX) {
15512 		verbose(env,
15513 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15514 		return -EINVAL;
15515 	}
15516 
15517 	if (mode == BPF_IND) {
15518 		/* check explicit source operand */
15519 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15520 		if (err)
15521 			return err;
15522 	}
15523 
15524 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
15525 	if (err < 0)
15526 		return err;
15527 
15528 	/* reset caller saved regs to unreadable */
15529 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
15530 		mark_reg_not_init(env, regs, caller_saved[i]);
15531 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15532 	}
15533 
15534 	/* mark destination R0 register as readable, since it contains
15535 	 * the value fetched from the packet.
15536 	 * Already marked as written above.
15537 	 */
15538 	mark_reg_unknown(env, regs, BPF_REG_0);
15539 	/* ld_abs load up to 32-bit skb data. */
15540 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15541 	return 0;
15542 }
15543 
15544 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
15545 {
15546 	const char *exit_ctx = "At program exit";
15547 	struct tnum enforce_attach_type_range = tnum_unknown;
15548 	const struct bpf_prog *prog = env->prog;
15549 	struct bpf_reg_state *reg;
15550 	struct bpf_retval_range range = retval_range(0, 1);
15551 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15552 	int err;
15553 	struct bpf_func_state *frame = env->cur_state->frame[0];
15554 	const bool is_subprog = frame->subprogno;
15555 
15556 	/* LSM and struct_ops func-ptr's return type could be "void" */
15557 	if (!is_subprog || frame->in_exception_callback_fn) {
15558 		switch (prog_type) {
15559 		case BPF_PROG_TYPE_LSM:
15560 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
15561 				/* See below, can be 0 or 0-1 depending on hook. */
15562 				break;
15563 			fallthrough;
15564 		case BPF_PROG_TYPE_STRUCT_OPS:
15565 			if (!prog->aux->attach_func_proto->type)
15566 				return 0;
15567 			break;
15568 		default:
15569 			break;
15570 		}
15571 	}
15572 
15573 	/* eBPF calling convention is such that R0 is used
15574 	 * to return the value from eBPF program.
15575 	 * Make sure that it's readable at this time
15576 	 * of bpf_exit, which means that program wrote
15577 	 * something into it earlier
15578 	 */
15579 	err = check_reg_arg(env, regno, SRC_OP);
15580 	if (err)
15581 		return err;
15582 
15583 	if (is_pointer_value(env, regno)) {
15584 		verbose(env, "R%d leaks addr as return value\n", regno);
15585 		return -EACCES;
15586 	}
15587 
15588 	reg = cur_regs(env) + regno;
15589 
15590 	if (frame->in_async_callback_fn) {
15591 		/* enforce return zero from async callbacks like timer */
15592 		exit_ctx = "At async callback return";
15593 		range = retval_range(0, 0);
15594 		goto enforce_retval;
15595 	}
15596 
15597 	if (is_subprog && !frame->in_exception_callback_fn) {
15598 		if (reg->type != SCALAR_VALUE) {
15599 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15600 				regno, reg_type_str(env, reg->type));
15601 			return -EINVAL;
15602 		}
15603 		return 0;
15604 	}
15605 
15606 	switch (prog_type) {
15607 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15608 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15609 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15610 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15611 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15612 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15613 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15614 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15615 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15616 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15617 			range = retval_range(1, 1);
15618 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15619 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15620 			range = retval_range(0, 3);
15621 		break;
15622 	case BPF_PROG_TYPE_CGROUP_SKB:
15623 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15624 			range = retval_range(0, 3);
15625 			enforce_attach_type_range = tnum_range(2, 3);
15626 		}
15627 		break;
15628 	case BPF_PROG_TYPE_CGROUP_SOCK:
15629 	case BPF_PROG_TYPE_SOCK_OPS:
15630 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15631 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15632 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15633 		break;
15634 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15635 		if (!env->prog->aux->attach_btf_id)
15636 			return 0;
15637 		range = retval_range(0, 0);
15638 		break;
15639 	case BPF_PROG_TYPE_TRACING:
15640 		switch (env->prog->expected_attach_type) {
15641 		case BPF_TRACE_FENTRY:
15642 		case BPF_TRACE_FEXIT:
15643 			range = retval_range(0, 0);
15644 			break;
15645 		case BPF_TRACE_RAW_TP:
15646 		case BPF_MODIFY_RETURN:
15647 			return 0;
15648 		case BPF_TRACE_ITER:
15649 			break;
15650 		default:
15651 			return -ENOTSUPP;
15652 		}
15653 		break;
15654 	case BPF_PROG_TYPE_SK_LOOKUP:
15655 		range = retval_range(SK_DROP, SK_PASS);
15656 		break;
15657 
15658 	case BPF_PROG_TYPE_LSM:
15659 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15660 			/* Regular BPF_PROG_TYPE_LSM programs can return
15661 			 * any value.
15662 			 */
15663 			return 0;
15664 		}
15665 		if (!env->prog->aux->attach_func_proto->type) {
15666 			/* Make sure programs that attach to void
15667 			 * hooks don't try to modify return value.
15668 			 */
15669 			range = retval_range(1, 1);
15670 		}
15671 		break;
15672 
15673 	case BPF_PROG_TYPE_NETFILTER:
15674 		range = retval_range(NF_DROP, NF_ACCEPT);
15675 		break;
15676 	case BPF_PROG_TYPE_EXT:
15677 		/* freplace program can return anything as its return value
15678 		 * depends on the to-be-replaced kernel func or bpf program.
15679 		 */
15680 	default:
15681 		return 0;
15682 	}
15683 
15684 enforce_retval:
15685 	if (reg->type != SCALAR_VALUE) {
15686 		verbose(env, "%s the register R%d is not a known value (%s)\n",
15687 			exit_ctx, regno, reg_type_str(env, reg->type));
15688 		return -EINVAL;
15689 	}
15690 
15691 	err = mark_chain_precision(env, regno);
15692 	if (err)
15693 		return err;
15694 
15695 	if (!retval_range_within(range, reg)) {
15696 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
15697 		if (!is_subprog &&
15698 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
15699 		    prog_type == BPF_PROG_TYPE_LSM &&
15700 		    !prog->aux->attach_func_proto->type)
15701 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15702 		return -EINVAL;
15703 	}
15704 
15705 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15706 	    tnum_in(enforce_attach_type_range, reg->var_off))
15707 		env->prog->enforce_expected_attach_type = 1;
15708 	return 0;
15709 }
15710 
15711 /* non-recursive DFS pseudo code
15712  * 1  procedure DFS-iterative(G,v):
15713  * 2      label v as discovered
15714  * 3      let S be a stack
15715  * 4      S.push(v)
15716  * 5      while S is not empty
15717  * 6            t <- S.peek()
15718  * 7            if t is what we're looking for:
15719  * 8                return t
15720  * 9            for all edges e in G.adjacentEdges(t) do
15721  * 10               if edge e is already labelled
15722  * 11                   continue with the next edge
15723  * 12               w <- G.adjacentVertex(t,e)
15724  * 13               if vertex w is not discovered and not explored
15725  * 14                   label e as tree-edge
15726  * 15                   label w as discovered
15727  * 16                   S.push(w)
15728  * 17                   continue at 5
15729  * 18               else if vertex w is discovered
15730  * 19                   label e as back-edge
15731  * 20               else
15732  * 21                   // vertex w is explored
15733  * 22                   label e as forward- or cross-edge
15734  * 23           label t as explored
15735  * 24           S.pop()
15736  *
15737  * convention:
15738  * 0x10 - discovered
15739  * 0x11 - discovered and fall-through edge labelled
15740  * 0x12 - discovered and fall-through and branch edges labelled
15741  * 0x20 - explored
15742  */
15743 
15744 enum {
15745 	DISCOVERED = 0x10,
15746 	EXPLORED = 0x20,
15747 	FALLTHROUGH = 1,
15748 	BRANCH = 2,
15749 };
15750 
15751 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15752 {
15753 	env->insn_aux_data[idx].prune_point = true;
15754 }
15755 
15756 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15757 {
15758 	return env->insn_aux_data[insn_idx].prune_point;
15759 }
15760 
15761 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15762 {
15763 	env->insn_aux_data[idx].force_checkpoint = true;
15764 }
15765 
15766 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15767 {
15768 	return env->insn_aux_data[insn_idx].force_checkpoint;
15769 }
15770 
15771 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15772 {
15773 	env->insn_aux_data[idx].calls_callback = true;
15774 }
15775 
15776 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15777 {
15778 	return env->insn_aux_data[insn_idx].calls_callback;
15779 }
15780 
15781 enum {
15782 	DONE_EXPLORING = 0,
15783 	KEEP_EXPLORING = 1,
15784 };
15785 
15786 /* t, w, e - match pseudo-code above:
15787  * t - index of current instruction
15788  * w - next instruction
15789  * e - edge
15790  */
15791 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15792 {
15793 	int *insn_stack = env->cfg.insn_stack;
15794 	int *insn_state = env->cfg.insn_state;
15795 
15796 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15797 		return DONE_EXPLORING;
15798 
15799 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15800 		return DONE_EXPLORING;
15801 
15802 	if (w < 0 || w >= env->prog->len) {
15803 		verbose_linfo(env, t, "%d: ", t);
15804 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15805 		return -EINVAL;
15806 	}
15807 
15808 	if (e == BRANCH) {
15809 		/* mark branch target for state pruning */
15810 		mark_prune_point(env, w);
15811 		mark_jmp_point(env, w);
15812 	}
15813 
15814 	if (insn_state[w] == 0) {
15815 		/* tree-edge */
15816 		insn_state[t] = DISCOVERED | e;
15817 		insn_state[w] = DISCOVERED;
15818 		if (env->cfg.cur_stack >= env->prog->len)
15819 			return -E2BIG;
15820 		insn_stack[env->cfg.cur_stack++] = w;
15821 		return KEEP_EXPLORING;
15822 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15823 		if (env->bpf_capable)
15824 			return DONE_EXPLORING;
15825 		verbose_linfo(env, t, "%d: ", t);
15826 		verbose_linfo(env, w, "%d: ", w);
15827 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15828 		return -EINVAL;
15829 	} else if (insn_state[w] == EXPLORED) {
15830 		/* forward- or cross-edge */
15831 		insn_state[t] = DISCOVERED | e;
15832 	} else {
15833 		verbose(env, "insn state internal bug\n");
15834 		return -EFAULT;
15835 	}
15836 	return DONE_EXPLORING;
15837 }
15838 
15839 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15840 				struct bpf_verifier_env *env,
15841 				bool visit_callee)
15842 {
15843 	int ret, insn_sz;
15844 
15845 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15846 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15847 	if (ret)
15848 		return ret;
15849 
15850 	mark_prune_point(env, t + insn_sz);
15851 	/* when we exit from subprog, we need to record non-linear history */
15852 	mark_jmp_point(env, t + insn_sz);
15853 
15854 	if (visit_callee) {
15855 		mark_prune_point(env, t);
15856 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15857 	}
15858 	return ret;
15859 }
15860 
15861 /* Visits the instruction at index t and returns one of the following:
15862  *  < 0 - an error occurred
15863  *  DONE_EXPLORING - the instruction was fully explored
15864  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15865  */
15866 static int visit_insn(int t, struct bpf_verifier_env *env)
15867 {
15868 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15869 	int ret, off, insn_sz;
15870 
15871 	if (bpf_pseudo_func(insn))
15872 		return visit_func_call_insn(t, insns, env, true);
15873 
15874 	/* All non-branch instructions have a single fall-through edge. */
15875 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15876 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15877 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15878 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15879 	}
15880 
15881 	switch (BPF_OP(insn->code)) {
15882 	case BPF_EXIT:
15883 		return DONE_EXPLORING;
15884 
15885 	case BPF_CALL:
15886 		if (is_async_callback_calling_insn(insn))
15887 			/* Mark this call insn as a prune point to trigger
15888 			 * is_state_visited() check before call itself is
15889 			 * processed by __check_func_call(). Otherwise new
15890 			 * async state will be pushed for further exploration.
15891 			 */
15892 			mark_prune_point(env, t);
15893 		/* For functions that invoke callbacks it is not known how many times
15894 		 * callback would be called. Verifier models callback calling functions
15895 		 * by repeatedly visiting callback bodies and returning to origin call
15896 		 * instruction.
15897 		 * In order to stop such iteration verifier needs to identify when a
15898 		 * state identical some state from a previous iteration is reached.
15899 		 * Check below forces creation of checkpoint before callback calling
15900 		 * instruction to allow search for such identical states.
15901 		 */
15902 		if (is_sync_callback_calling_insn(insn)) {
15903 			mark_calls_callback(env, t);
15904 			mark_force_checkpoint(env, t);
15905 			mark_prune_point(env, t);
15906 			mark_jmp_point(env, t);
15907 		}
15908 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15909 			struct bpf_kfunc_call_arg_meta meta;
15910 
15911 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15912 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15913 				mark_prune_point(env, t);
15914 				/* Checking and saving state checkpoints at iter_next() call
15915 				 * is crucial for fast convergence of open-coded iterator loop
15916 				 * logic, so we need to force it. If we don't do that,
15917 				 * is_state_visited() might skip saving a checkpoint, causing
15918 				 * unnecessarily long sequence of not checkpointed
15919 				 * instructions and jumps, leading to exhaustion of jump
15920 				 * history buffer, and potentially other undesired outcomes.
15921 				 * It is expected that with correct open-coded iterators
15922 				 * convergence will happen quickly, so we don't run a risk of
15923 				 * exhausting memory.
15924 				 */
15925 				mark_force_checkpoint(env, t);
15926 			}
15927 		}
15928 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15929 
15930 	case BPF_JA:
15931 		if (BPF_SRC(insn->code) != BPF_K)
15932 			return -EINVAL;
15933 
15934 		if (BPF_CLASS(insn->code) == BPF_JMP)
15935 			off = insn->off;
15936 		else
15937 			off = insn->imm;
15938 
15939 		/* unconditional jump with single edge */
15940 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15941 		if (ret)
15942 			return ret;
15943 
15944 		mark_prune_point(env, t + off + 1);
15945 		mark_jmp_point(env, t + off + 1);
15946 
15947 		return ret;
15948 
15949 	default:
15950 		/* conditional jump with two edges */
15951 		mark_prune_point(env, t);
15952 		if (is_may_goto_insn(insn))
15953 			mark_force_checkpoint(env, t);
15954 
15955 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15956 		if (ret)
15957 			return ret;
15958 
15959 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15960 	}
15961 }
15962 
15963 /* non-recursive depth-first-search to detect loops in BPF program
15964  * loop == back-edge in directed graph
15965  */
15966 static int check_cfg(struct bpf_verifier_env *env)
15967 {
15968 	int insn_cnt = env->prog->len;
15969 	int *insn_stack, *insn_state;
15970 	int ex_insn_beg, i, ret = 0;
15971 	bool ex_done = false;
15972 
15973 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15974 	if (!insn_state)
15975 		return -ENOMEM;
15976 
15977 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15978 	if (!insn_stack) {
15979 		kvfree(insn_state);
15980 		return -ENOMEM;
15981 	}
15982 
15983 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15984 	insn_stack[0] = 0; /* 0 is the first instruction */
15985 	env->cfg.cur_stack = 1;
15986 
15987 walk_cfg:
15988 	while (env->cfg.cur_stack > 0) {
15989 		int t = insn_stack[env->cfg.cur_stack - 1];
15990 
15991 		ret = visit_insn(t, env);
15992 		switch (ret) {
15993 		case DONE_EXPLORING:
15994 			insn_state[t] = EXPLORED;
15995 			env->cfg.cur_stack--;
15996 			break;
15997 		case KEEP_EXPLORING:
15998 			break;
15999 		default:
16000 			if (ret > 0) {
16001 				verbose(env, "visit_insn internal bug\n");
16002 				ret = -EFAULT;
16003 			}
16004 			goto err_free;
16005 		}
16006 	}
16007 
16008 	if (env->cfg.cur_stack < 0) {
16009 		verbose(env, "pop stack internal bug\n");
16010 		ret = -EFAULT;
16011 		goto err_free;
16012 	}
16013 
16014 	if (env->exception_callback_subprog && !ex_done) {
16015 		ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
16016 
16017 		insn_state[ex_insn_beg] = DISCOVERED;
16018 		insn_stack[0] = ex_insn_beg;
16019 		env->cfg.cur_stack = 1;
16020 		ex_done = true;
16021 		goto walk_cfg;
16022 	}
16023 
16024 	for (i = 0; i < insn_cnt; i++) {
16025 		struct bpf_insn *insn = &env->prog->insnsi[i];
16026 
16027 		if (insn_state[i] != EXPLORED) {
16028 			verbose(env, "unreachable insn %d\n", i);
16029 			ret = -EINVAL;
16030 			goto err_free;
16031 		}
16032 		if (bpf_is_ldimm64(insn)) {
16033 			if (insn_state[i + 1] != 0) {
16034 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
16035 				ret = -EINVAL;
16036 				goto err_free;
16037 			}
16038 			i++; /* skip second half of ldimm64 */
16039 		}
16040 	}
16041 	ret = 0; /* cfg looks good */
16042 
16043 err_free:
16044 	kvfree(insn_state);
16045 	kvfree(insn_stack);
16046 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
16047 	return ret;
16048 }
16049 
16050 static int check_abnormal_return(struct bpf_verifier_env *env)
16051 {
16052 	int i;
16053 
16054 	for (i = 1; i < env->subprog_cnt; i++) {
16055 		if (env->subprog_info[i].has_ld_abs) {
16056 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
16057 			return -EINVAL;
16058 		}
16059 		if (env->subprog_info[i].has_tail_call) {
16060 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
16061 			return -EINVAL;
16062 		}
16063 	}
16064 	return 0;
16065 }
16066 
16067 /* The minimum supported BTF func info size */
16068 #define MIN_BPF_FUNCINFO_SIZE	8
16069 #define MAX_FUNCINFO_REC_SIZE	252
16070 
16071 static int check_btf_func_early(struct bpf_verifier_env *env,
16072 				const union bpf_attr *attr,
16073 				bpfptr_t uattr)
16074 {
16075 	u32 krec_size = sizeof(struct bpf_func_info);
16076 	const struct btf_type *type, *func_proto;
16077 	u32 i, nfuncs, urec_size, min_size;
16078 	struct bpf_func_info *krecord;
16079 	struct bpf_prog *prog;
16080 	const struct btf *btf;
16081 	u32 prev_offset = 0;
16082 	bpfptr_t urecord;
16083 	int ret = -ENOMEM;
16084 
16085 	nfuncs = attr->func_info_cnt;
16086 	if (!nfuncs) {
16087 		if (check_abnormal_return(env))
16088 			return -EINVAL;
16089 		return 0;
16090 	}
16091 
16092 	urec_size = attr->func_info_rec_size;
16093 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
16094 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
16095 	    urec_size % sizeof(u32)) {
16096 		verbose(env, "invalid func info rec size %u\n", urec_size);
16097 		return -EINVAL;
16098 	}
16099 
16100 	prog = env->prog;
16101 	btf = prog->aux->btf;
16102 
16103 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16104 	min_size = min_t(u32, krec_size, urec_size);
16105 
16106 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
16107 	if (!krecord)
16108 		return -ENOMEM;
16109 
16110 	for (i = 0; i < nfuncs; i++) {
16111 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
16112 		if (ret) {
16113 			if (ret == -E2BIG) {
16114 				verbose(env, "nonzero tailing record in func info");
16115 				/* set the size kernel expects so loader can zero
16116 				 * out the rest of the record.
16117 				 */
16118 				if (copy_to_bpfptr_offset(uattr,
16119 							  offsetof(union bpf_attr, func_info_rec_size),
16120 							  &min_size, sizeof(min_size)))
16121 					ret = -EFAULT;
16122 			}
16123 			goto err_free;
16124 		}
16125 
16126 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
16127 			ret = -EFAULT;
16128 			goto err_free;
16129 		}
16130 
16131 		/* check insn_off */
16132 		ret = -EINVAL;
16133 		if (i == 0) {
16134 			if (krecord[i].insn_off) {
16135 				verbose(env,
16136 					"nonzero insn_off %u for the first func info record",
16137 					krecord[i].insn_off);
16138 				goto err_free;
16139 			}
16140 		} else if (krecord[i].insn_off <= prev_offset) {
16141 			verbose(env,
16142 				"same or smaller insn offset (%u) than previous func info record (%u)",
16143 				krecord[i].insn_off, prev_offset);
16144 			goto err_free;
16145 		}
16146 
16147 		/* check type_id */
16148 		type = btf_type_by_id(btf, krecord[i].type_id);
16149 		if (!type || !btf_type_is_func(type)) {
16150 			verbose(env, "invalid type id %d in func info",
16151 				krecord[i].type_id);
16152 			goto err_free;
16153 		}
16154 
16155 		func_proto = btf_type_by_id(btf, type->type);
16156 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
16157 			/* btf_func_check() already verified it during BTF load */
16158 			goto err_free;
16159 
16160 		prev_offset = krecord[i].insn_off;
16161 		bpfptr_add(&urecord, urec_size);
16162 	}
16163 
16164 	prog->aux->func_info = krecord;
16165 	prog->aux->func_info_cnt = nfuncs;
16166 	return 0;
16167 
16168 err_free:
16169 	kvfree(krecord);
16170 	return ret;
16171 }
16172 
16173 static int check_btf_func(struct bpf_verifier_env *env,
16174 			  const union bpf_attr *attr,
16175 			  bpfptr_t uattr)
16176 {
16177 	const struct btf_type *type, *func_proto, *ret_type;
16178 	u32 i, nfuncs, urec_size;
16179 	struct bpf_func_info *krecord;
16180 	struct bpf_func_info_aux *info_aux = NULL;
16181 	struct bpf_prog *prog;
16182 	const struct btf *btf;
16183 	bpfptr_t urecord;
16184 	bool scalar_return;
16185 	int ret = -ENOMEM;
16186 
16187 	nfuncs = attr->func_info_cnt;
16188 	if (!nfuncs) {
16189 		if (check_abnormal_return(env))
16190 			return -EINVAL;
16191 		return 0;
16192 	}
16193 	if (nfuncs != env->subprog_cnt) {
16194 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
16195 		return -EINVAL;
16196 	}
16197 
16198 	urec_size = attr->func_info_rec_size;
16199 
16200 	prog = env->prog;
16201 	btf = prog->aux->btf;
16202 
16203 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16204 
16205 	krecord = prog->aux->func_info;
16206 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
16207 	if (!info_aux)
16208 		return -ENOMEM;
16209 
16210 	for (i = 0; i < nfuncs; i++) {
16211 		/* check insn_off */
16212 		ret = -EINVAL;
16213 
16214 		if (env->subprog_info[i].start != krecord[i].insn_off) {
16215 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
16216 			goto err_free;
16217 		}
16218 
16219 		/* Already checked type_id */
16220 		type = btf_type_by_id(btf, krecord[i].type_id);
16221 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
16222 		/* Already checked func_proto */
16223 		func_proto = btf_type_by_id(btf, type->type);
16224 
16225 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
16226 		scalar_return =
16227 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
16228 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
16229 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
16230 			goto err_free;
16231 		}
16232 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
16233 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
16234 			goto err_free;
16235 		}
16236 
16237 		bpfptr_add(&urecord, urec_size);
16238 	}
16239 
16240 	prog->aux->func_info_aux = info_aux;
16241 	return 0;
16242 
16243 err_free:
16244 	kfree(info_aux);
16245 	return ret;
16246 }
16247 
16248 static void adjust_btf_func(struct bpf_verifier_env *env)
16249 {
16250 	struct bpf_prog_aux *aux = env->prog->aux;
16251 	int i;
16252 
16253 	if (!aux->func_info)
16254 		return;
16255 
16256 	/* func_info is not available for hidden subprogs */
16257 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
16258 		aux->func_info[i].insn_off = env->subprog_info[i].start;
16259 }
16260 
16261 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
16262 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
16263 
16264 static int check_btf_line(struct bpf_verifier_env *env,
16265 			  const union bpf_attr *attr,
16266 			  bpfptr_t uattr)
16267 {
16268 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
16269 	struct bpf_subprog_info *sub;
16270 	struct bpf_line_info *linfo;
16271 	struct bpf_prog *prog;
16272 	const struct btf *btf;
16273 	bpfptr_t ulinfo;
16274 	int err;
16275 
16276 	nr_linfo = attr->line_info_cnt;
16277 	if (!nr_linfo)
16278 		return 0;
16279 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
16280 		return -EINVAL;
16281 
16282 	rec_size = attr->line_info_rec_size;
16283 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
16284 	    rec_size > MAX_LINEINFO_REC_SIZE ||
16285 	    rec_size & (sizeof(u32) - 1))
16286 		return -EINVAL;
16287 
16288 	/* Need to zero it in case the userspace may
16289 	 * pass in a smaller bpf_line_info object.
16290 	 */
16291 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
16292 			 GFP_KERNEL | __GFP_NOWARN);
16293 	if (!linfo)
16294 		return -ENOMEM;
16295 
16296 	prog = env->prog;
16297 	btf = prog->aux->btf;
16298 
16299 	s = 0;
16300 	sub = env->subprog_info;
16301 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
16302 	expected_size = sizeof(struct bpf_line_info);
16303 	ncopy = min_t(u32, expected_size, rec_size);
16304 	for (i = 0; i < nr_linfo; i++) {
16305 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
16306 		if (err) {
16307 			if (err == -E2BIG) {
16308 				verbose(env, "nonzero tailing record in line_info");
16309 				if (copy_to_bpfptr_offset(uattr,
16310 							  offsetof(union bpf_attr, line_info_rec_size),
16311 							  &expected_size, sizeof(expected_size)))
16312 					err = -EFAULT;
16313 			}
16314 			goto err_free;
16315 		}
16316 
16317 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
16318 			err = -EFAULT;
16319 			goto err_free;
16320 		}
16321 
16322 		/*
16323 		 * Check insn_off to ensure
16324 		 * 1) strictly increasing AND
16325 		 * 2) bounded by prog->len
16326 		 *
16327 		 * The linfo[0].insn_off == 0 check logically falls into
16328 		 * the later "missing bpf_line_info for func..." case
16329 		 * because the first linfo[0].insn_off must be the
16330 		 * first sub also and the first sub must have
16331 		 * subprog_info[0].start == 0.
16332 		 */
16333 		if ((i && linfo[i].insn_off <= prev_offset) ||
16334 		    linfo[i].insn_off >= prog->len) {
16335 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
16336 				i, linfo[i].insn_off, prev_offset,
16337 				prog->len);
16338 			err = -EINVAL;
16339 			goto err_free;
16340 		}
16341 
16342 		if (!prog->insnsi[linfo[i].insn_off].code) {
16343 			verbose(env,
16344 				"Invalid insn code at line_info[%u].insn_off\n",
16345 				i);
16346 			err = -EINVAL;
16347 			goto err_free;
16348 		}
16349 
16350 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
16351 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
16352 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
16353 			err = -EINVAL;
16354 			goto err_free;
16355 		}
16356 
16357 		if (s != env->subprog_cnt) {
16358 			if (linfo[i].insn_off == sub[s].start) {
16359 				sub[s].linfo_idx = i;
16360 				s++;
16361 			} else if (sub[s].start < linfo[i].insn_off) {
16362 				verbose(env, "missing bpf_line_info for func#%u\n", s);
16363 				err = -EINVAL;
16364 				goto err_free;
16365 			}
16366 		}
16367 
16368 		prev_offset = linfo[i].insn_off;
16369 		bpfptr_add(&ulinfo, rec_size);
16370 	}
16371 
16372 	if (s != env->subprog_cnt) {
16373 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
16374 			env->subprog_cnt - s, s);
16375 		err = -EINVAL;
16376 		goto err_free;
16377 	}
16378 
16379 	prog->aux->linfo = linfo;
16380 	prog->aux->nr_linfo = nr_linfo;
16381 
16382 	return 0;
16383 
16384 err_free:
16385 	kvfree(linfo);
16386 	return err;
16387 }
16388 
16389 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
16390 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
16391 
16392 static int check_core_relo(struct bpf_verifier_env *env,
16393 			   const union bpf_attr *attr,
16394 			   bpfptr_t uattr)
16395 {
16396 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16397 	struct bpf_core_relo core_relo = {};
16398 	struct bpf_prog *prog = env->prog;
16399 	const struct btf *btf = prog->aux->btf;
16400 	struct bpf_core_ctx ctx = {
16401 		.log = &env->log,
16402 		.btf = btf,
16403 	};
16404 	bpfptr_t u_core_relo;
16405 	int err;
16406 
16407 	nr_core_relo = attr->core_relo_cnt;
16408 	if (!nr_core_relo)
16409 		return 0;
16410 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16411 		return -EINVAL;
16412 
16413 	rec_size = attr->core_relo_rec_size;
16414 	if (rec_size < MIN_CORE_RELO_SIZE ||
16415 	    rec_size > MAX_CORE_RELO_SIZE ||
16416 	    rec_size % sizeof(u32))
16417 		return -EINVAL;
16418 
16419 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16420 	expected_size = sizeof(struct bpf_core_relo);
16421 	ncopy = min_t(u32, expected_size, rec_size);
16422 
16423 	/* Unlike func_info and line_info, copy and apply each CO-RE
16424 	 * relocation record one at a time.
16425 	 */
16426 	for (i = 0; i < nr_core_relo; i++) {
16427 		/* future proofing when sizeof(bpf_core_relo) changes */
16428 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16429 		if (err) {
16430 			if (err == -E2BIG) {
16431 				verbose(env, "nonzero tailing record in core_relo");
16432 				if (copy_to_bpfptr_offset(uattr,
16433 							  offsetof(union bpf_attr, core_relo_rec_size),
16434 							  &expected_size, sizeof(expected_size)))
16435 					err = -EFAULT;
16436 			}
16437 			break;
16438 		}
16439 
16440 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16441 			err = -EFAULT;
16442 			break;
16443 		}
16444 
16445 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16446 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16447 				i, core_relo.insn_off, prog->len);
16448 			err = -EINVAL;
16449 			break;
16450 		}
16451 
16452 		err = bpf_core_apply(&ctx, &core_relo, i,
16453 				     &prog->insnsi[core_relo.insn_off / 8]);
16454 		if (err)
16455 			break;
16456 		bpfptr_add(&u_core_relo, rec_size);
16457 	}
16458 	return err;
16459 }
16460 
16461 static int check_btf_info_early(struct bpf_verifier_env *env,
16462 				const union bpf_attr *attr,
16463 				bpfptr_t uattr)
16464 {
16465 	struct btf *btf;
16466 	int err;
16467 
16468 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
16469 		if (check_abnormal_return(env))
16470 			return -EINVAL;
16471 		return 0;
16472 	}
16473 
16474 	btf = btf_get_by_fd(attr->prog_btf_fd);
16475 	if (IS_ERR(btf))
16476 		return PTR_ERR(btf);
16477 	if (btf_is_kernel(btf)) {
16478 		btf_put(btf);
16479 		return -EACCES;
16480 	}
16481 	env->prog->aux->btf = btf;
16482 
16483 	err = check_btf_func_early(env, attr, uattr);
16484 	if (err)
16485 		return err;
16486 	return 0;
16487 }
16488 
16489 static int check_btf_info(struct bpf_verifier_env *env,
16490 			  const union bpf_attr *attr,
16491 			  bpfptr_t uattr)
16492 {
16493 	int err;
16494 
16495 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
16496 		if (check_abnormal_return(env))
16497 			return -EINVAL;
16498 		return 0;
16499 	}
16500 
16501 	err = check_btf_func(env, attr, uattr);
16502 	if (err)
16503 		return err;
16504 
16505 	err = check_btf_line(env, attr, uattr);
16506 	if (err)
16507 		return err;
16508 
16509 	err = check_core_relo(env, attr, uattr);
16510 	if (err)
16511 		return err;
16512 
16513 	return 0;
16514 }
16515 
16516 /* check %cur's range satisfies %old's */
16517 static bool range_within(const struct bpf_reg_state *old,
16518 			 const struct bpf_reg_state *cur)
16519 {
16520 	return old->umin_value <= cur->umin_value &&
16521 	       old->umax_value >= cur->umax_value &&
16522 	       old->smin_value <= cur->smin_value &&
16523 	       old->smax_value >= cur->smax_value &&
16524 	       old->u32_min_value <= cur->u32_min_value &&
16525 	       old->u32_max_value >= cur->u32_max_value &&
16526 	       old->s32_min_value <= cur->s32_min_value &&
16527 	       old->s32_max_value >= cur->s32_max_value;
16528 }
16529 
16530 /* If in the old state two registers had the same id, then they need to have
16531  * the same id in the new state as well.  But that id could be different from
16532  * the old state, so we need to track the mapping from old to new ids.
16533  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16534  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
16535  * regs with a different old id could still have new id 9, we don't care about
16536  * that.
16537  * So we look through our idmap to see if this old id has been seen before.  If
16538  * so, we require the new id to match; otherwise, we add the id pair to the map.
16539  */
16540 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16541 {
16542 	struct bpf_id_pair *map = idmap->map;
16543 	unsigned int i;
16544 
16545 	/* either both IDs should be set or both should be zero */
16546 	if (!!old_id != !!cur_id)
16547 		return false;
16548 
16549 	if (old_id == 0) /* cur_id == 0 as well */
16550 		return true;
16551 
16552 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
16553 		if (!map[i].old) {
16554 			/* Reached an empty slot; haven't seen this id before */
16555 			map[i].old = old_id;
16556 			map[i].cur = cur_id;
16557 			return true;
16558 		}
16559 		if (map[i].old == old_id)
16560 			return map[i].cur == cur_id;
16561 		if (map[i].cur == cur_id)
16562 			return false;
16563 	}
16564 	/* We ran out of idmap slots, which should be impossible */
16565 	WARN_ON_ONCE(1);
16566 	return false;
16567 }
16568 
16569 /* Similar to check_ids(), but allocate a unique temporary ID
16570  * for 'old_id' or 'cur_id' of zero.
16571  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16572  */
16573 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16574 {
16575 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16576 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16577 
16578 	return check_ids(old_id, cur_id, idmap);
16579 }
16580 
16581 static void clean_func_state(struct bpf_verifier_env *env,
16582 			     struct bpf_func_state *st)
16583 {
16584 	enum bpf_reg_liveness live;
16585 	int i, j;
16586 
16587 	for (i = 0; i < BPF_REG_FP; i++) {
16588 		live = st->regs[i].live;
16589 		/* liveness must not touch this register anymore */
16590 		st->regs[i].live |= REG_LIVE_DONE;
16591 		if (!(live & REG_LIVE_READ))
16592 			/* since the register is unused, clear its state
16593 			 * to make further comparison simpler
16594 			 */
16595 			__mark_reg_not_init(env, &st->regs[i]);
16596 	}
16597 
16598 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16599 		live = st->stack[i].spilled_ptr.live;
16600 		/* liveness must not touch this stack slot anymore */
16601 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16602 		if (!(live & REG_LIVE_READ)) {
16603 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16604 			for (j = 0; j < BPF_REG_SIZE; j++)
16605 				st->stack[i].slot_type[j] = STACK_INVALID;
16606 		}
16607 	}
16608 }
16609 
16610 static void clean_verifier_state(struct bpf_verifier_env *env,
16611 				 struct bpf_verifier_state *st)
16612 {
16613 	int i;
16614 
16615 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16616 		/* all regs in this state in all frames were already marked */
16617 		return;
16618 
16619 	for (i = 0; i <= st->curframe; i++)
16620 		clean_func_state(env, st->frame[i]);
16621 }
16622 
16623 /* the parentage chains form a tree.
16624  * the verifier states are added to state lists at given insn and
16625  * pushed into state stack for future exploration.
16626  * when the verifier reaches bpf_exit insn some of the verifer states
16627  * stored in the state lists have their final liveness state already,
16628  * but a lot of states will get revised from liveness point of view when
16629  * the verifier explores other branches.
16630  * Example:
16631  * 1: r0 = 1
16632  * 2: if r1 == 100 goto pc+1
16633  * 3: r0 = 2
16634  * 4: exit
16635  * when the verifier reaches exit insn the register r0 in the state list of
16636  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16637  * of insn 2 and goes exploring further. At the insn 4 it will walk the
16638  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16639  *
16640  * Since the verifier pushes the branch states as it sees them while exploring
16641  * the program the condition of walking the branch instruction for the second
16642  * time means that all states below this branch were already explored and
16643  * their final liveness marks are already propagated.
16644  * Hence when the verifier completes the search of state list in is_state_visited()
16645  * we can call this clean_live_states() function to mark all liveness states
16646  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16647  * will not be used.
16648  * This function also clears the registers and stack for states that !READ
16649  * to simplify state merging.
16650  *
16651  * Important note here that walking the same branch instruction in the callee
16652  * doesn't meant that the states are DONE. The verifier has to compare
16653  * the callsites
16654  */
16655 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16656 			      struct bpf_verifier_state *cur)
16657 {
16658 	struct bpf_verifier_state_list *sl;
16659 
16660 	sl = *explored_state(env, insn);
16661 	while (sl) {
16662 		if (sl->state.branches)
16663 			goto next;
16664 		if (sl->state.insn_idx != insn ||
16665 		    !same_callsites(&sl->state, cur))
16666 			goto next;
16667 		clean_verifier_state(env, &sl->state);
16668 next:
16669 		sl = sl->next;
16670 	}
16671 }
16672 
16673 static bool regs_exact(const struct bpf_reg_state *rold,
16674 		       const struct bpf_reg_state *rcur,
16675 		       struct bpf_idmap *idmap)
16676 {
16677 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16678 	       check_ids(rold->id, rcur->id, idmap) &&
16679 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16680 }
16681 
16682 enum exact_level {
16683 	NOT_EXACT,
16684 	EXACT,
16685 	RANGE_WITHIN
16686 };
16687 
16688 /* Returns true if (rold safe implies rcur safe) */
16689 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16690 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
16691 		    enum exact_level exact)
16692 {
16693 	if (exact == EXACT)
16694 		return regs_exact(rold, rcur, idmap);
16695 
16696 	if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
16697 		/* explored state didn't use this */
16698 		return true;
16699 	if (rold->type == NOT_INIT) {
16700 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
16701 			/* explored state can't have used this */
16702 			return true;
16703 	}
16704 
16705 	/* Enforce that register types have to match exactly, including their
16706 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16707 	 * rule.
16708 	 *
16709 	 * One can make a point that using a pointer register as unbounded
16710 	 * SCALAR would be technically acceptable, but this could lead to
16711 	 * pointer leaks because scalars are allowed to leak while pointers
16712 	 * are not. We could make this safe in special cases if root is
16713 	 * calling us, but it's probably not worth the hassle.
16714 	 *
16715 	 * Also, register types that are *not* MAYBE_NULL could technically be
16716 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16717 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16718 	 * to the same map).
16719 	 * However, if the old MAYBE_NULL register then got NULL checked,
16720 	 * doing so could have affected others with the same id, and we can't
16721 	 * check for that because we lost the id when we converted to
16722 	 * a non-MAYBE_NULL variant.
16723 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16724 	 * non-MAYBE_NULL registers as well.
16725 	 */
16726 	if (rold->type != rcur->type)
16727 		return false;
16728 
16729 	switch (base_type(rold->type)) {
16730 	case SCALAR_VALUE:
16731 		if (env->explore_alu_limits) {
16732 			/* explore_alu_limits disables tnum_in() and range_within()
16733 			 * logic and requires everything to be strict
16734 			 */
16735 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16736 			       check_scalar_ids(rold->id, rcur->id, idmap);
16737 		}
16738 		if (!rold->precise && exact == NOT_EXACT)
16739 			return true;
16740 		/* Why check_ids() for scalar registers?
16741 		 *
16742 		 * Consider the following BPF code:
16743 		 *   1: r6 = ... unbound scalar, ID=a ...
16744 		 *   2: r7 = ... unbound scalar, ID=b ...
16745 		 *   3: if (r6 > r7) goto +1
16746 		 *   4: r6 = r7
16747 		 *   5: if (r6 > X) goto ...
16748 		 *   6: ... memory operation using r7 ...
16749 		 *
16750 		 * First verification path is [1-6]:
16751 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16752 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16753 		 *   r7 <= X, because r6 and r7 share same id.
16754 		 * Next verification path is [1-4, 6].
16755 		 *
16756 		 * Instruction (6) would be reached in two states:
16757 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16758 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16759 		 *
16760 		 * Use check_ids() to distinguish these states.
16761 		 * ---
16762 		 * Also verify that new value satisfies old value range knowledge.
16763 		 */
16764 		return range_within(rold, rcur) &&
16765 		       tnum_in(rold->var_off, rcur->var_off) &&
16766 		       check_scalar_ids(rold->id, rcur->id, idmap);
16767 	case PTR_TO_MAP_KEY:
16768 	case PTR_TO_MAP_VALUE:
16769 	case PTR_TO_MEM:
16770 	case PTR_TO_BUF:
16771 	case PTR_TO_TP_BUFFER:
16772 		/* If the new min/max/var_off satisfy the old ones and
16773 		 * everything else matches, we are OK.
16774 		 */
16775 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16776 		       range_within(rold, rcur) &&
16777 		       tnum_in(rold->var_off, rcur->var_off) &&
16778 		       check_ids(rold->id, rcur->id, idmap) &&
16779 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16780 	case PTR_TO_PACKET_META:
16781 	case PTR_TO_PACKET:
16782 		/* We must have at least as much range as the old ptr
16783 		 * did, so that any accesses which were safe before are
16784 		 * still safe.  This is true even if old range < old off,
16785 		 * since someone could have accessed through (ptr - k), or
16786 		 * even done ptr -= k in a register, to get a safe access.
16787 		 */
16788 		if (rold->range > rcur->range)
16789 			return false;
16790 		/* If the offsets don't match, we can't trust our alignment;
16791 		 * nor can we be sure that we won't fall out of range.
16792 		 */
16793 		if (rold->off != rcur->off)
16794 			return false;
16795 		/* id relations must be preserved */
16796 		if (!check_ids(rold->id, rcur->id, idmap))
16797 			return false;
16798 		/* new val must satisfy old val knowledge */
16799 		return range_within(rold, rcur) &&
16800 		       tnum_in(rold->var_off, rcur->var_off);
16801 	case PTR_TO_STACK:
16802 		/* two stack pointers are equal only if they're pointing to
16803 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16804 		 */
16805 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16806 	case PTR_TO_ARENA:
16807 		return true;
16808 	default:
16809 		return regs_exact(rold, rcur, idmap);
16810 	}
16811 }
16812 
16813 static struct bpf_reg_state unbound_reg;
16814 
16815 static __init int unbound_reg_init(void)
16816 {
16817 	__mark_reg_unknown_imprecise(&unbound_reg);
16818 	unbound_reg.live |= REG_LIVE_READ;
16819 	return 0;
16820 }
16821 late_initcall(unbound_reg_init);
16822 
16823 static bool is_stack_all_misc(struct bpf_verifier_env *env,
16824 			      struct bpf_stack_state *stack)
16825 {
16826 	u32 i;
16827 
16828 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
16829 		if ((stack->slot_type[i] == STACK_MISC) ||
16830 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
16831 			continue;
16832 		return false;
16833 	}
16834 
16835 	return true;
16836 }
16837 
16838 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
16839 						  struct bpf_stack_state *stack)
16840 {
16841 	if (is_spilled_scalar_reg64(stack))
16842 		return &stack->spilled_ptr;
16843 
16844 	if (is_stack_all_misc(env, stack))
16845 		return &unbound_reg;
16846 
16847 	return NULL;
16848 }
16849 
16850 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16851 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
16852 		      enum exact_level exact)
16853 {
16854 	int i, spi;
16855 
16856 	/* walk slots of the explored stack and ignore any additional
16857 	 * slots in the current stack, since explored(safe) state
16858 	 * didn't use them
16859 	 */
16860 	for (i = 0; i < old->allocated_stack; i++) {
16861 		struct bpf_reg_state *old_reg, *cur_reg;
16862 
16863 		spi = i / BPF_REG_SIZE;
16864 
16865 		if (exact != NOT_EXACT &&
16866 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16867 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16868 			return false;
16869 
16870 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
16871 		    && exact == NOT_EXACT) {
16872 			i += BPF_REG_SIZE - 1;
16873 			/* explored state didn't use this */
16874 			continue;
16875 		}
16876 
16877 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16878 			continue;
16879 
16880 		if (env->allow_uninit_stack &&
16881 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16882 			continue;
16883 
16884 		/* explored stack has more populated slots than current stack
16885 		 * and these slots were used
16886 		 */
16887 		if (i >= cur->allocated_stack)
16888 			return false;
16889 
16890 		/* 64-bit scalar spill vs all slots MISC and vice versa.
16891 		 * Load from all slots MISC produces unbound scalar.
16892 		 * Construct a fake register for such stack and call
16893 		 * regsafe() to ensure scalar ids are compared.
16894 		 */
16895 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
16896 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
16897 		if (old_reg && cur_reg) {
16898 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
16899 				return false;
16900 			i += BPF_REG_SIZE - 1;
16901 			continue;
16902 		}
16903 
16904 		/* if old state was safe with misc data in the stack
16905 		 * it will be safe with zero-initialized stack.
16906 		 * The opposite is not true
16907 		 */
16908 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16909 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16910 			continue;
16911 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16912 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16913 			/* Ex: old explored (safe) state has STACK_SPILL in
16914 			 * this stack slot, but current has STACK_MISC ->
16915 			 * this verifier states are not equivalent,
16916 			 * return false to continue verification of this path
16917 			 */
16918 			return false;
16919 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16920 			continue;
16921 		/* Both old and cur are having same slot_type */
16922 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16923 		case STACK_SPILL:
16924 			/* when explored and current stack slot are both storing
16925 			 * spilled registers, check that stored pointers types
16926 			 * are the same as well.
16927 			 * Ex: explored safe path could have stored
16928 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16929 			 * but current path has stored:
16930 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16931 			 * such verifier states are not equivalent.
16932 			 * return false to continue verification of this path
16933 			 */
16934 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16935 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16936 				return false;
16937 			break;
16938 		case STACK_DYNPTR:
16939 			old_reg = &old->stack[spi].spilled_ptr;
16940 			cur_reg = &cur->stack[spi].spilled_ptr;
16941 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16942 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16943 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16944 				return false;
16945 			break;
16946 		case STACK_ITER:
16947 			old_reg = &old->stack[spi].spilled_ptr;
16948 			cur_reg = &cur->stack[spi].spilled_ptr;
16949 			/* iter.depth is not compared between states as it
16950 			 * doesn't matter for correctness and would otherwise
16951 			 * prevent convergence; we maintain it only to prevent
16952 			 * infinite loop check triggering, see
16953 			 * iter_active_depths_differ()
16954 			 */
16955 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16956 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16957 			    old_reg->iter.state != cur_reg->iter.state ||
16958 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16959 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16960 				return false;
16961 			break;
16962 		case STACK_MISC:
16963 		case STACK_ZERO:
16964 		case STACK_INVALID:
16965 			continue;
16966 		/* Ensure that new unhandled slot types return false by default */
16967 		default:
16968 			return false;
16969 		}
16970 	}
16971 	return true;
16972 }
16973 
16974 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16975 		    struct bpf_idmap *idmap)
16976 {
16977 	int i;
16978 
16979 	if (old->acquired_refs != cur->acquired_refs)
16980 		return false;
16981 
16982 	for (i = 0; i < old->acquired_refs; i++) {
16983 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16984 			return false;
16985 	}
16986 
16987 	return true;
16988 }
16989 
16990 /* compare two verifier states
16991  *
16992  * all states stored in state_list are known to be valid, since
16993  * verifier reached 'bpf_exit' instruction through them
16994  *
16995  * this function is called when verifier exploring different branches of
16996  * execution popped from the state stack. If it sees an old state that has
16997  * more strict register state and more strict stack state then this execution
16998  * branch doesn't need to be explored further, since verifier already
16999  * concluded that more strict state leads to valid finish.
17000  *
17001  * Therefore two states are equivalent if register state is more conservative
17002  * and explored stack state is more conservative than the current one.
17003  * Example:
17004  *       explored                   current
17005  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
17006  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
17007  *
17008  * In other words if current stack state (one being explored) has more
17009  * valid slots than old one that already passed validation, it means
17010  * the verifier can stop exploring and conclude that current state is valid too
17011  *
17012  * Similarly with registers. If explored state has register type as invalid
17013  * whereas register type in current state is meaningful, it means that
17014  * the current state will reach 'bpf_exit' instruction safely
17015  */
17016 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
17017 			      struct bpf_func_state *cur, enum exact_level exact)
17018 {
17019 	int i;
17020 
17021 	if (old->callback_depth > cur->callback_depth)
17022 		return false;
17023 
17024 	for (i = 0; i < MAX_BPF_REG; i++)
17025 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
17026 			     &env->idmap_scratch, exact))
17027 			return false;
17028 
17029 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
17030 		return false;
17031 
17032 	if (!refsafe(old, cur, &env->idmap_scratch))
17033 		return false;
17034 
17035 	return true;
17036 }
17037 
17038 static void reset_idmap_scratch(struct bpf_verifier_env *env)
17039 {
17040 	env->idmap_scratch.tmp_id_gen = env->id_gen;
17041 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
17042 }
17043 
17044 static bool states_equal(struct bpf_verifier_env *env,
17045 			 struct bpf_verifier_state *old,
17046 			 struct bpf_verifier_state *cur,
17047 			 enum exact_level exact)
17048 {
17049 	int i;
17050 
17051 	if (old->curframe != cur->curframe)
17052 		return false;
17053 
17054 	reset_idmap_scratch(env);
17055 
17056 	/* Verification state from speculative execution simulation
17057 	 * must never prune a non-speculative execution one.
17058 	 */
17059 	if (old->speculative && !cur->speculative)
17060 		return false;
17061 
17062 	if (old->active_lock.ptr != cur->active_lock.ptr)
17063 		return false;
17064 
17065 	/* Old and cur active_lock's have to be either both present
17066 	 * or both absent.
17067 	 */
17068 	if (!!old->active_lock.id != !!cur->active_lock.id)
17069 		return false;
17070 
17071 	if (old->active_lock.id &&
17072 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
17073 		return false;
17074 
17075 	if (old->active_rcu_lock != cur->active_rcu_lock)
17076 		return false;
17077 
17078 	if (old->active_preempt_lock != cur->active_preempt_lock)
17079 		return false;
17080 
17081 	if (old->in_sleepable != cur->in_sleepable)
17082 		return false;
17083 
17084 	/* for states to be equal callsites have to be the same
17085 	 * and all frame states need to be equivalent
17086 	 */
17087 	for (i = 0; i <= old->curframe; i++) {
17088 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
17089 			return false;
17090 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
17091 			return false;
17092 	}
17093 	return true;
17094 }
17095 
17096 /* Return 0 if no propagation happened. Return negative error code if error
17097  * happened. Otherwise, return the propagated bit.
17098  */
17099 static int propagate_liveness_reg(struct bpf_verifier_env *env,
17100 				  struct bpf_reg_state *reg,
17101 				  struct bpf_reg_state *parent_reg)
17102 {
17103 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
17104 	u8 flag = reg->live & REG_LIVE_READ;
17105 	int err;
17106 
17107 	/* When comes here, read flags of PARENT_REG or REG could be any of
17108 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
17109 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
17110 	 */
17111 	if (parent_flag == REG_LIVE_READ64 ||
17112 	    /* Or if there is no read flag from REG. */
17113 	    !flag ||
17114 	    /* Or if the read flag from REG is the same as PARENT_REG. */
17115 	    parent_flag == flag)
17116 		return 0;
17117 
17118 	err = mark_reg_read(env, reg, parent_reg, flag);
17119 	if (err)
17120 		return err;
17121 
17122 	return flag;
17123 }
17124 
17125 /* A write screens off any subsequent reads; but write marks come from the
17126  * straight-line code between a state and its parent.  When we arrive at an
17127  * equivalent state (jump target or such) we didn't arrive by the straight-line
17128  * code, so read marks in the state must propagate to the parent regardless
17129  * of the state's write marks. That's what 'parent == state->parent' comparison
17130  * in mark_reg_read() is for.
17131  */
17132 static int propagate_liveness(struct bpf_verifier_env *env,
17133 			      const struct bpf_verifier_state *vstate,
17134 			      struct bpf_verifier_state *vparent)
17135 {
17136 	struct bpf_reg_state *state_reg, *parent_reg;
17137 	struct bpf_func_state *state, *parent;
17138 	int i, frame, err = 0;
17139 
17140 	if (vparent->curframe != vstate->curframe) {
17141 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
17142 		     vparent->curframe, vstate->curframe);
17143 		return -EFAULT;
17144 	}
17145 	/* Propagate read liveness of registers... */
17146 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
17147 	for (frame = 0; frame <= vstate->curframe; frame++) {
17148 		parent = vparent->frame[frame];
17149 		state = vstate->frame[frame];
17150 		parent_reg = parent->regs;
17151 		state_reg = state->regs;
17152 		/* We don't need to worry about FP liveness, it's read-only */
17153 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
17154 			err = propagate_liveness_reg(env, &state_reg[i],
17155 						     &parent_reg[i]);
17156 			if (err < 0)
17157 				return err;
17158 			if (err == REG_LIVE_READ64)
17159 				mark_insn_zext(env, &parent_reg[i]);
17160 		}
17161 
17162 		/* Propagate stack slots. */
17163 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
17164 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
17165 			parent_reg = &parent->stack[i].spilled_ptr;
17166 			state_reg = &state->stack[i].spilled_ptr;
17167 			err = propagate_liveness_reg(env, state_reg,
17168 						     parent_reg);
17169 			if (err < 0)
17170 				return err;
17171 		}
17172 	}
17173 	return 0;
17174 }
17175 
17176 /* find precise scalars in the previous equivalent state and
17177  * propagate them into the current state
17178  */
17179 static int propagate_precision(struct bpf_verifier_env *env,
17180 			       const struct bpf_verifier_state *old)
17181 {
17182 	struct bpf_reg_state *state_reg;
17183 	struct bpf_func_state *state;
17184 	int i, err = 0, fr;
17185 	bool first;
17186 
17187 	for (fr = old->curframe; fr >= 0; fr--) {
17188 		state = old->frame[fr];
17189 		state_reg = state->regs;
17190 		first = true;
17191 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
17192 			if (state_reg->type != SCALAR_VALUE ||
17193 			    !state_reg->precise ||
17194 			    !(state_reg->live & REG_LIVE_READ))
17195 				continue;
17196 			if (env->log.level & BPF_LOG_LEVEL2) {
17197 				if (first)
17198 					verbose(env, "frame %d: propagating r%d", fr, i);
17199 				else
17200 					verbose(env, ",r%d", i);
17201 			}
17202 			bt_set_frame_reg(&env->bt, fr, i);
17203 			first = false;
17204 		}
17205 
17206 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17207 			if (!is_spilled_reg(&state->stack[i]))
17208 				continue;
17209 			state_reg = &state->stack[i].spilled_ptr;
17210 			if (state_reg->type != SCALAR_VALUE ||
17211 			    !state_reg->precise ||
17212 			    !(state_reg->live & REG_LIVE_READ))
17213 				continue;
17214 			if (env->log.level & BPF_LOG_LEVEL2) {
17215 				if (first)
17216 					verbose(env, "frame %d: propagating fp%d",
17217 						fr, (-i - 1) * BPF_REG_SIZE);
17218 				else
17219 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
17220 			}
17221 			bt_set_frame_slot(&env->bt, fr, i);
17222 			first = false;
17223 		}
17224 		if (!first)
17225 			verbose(env, "\n");
17226 	}
17227 
17228 	err = mark_chain_precision_batch(env);
17229 	if (err < 0)
17230 		return err;
17231 
17232 	return 0;
17233 }
17234 
17235 static bool states_maybe_looping(struct bpf_verifier_state *old,
17236 				 struct bpf_verifier_state *cur)
17237 {
17238 	struct bpf_func_state *fold, *fcur;
17239 	int i, fr = cur->curframe;
17240 
17241 	if (old->curframe != fr)
17242 		return false;
17243 
17244 	fold = old->frame[fr];
17245 	fcur = cur->frame[fr];
17246 	for (i = 0; i < MAX_BPF_REG; i++)
17247 		if (memcmp(&fold->regs[i], &fcur->regs[i],
17248 			   offsetof(struct bpf_reg_state, parent)))
17249 			return false;
17250 	return true;
17251 }
17252 
17253 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
17254 {
17255 	return env->insn_aux_data[insn_idx].is_iter_next;
17256 }
17257 
17258 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
17259  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
17260  * states to match, which otherwise would look like an infinite loop. So while
17261  * iter_next() calls are taken care of, we still need to be careful and
17262  * prevent erroneous and too eager declaration of "ininite loop", when
17263  * iterators are involved.
17264  *
17265  * Here's a situation in pseudo-BPF assembly form:
17266  *
17267  *   0: again:                          ; set up iter_next() call args
17268  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
17269  *   2:   call bpf_iter_num_next        ; this is iter_next() call
17270  *   3:   if r0 == 0 goto done
17271  *   4:   ... something useful here ...
17272  *   5:   goto again                    ; another iteration
17273  *   6: done:
17274  *   7:   r1 = &it
17275  *   8:   call bpf_iter_num_destroy     ; clean up iter state
17276  *   9:   exit
17277  *
17278  * This is a typical loop. Let's assume that we have a prune point at 1:,
17279  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
17280  * again`, assuming other heuristics don't get in a way).
17281  *
17282  * When we first time come to 1:, let's say we have some state X. We proceed
17283  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
17284  * Now we come back to validate that forked ACTIVE state. We proceed through
17285  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
17286  * are converging. But the problem is that we don't know that yet, as this
17287  * convergence has to happen at iter_next() call site only. So if nothing is
17288  * done, at 1: verifier will use bounded loop logic and declare infinite
17289  * looping (and would be *technically* correct, if not for iterator's
17290  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
17291  * don't want that. So what we do in process_iter_next_call() when we go on
17292  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
17293  * a different iteration. So when we suspect an infinite loop, we additionally
17294  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
17295  * pretend we are not looping and wait for next iter_next() call.
17296  *
17297  * This only applies to ACTIVE state. In DRAINED state we don't expect to
17298  * loop, because that would actually mean infinite loop, as DRAINED state is
17299  * "sticky", and so we'll keep returning into the same instruction with the
17300  * same state (at least in one of possible code paths).
17301  *
17302  * This approach allows to keep infinite loop heuristic even in the face of
17303  * active iterator. E.g., C snippet below is and will be detected as
17304  * inifintely looping:
17305  *
17306  *   struct bpf_iter_num it;
17307  *   int *p, x;
17308  *
17309  *   bpf_iter_num_new(&it, 0, 10);
17310  *   while ((p = bpf_iter_num_next(&t))) {
17311  *       x = p;
17312  *       while (x--) {} // <<-- infinite loop here
17313  *   }
17314  *
17315  */
17316 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
17317 {
17318 	struct bpf_reg_state *slot, *cur_slot;
17319 	struct bpf_func_state *state;
17320 	int i, fr;
17321 
17322 	for (fr = old->curframe; fr >= 0; fr--) {
17323 		state = old->frame[fr];
17324 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17325 			if (state->stack[i].slot_type[0] != STACK_ITER)
17326 				continue;
17327 
17328 			slot = &state->stack[i].spilled_ptr;
17329 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
17330 				continue;
17331 
17332 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
17333 			if (cur_slot->iter.depth != slot->iter.depth)
17334 				return true;
17335 		}
17336 	}
17337 	return false;
17338 }
17339 
17340 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
17341 {
17342 	struct bpf_verifier_state_list *new_sl;
17343 	struct bpf_verifier_state_list *sl, **pprev;
17344 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
17345 	int i, j, n, err, states_cnt = 0;
17346 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
17347 	bool add_new_state = force_new_state;
17348 	bool force_exact;
17349 
17350 	/* bpf progs typically have pruning point every 4 instructions
17351 	 * http://vger.kernel.org/bpfconf2019.html#session-1
17352 	 * Do not add new state for future pruning if the verifier hasn't seen
17353 	 * at least 2 jumps and at least 8 instructions.
17354 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
17355 	 * In tests that amounts to up to 50% reduction into total verifier
17356 	 * memory consumption and 20% verifier time speedup.
17357 	 */
17358 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
17359 	    env->insn_processed - env->prev_insn_processed >= 8)
17360 		add_new_state = true;
17361 
17362 	pprev = explored_state(env, insn_idx);
17363 	sl = *pprev;
17364 
17365 	clean_live_states(env, insn_idx, cur);
17366 
17367 	while (sl) {
17368 		states_cnt++;
17369 		if (sl->state.insn_idx != insn_idx)
17370 			goto next;
17371 
17372 		if (sl->state.branches) {
17373 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
17374 
17375 			if (frame->in_async_callback_fn &&
17376 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
17377 				/* Different async_entry_cnt means that the verifier is
17378 				 * processing another entry into async callback.
17379 				 * Seeing the same state is not an indication of infinite
17380 				 * loop or infinite recursion.
17381 				 * But finding the same state doesn't mean that it's safe
17382 				 * to stop processing the current state. The previous state
17383 				 * hasn't yet reached bpf_exit, since state.branches > 0.
17384 				 * Checking in_async_callback_fn alone is not enough either.
17385 				 * Since the verifier still needs to catch infinite loops
17386 				 * inside async callbacks.
17387 				 */
17388 				goto skip_inf_loop_check;
17389 			}
17390 			/* BPF open-coded iterators loop detection is special.
17391 			 * states_maybe_looping() logic is too simplistic in detecting
17392 			 * states that *might* be equivalent, because it doesn't know
17393 			 * about ID remapping, so don't even perform it.
17394 			 * See process_iter_next_call() and iter_active_depths_differ()
17395 			 * for overview of the logic. When current and one of parent
17396 			 * states are detected as equivalent, it's a good thing: we prove
17397 			 * convergence and can stop simulating further iterations.
17398 			 * It's safe to assume that iterator loop will finish, taking into
17399 			 * account iter_next() contract of eventually returning
17400 			 * sticky NULL result.
17401 			 *
17402 			 * Note, that states have to be compared exactly in this case because
17403 			 * read and precision marks might not be finalized inside the loop.
17404 			 * E.g. as in the program below:
17405 			 *
17406 			 *     1. r7 = -16
17407 			 *     2. r6 = bpf_get_prandom_u32()
17408 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
17409 			 *     4.   if (r6 != 42) {
17410 			 *     5.     r7 = -32
17411 			 *     6.     r6 = bpf_get_prandom_u32()
17412 			 *     7.     continue
17413 			 *     8.   }
17414 			 *     9.   r0 = r10
17415 			 *    10.   r0 += r7
17416 			 *    11.   r8 = *(u64 *)(r0 + 0)
17417 			 *    12.   r6 = bpf_get_prandom_u32()
17418 			 *    13. }
17419 			 *
17420 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
17421 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
17422 			 * not have read or precision mark for r7 yet, thus inexact states
17423 			 * comparison would discard current state with r7=-32
17424 			 * => unsafe memory access at 11 would not be caught.
17425 			 */
17426 			if (is_iter_next_insn(env, insn_idx)) {
17427 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17428 					struct bpf_func_state *cur_frame;
17429 					struct bpf_reg_state *iter_state, *iter_reg;
17430 					int spi;
17431 
17432 					cur_frame = cur->frame[cur->curframe];
17433 					/* btf_check_iter_kfuncs() enforces that
17434 					 * iter state pointer is always the first arg
17435 					 */
17436 					iter_reg = &cur_frame->regs[BPF_REG_1];
17437 					/* current state is valid due to states_equal(),
17438 					 * so we can assume valid iter and reg state,
17439 					 * no need for extra (re-)validations
17440 					 */
17441 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
17442 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
17443 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
17444 						update_loop_entry(cur, &sl->state);
17445 						goto hit;
17446 					}
17447 				}
17448 				goto skip_inf_loop_check;
17449 			}
17450 			if (is_may_goto_insn_at(env, insn_idx)) {
17451 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17452 					update_loop_entry(cur, &sl->state);
17453 					goto hit;
17454 				}
17455 				goto skip_inf_loop_check;
17456 			}
17457 			if (calls_callback(env, insn_idx)) {
17458 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
17459 					goto hit;
17460 				goto skip_inf_loop_check;
17461 			}
17462 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
17463 			if (states_maybe_looping(&sl->state, cur) &&
17464 			    states_equal(env, &sl->state, cur, EXACT) &&
17465 			    !iter_active_depths_differ(&sl->state, cur) &&
17466 			    sl->state.may_goto_depth == cur->may_goto_depth &&
17467 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
17468 				verbose_linfo(env, insn_idx, "; ");
17469 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
17470 				verbose(env, "cur state:");
17471 				print_verifier_state(env, cur->frame[cur->curframe], true);
17472 				verbose(env, "old state:");
17473 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
17474 				return -EINVAL;
17475 			}
17476 			/* if the verifier is processing a loop, avoid adding new state
17477 			 * too often, since different loop iterations have distinct
17478 			 * states and may not help future pruning.
17479 			 * This threshold shouldn't be too low to make sure that
17480 			 * a loop with large bound will be rejected quickly.
17481 			 * The most abusive loop will be:
17482 			 * r1 += 1
17483 			 * if r1 < 1000000 goto pc-2
17484 			 * 1M insn_procssed limit / 100 == 10k peak states.
17485 			 * This threshold shouldn't be too high either, since states
17486 			 * at the end of the loop are likely to be useful in pruning.
17487 			 */
17488 skip_inf_loop_check:
17489 			if (!force_new_state &&
17490 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
17491 			    env->insn_processed - env->prev_insn_processed < 100)
17492 				add_new_state = false;
17493 			goto miss;
17494 		}
17495 		/* If sl->state is a part of a loop and this loop's entry is a part of
17496 		 * current verification path then states have to be compared exactly.
17497 		 * 'force_exact' is needed to catch the following case:
17498 		 *
17499 		 *                initial     Here state 'succ' was processed first,
17500 		 *                  |         it was eventually tracked to produce a
17501 		 *                  V         state identical to 'hdr'.
17502 		 *     .---------> hdr        All branches from 'succ' had been explored
17503 		 *     |            |         and thus 'succ' has its .branches == 0.
17504 		 *     |            V
17505 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
17506 		 *     |    |       |         to the same instruction + callsites.
17507 		 *     |    V       V         In such case it is necessary to check
17508 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
17509 		 *     |    |       |         If 'succ' and 'cur' are a part of the
17510 		 *     |    V       V         same loop exact flag has to be set.
17511 		 *     |   succ <- cur        To check if that is the case, verify
17512 		 *     |    |                 if loop entry of 'succ' is in current
17513 		 *     |    V                 DFS path.
17514 		 *     |   ...
17515 		 *     |    |
17516 		 *     '----'
17517 		 *
17518 		 * Additional details are in the comment before get_loop_entry().
17519 		 */
17520 		loop_entry = get_loop_entry(&sl->state);
17521 		force_exact = loop_entry && loop_entry->branches > 0;
17522 		if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) {
17523 			if (force_exact)
17524 				update_loop_entry(cur, loop_entry);
17525 hit:
17526 			sl->hit_cnt++;
17527 			/* reached equivalent register/stack state,
17528 			 * prune the search.
17529 			 * Registers read by the continuation are read by us.
17530 			 * If we have any write marks in env->cur_state, they
17531 			 * will prevent corresponding reads in the continuation
17532 			 * from reaching our parent (an explored_state).  Our
17533 			 * own state will get the read marks recorded, but
17534 			 * they'll be immediately forgotten as we're pruning
17535 			 * this state and will pop a new one.
17536 			 */
17537 			err = propagate_liveness(env, &sl->state, cur);
17538 
17539 			/* if previous state reached the exit with precision and
17540 			 * current state is equivalent to it (except precision marks)
17541 			 * the precision needs to be propagated back in
17542 			 * the current state.
17543 			 */
17544 			if (is_jmp_point(env, env->insn_idx))
17545 				err = err ? : push_jmp_history(env, cur, 0);
17546 			err = err ? : propagate_precision(env, &sl->state);
17547 			if (err)
17548 				return err;
17549 			return 1;
17550 		}
17551 miss:
17552 		/* when new state is not going to be added do not increase miss count.
17553 		 * Otherwise several loop iterations will remove the state
17554 		 * recorded earlier. The goal of these heuristics is to have
17555 		 * states from some iterations of the loop (some in the beginning
17556 		 * and some at the end) to help pruning.
17557 		 */
17558 		if (add_new_state)
17559 			sl->miss_cnt++;
17560 		/* heuristic to determine whether this state is beneficial
17561 		 * to keep checking from state equivalence point of view.
17562 		 * Higher numbers increase max_states_per_insn and verification time,
17563 		 * but do not meaningfully decrease insn_processed.
17564 		 * 'n' controls how many times state could miss before eviction.
17565 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
17566 		 * too early would hinder iterator convergence.
17567 		 */
17568 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17569 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
17570 			/* the state is unlikely to be useful. Remove it to
17571 			 * speed up verification
17572 			 */
17573 			*pprev = sl->next;
17574 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17575 			    !sl->state.used_as_loop_entry) {
17576 				u32 br = sl->state.branches;
17577 
17578 				WARN_ONCE(br,
17579 					  "BUG live_done but branches_to_explore %d\n",
17580 					  br);
17581 				free_verifier_state(&sl->state, false);
17582 				kfree(sl);
17583 				env->peak_states--;
17584 			} else {
17585 				/* cannot free this state, since parentage chain may
17586 				 * walk it later. Add it for free_list instead to
17587 				 * be freed at the end of verification
17588 				 */
17589 				sl->next = env->free_list;
17590 				env->free_list = sl;
17591 			}
17592 			sl = *pprev;
17593 			continue;
17594 		}
17595 next:
17596 		pprev = &sl->next;
17597 		sl = *pprev;
17598 	}
17599 
17600 	if (env->max_states_per_insn < states_cnt)
17601 		env->max_states_per_insn = states_cnt;
17602 
17603 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
17604 		return 0;
17605 
17606 	if (!add_new_state)
17607 		return 0;
17608 
17609 	/* There were no equivalent states, remember the current one.
17610 	 * Technically the current state is not proven to be safe yet,
17611 	 * but it will either reach outer most bpf_exit (which means it's safe)
17612 	 * or it will be rejected. When there are no loops the verifier won't be
17613 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
17614 	 * again on the way to bpf_exit.
17615 	 * When looping the sl->state.branches will be > 0 and this state
17616 	 * will not be considered for equivalence until branches == 0.
17617 	 */
17618 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
17619 	if (!new_sl)
17620 		return -ENOMEM;
17621 	env->total_states++;
17622 	env->peak_states++;
17623 	env->prev_jmps_processed = env->jmps_processed;
17624 	env->prev_insn_processed = env->insn_processed;
17625 
17626 	/* forget precise markings we inherited, see __mark_chain_precision */
17627 	if (env->bpf_capable)
17628 		mark_all_scalars_imprecise(env, cur);
17629 
17630 	/* add new state to the head of linked list */
17631 	new = &new_sl->state;
17632 	err = copy_verifier_state(new, cur);
17633 	if (err) {
17634 		free_verifier_state(new, false);
17635 		kfree(new_sl);
17636 		return err;
17637 	}
17638 	new->insn_idx = insn_idx;
17639 	WARN_ONCE(new->branches != 1,
17640 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
17641 
17642 	cur->parent = new;
17643 	cur->first_insn_idx = insn_idx;
17644 	cur->dfs_depth = new->dfs_depth + 1;
17645 	clear_jmp_history(cur);
17646 	new_sl->next = *explored_state(env, insn_idx);
17647 	*explored_state(env, insn_idx) = new_sl;
17648 	/* connect new state to parentage chain. Current frame needs all
17649 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
17650 	 * to the stack implicitly by JITs) so in callers' frames connect just
17651 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17652 	 * the state of the call instruction (with WRITTEN set), and r0 comes
17653 	 * from callee with its full parentage chain, anyway.
17654 	 */
17655 	/* clear write marks in current state: the writes we did are not writes
17656 	 * our child did, so they don't screen off its reads from us.
17657 	 * (There are no read marks in current state, because reads always mark
17658 	 * their parent and current state never has children yet.  Only
17659 	 * explored_states can get read marks.)
17660 	 */
17661 	for (j = 0; j <= cur->curframe; j++) {
17662 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17663 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17664 		for (i = 0; i < BPF_REG_FP; i++)
17665 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17666 	}
17667 
17668 	/* all stack frames are accessible from callee, clear them all */
17669 	for (j = 0; j <= cur->curframe; j++) {
17670 		struct bpf_func_state *frame = cur->frame[j];
17671 		struct bpf_func_state *newframe = new->frame[j];
17672 
17673 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17674 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17675 			frame->stack[i].spilled_ptr.parent =
17676 						&newframe->stack[i].spilled_ptr;
17677 		}
17678 	}
17679 	return 0;
17680 }
17681 
17682 /* Return true if it's OK to have the same insn return a different type. */
17683 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17684 {
17685 	switch (base_type(type)) {
17686 	case PTR_TO_CTX:
17687 	case PTR_TO_SOCKET:
17688 	case PTR_TO_SOCK_COMMON:
17689 	case PTR_TO_TCP_SOCK:
17690 	case PTR_TO_XDP_SOCK:
17691 	case PTR_TO_BTF_ID:
17692 	case PTR_TO_ARENA:
17693 		return false;
17694 	default:
17695 		return true;
17696 	}
17697 }
17698 
17699 /* If an instruction was previously used with particular pointer types, then we
17700  * need to be careful to avoid cases such as the below, where it may be ok
17701  * for one branch accessing the pointer, but not ok for the other branch:
17702  *
17703  * R1 = sock_ptr
17704  * goto X;
17705  * ...
17706  * R1 = some_other_valid_ptr;
17707  * goto X;
17708  * ...
17709  * R2 = *(u32 *)(R1 + 0);
17710  */
17711 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17712 {
17713 	return src != prev && (!reg_type_mismatch_ok(src) ||
17714 			       !reg_type_mismatch_ok(prev));
17715 }
17716 
17717 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17718 			     bool allow_trust_mismatch)
17719 {
17720 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17721 
17722 	if (*prev_type == NOT_INIT) {
17723 		/* Saw a valid insn
17724 		 * dst_reg = *(u32 *)(src_reg + off)
17725 		 * save type to validate intersecting paths
17726 		 */
17727 		*prev_type = type;
17728 	} else if (reg_type_mismatch(type, *prev_type)) {
17729 		/* Abuser program is trying to use the same insn
17730 		 * dst_reg = *(u32*) (src_reg + off)
17731 		 * with different pointer types:
17732 		 * src_reg == ctx in one branch and
17733 		 * src_reg == stack|map in some other branch.
17734 		 * Reject it.
17735 		 */
17736 		if (allow_trust_mismatch &&
17737 		    base_type(type) == PTR_TO_BTF_ID &&
17738 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
17739 			/*
17740 			 * Have to support a use case when one path through
17741 			 * the program yields TRUSTED pointer while another
17742 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17743 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17744 			 */
17745 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17746 		} else {
17747 			verbose(env, "same insn cannot be used with different pointers\n");
17748 			return -EINVAL;
17749 		}
17750 	}
17751 
17752 	return 0;
17753 }
17754 
17755 static int do_check(struct bpf_verifier_env *env)
17756 {
17757 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17758 	struct bpf_verifier_state *state = env->cur_state;
17759 	struct bpf_insn *insns = env->prog->insnsi;
17760 	struct bpf_reg_state *regs;
17761 	int insn_cnt = env->prog->len;
17762 	bool do_print_state = false;
17763 	int prev_insn_idx = -1;
17764 
17765 	for (;;) {
17766 		bool exception_exit = false;
17767 		struct bpf_insn *insn;
17768 		u8 class;
17769 		int err;
17770 
17771 		/* reset current history entry on each new instruction */
17772 		env->cur_hist_ent = NULL;
17773 
17774 		env->prev_insn_idx = prev_insn_idx;
17775 		if (env->insn_idx >= insn_cnt) {
17776 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17777 				env->insn_idx, insn_cnt);
17778 			return -EFAULT;
17779 		}
17780 
17781 		insn = &insns[env->insn_idx];
17782 		class = BPF_CLASS(insn->code);
17783 
17784 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17785 			verbose(env,
17786 				"BPF program is too large. Processed %d insn\n",
17787 				env->insn_processed);
17788 			return -E2BIG;
17789 		}
17790 
17791 		state->last_insn_idx = env->prev_insn_idx;
17792 
17793 		if (is_prune_point(env, env->insn_idx)) {
17794 			err = is_state_visited(env, env->insn_idx);
17795 			if (err < 0)
17796 				return err;
17797 			if (err == 1) {
17798 				/* found equivalent state, can prune the search */
17799 				if (env->log.level & BPF_LOG_LEVEL) {
17800 					if (do_print_state)
17801 						verbose(env, "\nfrom %d to %d%s: safe\n",
17802 							env->prev_insn_idx, env->insn_idx,
17803 							env->cur_state->speculative ?
17804 							" (speculative execution)" : "");
17805 					else
17806 						verbose(env, "%d: safe\n", env->insn_idx);
17807 				}
17808 				goto process_bpf_exit;
17809 			}
17810 		}
17811 
17812 		if (is_jmp_point(env, env->insn_idx)) {
17813 			err = push_jmp_history(env, state, 0);
17814 			if (err)
17815 				return err;
17816 		}
17817 
17818 		if (signal_pending(current))
17819 			return -EAGAIN;
17820 
17821 		if (need_resched())
17822 			cond_resched();
17823 
17824 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17825 			verbose(env, "\nfrom %d to %d%s:",
17826 				env->prev_insn_idx, env->insn_idx,
17827 				env->cur_state->speculative ?
17828 				" (speculative execution)" : "");
17829 			print_verifier_state(env, state->frame[state->curframe], true);
17830 			do_print_state = false;
17831 		}
17832 
17833 		if (env->log.level & BPF_LOG_LEVEL) {
17834 			const struct bpf_insn_cbs cbs = {
17835 				.cb_call	= disasm_kfunc_name,
17836 				.cb_print	= verbose,
17837 				.private_data	= env,
17838 			};
17839 
17840 			if (verifier_state_scratched(env))
17841 				print_insn_state(env, state->frame[state->curframe]);
17842 
17843 			verbose_linfo(env, env->insn_idx, "; ");
17844 			env->prev_log_pos = env->log.end_pos;
17845 			verbose(env, "%d: ", env->insn_idx);
17846 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17847 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17848 			env->prev_log_pos = env->log.end_pos;
17849 		}
17850 
17851 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17852 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17853 							   env->prev_insn_idx);
17854 			if (err)
17855 				return err;
17856 		}
17857 
17858 		regs = cur_regs(env);
17859 		sanitize_mark_insn_seen(env);
17860 		prev_insn_idx = env->insn_idx;
17861 
17862 		if (class == BPF_ALU || class == BPF_ALU64) {
17863 			err = check_alu_op(env, insn);
17864 			if (err)
17865 				return err;
17866 
17867 		} else if (class == BPF_LDX) {
17868 			enum bpf_reg_type src_reg_type;
17869 
17870 			/* check for reserved fields is already done */
17871 
17872 			/* check src operand */
17873 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17874 			if (err)
17875 				return err;
17876 
17877 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17878 			if (err)
17879 				return err;
17880 
17881 			src_reg_type = regs[insn->src_reg].type;
17882 
17883 			/* check that memory (src_reg + off) is readable,
17884 			 * the state of dst_reg will be updated by this func
17885 			 */
17886 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17887 					       insn->off, BPF_SIZE(insn->code),
17888 					       BPF_READ, insn->dst_reg, false,
17889 					       BPF_MODE(insn->code) == BPF_MEMSX);
17890 			err = err ?: save_aux_ptr_type(env, src_reg_type, true);
17891 			err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], "ldx");
17892 			if (err)
17893 				return err;
17894 		} else if (class == BPF_STX) {
17895 			enum bpf_reg_type dst_reg_type;
17896 
17897 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17898 				err = check_atomic(env, env->insn_idx, insn);
17899 				if (err)
17900 					return err;
17901 				env->insn_idx++;
17902 				continue;
17903 			}
17904 
17905 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17906 				verbose(env, "BPF_STX uses reserved fields\n");
17907 				return -EINVAL;
17908 			}
17909 
17910 			/* check src1 operand */
17911 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17912 			if (err)
17913 				return err;
17914 			/* check src2 operand */
17915 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17916 			if (err)
17917 				return err;
17918 
17919 			dst_reg_type = regs[insn->dst_reg].type;
17920 
17921 			/* check that memory (dst_reg + off) is writeable */
17922 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17923 					       insn->off, BPF_SIZE(insn->code),
17924 					       BPF_WRITE, insn->src_reg, false, false);
17925 			if (err)
17926 				return err;
17927 
17928 			err = save_aux_ptr_type(env, dst_reg_type, false);
17929 			if (err)
17930 				return err;
17931 		} else if (class == BPF_ST) {
17932 			enum bpf_reg_type dst_reg_type;
17933 
17934 			if (BPF_MODE(insn->code) != BPF_MEM ||
17935 			    insn->src_reg != BPF_REG_0) {
17936 				verbose(env, "BPF_ST uses reserved fields\n");
17937 				return -EINVAL;
17938 			}
17939 			/* check src operand */
17940 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17941 			if (err)
17942 				return err;
17943 
17944 			dst_reg_type = regs[insn->dst_reg].type;
17945 
17946 			/* check that memory (dst_reg + off) is writeable */
17947 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17948 					       insn->off, BPF_SIZE(insn->code),
17949 					       BPF_WRITE, -1, false, false);
17950 			if (err)
17951 				return err;
17952 
17953 			err = save_aux_ptr_type(env, dst_reg_type, false);
17954 			if (err)
17955 				return err;
17956 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17957 			u8 opcode = BPF_OP(insn->code);
17958 
17959 			env->jmps_processed++;
17960 			if (opcode == BPF_CALL) {
17961 				if (BPF_SRC(insn->code) != BPF_K ||
17962 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17963 				     && insn->off != 0) ||
17964 				    (insn->src_reg != BPF_REG_0 &&
17965 				     insn->src_reg != BPF_PSEUDO_CALL &&
17966 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17967 				    insn->dst_reg != BPF_REG_0 ||
17968 				    class == BPF_JMP32) {
17969 					verbose(env, "BPF_CALL uses reserved fields\n");
17970 					return -EINVAL;
17971 				}
17972 
17973 				if (env->cur_state->active_lock.ptr) {
17974 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17975 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17976 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17977 						verbose(env, "function calls are not allowed while holding a lock\n");
17978 						return -EINVAL;
17979 					}
17980 				}
17981 				if (insn->src_reg == BPF_PSEUDO_CALL) {
17982 					err = check_func_call(env, insn, &env->insn_idx);
17983 				} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17984 					err = check_kfunc_call(env, insn, &env->insn_idx);
17985 					if (!err && is_bpf_throw_kfunc(insn)) {
17986 						exception_exit = true;
17987 						goto process_bpf_exit_full;
17988 					}
17989 				} else {
17990 					err = check_helper_call(env, insn, &env->insn_idx);
17991 				}
17992 				if (err)
17993 					return err;
17994 
17995 				mark_reg_scratched(env, BPF_REG_0);
17996 			} else if (opcode == BPF_JA) {
17997 				if (BPF_SRC(insn->code) != BPF_K ||
17998 				    insn->src_reg != BPF_REG_0 ||
17999 				    insn->dst_reg != BPF_REG_0 ||
18000 				    (class == BPF_JMP && insn->imm != 0) ||
18001 				    (class == BPF_JMP32 && insn->off != 0)) {
18002 					verbose(env, "BPF_JA uses reserved fields\n");
18003 					return -EINVAL;
18004 				}
18005 
18006 				if (class == BPF_JMP)
18007 					env->insn_idx += insn->off + 1;
18008 				else
18009 					env->insn_idx += insn->imm + 1;
18010 				continue;
18011 
18012 			} else if (opcode == BPF_EXIT) {
18013 				if (BPF_SRC(insn->code) != BPF_K ||
18014 				    insn->imm != 0 ||
18015 				    insn->src_reg != BPF_REG_0 ||
18016 				    insn->dst_reg != BPF_REG_0 ||
18017 				    class == BPF_JMP32) {
18018 					verbose(env, "BPF_EXIT uses reserved fields\n");
18019 					return -EINVAL;
18020 				}
18021 process_bpf_exit_full:
18022 				if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) {
18023 					verbose(env, "bpf_spin_unlock is missing\n");
18024 					return -EINVAL;
18025 				}
18026 
18027 				if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) {
18028 					verbose(env, "bpf_rcu_read_unlock is missing\n");
18029 					return -EINVAL;
18030 				}
18031 
18032 				if (env->cur_state->active_preempt_lock && !env->cur_state->curframe) {
18033 					verbose(env, "%d bpf_preempt_enable%s missing\n",
18034 						env->cur_state->active_preempt_lock,
18035 						env->cur_state->active_preempt_lock == 1 ? " is" : "(s) are");
18036 					return -EINVAL;
18037 				}
18038 
18039 				/* We must do check_reference_leak here before
18040 				 * prepare_func_exit to handle the case when
18041 				 * state->curframe > 0, it may be a callback
18042 				 * function, for which reference_state must
18043 				 * match caller reference state when it exits.
18044 				 */
18045 				err = check_reference_leak(env, exception_exit);
18046 				if (err)
18047 					return err;
18048 
18049 				/* The side effect of the prepare_func_exit
18050 				 * which is being skipped is that it frees
18051 				 * bpf_func_state. Typically, process_bpf_exit
18052 				 * will only be hit with outermost exit.
18053 				 * copy_verifier_state in pop_stack will handle
18054 				 * freeing of any extra bpf_func_state left over
18055 				 * from not processing all nested function
18056 				 * exits. We also skip return code checks as
18057 				 * they are not needed for exceptional exits.
18058 				 */
18059 				if (exception_exit)
18060 					goto process_bpf_exit;
18061 
18062 				if (state->curframe) {
18063 					/* exit from nested function */
18064 					err = prepare_func_exit(env, &env->insn_idx);
18065 					if (err)
18066 						return err;
18067 					do_print_state = true;
18068 					continue;
18069 				}
18070 
18071 				err = check_return_code(env, BPF_REG_0, "R0");
18072 				if (err)
18073 					return err;
18074 process_bpf_exit:
18075 				mark_verifier_state_scratched(env);
18076 				update_branch_counts(env, env->cur_state);
18077 				err = pop_stack(env, &prev_insn_idx,
18078 						&env->insn_idx, pop_log);
18079 				if (err < 0) {
18080 					if (err != -ENOENT)
18081 						return err;
18082 					break;
18083 				} else {
18084 					do_print_state = true;
18085 					continue;
18086 				}
18087 			} else {
18088 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
18089 				if (err)
18090 					return err;
18091 			}
18092 		} else if (class == BPF_LD) {
18093 			u8 mode = BPF_MODE(insn->code);
18094 
18095 			if (mode == BPF_ABS || mode == BPF_IND) {
18096 				err = check_ld_abs(env, insn);
18097 				if (err)
18098 					return err;
18099 
18100 			} else if (mode == BPF_IMM) {
18101 				err = check_ld_imm(env, insn);
18102 				if (err)
18103 					return err;
18104 
18105 				env->insn_idx++;
18106 				sanitize_mark_insn_seen(env);
18107 			} else {
18108 				verbose(env, "invalid BPF_LD mode\n");
18109 				return -EINVAL;
18110 			}
18111 		} else {
18112 			verbose(env, "unknown insn class %d\n", class);
18113 			return -EINVAL;
18114 		}
18115 
18116 		env->insn_idx++;
18117 	}
18118 
18119 	return 0;
18120 }
18121 
18122 static int find_btf_percpu_datasec(struct btf *btf)
18123 {
18124 	const struct btf_type *t;
18125 	const char *tname;
18126 	int i, n;
18127 
18128 	/*
18129 	 * Both vmlinux and module each have their own ".data..percpu"
18130 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
18131 	 * types to look at only module's own BTF types.
18132 	 */
18133 	n = btf_nr_types(btf);
18134 	if (btf_is_module(btf))
18135 		i = btf_nr_types(btf_vmlinux);
18136 	else
18137 		i = 1;
18138 
18139 	for(; i < n; i++) {
18140 		t = btf_type_by_id(btf, i);
18141 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
18142 			continue;
18143 
18144 		tname = btf_name_by_offset(btf, t->name_off);
18145 		if (!strcmp(tname, ".data..percpu"))
18146 			return i;
18147 	}
18148 
18149 	return -ENOENT;
18150 }
18151 
18152 /* replace pseudo btf_id with kernel symbol address */
18153 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
18154 			       struct bpf_insn *insn,
18155 			       struct bpf_insn_aux_data *aux)
18156 {
18157 	const struct btf_var_secinfo *vsi;
18158 	const struct btf_type *datasec;
18159 	struct btf_mod_pair *btf_mod;
18160 	const struct btf_type *t;
18161 	const char *sym_name;
18162 	bool percpu = false;
18163 	u32 type, id = insn->imm;
18164 	struct btf *btf;
18165 	s32 datasec_id;
18166 	u64 addr;
18167 	int i, btf_fd, err;
18168 
18169 	btf_fd = insn[1].imm;
18170 	if (btf_fd) {
18171 		btf = btf_get_by_fd(btf_fd);
18172 		if (IS_ERR(btf)) {
18173 			verbose(env, "invalid module BTF object FD specified.\n");
18174 			return -EINVAL;
18175 		}
18176 	} else {
18177 		if (!btf_vmlinux) {
18178 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
18179 			return -EINVAL;
18180 		}
18181 		btf = btf_vmlinux;
18182 		btf_get(btf);
18183 	}
18184 
18185 	t = btf_type_by_id(btf, id);
18186 	if (!t) {
18187 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
18188 		err = -ENOENT;
18189 		goto err_put;
18190 	}
18191 
18192 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
18193 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
18194 		err = -EINVAL;
18195 		goto err_put;
18196 	}
18197 
18198 	sym_name = btf_name_by_offset(btf, t->name_off);
18199 	addr = kallsyms_lookup_name(sym_name);
18200 	if (!addr) {
18201 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
18202 			sym_name);
18203 		err = -ENOENT;
18204 		goto err_put;
18205 	}
18206 	insn[0].imm = (u32)addr;
18207 	insn[1].imm = addr >> 32;
18208 
18209 	if (btf_type_is_func(t)) {
18210 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18211 		aux->btf_var.mem_size = 0;
18212 		goto check_btf;
18213 	}
18214 
18215 	datasec_id = find_btf_percpu_datasec(btf);
18216 	if (datasec_id > 0) {
18217 		datasec = btf_type_by_id(btf, datasec_id);
18218 		for_each_vsi(i, datasec, vsi) {
18219 			if (vsi->type == id) {
18220 				percpu = true;
18221 				break;
18222 			}
18223 		}
18224 	}
18225 
18226 	type = t->type;
18227 	t = btf_type_skip_modifiers(btf, type, NULL);
18228 	if (percpu) {
18229 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
18230 		aux->btf_var.btf = btf;
18231 		aux->btf_var.btf_id = type;
18232 	} else if (!btf_type_is_struct(t)) {
18233 		const struct btf_type *ret;
18234 		const char *tname;
18235 		u32 tsize;
18236 
18237 		/* resolve the type size of ksym. */
18238 		ret = btf_resolve_size(btf, t, &tsize);
18239 		if (IS_ERR(ret)) {
18240 			tname = btf_name_by_offset(btf, t->name_off);
18241 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
18242 				tname, PTR_ERR(ret));
18243 			err = -EINVAL;
18244 			goto err_put;
18245 		}
18246 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18247 		aux->btf_var.mem_size = tsize;
18248 	} else {
18249 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
18250 		aux->btf_var.btf = btf;
18251 		aux->btf_var.btf_id = type;
18252 	}
18253 check_btf:
18254 	/* check whether we recorded this BTF (and maybe module) already */
18255 	for (i = 0; i < env->used_btf_cnt; i++) {
18256 		if (env->used_btfs[i].btf == btf) {
18257 			btf_put(btf);
18258 			return 0;
18259 		}
18260 	}
18261 
18262 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
18263 		err = -E2BIG;
18264 		goto err_put;
18265 	}
18266 
18267 	btf_mod = &env->used_btfs[env->used_btf_cnt];
18268 	btf_mod->btf = btf;
18269 	btf_mod->module = NULL;
18270 
18271 	/* if we reference variables from kernel module, bump its refcount */
18272 	if (btf_is_module(btf)) {
18273 		btf_mod->module = btf_try_get_module(btf);
18274 		if (!btf_mod->module) {
18275 			err = -ENXIO;
18276 			goto err_put;
18277 		}
18278 	}
18279 
18280 	env->used_btf_cnt++;
18281 
18282 	return 0;
18283 err_put:
18284 	btf_put(btf);
18285 	return err;
18286 }
18287 
18288 static bool is_tracing_prog_type(enum bpf_prog_type type)
18289 {
18290 	switch (type) {
18291 	case BPF_PROG_TYPE_KPROBE:
18292 	case BPF_PROG_TYPE_TRACEPOINT:
18293 	case BPF_PROG_TYPE_PERF_EVENT:
18294 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
18295 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
18296 		return true;
18297 	default:
18298 		return false;
18299 	}
18300 }
18301 
18302 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
18303 					struct bpf_map *map,
18304 					struct bpf_prog *prog)
18305 
18306 {
18307 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18308 
18309 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
18310 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
18311 		if (is_tracing_prog_type(prog_type)) {
18312 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
18313 			return -EINVAL;
18314 		}
18315 	}
18316 
18317 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
18318 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
18319 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
18320 			return -EINVAL;
18321 		}
18322 
18323 		if (is_tracing_prog_type(prog_type)) {
18324 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
18325 			return -EINVAL;
18326 		}
18327 	}
18328 
18329 	if (btf_record_has_field(map->record, BPF_TIMER)) {
18330 		if (is_tracing_prog_type(prog_type)) {
18331 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
18332 			return -EINVAL;
18333 		}
18334 	}
18335 
18336 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
18337 		if (is_tracing_prog_type(prog_type)) {
18338 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
18339 			return -EINVAL;
18340 		}
18341 	}
18342 
18343 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
18344 	    !bpf_offload_prog_map_match(prog, map)) {
18345 		verbose(env, "offload device mismatch between prog and map\n");
18346 		return -EINVAL;
18347 	}
18348 
18349 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
18350 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
18351 		return -EINVAL;
18352 	}
18353 
18354 	if (prog->sleepable)
18355 		switch (map->map_type) {
18356 		case BPF_MAP_TYPE_HASH:
18357 		case BPF_MAP_TYPE_LRU_HASH:
18358 		case BPF_MAP_TYPE_ARRAY:
18359 		case BPF_MAP_TYPE_PERCPU_HASH:
18360 		case BPF_MAP_TYPE_PERCPU_ARRAY:
18361 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
18362 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
18363 		case BPF_MAP_TYPE_HASH_OF_MAPS:
18364 		case BPF_MAP_TYPE_RINGBUF:
18365 		case BPF_MAP_TYPE_USER_RINGBUF:
18366 		case BPF_MAP_TYPE_INODE_STORAGE:
18367 		case BPF_MAP_TYPE_SK_STORAGE:
18368 		case BPF_MAP_TYPE_TASK_STORAGE:
18369 		case BPF_MAP_TYPE_CGRP_STORAGE:
18370 		case BPF_MAP_TYPE_QUEUE:
18371 		case BPF_MAP_TYPE_STACK:
18372 		case BPF_MAP_TYPE_ARENA:
18373 			break;
18374 		default:
18375 			verbose(env,
18376 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
18377 			return -EINVAL;
18378 		}
18379 
18380 	return 0;
18381 }
18382 
18383 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
18384 {
18385 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
18386 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
18387 }
18388 
18389 /* find and rewrite pseudo imm in ld_imm64 instructions:
18390  *
18391  * 1. if it accesses map FD, replace it with actual map pointer.
18392  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
18393  *
18394  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
18395  */
18396 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
18397 {
18398 	struct bpf_insn *insn = env->prog->insnsi;
18399 	int insn_cnt = env->prog->len;
18400 	int i, j, err;
18401 
18402 	err = bpf_prog_calc_tag(env->prog);
18403 	if (err)
18404 		return err;
18405 
18406 	for (i = 0; i < insn_cnt; i++, insn++) {
18407 		if (BPF_CLASS(insn->code) == BPF_LDX &&
18408 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
18409 		    insn->imm != 0)) {
18410 			verbose(env, "BPF_LDX uses reserved fields\n");
18411 			return -EINVAL;
18412 		}
18413 
18414 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
18415 			struct bpf_insn_aux_data *aux;
18416 			struct bpf_map *map;
18417 			struct fd f;
18418 			u64 addr;
18419 			u32 fd;
18420 
18421 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
18422 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
18423 			    insn[1].off != 0) {
18424 				verbose(env, "invalid bpf_ld_imm64 insn\n");
18425 				return -EINVAL;
18426 			}
18427 
18428 			if (insn[0].src_reg == 0)
18429 				/* valid generic load 64-bit imm */
18430 				goto next_insn;
18431 
18432 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
18433 				aux = &env->insn_aux_data[i];
18434 				err = check_pseudo_btf_id(env, insn, aux);
18435 				if (err)
18436 					return err;
18437 				goto next_insn;
18438 			}
18439 
18440 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
18441 				aux = &env->insn_aux_data[i];
18442 				aux->ptr_type = PTR_TO_FUNC;
18443 				goto next_insn;
18444 			}
18445 
18446 			/* In final convert_pseudo_ld_imm64() step, this is
18447 			 * converted into regular 64-bit imm load insn.
18448 			 */
18449 			switch (insn[0].src_reg) {
18450 			case BPF_PSEUDO_MAP_VALUE:
18451 			case BPF_PSEUDO_MAP_IDX_VALUE:
18452 				break;
18453 			case BPF_PSEUDO_MAP_FD:
18454 			case BPF_PSEUDO_MAP_IDX:
18455 				if (insn[1].imm == 0)
18456 					break;
18457 				fallthrough;
18458 			default:
18459 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
18460 				return -EINVAL;
18461 			}
18462 
18463 			switch (insn[0].src_reg) {
18464 			case BPF_PSEUDO_MAP_IDX_VALUE:
18465 			case BPF_PSEUDO_MAP_IDX:
18466 				if (bpfptr_is_null(env->fd_array)) {
18467 					verbose(env, "fd_idx without fd_array is invalid\n");
18468 					return -EPROTO;
18469 				}
18470 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
18471 							    insn[0].imm * sizeof(fd),
18472 							    sizeof(fd)))
18473 					return -EFAULT;
18474 				break;
18475 			default:
18476 				fd = insn[0].imm;
18477 				break;
18478 			}
18479 
18480 			f = fdget(fd);
18481 			map = __bpf_map_get(f);
18482 			if (IS_ERR(map)) {
18483 				verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
18484 				return PTR_ERR(map);
18485 			}
18486 
18487 			err = check_map_prog_compatibility(env, map, env->prog);
18488 			if (err) {
18489 				fdput(f);
18490 				return err;
18491 			}
18492 
18493 			aux = &env->insn_aux_data[i];
18494 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18495 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
18496 				addr = (unsigned long)map;
18497 			} else {
18498 				u32 off = insn[1].imm;
18499 
18500 				if (off >= BPF_MAX_VAR_OFF) {
18501 					verbose(env, "direct value offset of %u is not allowed\n", off);
18502 					fdput(f);
18503 					return -EINVAL;
18504 				}
18505 
18506 				if (!map->ops->map_direct_value_addr) {
18507 					verbose(env, "no direct value access support for this map type\n");
18508 					fdput(f);
18509 					return -EINVAL;
18510 				}
18511 
18512 				err = map->ops->map_direct_value_addr(map, &addr, off);
18513 				if (err) {
18514 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18515 						map->value_size, off);
18516 					fdput(f);
18517 					return err;
18518 				}
18519 
18520 				aux->map_off = off;
18521 				addr += off;
18522 			}
18523 
18524 			insn[0].imm = (u32)addr;
18525 			insn[1].imm = addr >> 32;
18526 
18527 			/* check whether we recorded this map already */
18528 			for (j = 0; j < env->used_map_cnt; j++) {
18529 				if (env->used_maps[j] == map) {
18530 					aux->map_index = j;
18531 					fdput(f);
18532 					goto next_insn;
18533 				}
18534 			}
18535 
18536 			if (env->used_map_cnt >= MAX_USED_MAPS) {
18537 				verbose(env, "The total number of maps per program has reached the limit of %u\n",
18538 					MAX_USED_MAPS);
18539 				fdput(f);
18540 				return -E2BIG;
18541 			}
18542 
18543 			if (env->prog->sleepable)
18544 				atomic64_inc(&map->sleepable_refcnt);
18545 			/* hold the map. If the program is rejected by verifier,
18546 			 * the map will be released by release_maps() or it
18547 			 * will be used by the valid program until it's unloaded
18548 			 * and all maps are released in bpf_free_used_maps()
18549 			 */
18550 			bpf_map_inc(map);
18551 
18552 			aux->map_index = env->used_map_cnt;
18553 			env->used_maps[env->used_map_cnt++] = map;
18554 
18555 			if (bpf_map_is_cgroup_storage(map) &&
18556 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
18557 				verbose(env, "only one cgroup storage of each type is allowed\n");
18558 				fdput(f);
18559 				return -EBUSY;
18560 			}
18561 			if (map->map_type == BPF_MAP_TYPE_ARENA) {
18562 				if (env->prog->aux->arena) {
18563 					verbose(env, "Only one arena per program\n");
18564 					fdput(f);
18565 					return -EBUSY;
18566 				}
18567 				if (!env->allow_ptr_leaks || !env->bpf_capable) {
18568 					verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
18569 					fdput(f);
18570 					return -EPERM;
18571 				}
18572 				if (!env->prog->jit_requested) {
18573 					verbose(env, "JIT is required to use arena\n");
18574 					fdput(f);
18575 					return -EOPNOTSUPP;
18576 				}
18577 				if (!bpf_jit_supports_arena()) {
18578 					verbose(env, "JIT doesn't support arena\n");
18579 					fdput(f);
18580 					return -EOPNOTSUPP;
18581 				}
18582 				env->prog->aux->arena = (void *)map;
18583 				if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
18584 					verbose(env, "arena's user address must be set via map_extra or mmap()\n");
18585 					fdput(f);
18586 					return -EINVAL;
18587 				}
18588 			}
18589 
18590 			fdput(f);
18591 next_insn:
18592 			insn++;
18593 			i++;
18594 			continue;
18595 		}
18596 
18597 		/* Basic sanity check before we invest more work here. */
18598 		if (!bpf_opcode_in_insntable(insn->code)) {
18599 			verbose(env, "unknown opcode %02x\n", insn->code);
18600 			return -EINVAL;
18601 		}
18602 	}
18603 
18604 	/* now all pseudo BPF_LD_IMM64 instructions load valid
18605 	 * 'struct bpf_map *' into a register instead of user map_fd.
18606 	 * These pointers will be used later by verifier to validate map access.
18607 	 */
18608 	return 0;
18609 }
18610 
18611 /* drop refcnt of maps used by the rejected program */
18612 static void release_maps(struct bpf_verifier_env *env)
18613 {
18614 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
18615 			     env->used_map_cnt);
18616 }
18617 
18618 /* drop refcnt of maps used by the rejected program */
18619 static void release_btfs(struct bpf_verifier_env *env)
18620 {
18621 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
18622 			     env->used_btf_cnt);
18623 }
18624 
18625 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18626 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18627 {
18628 	struct bpf_insn *insn = env->prog->insnsi;
18629 	int insn_cnt = env->prog->len;
18630 	int i;
18631 
18632 	for (i = 0; i < insn_cnt; i++, insn++) {
18633 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18634 			continue;
18635 		if (insn->src_reg == BPF_PSEUDO_FUNC)
18636 			continue;
18637 		insn->src_reg = 0;
18638 	}
18639 }
18640 
18641 /* single env->prog->insni[off] instruction was replaced with the range
18642  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
18643  * [0, off) and [off, end) to new locations, so the patched range stays zero
18644  */
18645 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18646 				 struct bpf_insn_aux_data *new_data,
18647 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
18648 {
18649 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
18650 	struct bpf_insn *insn = new_prog->insnsi;
18651 	u32 old_seen = old_data[off].seen;
18652 	u32 prog_len;
18653 	int i;
18654 
18655 	/* aux info at OFF always needs adjustment, no matter fast path
18656 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18657 	 * original insn at old prog.
18658 	 */
18659 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18660 
18661 	if (cnt == 1)
18662 		return;
18663 	prog_len = new_prog->len;
18664 
18665 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18666 	memcpy(new_data + off + cnt - 1, old_data + off,
18667 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
18668 	for (i = off; i < off + cnt - 1; i++) {
18669 		/* Expand insni[off]'s seen count to the patched range. */
18670 		new_data[i].seen = old_seen;
18671 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
18672 	}
18673 	env->insn_aux_data = new_data;
18674 	vfree(old_data);
18675 }
18676 
18677 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18678 {
18679 	int i;
18680 
18681 	if (len == 1)
18682 		return;
18683 	/* NOTE: fake 'exit' subprog should be updated as well. */
18684 	for (i = 0; i <= env->subprog_cnt; i++) {
18685 		if (env->subprog_info[i].start <= off)
18686 			continue;
18687 		env->subprog_info[i].start += len - 1;
18688 	}
18689 }
18690 
18691 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
18692 {
18693 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18694 	int i, sz = prog->aux->size_poke_tab;
18695 	struct bpf_jit_poke_descriptor *desc;
18696 
18697 	for (i = 0; i < sz; i++) {
18698 		desc = &tab[i];
18699 		if (desc->insn_idx <= off)
18700 			continue;
18701 		desc->insn_idx += len - 1;
18702 	}
18703 }
18704 
18705 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18706 					    const struct bpf_insn *patch, u32 len)
18707 {
18708 	struct bpf_prog *new_prog;
18709 	struct bpf_insn_aux_data *new_data = NULL;
18710 
18711 	if (len > 1) {
18712 		new_data = vzalloc(array_size(env->prog->len + len - 1,
18713 					      sizeof(struct bpf_insn_aux_data)));
18714 		if (!new_data)
18715 			return NULL;
18716 	}
18717 
18718 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18719 	if (IS_ERR(new_prog)) {
18720 		if (PTR_ERR(new_prog) == -ERANGE)
18721 			verbose(env,
18722 				"insn %d cannot be patched due to 16-bit range\n",
18723 				env->insn_aux_data[off].orig_idx);
18724 		vfree(new_data);
18725 		return NULL;
18726 	}
18727 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
18728 	adjust_subprog_starts(env, off, len);
18729 	adjust_poke_descs(new_prog, off, len);
18730 	return new_prog;
18731 }
18732 
18733 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18734 					      u32 off, u32 cnt)
18735 {
18736 	int i, j;
18737 
18738 	/* find first prog starting at or after off (first to remove) */
18739 	for (i = 0; i < env->subprog_cnt; i++)
18740 		if (env->subprog_info[i].start >= off)
18741 			break;
18742 	/* find first prog starting at or after off + cnt (first to stay) */
18743 	for (j = i; j < env->subprog_cnt; j++)
18744 		if (env->subprog_info[j].start >= off + cnt)
18745 			break;
18746 	/* if j doesn't start exactly at off + cnt, we are just removing
18747 	 * the front of previous prog
18748 	 */
18749 	if (env->subprog_info[j].start != off + cnt)
18750 		j--;
18751 
18752 	if (j > i) {
18753 		struct bpf_prog_aux *aux = env->prog->aux;
18754 		int move;
18755 
18756 		/* move fake 'exit' subprog as well */
18757 		move = env->subprog_cnt + 1 - j;
18758 
18759 		memmove(env->subprog_info + i,
18760 			env->subprog_info + j,
18761 			sizeof(*env->subprog_info) * move);
18762 		env->subprog_cnt -= j - i;
18763 
18764 		/* remove func_info */
18765 		if (aux->func_info) {
18766 			move = aux->func_info_cnt - j;
18767 
18768 			memmove(aux->func_info + i,
18769 				aux->func_info + j,
18770 				sizeof(*aux->func_info) * move);
18771 			aux->func_info_cnt -= j - i;
18772 			/* func_info->insn_off is set after all code rewrites,
18773 			 * in adjust_btf_func() - no need to adjust
18774 			 */
18775 		}
18776 	} else {
18777 		/* convert i from "first prog to remove" to "first to adjust" */
18778 		if (env->subprog_info[i].start == off)
18779 			i++;
18780 	}
18781 
18782 	/* update fake 'exit' subprog as well */
18783 	for (; i <= env->subprog_cnt; i++)
18784 		env->subprog_info[i].start -= cnt;
18785 
18786 	return 0;
18787 }
18788 
18789 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18790 				      u32 cnt)
18791 {
18792 	struct bpf_prog *prog = env->prog;
18793 	u32 i, l_off, l_cnt, nr_linfo;
18794 	struct bpf_line_info *linfo;
18795 
18796 	nr_linfo = prog->aux->nr_linfo;
18797 	if (!nr_linfo)
18798 		return 0;
18799 
18800 	linfo = prog->aux->linfo;
18801 
18802 	/* find first line info to remove, count lines to be removed */
18803 	for (i = 0; i < nr_linfo; i++)
18804 		if (linfo[i].insn_off >= off)
18805 			break;
18806 
18807 	l_off = i;
18808 	l_cnt = 0;
18809 	for (; i < nr_linfo; i++)
18810 		if (linfo[i].insn_off < off + cnt)
18811 			l_cnt++;
18812 		else
18813 			break;
18814 
18815 	/* First live insn doesn't match first live linfo, it needs to "inherit"
18816 	 * last removed linfo.  prog is already modified, so prog->len == off
18817 	 * means no live instructions after (tail of the program was removed).
18818 	 */
18819 	if (prog->len != off && l_cnt &&
18820 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18821 		l_cnt--;
18822 		linfo[--i].insn_off = off + cnt;
18823 	}
18824 
18825 	/* remove the line info which refer to the removed instructions */
18826 	if (l_cnt) {
18827 		memmove(linfo + l_off, linfo + i,
18828 			sizeof(*linfo) * (nr_linfo - i));
18829 
18830 		prog->aux->nr_linfo -= l_cnt;
18831 		nr_linfo = prog->aux->nr_linfo;
18832 	}
18833 
18834 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
18835 	for (i = l_off; i < nr_linfo; i++)
18836 		linfo[i].insn_off -= cnt;
18837 
18838 	/* fix up all subprogs (incl. 'exit') which start >= off */
18839 	for (i = 0; i <= env->subprog_cnt; i++)
18840 		if (env->subprog_info[i].linfo_idx > l_off) {
18841 			/* program may have started in the removed region but
18842 			 * may not be fully removed
18843 			 */
18844 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18845 				env->subprog_info[i].linfo_idx -= l_cnt;
18846 			else
18847 				env->subprog_info[i].linfo_idx = l_off;
18848 		}
18849 
18850 	return 0;
18851 }
18852 
18853 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18854 {
18855 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18856 	unsigned int orig_prog_len = env->prog->len;
18857 	int err;
18858 
18859 	if (bpf_prog_is_offloaded(env->prog->aux))
18860 		bpf_prog_offload_remove_insns(env, off, cnt);
18861 
18862 	err = bpf_remove_insns(env->prog, off, cnt);
18863 	if (err)
18864 		return err;
18865 
18866 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18867 	if (err)
18868 		return err;
18869 
18870 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18871 	if (err)
18872 		return err;
18873 
18874 	memmove(aux_data + off,	aux_data + off + cnt,
18875 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18876 
18877 	return 0;
18878 }
18879 
18880 /* The verifier does more data flow analysis than llvm and will not
18881  * explore branches that are dead at run time. Malicious programs can
18882  * have dead code too. Therefore replace all dead at-run-time code
18883  * with 'ja -1'.
18884  *
18885  * Just nops are not optimal, e.g. if they would sit at the end of the
18886  * program and through another bug we would manage to jump there, then
18887  * we'd execute beyond program memory otherwise. Returning exception
18888  * code also wouldn't work since we can have subprogs where the dead
18889  * code could be located.
18890  */
18891 static void sanitize_dead_code(struct bpf_verifier_env *env)
18892 {
18893 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18894 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18895 	struct bpf_insn *insn = env->prog->insnsi;
18896 	const int insn_cnt = env->prog->len;
18897 	int i;
18898 
18899 	for (i = 0; i < insn_cnt; i++) {
18900 		if (aux_data[i].seen)
18901 			continue;
18902 		memcpy(insn + i, &trap, sizeof(trap));
18903 		aux_data[i].zext_dst = false;
18904 	}
18905 }
18906 
18907 static bool insn_is_cond_jump(u8 code)
18908 {
18909 	u8 op;
18910 
18911 	op = BPF_OP(code);
18912 	if (BPF_CLASS(code) == BPF_JMP32)
18913 		return op != BPF_JA;
18914 
18915 	if (BPF_CLASS(code) != BPF_JMP)
18916 		return false;
18917 
18918 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18919 }
18920 
18921 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18922 {
18923 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18924 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18925 	struct bpf_insn *insn = env->prog->insnsi;
18926 	const int insn_cnt = env->prog->len;
18927 	int i;
18928 
18929 	for (i = 0; i < insn_cnt; i++, insn++) {
18930 		if (!insn_is_cond_jump(insn->code))
18931 			continue;
18932 
18933 		if (!aux_data[i + 1].seen)
18934 			ja.off = insn->off;
18935 		else if (!aux_data[i + 1 + insn->off].seen)
18936 			ja.off = 0;
18937 		else
18938 			continue;
18939 
18940 		if (bpf_prog_is_offloaded(env->prog->aux))
18941 			bpf_prog_offload_replace_insn(env, i, &ja);
18942 
18943 		memcpy(insn, &ja, sizeof(ja));
18944 	}
18945 }
18946 
18947 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18948 {
18949 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18950 	int insn_cnt = env->prog->len;
18951 	int i, err;
18952 
18953 	for (i = 0; i < insn_cnt; i++) {
18954 		int j;
18955 
18956 		j = 0;
18957 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18958 			j++;
18959 		if (!j)
18960 			continue;
18961 
18962 		err = verifier_remove_insns(env, i, j);
18963 		if (err)
18964 			return err;
18965 		insn_cnt = env->prog->len;
18966 	}
18967 
18968 	return 0;
18969 }
18970 
18971 static int opt_remove_nops(struct bpf_verifier_env *env)
18972 {
18973 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18974 	struct bpf_insn *insn = env->prog->insnsi;
18975 	int insn_cnt = env->prog->len;
18976 	int i, err;
18977 
18978 	for (i = 0; i < insn_cnt; i++) {
18979 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18980 			continue;
18981 
18982 		err = verifier_remove_insns(env, i, 1);
18983 		if (err)
18984 			return err;
18985 		insn_cnt--;
18986 		i--;
18987 	}
18988 
18989 	return 0;
18990 }
18991 
18992 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18993 					 const union bpf_attr *attr)
18994 {
18995 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18996 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18997 	int i, patch_len, delta = 0, len = env->prog->len;
18998 	struct bpf_insn *insns = env->prog->insnsi;
18999 	struct bpf_prog *new_prog;
19000 	bool rnd_hi32;
19001 
19002 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
19003 	zext_patch[1] = BPF_ZEXT_REG(0);
19004 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
19005 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
19006 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
19007 	for (i = 0; i < len; i++) {
19008 		int adj_idx = i + delta;
19009 		struct bpf_insn insn;
19010 		int load_reg;
19011 
19012 		insn = insns[adj_idx];
19013 		load_reg = insn_def_regno(&insn);
19014 		if (!aux[adj_idx].zext_dst) {
19015 			u8 code, class;
19016 			u32 imm_rnd;
19017 
19018 			if (!rnd_hi32)
19019 				continue;
19020 
19021 			code = insn.code;
19022 			class = BPF_CLASS(code);
19023 			if (load_reg == -1)
19024 				continue;
19025 
19026 			/* NOTE: arg "reg" (the fourth one) is only used for
19027 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
19028 			 *       here.
19029 			 */
19030 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
19031 				if (class == BPF_LD &&
19032 				    BPF_MODE(code) == BPF_IMM)
19033 					i++;
19034 				continue;
19035 			}
19036 
19037 			/* ctx load could be transformed into wider load. */
19038 			if (class == BPF_LDX &&
19039 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
19040 				continue;
19041 
19042 			imm_rnd = get_random_u32();
19043 			rnd_hi32_patch[0] = insn;
19044 			rnd_hi32_patch[1].imm = imm_rnd;
19045 			rnd_hi32_patch[3].dst_reg = load_reg;
19046 			patch = rnd_hi32_patch;
19047 			patch_len = 4;
19048 			goto apply_patch_buffer;
19049 		}
19050 
19051 		/* Add in an zero-extend instruction if a) the JIT has requested
19052 		 * it or b) it's a CMPXCHG.
19053 		 *
19054 		 * The latter is because: BPF_CMPXCHG always loads a value into
19055 		 * R0, therefore always zero-extends. However some archs'
19056 		 * equivalent instruction only does this load when the
19057 		 * comparison is successful. This detail of CMPXCHG is
19058 		 * orthogonal to the general zero-extension behaviour of the
19059 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
19060 		 */
19061 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
19062 			continue;
19063 
19064 		/* Zero-extension is done by the caller. */
19065 		if (bpf_pseudo_kfunc_call(&insn))
19066 			continue;
19067 
19068 		if (WARN_ON(load_reg == -1)) {
19069 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
19070 			return -EFAULT;
19071 		}
19072 
19073 		zext_patch[0] = insn;
19074 		zext_patch[1].dst_reg = load_reg;
19075 		zext_patch[1].src_reg = load_reg;
19076 		patch = zext_patch;
19077 		patch_len = 2;
19078 apply_patch_buffer:
19079 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
19080 		if (!new_prog)
19081 			return -ENOMEM;
19082 		env->prog = new_prog;
19083 		insns = new_prog->insnsi;
19084 		aux = env->insn_aux_data;
19085 		delta += patch_len - 1;
19086 	}
19087 
19088 	return 0;
19089 }
19090 
19091 /* convert load instructions that access fields of a context type into a
19092  * sequence of instructions that access fields of the underlying structure:
19093  *     struct __sk_buff    -> struct sk_buff
19094  *     struct bpf_sock_ops -> struct sock
19095  */
19096 static int convert_ctx_accesses(struct bpf_verifier_env *env)
19097 {
19098 	const struct bpf_verifier_ops *ops = env->ops;
19099 	int i, cnt, size, ctx_field_size, delta = 0;
19100 	const int insn_cnt = env->prog->len;
19101 	struct bpf_insn insn_buf[16], *insn;
19102 	u32 target_size, size_default, off;
19103 	struct bpf_prog *new_prog;
19104 	enum bpf_access_type type;
19105 	bool is_narrower_load;
19106 
19107 	if (ops->gen_prologue || env->seen_direct_write) {
19108 		if (!ops->gen_prologue) {
19109 			verbose(env, "bpf verifier is misconfigured\n");
19110 			return -EINVAL;
19111 		}
19112 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
19113 					env->prog);
19114 		if (cnt >= ARRAY_SIZE(insn_buf)) {
19115 			verbose(env, "bpf verifier is misconfigured\n");
19116 			return -EINVAL;
19117 		} else if (cnt) {
19118 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
19119 			if (!new_prog)
19120 				return -ENOMEM;
19121 
19122 			env->prog = new_prog;
19123 			delta += cnt - 1;
19124 		}
19125 	}
19126 
19127 	if (bpf_prog_is_offloaded(env->prog->aux))
19128 		return 0;
19129 
19130 	insn = env->prog->insnsi + delta;
19131 
19132 	for (i = 0; i < insn_cnt; i++, insn++) {
19133 		bpf_convert_ctx_access_t convert_ctx_access;
19134 		u8 mode;
19135 
19136 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
19137 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
19138 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
19139 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
19140 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
19141 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
19142 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
19143 			type = BPF_READ;
19144 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
19145 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
19146 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
19147 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
19148 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
19149 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
19150 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
19151 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
19152 			type = BPF_WRITE;
19153 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
19154 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
19155 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
19156 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
19157 			env->prog->aux->num_exentries++;
19158 			continue;
19159 		} else {
19160 			continue;
19161 		}
19162 
19163 		if (type == BPF_WRITE &&
19164 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
19165 			struct bpf_insn patch[] = {
19166 				*insn,
19167 				BPF_ST_NOSPEC(),
19168 			};
19169 
19170 			cnt = ARRAY_SIZE(patch);
19171 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
19172 			if (!new_prog)
19173 				return -ENOMEM;
19174 
19175 			delta    += cnt - 1;
19176 			env->prog = new_prog;
19177 			insn      = new_prog->insnsi + i + delta;
19178 			continue;
19179 		}
19180 
19181 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
19182 		case PTR_TO_CTX:
19183 			if (!ops->convert_ctx_access)
19184 				continue;
19185 			convert_ctx_access = ops->convert_ctx_access;
19186 			break;
19187 		case PTR_TO_SOCKET:
19188 		case PTR_TO_SOCK_COMMON:
19189 			convert_ctx_access = bpf_sock_convert_ctx_access;
19190 			break;
19191 		case PTR_TO_TCP_SOCK:
19192 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
19193 			break;
19194 		case PTR_TO_XDP_SOCK:
19195 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
19196 			break;
19197 		case PTR_TO_BTF_ID:
19198 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
19199 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
19200 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
19201 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
19202 		 * any faults for loads into such types. BPF_WRITE is disallowed
19203 		 * for this case.
19204 		 */
19205 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
19206 			if (type == BPF_READ) {
19207 				if (BPF_MODE(insn->code) == BPF_MEM)
19208 					insn->code = BPF_LDX | BPF_PROBE_MEM |
19209 						     BPF_SIZE((insn)->code);
19210 				else
19211 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
19212 						     BPF_SIZE((insn)->code);
19213 				env->prog->aux->num_exentries++;
19214 			}
19215 			continue;
19216 		case PTR_TO_ARENA:
19217 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
19218 				verbose(env, "sign extending loads from arena are not supported yet\n");
19219 				return -EOPNOTSUPP;
19220 			}
19221 			insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
19222 			env->prog->aux->num_exentries++;
19223 			continue;
19224 		default:
19225 			continue;
19226 		}
19227 
19228 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
19229 		size = BPF_LDST_BYTES(insn);
19230 		mode = BPF_MODE(insn->code);
19231 
19232 		/* If the read access is a narrower load of the field,
19233 		 * convert to a 4/8-byte load, to minimum program type specific
19234 		 * convert_ctx_access changes. If conversion is successful,
19235 		 * we will apply proper mask to the result.
19236 		 */
19237 		is_narrower_load = size < ctx_field_size;
19238 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
19239 		off = insn->off;
19240 		if (is_narrower_load) {
19241 			u8 size_code;
19242 
19243 			if (type == BPF_WRITE) {
19244 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
19245 				return -EINVAL;
19246 			}
19247 
19248 			size_code = BPF_H;
19249 			if (ctx_field_size == 4)
19250 				size_code = BPF_W;
19251 			else if (ctx_field_size == 8)
19252 				size_code = BPF_DW;
19253 
19254 			insn->off = off & ~(size_default - 1);
19255 			insn->code = BPF_LDX | BPF_MEM | size_code;
19256 		}
19257 
19258 		target_size = 0;
19259 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
19260 					 &target_size);
19261 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
19262 		    (ctx_field_size && !target_size)) {
19263 			verbose(env, "bpf verifier is misconfigured\n");
19264 			return -EINVAL;
19265 		}
19266 
19267 		if (is_narrower_load && size < target_size) {
19268 			u8 shift = bpf_ctx_narrow_access_offset(
19269 				off, size, size_default) * 8;
19270 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
19271 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
19272 				return -EINVAL;
19273 			}
19274 			if (ctx_field_size <= 4) {
19275 				if (shift)
19276 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
19277 									insn->dst_reg,
19278 									shift);
19279 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19280 								(1 << size * 8) - 1);
19281 			} else {
19282 				if (shift)
19283 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
19284 									insn->dst_reg,
19285 									shift);
19286 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19287 								(1ULL << size * 8) - 1);
19288 			}
19289 		}
19290 		if (mode == BPF_MEMSX)
19291 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
19292 						       insn->dst_reg, insn->dst_reg,
19293 						       size * 8, 0);
19294 
19295 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19296 		if (!new_prog)
19297 			return -ENOMEM;
19298 
19299 		delta += cnt - 1;
19300 
19301 		/* keep walking new program and skip insns we just inserted */
19302 		env->prog = new_prog;
19303 		insn      = new_prog->insnsi + i + delta;
19304 	}
19305 
19306 	return 0;
19307 }
19308 
19309 static int jit_subprogs(struct bpf_verifier_env *env)
19310 {
19311 	struct bpf_prog *prog = env->prog, **func, *tmp;
19312 	int i, j, subprog_start, subprog_end = 0, len, subprog;
19313 	struct bpf_map *map_ptr;
19314 	struct bpf_insn *insn;
19315 	void *old_bpf_func;
19316 	int err, num_exentries;
19317 
19318 	if (env->subprog_cnt <= 1)
19319 		return 0;
19320 
19321 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19322 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
19323 			continue;
19324 
19325 		/* Upon error here we cannot fall back to interpreter but
19326 		 * need a hard reject of the program. Thus -EFAULT is
19327 		 * propagated in any case.
19328 		 */
19329 		subprog = find_subprog(env, i + insn->imm + 1);
19330 		if (subprog < 0) {
19331 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
19332 				  i + insn->imm + 1);
19333 			return -EFAULT;
19334 		}
19335 		/* temporarily remember subprog id inside insn instead of
19336 		 * aux_data, since next loop will split up all insns into funcs
19337 		 */
19338 		insn->off = subprog;
19339 		/* remember original imm in case JIT fails and fallback
19340 		 * to interpreter will be needed
19341 		 */
19342 		env->insn_aux_data[i].call_imm = insn->imm;
19343 		/* point imm to __bpf_call_base+1 from JITs point of view */
19344 		insn->imm = 1;
19345 		if (bpf_pseudo_func(insn)) {
19346 #if defined(MODULES_VADDR)
19347 			u64 addr = MODULES_VADDR;
19348 #else
19349 			u64 addr = VMALLOC_START;
19350 #endif
19351 			/* jit (e.g. x86_64) may emit fewer instructions
19352 			 * if it learns a u32 imm is the same as a u64 imm.
19353 			 * Set close enough to possible prog address.
19354 			 */
19355 			insn[0].imm = (u32)addr;
19356 			insn[1].imm = addr >> 32;
19357 		}
19358 	}
19359 
19360 	err = bpf_prog_alloc_jited_linfo(prog);
19361 	if (err)
19362 		goto out_undo_insn;
19363 
19364 	err = -ENOMEM;
19365 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
19366 	if (!func)
19367 		goto out_undo_insn;
19368 
19369 	for (i = 0; i < env->subprog_cnt; i++) {
19370 		subprog_start = subprog_end;
19371 		subprog_end = env->subprog_info[i + 1].start;
19372 
19373 		len = subprog_end - subprog_start;
19374 		/* bpf_prog_run() doesn't call subprogs directly,
19375 		 * hence main prog stats include the runtime of subprogs.
19376 		 * subprogs don't have IDs and not reachable via prog_get_next_id
19377 		 * func[i]->stats will never be accessed and stays NULL
19378 		 */
19379 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
19380 		if (!func[i])
19381 			goto out_free;
19382 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
19383 		       len * sizeof(struct bpf_insn));
19384 		func[i]->type = prog->type;
19385 		func[i]->len = len;
19386 		if (bpf_prog_calc_tag(func[i]))
19387 			goto out_free;
19388 		func[i]->is_func = 1;
19389 		func[i]->sleepable = prog->sleepable;
19390 		func[i]->aux->func_idx = i;
19391 		/* Below members will be freed only at prog->aux */
19392 		func[i]->aux->btf = prog->aux->btf;
19393 		func[i]->aux->func_info = prog->aux->func_info;
19394 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
19395 		func[i]->aux->poke_tab = prog->aux->poke_tab;
19396 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
19397 
19398 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
19399 			struct bpf_jit_poke_descriptor *poke;
19400 
19401 			poke = &prog->aux->poke_tab[j];
19402 			if (poke->insn_idx < subprog_end &&
19403 			    poke->insn_idx >= subprog_start)
19404 				poke->aux = func[i]->aux;
19405 		}
19406 
19407 		func[i]->aux->name[0] = 'F';
19408 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
19409 		func[i]->jit_requested = 1;
19410 		func[i]->blinding_requested = prog->blinding_requested;
19411 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
19412 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
19413 		func[i]->aux->linfo = prog->aux->linfo;
19414 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
19415 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
19416 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
19417 		func[i]->aux->arena = prog->aux->arena;
19418 		num_exentries = 0;
19419 		insn = func[i]->insnsi;
19420 		for (j = 0; j < func[i]->len; j++, insn++) {
19421 			if (BPF_CLASS(insn->code) == BPF_LDX &&
19422 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
19423 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
19424 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
19425 				num_exentries++;
19426 			if ((BPF_CLASS(insn->code) == BPF_STX ||
19427 			     BPF_CLASS(insn->code) == BPF_ST) &&
19428 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
19429 				num_exentries++;
19430 			if (BPF_CLASS(insn->code) == BPF_STX &&
19431 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
19432 				num_exentries++;
19433 		}
19434 		func[i]->aux->num_exentries = num_exentries;
19435 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
19436 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
19437 		if (!i)
19438 			func[i]->aux->exception_boundary = env->seen_exception;
19439 		func[i] = bpf_int_jit_compile(func[i]);
19440 		if (!func[i]->jited) {
19441 			err = -ENOTSUPP;
19442 			goto out_free;
19443 		}
19444 		cond_resched();
19445 	}
19446 
19447 	/* at this point all bpf functions were successfully JITed
19448 	 * now populate all bpf_calls with correct addresses and
19449 	 * run last pass of JIT
19450 	 */
19451 	for (i = 0; i < env->subprog_cnt; i++) {
19452 		insn = func[i]->insnsi;
19453 		for (j = 0; j < func[i]->len; j++, insn++) {
19454 			if (bpf_pseudo_func(insn)) {
19455 				subprog = insn->off;
19456 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
19457 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
19458 				continue;
19459 			}
19460 			if (!bpf_pseudo_call(insn))
19461 				continue;
19462 			subprog = insn->off;
19463 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
19464 		}
19465 
19466 		/* we use the aux data to keep a list of the start addresses
19467 		 * of the JITed images for each function in the program
19468 		 *
19469 		 * for some architectures, such as powerpc64, the imm field
19470 		 * might not be large enough to hold the offset of the start
19471 		 * address of the callee's JITed image from __bpf_call_base
19472 		 *
19473 		 * in such cases, we can lookup the start address of a callee
19474 		 * by using its subprog id, available from the off field of
19475 		 * the call instruction, as an index for this list
19476 		 */
19477 		func[i]->aux->func = func;
19478 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19479 		func[i]->aux->real_func_cnt = env->subprog_cnt;
19480 	}
19481 	for (i = 0; i < env->subprog_cnt; i++) {
19482 		old_bpf_func = func[i]->bpf_func;
19483 		tmp = bpf_int_jit_compile(func[i]);
19484 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
19485 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
19486 			err = -ENOTSUPP;
19487 			goto out_free;
19488 		}
19489 		cond_resched();
19490 	}
19491 
19492 	/* finally lock prog and jit images for all functions and
19493 	 * populate kallsysm. Begin at the first subprogram, since
19494 	 * bpf_prog_load will add the kallsyms for the main program.
19495 	 */
19496 	for (i = 1; i < env->subprog_cnt; i++) {
19497 		err = bpf_prog_lock_ro(func[i]);
19498 		if (err)
19499 			goto out_free;
19500 	}
19501 
19502 	for (i = 1; i < env->subprog_cnt; i++)
19503 		bpf_prog_kallsyms_add(func[i]);
19504 
19505 	/* Last step: make now unused interpreter insns from main
19506 	 * prog consistent for later dump requests, so they can
19507 	 * later look the same as if they were interpreted only.
19508 	 */
19509 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19510 		if (bpf_pseudo_func(insn)) {
19511 			insn[0].imm = env->insn_aux_data[i].call_imm;
19512 			insn[1].imm = insn->off;
19513 			insn->off = 0;
19514 			continue;
19515 		}
19516 		if (!bpf_pseudo_call(insn))
19517 			continue;
19518 		insn->off = env->insn_aux_data[i].call_imm;
19519 		subprog = find_subprog(env, i + insn->off + 1);
19520 		insn->imm = subprog;
19521 	}
19522 
19523 	prog->jited = 1;
19524 	prog->bpf_func = func[0]->bpf_func;
19525 	prog->jited_len = func[0]->jited_len;
19526 	prog->aux->extable = func[0]->aux->extable;
19527 	prog->aux->num_exentries = func[0]->aux->num_exentries;
19528 	prog->aux->func = func;
19529 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19530 	prog->aux->real_func_cnt = env->subprog_cnt;
19531 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
19532 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
19533 	bpf_prog_jit_attempt_done(prog);
19534 	return 0;
19535 out_free:
19536 	/* We failed JIT'ing, so at this point we need to unregister poke
19537 	 * descriptors from subprogs, so that kernel is not attempting to
19538 	 * patch it anymore as we're freeing the subprog JIT memory.
19539 	 */
19540 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19541 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19542 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
19543 	}
19544 	/* At this point we're guaranteed that poke descriptors are not
19545 	 * live anymore. We can just unlink its descriptor table as it's
19546 	 * released with the main prog.
19547 	 */
19548 	for (i = 0; i < env->subprog_cnt; i++) {
19549 		if (!func[i])
19550 			continue;
19551 		func[i]->aux->poke_tab = NULL;
19552 		bpf_jit_free(func[i]);
19553 	}
19554 	kfree(func);
19555 out_undo_insn:
19556 	/* cleanup main prog to be interpreted */
19557 	prog->jit_requested = 0;
19558 	prog->blinding_requested = 0;
19559 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19560 		if (!bpf_pseudo_call(insn))
19561 			continue;
19562 		insn->off = 0;
19563 		insn->imm = env->insn_aux_data[i].call_imm;
19564 	}
19565 	bpf_prog_jit_attempt_done(prog);
19566 	return err;
19567 }
19568 
19569 static int fixup_call_args(struct bpf_verifier_env *env)
19570 {
19571 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19572 	struct bpf_prog *prog = env->prog;
19573 	struct bpf_insn *insn = prog->insnsi;
19574 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
19575 	int i, depth;
19576 #endif
19577 	int err = 0;
19578 
19579 	if (env->prog->jit_requested &&
19580 	    !bpf_prog_is_offloaded(env->prog->aux)) {
19581 		err = jit_subprogs(env);
19582 		if (err == 0)
19583 			return 0;
19584 		if (err == -EFAULT)
19585 			return err;
19586 	}
19587 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19588 	if (has_kfunc_call) {
19589 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
19590 		return -EINVAL;
19591 	}
19592 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
19593 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
19594 		 * have to be rejected, since interpreter doesn't support them yet.
19595 		 */
19596 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
19597 		return -EINVAL;
19598 	}
19599 	for (i = 0; i < prog->len; i++, insn++) {
19600 		if (bpf_pseudo_func(insn)) {
19601 			/* When JIT fails the progs with callback calls
19602 			 * have to be rejected, since interpreter doesn't support them yet.
19603 			 */
19604 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
19605 			return -EINVAL;
19606 		}
19607 
19608 		if (!bpf_pseudo_call(insn))
19609 			continue;
19610 		depth = get_callee_stack_depth(env, insn, i);
19611 		if (depth < 0)
19612 			return depth;
19613 		bpf_patch_call_args(insn, depth);
19614 	}
19615 	err = 0;
19616 #endif
19617 	return err;
19618 }
19619 
19620 /* replace a generic kfunc with a specialized version if necessary */
19621 static void specialize_kfunc(struct bpf_verifier_env *env,
19622 			     u32 func_id, u16 offset, unsigned long *addr)
19623 {
19624 	struct bpf_prog *prog = env->prog;
19625 	bool seen_direct_write;
19626 	void *xdp_kfunc;
19627 	bool is_rdonly;
19628 
19629 	if (bpf_dev_bound_kfunc_id(func_id)) {
19630 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19631 		if (xdp_kfunc) {
19632 			*addr = (unsigned long)xdp_kfunc;
19633 			return;
19634 		}
19635 		/* fallback to default kfunc when not supported by netdev */
19636 	}
19637 
19638 	if (offset)
19639 		return;
19640 
19641 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19642 		seen_direct_write = env->seen_direct_write;
19643 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19644 
19645 		if (is_rdonly)
19646 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19647 
19648 		/* restore env->seen_direct_write to its original value, since
19649 		 * may_access_direct_pkt_data mutates it
19650 		 */
19651 		env->seen_direct_write = seen_direct_write;
19652 	}
19653 }
19654 
19655 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19656 					    u16 struct_meta_reg,
19657 					    u16 node_offset_reg,
19658 					    struct bpf_insn *insn,
19659 					    struct bpf_insn *insn_buf,
19660 					    int *cnt)
19661 {
19662 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19663 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19664 
19665 	insn_buf[0] = addr[0];
19666 	insn_buf[1] = addr[1];
19667 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19668 	insn_buf[3] = *insn;
19669 	*cnt = 4;
19670 }
19671 
19672 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19673 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19674 {
19675 	const struct bpf_kfunc_desc *desc;
19676 
19677 	if (!insn->imm) {
19678 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19679 		return -EINVAL;
19680 	}
19681 
19682 	*cnt = 0;
19683 
19684 	/* insn->imm has the btf func_id. Replace it with an offset relative to
19685 	 * __bpf_call_base, unless the JIT needs to call functions that are
19686 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19687 	 */
19688 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19689 	if (!desc) {
19690 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19691 			insn->imm);
19692 		return -EFAULT;
19693 	}
19694 
19695 	if (!bpf_jit_supports_far_kfunc_call())
19696 		insn->imm = BPF_CALL_IMM(desc->addr);
19697 	if (insn->off)
19698 		return 0;
19699 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19700 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
19701 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19702 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19703 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19704 
19705 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19706 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19707 				insn_idx);
19708 			return -EFAULT;
19709 		}
19710 
19711 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19712 		insn_buf[1] = addr[0];
19713 		insn_buf[2] = addr[1];
19714 		insn_buf[3] = *insn;
19715 		*cnt = 4;
19716 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
19717 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
19718 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
19719 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19720 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19721 
19722 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19723 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19724 				insn_idx);
19725 			return -EFAULT;
19726 		}
19727 
19728 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19729 		    !kptr_struct_meta) {
19730 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19731 				insn_idx);
19732 			return -EFAULT;
19733 		}
19734 
19735 		insn_buf[0] = addr[0];
19736 		insn_buf[1] = addr[1];
19737 		insn_buf[2] = *insn;
19738 		*cnt = 3;
19739 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19740 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19741 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19742 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19743 		int struct_meta_reg = BPF_REG_3;
19744 		int node_offset_reg = BPF_REG_4;
19745 
19746 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19747 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19748 			struct_meta_reg = BPF_REG_4;
19749 			node_offset_reg = BPF_REG_5;
19750 		}
19751 
19752 		if (!kptr_struct_meta) {
19753 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19754 				insn_idx);
19755 			return -EFAULT;
19756 		}
19757 
19758 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19759 						node_offset_reg, insn, insn_buf, cnt);
19760 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19761 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19762 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19763 		*cnt = 1;
19764 	} else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) {
19765 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) };
19766 
19767 		insn_buf[0] = ld_addrs[0];
19768 		insn_buf[1] = ld_addrs[1];
19769 		insn_buf[2] = *insn;
19770 		*cnt = 3;
19771 	}
19772 	return 0;
19773 }
19774 
19775 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
19776 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19777 {
19778 	struct bpf_subprog_info *info = env->subprog_info;
19779 	int cnt = env->subprog_cnt;
19780 	struct bpf_prog *prog;
19781 
19782 	/* We only reserve one slot for hidden subprogs in subprog_info. */
19783 	if (env->hidden_subprog_cnt) {
19784 		verbose(env, "verifier internal error: only one hidden subprog supported\n");
19785 		return -EFAULT;
19786 	}
19787 	/* We're not patching any existing instruction, just appending the new
19788 	 * ones for the hidden subprog. Hence all of the adjustment operations
19789 	 * in bpf_patch_insn_data are no-ops.
19790 	 */
19791 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19792 	if (!prog)
19793 		return -ENOMEM;
19794 	env->prog = prog;
19795 	info[cnt + 1].start = info[cnt].start;
19796 	info[cnt].start = prog->len - len + 1;
19797 	env->subprog_cnt++;
19798 	env->hidden_subprog_cnt++;
19799 	return 0;
19800 }
19801 
19802 /* Do various post-verification rewrites in a single program pass.
19803  * These rewrites simplify JIT and interpreter implementations.
19804  */
19805 static int do_misc_fixups(struct bpf_verifier_env *env)
19806 {
19807 	struct bpf_prog *prog = env->prog;
19808 	enum bpf_attach_type eatype = prog->expected_attach_type;
19809 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
19810 	struct bpf_insn *insn = prog->insnsi;
19811 	const struct bpf_func_proto *fn;
19812 	const int insn_cnt = prog->len;
19813 	const struct bpf_map_ops *ops;
19814 	struct bpf_insn_aux_data *aux;
19815 	struct bpf_insn insn_buf[16];
19816 	struct bpf_prog *new_prog;
19817 	struct bpf_map *map_ptr;
19818 	int i, ret, cnt, delta = 0, cur_subprog = 0;
19819 	struct bpf_subprog_info *subprogs = env->subprog_info;
19820 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19821 	u16 stack_depth_extra = 0;
19822 
19823 	if (env->seen_exception && !env->exception_callback_subprog) {
19824 		struct bpf_insn patch[] = {
19825 			env->prog->insnsi[insn_cnt - 1],
19826 			BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19827 			BPF_EXIT_INSN(),
19828 		};
19829 
19830 		ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19831 		if (ret < 0)
19832 			return ret;
19833 		prog = env->prog;
19834 		insn = prog->insnsi;
19835 
19836 		env->exception_callback_subprog = env->subprog_cnt - 1;
19837 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19838 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
19839 	}
19840 
19841 	for (i = 0; i < insn_cnt;) {
19842 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
19843 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
19844 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
19845 				/* convert to 32-bit mov that clears upper 32-bit */
19846 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
19847 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
19848 				insn->off = 0;
19849 				insn->imm = 0;
19850 			} /* cast from as(0) to as(1) should be handled by JIT */
19851 			goto next_insn;
19852 		}
19853 
19854 		if (env->insn_aux_data[i + delta].needs_zext)
19855 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
19856 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
19857 
19858 		/* Make divide-by-zero exceptions impossible. */
19859 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19860 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19861 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19862 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19863 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19864 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19865 			struct bpf_insn *patchlet;
19866 			struct bpf_insn chk_and_div[] = {
19867 				/* [R,W]x div 0 -> 0 */
19868 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19869 					     BPF_JNE | BPF_K, insn->src_reg,
19870 					     0, 2, 0),
19871 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19872 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19873 				*insn,
19874 			};
19875 			struct bpf_insn chk_and_mod[] = {
19876 				/* [R,W]x mod 0 -> [R,W]x */
19877 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19878 					     BPF_JEQ | BPF_K, insn->src_reg,
19879 					     0, 1 + (is64 ? 0 : 1), 0),
19880 				*insn,
19881 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19882 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19883 			};
19884 
19885 			patchlet = isdiv ? chk_and_div : chk_and_mod;
19886 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19887 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19888 
19889 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19890 			if (!new_prog)
19891 				return -ENOMEM;
19892 
19893 			delta    += cnt - 1;
19894 			env->prog = prog = new_prog;
19895 			insn      = new_prog->insnsi + i + delta;
19896 			goto next_insn;
19897 		}
19898 
19899 		/* Make it impossible to de-reference a userspace address */
19900 		if (BPF_CLASS(insn->code) == BPF_LDX &&
19901 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
19902 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
19903 			struct bpf_insn *patch = &insn_buf[0];
19904 			u64 uaddress_limit = bpf_arch_uaddress_limit();
19905 
19906 			if (!uaddress_limit)
19907 				goto next_insn;
19908 
19909 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
19910 			if (insn->off)
19911 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
19912 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
19913 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
19914 			*patch++ = *insn;
19915 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
19916 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
19917 
19918 			cnt = patch - insn_buf;
19919 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19920 			if (!new_prog)
19921 				return -ENOMEM;
19922 
19923 			delta    += cnt - 1;
19924 			env->prog = prog = new_prog;
19925 			insn      = new_prog->insnsi + i + delta;
19926 			goto next_insn;
19927 		}
19928 
19929 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19930 		if (BPF_CLASS(insn->code) == BPF_LD &&
19931 		    (BPF_MODE(insn->code) == BPF_ABS ||
19932 		     BPF_MODE(insn->code) == BPF_IND)) {
19933 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
19934 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19935 				verbose(env, "bpf verifier is misconfigured\n");
19936 				return -EINVAL;
19937 			}
19938 
19939 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19940 			if (!new_prog)
19941 				return -ENOMEM;
19942 
19943 			delta    += cnt - 1;
19944 			env->prog = prog = new_prog;
19945 			insn      = new_prog->insnsi + i + delta;
19946 			goto next_insn;
19947 		}
19948 
19949 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
19950 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19951 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19952 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19953 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19954 			struct bpf_insn *patch = &insn_buf[0];
19955 			bool issrc, isneg, isimm;
19956 			u32 off_reg;
19957 
19958 			aux = &env->insn_aux_data[i + delta];
19959 			if (!aux->alu_state ||
19960 			    aux->alu_state == BPF_ALU_NON_POINTER)
19961 				goto next_insn;
19962 
19963 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19964 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19965 				BPF_ALU_SANITIZE_SRC;
19966 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19967 
19968 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
19969 			if (isimm) {
19970 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19971 			} else {
19972 				if (isneg)
19973 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19974 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19975 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19976 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19977 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19978 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19979 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19980 			}
19981 			if (!issrc)
19982 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19983 			insn->src_reg = BPF_REG_AX;
19984 			if (isneg)
19985 				insn->code = insn->code == code_add ?
19986 					     code_sub : code_add;
19987 			*patch++ = *insn;
19988 			if (issrc && isneg && !isimm)
19989 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19990 			cnt = patch - insn_buf;
19991 
19992 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19993 			if (!new_prog)
19994 				return -ENOMEM;
19995 
19996 			delta    += cnt - 1;
19997 			env->prog = prog = new_prog;
19998 			insn      = new_prog->insnsi + i + delta;
19999 			goto next_insn;
20000 		}
20001 
20002 		if (is_may_goto_insn(insn)) {
20003 			int stack_off = -stack_depth - 8;
20004 
20005 			stack_depth_extra = 8;
20006 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
20007 			insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
20008 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
20009 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
20010 			cnt = 4;
20011 
20012 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20013 			if (!new_prog)
20014 				return -ENOMEM;
20015 
20016 			delta += cnt - 1;
20017 			env->prog = prog = new_prog;
20018 			insn = new_prog->insnsi + i + delta;
20019 			goto next_insn;
20020 		}
20021 
20022 		if (insn->code != (BPF_JMP | BPF_CALL))
20023 			goto next_insn;
20024 		if (insn->src_reg == BPF_PSEUDO_CALL)
20025 			goto next_insn;
20026 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
20027 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
20028 			if (ret)
20029 				return ret;
20030 			if (cnt == 0)
20031 				goto next_insn;
20032 
20033 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20034 			if (!new_prog)
20035 				return -ENOMEM;
20036 
20037 			delta	 += cnt - 1;
20038 			env->prog = prog = new_prog;
20039 			insn	  = new_prog->insnsi + i + delta;
20040 			goto next_insn;
20041 		}
20042 
20043 		/* Skip inlining the helper call if the JIT does it. */
20044 		if (bpf_jit_inlines_helper_call(insn->imm))
20045 			goto next_insn;
20046 
20047 		if (insn->imm == BPF_FUNC_get_route_realm)
20048 			prog->dst_needed = 1;
20049 		if (insn->imm == BPF_FUNC_get_prandom_u32)
20050 			bpf_user_rnd_init_once();
20051 		if (insn->imm == BPF_FUNC_override_return)
20052 			prog->kprobe_override = 1;
20053 		if (insn->imm == BPF_FUNC_tail_call) {
20054 			/* If we tail call into other programs, we
20055 			 * cannot make any assumptions since they can
20056 			 * be replaced dynamically during runtime in
20057 			 * the program array.
20058 			 */
20059 			prog->cb_access = 1;
20060 			if (!allow_tail_call_in_subprogs(env))
20061 				prog->aux->stack_depth = MAX_BPF_STACK;
20062 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
20063 
20064 			/* mark bpf_tail_call as different opcode to avoid
20065 			 * conditional branch in the interpreter for every normal
20066 			 * call and to prevent accidental JITing by JIT compiler
20067 			 * that doesn't support bpf_tail_call yet
20068 			 */
20069 			insn->imm = 0;
20070 			insn->code = BPF_JMP | BPF_TAIL_CALL;
20071 
20072 			aux = &env->insn_aux_data[i + delta];
20073 			if (env->bpf_capable && !prog->blinding_requested &&
20074 			    prog->jit_requested &&
20075 			    !bpf_map_key_poisoned(aux) &&
20076 			    !bpf_map_ptr_poisoned(aux) &&
20077 			    !bpf_map_ptr_unpriv(aux)) {
20078 				struct bpf_jit_poke_descriptor desc = {
20079 					.reason = BPF_POKE_REASON_TAIL_CALL,
20080 					.tail_call.map = aux->map_ptr_state.map_ptr,
20081 					.tail_call.key = bpf_map_key_immediate(aux),
20082 					.insn_idx = i + delta,
20083 				};
20084 
20085 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
20086 				if (ret < 0) {
20087 					verbose(env, "adding tail call poke descriptor failed\n");
20088 					return ret;
20089 				}
20090 
20091 				insn->imm = ret + 1;
20092 				goto next_insn;
20093 			}
20094 
20095 			if (!bpf_map_ptr_unpriv(aux))
20096 				goto next_insn;
20097 
20098 			/* instead of changing every JIT dealing with tail_call
20099 			 * emit two extra insns:
20100 			 * if (index >= max_entries) goto out;
20101 			 * index &= array->index_mask;
20102 			 * to avoid out-of-bounds cpu speculation
20103 			 */
20104 			if (bpf_map_ptr_poisoned(aux)) {
20105 				verbose(env, "tail_call abusing map_ptr\n");
20106 				return -EINVAL;
20107 			}
20108 
20109 			map_ptr = aux->map_ptr_state.map_ptr;
20110 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
20111 						  map_ptr->max_entries, 2);
20112 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
20113 						    container_of(map_ptr,
20114 								 struct bpf_array,
20115 								 map)->index_mask);
20116 			insn_buf[2] = *insn;
20117 			cnt = 3;
20118 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20119 			if (!new_prog)
20120 				return -ENOMEM;
20121 
20122 			delta    += cnt - 1;
20123 			env->prog = prog = new_prog;
20124 			insn      = new_prog->insnsi + i + delta;
20125 			goto next_insn;
20126 		}
20127 
20128 		if (insn->imm == BPF_FUNC_timer_set_callback) {
20129 			/* The verifier will process callback_fn as many times as necessary
20130 			 * with different maps and the register states prepared by
20131 			 * set_timer_callback_state will be accurate.
20132 			 *
20133 			 * The following use case is valid:
20134 			 *   map1 is shared by prog1, prog2, prog3.
20135 			 *   prog1 calls bpf_timer_init for some map1 elements
20136 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
20137 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
20138 			 *   prog3 calls bpf_timer_start for some map1 elements.
20139 			 *     Those that were not both bpf_timer_init-ed and
20140 			 *     bpf_timer_set_callback-ed will return -EINVAL.
20141 			 */
20142 			struct bpf_insn ld_addrs[2] = {
20143 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
20144 			};
20145 
20146 			insn_buf[0] = ld_addrs[0];
20147 			insn_buf[1] = ld_addrs[1];
20148 			insn_buf[2] = *insn;
20149 			cnt = 3;
20150 
20151 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20152 			if (!new_prog)
20153 				return -ENOMEM;
20154 
20155 			delta    += cnt - 1;
20156 			env->prog = prog = new_prog;
20157 			insn      = new_prog->insnsi + i + delta;
20158 			goto patch_call_imm;
20159 		}
20160 
20161 		if (is_storage_get_function(insn->imm)) {
20162 			if (!in_sleepable(env) ||
20163 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
20164 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
20165 			else
20166 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
20167 			insn_buf[1] = *insn;
20168 			cnt = 2;
20169 
20170 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20171 			if (!new_prog)
20172 				return -ENOMEM;
20173 
20174 			delta += cnt - 1;
20175 			env->prog = prog = new_prog;
20176 			insn = new_prog->insnsi + i + delta;
20177 			goto patch_call_imm;
20178 		}
20179 
20180 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
20181 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
20182 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
20183 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
20184 			 */
20185 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
20186 			insn_buf[1] = *insn;
20187 			cnt = 2;
20188 
20189 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20190 			if (!new_prog)
20191 				return -ENOMEM;
20192 
20193 			delta += cnt - 1;
20194 			env->prog = prog = new_prog;
20195 			insn = new_prog->insnsi + i + delta;
20196 			goto patch_call_imm;
20197 		}
20198 
20199 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
20200 		 * and other inlining handlers are currently limited to 64 bit
20201 		 * only.
20202 		 */
20203 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
20204 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
20205 		     insn->imm == BPF_FUNC_map_update_elem ||
20206 		     insn->imm == BPF_FUNC_map_delete_elem ||
20207 		     insn->imm == BPF_FUNC_map_push_elem   ||
20208 		     insn->imm == BPF_FUNC_map_pop_elem    ||
20209 		     insn->imm == BPF_FUNC_map_peek_elem   ||
20210 		     insn->imm == BPF_FUNC_redirect_map    ||
20211 		     insn->imm == BPF_FUNC_for_each_map_elem ||
20212 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
20213 			aux = &env->insn_aux_data[i + delta];
20214 			if (bpf_map_ptr_poisoned(aux))
20215 				goto patch_call_imm;
20216 
20217 			map_ptr = aux->map_ptr_state.map_ptr;
20218 			ops = map_ptr->ops;
20219 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
20220 			    ops->map_gen_lookup) {
20221 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
20222 				if (cnt == -EOPNOTSUPP)
20223 					goto patch_map_ops_generic;
20224 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
20225 					verbose(env, "bpf verifier is misconfigured\n");
20226 					return -EINVAL;
20227 				}
20228 
20229 				new_prog = bpf_patch_insn_data(env, i + delta,
20230 							       insn_buf, cnt);
20231 				if (!new_prog)
20232 					return -ENOMEM;
20233 
20234 				delta    += cnt - 1;
20235 				env->prog = prog = new_prog;
20236 				insn      = new_prog->insnsi + i + delta;
20237 				goto next_insn;
20238 			}
20239 
20240 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
20241 				     (void *(*)(struct bpf_map *map, void *key))NULL));
20242 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
20243 				     (long (*)(struct bpf_map *map, void *key))NULL));
20244 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
20245 				     (long (*)(struct bpf_map *map, void *key, void *value,
20246 					      u64 flags))NULL));
20247 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
20248 				     (long (*)(struct bpf_map *map, void *value,
20249 					      u64 flags))NULL));
20250 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
20251 				     (long (*)(struct bpf_map *map, void *value))NULL));
20252 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
20253 				     (long (*)(struct bpf_map *map, void *value))NULL));
20254 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
20255 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
20256 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
20257 				     (long (*)(struct bpf_map *map,
20258 					      bpf_callback_t callback_fn,
20259 					      void *callback_ctx,
20260 					      u64 flags))NULL));
20261 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
20262 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
20263 
20264 patch_map_ops_generic:
20265 			switch (insn->imm) {
20266 			case BPF_FUNC_map_lookup_elem:
20267 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
20268 				goto next_insn;
20269 			case BPF_FUNC_map_update_elem:
20270 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
20271 				goto next_insn;
20272 			case BPF_FUNC_map_delete_elem:
20273 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
20274 				goto next_insn;
20275 			case BPF_FUNC_map_push_elem:
20276 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
20277 				goto next_insn;
20278 			case BPF_FUNC_map_pop_elem:
20279 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
20280 				goto next_insn;
20281 			case BPF_FUNC_map_peek_elem:
20282 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
20283 				goto next_insn;
20284 			case BPF_FUNC_redirect_map:
20285 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
20286 				goto next_insn;
20287 			case BPF_FUNC_for_each_map_elem:
20288 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
20289 				goto next_insn;
20290 			case BPF_FUNC_map_lookup_percpu_elem:
20291 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
20292 				goto next_insn;
20293 			}
20294 
20295 			goto patch_call_imm;
20296 		}
20297 
20298 		/* Implement bpf_jiffies64 inline. */
20299 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
20300 		    insn->imm == BPF_FUNC_jiffies64) {
20301 			struct bpf_insn ld_jiffies_addr[2] = {
20302 				BPF_LD_IMM64(BPF_REG_0,
20303 					     (unsigned long)&jiffies),
20304 			};
20305 
20306 			insn_buf[0] = ld_jiffies_addr[0];
20307 			insn_buf[1] = ld_jiffies_addr[1];
20308 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
20309 						  BPF_REG_0, 0);
20310 			cnt = 3;
20311 
20312 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
20313 						       cnt);
20314 			if (!new_prog)
20315 				return -ENOMEM;
20316 
20317 			delta    += cnt - 1;
20318 			env->prog = prog = new_prog;
20319 			insn      = new_prog->insnsi + i + delta;
20320 			goto next_insn;
20321 		}
20322 
20323 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
20324 		/* Implement bpf_get_smp_processor_id() inline. */
20325 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
20326 		    prog->jit_requested && bpf_jit_supports_percpu_insn()) {
20327 			/* BPF_FUNC_get_smp_processor_id inlining is an
20328 			 * optimization, so if pcpu_hot.cpu_number is ever
20329 			 * changed in some incompatible and hard to support
20330 			 * way, it's fine to back out this inlining logic
20331 			 */
20332 			insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number);
20333 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
20334 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
20335 			cnt = 3;
20336 
20337 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20338 			if (!new_prog)
20339 				return -ENOMEM;
20340 
20341 			delta    += cnt - 1;
20342 			env->prog = prog = new_prog;
20343 			insn      = new_prog->insnsi + i + delta;
20344 			goto next_insn;
20345 		}
20346 #endif
20347 		/* Implement bpf_get_func_arg inline. */
20348 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20349 		    insn->imm == BPF_FUNC_get_func_arg) {
20350 			/* Load nr_args from ctx - 8 */
20351 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20352 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
20353 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
20354 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
20355 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
20356 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
20357 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
20358 			insn_buf[7] = BPF_JMP_A(1);
20359 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
20360 			cnt = 9;
20361 
20362 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20363 			if (!new_prog)
20364 				return -ENOMEM;
20365 
20366 			delta    += cnt - 1;
20367 			env->prog = prog = new_prog;
20368 			insn      = new_prog->insnsi + i + delta;
20369 			goto next_insn;
20370 		}
20371 
20372 		/* Implement bpf_get_func_ret inline. */
20373 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20374 		    insn->imm == BPF_FUNC_get_func_ret) {
20375 			if (eatype == BPF_TRACE_FEXIT ||
20376 			    eatype == BPF_MODIFY_RETURN) {
20377 				/* Load nr_args from ctx - 8 */
20378 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20379 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
20380 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
20381 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
20382 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
20383 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
20384 				cnt = 6;
20385 			} else {
20386 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
20387 				cnt = 1;
20388 			}
20389 
20390 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20391 			if (!new_prog)
20392 				return -ENOMEM;
20393 
20394 			delta    += cnt - 1;
20395 			env->prog = prog = new_prog;
20396 			insn      = new_prog->insnsi + i + delta;
20397 			goto next_insn;
20398 		}
20399 
20400 		/* Implement get_func_arg_cnt inline. */
20401 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20402 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
20403 			/* Load nr_args from ctx - 8 */
20404 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20405 
20406 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
20407 			if (!new_prog)
20408 				return -ENOMEM;
20409 
20410 			env->prog = prog = new_prog;
20411 			insn      = new_prog->insnsi + i + delta;
20412 			goto next_insn;
20413 		}
20414 
20415 		/* Implement bpf_get_func_ip inline. */
20416 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20417 		    insn->imm == BPF_FUNC_get_func_ip) {
20418 			/* Load IP address from ctx - 16 */
20419 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
20420 
20421 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
20422 			if (!new_prog)
20423 				return -ENOMEM;
20424 
20425 			env->prog = prog = new_prog;
20426 			insn      = new_prog->insnsi + i + delta;
20427 			goto next_insn;
20428 		}
20429 
20430 		/* Implement bpf_get_branch_snapshot inline. */
20431 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
20432 		    prog->jit_requested && BITS_PER_LONG == 64 &&
20433 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
20434 			/* We are dealing with the following func protos:
20435 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
20436 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
20437 			 */
20438 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
20439 
20440 			/* struct perf_branch_entry is part of UAPI and is
20441 			 * used as an array element, so extremely unlikely to
20442 			 * ever grow or shrink
20443 			 */
20444 			BUILD_BUG_ON(br_entry_size != 24);
20445 
20446 			/* if (unlikely(flags)) return -EINVAL */
20447 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
20448 
20449 			/* Transform size (bytes) into number of entries (cnt = size / 24).
20450 			 * But to avoid expensive division instruction, we implement
20451 			 * divide-by-3 through multiplication, followed by further
20452 			 * division by 8 through 3-bit right shift.
20453 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
20454 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
20455 			 *
20456 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
20457 			 */
20458 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
20459 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
20460 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
20461 
20462 			/* call perf_snapshot_branch_stack implementation */
20463 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
20464 			/* if (entry_cnt == 0) return -ENOENT */
20465 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
20466 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
20467 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
20468 			insn_buf[7] = BPF_JMP_A(3);
20469 			/* return -EINVAL; */
20470 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
20471 			insn_buf[9] = BPF_JMP_A(1);
20472 			/* return -ENOENT; */
20473 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
20474 			cnt = 11;
20475 
20476 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20477 			if (!new_prog)
20478 				return -ENOMEM;
20479 
20480 			delta    += cnt - 1;
20481 			env->prog = prog = new_prog;
20482 			insn      = new_prog->insnsi + i + delta;
20483 			continue;
20484 		}
20485 
20486 		/* Implement bpf_kptr_xchg inline */
20487 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
20488 		    insn->imm == BPF_FUNC_kptr_xchg &&
20489 		    bpf_jit_supports_ptr_xchg()) {
20490 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
20491 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
20492 			cnt = 2;
20493 
20494 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20495 			if (!new_prog)
20496 				return -ENOMEM;
20497 
20498 			delta    += cnt - 1;
20499 			env->prog = prog = new_prog;
20500 			insn      = new_prog->insnsi + i + delta;
20501 			goto next_insn;
20502 		}
20503 patch_call_imm:
20504 		fn = env->ops->get_func_proto(insn->imm, env->prog);
20505 		/* all functions that have prototype and verifier allowed
20506 		 * programs to call them, must be real in-kernel functions
20507 		 */
20508 		if (!fn->func) {
20509 			verbose(env,
20510 				"kernel subsystem misconfigured func %s#%d\n",
20511 				func_id_name(insn->imm), insn->imm);
20512 			return -EFAULT;
20513 		}
20514 		insn->imm = fn->func - __bpf_call_base;
20515 next_insn:
20516 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20517 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
20518 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
20519 			cur_subprog++;
20520 			stack_depth = subprogs[cur_subprog].stack_depth;
20521 			stack_depth_extra = 0;
20522 		}
20523 		i++;
20524 		insn++;
20525 	}
20526 
20527 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
20528 	for (i = 0; i < env->subprog_cnt; i++) {
20529 		int subprog_start = subprogs[i].start;
20530 		int stack_slots = subprogs[i].stack_extra / 8;
20531 
20532 		if (!stack_slots)
20533 			continue;
20534 		if (stack_slots > 1) {
20535 			verbose(env, "verifier bug: stack_slots supports may_goto only\n");
20536 			return -EFAULT;
20537 		}
20538 
20539 		/* Add ST insn to subprog prologue to init extra stack */
20540 		insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP,
20541 					 -subprogs[i].stack_depth, BPF_MAX_LOOPS);
20542 		/* Copy first actual insn to preserve it */
20543 		insn_buf[1] = env->prog->insnsi[subprog_start];
20544 
20545 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2);
20546 		if (!new_prog)
20547 			return -ENOMEM;
20548 		env->prog = prog = new_prog;
20549 	}
20550 
20551 	/* Since poke tab is now finalized, publish aux to tracker. */
20552 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
20553 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
20554 		if (!map_ptr->ops->map_poke_track ||
20555 		    !map_ptr->ops->map_poke_untrack ||
20556 		    !map_ptr->ops->map_poke_run) {
20557 			verbose(env, "bpf verifier is misconfigured\n");
20558 			return -EINVAL;
20559 		}
20560 
20561 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
20562 		if (ret < 0) {
20563 			verbose(env, "tracking tail call prog failed\n");
20564 			return ret;
20565 		}
20566 	}
20567 
20568 	sort_kfunc_descs_by_imm_off(env->prog);
20569 
20570 	return 0;
20571 }
20572 
20573 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
20574 					int position,
20575 					s32 stack_base,
20576 					u32 callback_subprogno,
20577 					u32 *cnt)
20578 {
20579 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
20580 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
20581 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
20582 	int reg_loop_max = BPF_REG_6;
20583 	int reg_loop_cnt = BPF_REG_7;
20584 	int reg_loop_ctx = BPF_REG_8;
20585 
20586 	struct bpf_prog *new_prog;
20587 	u32 callback_start;
20588 	u32 call_insn_offset;
20589 	s32 callback_offset;
20590 
20591 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
20592 	 * be careful to modify this code in sync.
20593 	 */
20594 	struct bpf_insn insn_buf[] = {
20595 		/* Return error and jump to the end of the patch if
20596 		 * expected number of iterations is too big.
20597 		 */
20598 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
20599 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
20600 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
20601 		/* spill R6, R7, R8 to use these as loop vars */
20602 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
20603 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
20604 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
20605 		/* initialize loop vars */
20606 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
20607 		BPF_MOV32_IMM(reg_loop_cnt, 0),
20608 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
20609 		/* loop header,
20610 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
20611 		 */
20612 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
20613 		/* callback call,
20614 		 * correct callback offset would be set after patching
20615 		 */
20616 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
20617 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
20618 		BPF_CALL_REL(0),
20619 		/* increment loop counter */
20620 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
20621 		/* jump to loop header if callback returned 0 */
20622 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
20623 		/* return value of bpf_loop,
20624 		 * set R0 to the number of iterations
20625 		 */
20626 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
20627 		/* restore original values of R6, R7, R8 */
20628 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
20629 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
20630 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
20631 	};
20632 
20633 	*cnt = ARRAY_SIZE(insn_buf);
20634 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
20635 	if (!new_prog)
20636 		return new_prog;
20637 
20638 	/* callback start is known only after patching */
20639 	callback_start = env->subprog_info[callback_subprogno].start;
20640 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
20641 	call_insn_offset = position + 12;
20642 	callback_offset = callback_start - call_insn_offset - 1;
20643 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
20644 
20645 	return new_prog;
20646 }
20647 
20648 static bool is_bpf_loop_call(struct bpf_insn *insn)
20649 {
20650 	return insn->code == (BPF_JMP | BPF_CALL) &&
20651 		insn->src_reg == 0 &&
20652 		insn->imm == BPF_FUNC_loop;
20653 }
20654 
20655 /* For all sub-programs in the program (including main) check
20656  * insn_aux_data to see if there are bpf_loop calls that require
20657  * inlining. If such calls are found the calls are replaced with a
20658  * sequence of instructions produced by `inline_bpf_loop` function and
20659  * subprog stack_depth is increased by the size of 3 registers.
20660  * This stack space is used to spill values of the R6, R7, R8.  These
20661  * registers are used to store the loop bound, counter and context
20662  * variables.
20663  */
20664 static int optimize_bpf_loop(struct bpf_verifier_env *env)
20665 {
20666 	struct bpf_subprog_info *subprogs = env->subprog_info;
20667 	int i, cur_subprog = 0, cnt, delta = 0;
20668 	struct bpf_insn *insn = env->prog->insnsi;
20669 	int insn_cnt = env->prog->len;
20670 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
20671 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20672 	u16 stack_depth_extra = 0;
20673 
20674 	for (i = 0; i < insn_cnt; i++, insn++) {
20675 		struct bpf_loop_inline_state *inline_state =
20676 			&env->insn_aux_data[i + delta].loop_inline_state;
20677 
20678 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
20679 			struct bpf_prog *new_prog;
20680 
20681 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
20682 			new_prog = inline_bpf_loop(env,
20683 						   i + delta,
20684 						   -(stack_depth + stack_depth_extra),
20685 						   inline_state->callback_subprogno,
20686 						   &cnt);
20687 			if (!new_prog)
20688 				return -ENOMEM;
20689 
20690 			delta     += cnt - 1;
20691 			env->prog  = new_prog;
20692 			insn       = new_prog->insnsi + i + delta;
20693 		}
20694 
20695 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20696 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
20697 			cur_subprog++;
20698 			stack_depth = subprogs[cur_subprog].stack_depth;
20699 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20700 			stack_depth_extra = 0;
20701 		}
20702 	}
20703 
20704 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20705 
20706 	return 0;
20707 }
20708 
20709 static void free_states(struct bpf_verifier_env *env)
20710 {
20711 	struct bpf_verifier_state_list *sl, *sln;
20712 	int i;
20713 
20714 	sl = env->free_list;
20715 	while (sl) {
20716 		sln = sl->next;
20717 		free_verifier_state(&sl->state, false);
20718 		kfree(sl);
20719 		sl = sln;
20720 	}
20721 	env->free_list = NULL;
20722 
20723 	if (!env->explored_states)
20724 		return;
20725 
20726 	for (i = 0; i < state_htab_size(env); i++) {
20727 		sl = env->explored_states[i];
20728 
20729 		while (sl) {
20730 			sln = sl->next;
20731 			free_verifier_state(&sl->state, false);
20732 			kfree(sl);
20733 			sl = sln;
20734 		}
20735 		env->explored_states[i] = NULL;
20736 	}
20737 }
20738 
20739 static int do_check_common(struct bpf_verifier_env *env, int subprog)
20740 {
20741 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20742 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
20743 	struct bpf_verifier_state *state;
20744 	struct bpf_reg_state *regs;
20745 	int ret, i;
20746 
20747 	env->prev_linfo = NULL;
20748 	env->pass_cnt++;
20749 
20750 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
20751 	if (!state)
20752 		return -ENOMEM;
20753 	state->curframe = 0;
20754 	state->speculative = false;
20755 	state->branches = 1;
20756 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
20757 	if (!state->frame[0]) {
20758 		kfree(state);
20759 		return -ENOMEM;
20760 	}
20761 	env->cur_state = state;
20762 	init_func_state(env, state->frame[0],
20763 			BPF_MAIN_FUNC /* callsite */,
20764 			0 /* frameno */,
20765 			subprog);
20766 	state->first_insn_idx = env->subprog_info[subprog].start;
20767 	state->last_insn_idx = -1;
20768 
20769 	regs = state->frame[state->curframe]->regs;
20770 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
20771 		const char *sub_name = subprog_name(env, subprog);
20772 		struct bpf_subprog_arg_info *arg;
20773 		struct bpf_reg_state *reg;
20774 
20775 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
20776 		ret = btf_prepare_func_args(env, subprog);
20777 		if (ret)
20778 			goto out;
20779 
20780 		if (subprog_is_exc_cb(env, subprog)) {
20781 			state->frame[0]->in_exception_callback_fn = true;
20782 			/* We have already ensured that the callback returns an integer, just
20783 			 * like all global subprogs. We need to determine it only has a single
20784 			 * scalar argument.
20785 			 */
20786 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
20787 				verbose(env, "exception cb only supports single integer argument\n");
20788 				ret = -EINVAL;
20789 				goto out;
20790 			}
20791 		}
20792 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
20793 			arg = &sub->args[i - BPF_REG_1];
20794 			reg = &regs[i];
20795 
20796 			if (arg->arg_type == ARG_PTR_TO_CTX) {
20797 				reg->type = PTR_TO_CTX;
20798 				mark_reg_known_zero(env, regs, i);
20799 			} else if (arg->arg_type == ARG_ANYTHING) {
20800 				reg->type = SCALAR_VALUE;
20801 				mark_reg_unknown(env, regs, i);
20802 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
20803 				/* assume unspecial LOCAL dynptr type */
20804 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
20805 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
20806 				reg->type = PTR_TO_MEM;
20807 				if (arg->arg_type & PTR_MAYBE_NULL)
20808 					reg->type |= PTR_MAYBE_NULL;
20809 				mark_reg_known_zero(env, regs, i);
20810 				reg->mem_size = arg->mem_size;
20811 				reg->id = ++env->id_gen;
20812 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
20813 				reg->type = PTR_TO_BTF_ID;
20814 				if (arg->arg_type & PTR_MAYBE_NULL)
20815 					reg->type |= PTR_MAYBE_NULL;
20816 				if (arg->arg_type & PTR_UNTRUSTED)
20817 					reg->type |= PTR_UNTRUSTED;
20818 				if (arg->arg_type & PTR_TRUSTED)
20819 					reg->type |= PTR_TRUSTED;
20820 				mark_reg_known_zero(env, regs, i);
20821 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
20822 				reg->btf_id = arg->btf_id;
20823 				reg->id = ++env->id_gen;
20824 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
20825 				/* caller can pass either PTR_TO_ARENA or SCALAR */
20826 				mark_reg_unknown(env, regs, i);
20827 			} else {
20828 				WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
20829 					  i - BPF_REG_1, arg->arg_type);
20830 				ret = -EFAULT;
20831 				goto out;
20832 			}
20833 		}
20834 	} else {
20835 		/* if main BPF program has associated BTF info, validate that
20836 		 * it's matching expected signature, and otherwise mark BTF
20837 		 * info for main program as unreliable
20838 		 */
20839 		if (env->prog->aux->func_info_aux) {
20840 			ret = btf_prepare_func_args(env, 0);
20841 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
20842 				env->prog->aux->func_info_aux[0].unreliable = true;
20843 		}
20844 
20845 		/* 1st arg to a function */
20846 		regs[BPF_REG_1].type = PTR_TO_CTX;
20847 		mark_reg_known_zero(env, regs, BPF_REG_1);
20848 	}
20849 
20850 	ret = do_check(env);
20851 out:
20852 	/* check for NULL is necessary, since cur_state can be freed inside
20853 	 * do_check() under memory pressure.
20854 	 */
20855 	if (env->cur_state) {
20856 		free_verifier_state(env->cur_state, true);
20857 		env->cur_state = NULL;
20858 	}
20859 	while (!pop_stack(env, NULL, NULL, false));
20860 	if (!ret && pop_log)
20861 		bpf_vlog_reset(&env->log, 0);
20862 	free_states(env);
20863 	return ret;
20864 }
20865 
20866 /* Lazily verify all global functions based on their BTF, if they are called
20867  * from main BPF program or any of subprograms transitively.
20868  * BPF global subprogs called from dead code are not validated.
20869  * All callable global functions must pass verification.
20870  * Otherwise the whole program is rejected.
20871  * Consider:
20872  * int bar(int);
20873  * int foo(int f)
20874  * {
20875  *    return bar(f);
20876  * }
20877  * int bar(int b)
20878  * {
20879  *    ...
20880  * }
20881  * foo() will be verified first for R1=any_scalar_value. During verification it
20882  * will be assumed that bar() already verified successfully and call to bar()
20883  * from foo() will be checked for type match only. Later bar() will be verified
20884  * independently to check that it's safe for R1=any_scalar_value.
20885  */
20886 static int do_check_subprogs(struct bpf_verifier_env *env)
20887 {
20888 	struct bpf_prog_aux *aux = env->prog->aux;
20889 	struct bpf_func_info_aux *sub_aux;
20890 	int i, ret, new_cnt;
20891 
20892 	if (!aux->func_info)
20893 		return 0;
20894 
20895 	/* exception callback is presumed to be always called */
20896 	if (env->exception_callback_subprog)
20897 		subprog_aux(env, env->exception_callback_subprog)->called = true;
20898 
20899 again:
20900 	new_cnt = 0;
20901 	for (i = 1; i < env->subprog_cnt; i++) {
20902 		if (!subprog_is_global(env, i))
20903 			continue;
20904 
20905 		sub_aux = subprog_aux(env, i);
20906 		if (!sub_aux->called || sub_aux->verified)
20907 			continue;
20908 
20909 		env->insn_idx = env->subprog_info[i].start;
20910 		WARN_ON_ONCE(env->insn_idx == 0);
20911 		ret = do_check_common(env, i);
20912 		if (ret) {
20913 			return ret;
20914 		} else if (env->log.level & BPF_LOG_LEVEL) {
20915 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
20916 				i, subprog_name(env, i));
20917 		}
20918 
20919 		/* We verified new global subprog, it might have called some
20920 		 * more global subprogs that we haven't verified yet, so we
20921 		 * need to do another pass over subprogs to verify those.
20922 		 */
20923 		sub_aux->verified = true;
20924 		new_cnt++;
20925 	}
20926 
20927 	/* We can't loop forever as we verify at least one global subprog on
20928 	 * each pass.
20929 	 */
20930 	if (new_cnt)
20931 		goto again;
20932 
20933 	return 0;
20934 }
20935 
20936 static int do_check_main(struct bpf_verifier_env *env)
20937 {
20938 	int ret;
20939 
20940 	env->insn_idx = 0;
20941 	ret = do_check_common(env, 0);
20942 	if (!ret)
20943 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20944 	return ret;
20945 }
20946 
20947 
20948 static void print_verification_stats(struct bpf_verifier_env *env)
20949 {
20950 	int i;
20951 
20952 	if (env->log.level & BPF_LOG_STATS) {
20953 		verbose(env, "verification time %lld usec\n",
20954 			div_u64(env->verification_time, 1000));
20955 		verbose(env, "stack depth ");
20956 		for (i = 0; i < env->subprog_cnt; i++) {
20957 			u32 depth = env->subprog_info[i].stack_depth;
20958 
20959 			verbose(env, "%d", depth);
20960 			if (i + 1 < env->subprog_cnt)
20961 				verbose(env, "+");
20962 		}
20963 		verbose(env, "\n");
20964 	}
20965 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
20966 		"total_states %d peak_states %d mark_read %d\n",
20967 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
20968 		env->max_states_per_insn, env->total_states,
20969 		env->peak_states, env->longest_mark_read_walk);
20970 }
20971 
20972 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
20973 {
20974 	const struct btf_type *t, *func_proto;
20975 	const struct bpf_struct_ops_desc *st_ops_desc;
20976 	const struct bpf_struct_ops *st_ops;
20977 	const struct btf_member *member;
20978 	struct bpf_prog *prog = env->prog;
20979 	u32 btf_id, member_idx;
20980 	struct btf *btf;
20981 	const char *mname;
20982 
20983 	if (!prog->gpl_compatible) {
20984 		verbose(env, "struct ops programs must have a GPL compatible license\n");
20985 		return -EINVAL;
20986 	}
20987 
20988 	if (!prog->aux->attach_btf_id)
20989 		return -ENOTSUPP;
20990 
20991 	btf = prog->aux->attach_btf;
20992 	if (btf_is_module(btf)) {
20993 		/* Make sure st_ops is valid through the lifetime of env */
20994 		env->attach_btf_mod = btf_try_get_module(btf);
20995 		if (!env->attach_btf_mod) {
20996 			verbose(env, "struct_ops module %s is not found\n",
20997 				btf_get_name(btf));
20998 			return -ENOTSUPP;
20999 		}
21000 	}
21001 
21002 	btf_id = prog->aux->attach_btf_id;
21003 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
21004 	if (!st_ops_desc) {
21005 		verbose(env, "attach_btf_id %u is not a supported struct\n",
21006 			btf_id);
21007 		return -ENOTSUPP;
21008 	}
21009 	st_ops = st_ops_desc->st_ops;
21010 
21011 	t = st_ops_desc->type;
21012 	member_idx = prog->expected_attach_type;
21013 	if (member_idx >= btf_type_vlen(t)) {
21014 		verbose(env, "attach to invalid member idx %u of struct %s\n",
21015 			member_idx, st_ops->name);
21016 		return -EINVAL;
21017 	}
21018 
21019 	member = &btf_type_member(t)[member_idx];
21020 	mname = btf_name_by_offset(btf, member->name_off);
21021 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
21022 					       NULL);
21023 	if (!func_proto) {
21024 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
21025 			mname, member_idx, st_ops->name);
21026 		return -EINVAL;
21027 	}
21028 
21029 	if (st_ops->check_member) {
21030 		int err = st_ops->check_member(t, member, prog);
21031 
21032 		if (err) {
21033 			verbose(env, "attach to unsupported member %s of struct %s\n",
21034 				mname, st_ops->name);
21035 			return err;
21036 		}
21037 	}
21038 
21039 	/* btf_ctx_access() used this to provide argument type info */
21040 	prog->aux->ctx_arg_info =
21041 		st_ops_desc->arg_info[member_idx].info;
21042 	prog->aux->ctx_arg_info_size =
21043 		st_ops_desc->arg_info[member_idx].cnt;
21044 
21045 	prog->aux->attach_func_proto = func_proto;
21046 	prog->aux->attach_func_name = mname;
21047 	env->ops = st_ops->verifier_ops;
21048 
21049 	return 0;
21050 }
21051 #define SECURITY_PREFIX "security_"
21052 
21053 static int check_attach_modify_return(unsigned long addr, const char *func_name)
21054 {
21055 	if (within_error_injection_list(addr) ||
21056 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
21057 		return 0;
21058 
21059 	return -EINVAL;
21060 }
21061 
21062 /* list of non-sleepable functions that are otherwise on
21063  * ALLOW_ERROR_INJECTION list
21064  */
21065 BTF_SET_START(btf_non_sleepable_error_inject)
21066 /* Three functions below can be called from sleepable and non-sleepable context.
21067  * Assume non-sleepable from bpf safety point of view.
21068  */
21069 BTF_ID(func, __filemap_add_folio)
21070 BTF_ID(func, should_fail_alloc_page)
21071 BTF_ID(func, should_failslab)
21072 BTF_SET_END(btf_non_sleepable_error_inject)
21073 
21074 static int check_non_sleepable_error_inject(u32 btf_id)
21075 {
21076 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
21077 }
21078 
21079 int bpf_check_attach_target(struct bpf_verifier_log *log,
21080 			    const struct bpf_prog *prog,
21081 			    const struct bpf_prog *tgt_prog,
21082 			    u32 btf_id,
21083 			    struct bpf_attach_target_info *tgt_info)
21084 {
21085 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
21086 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
21087 	const char prefix[] = "btf_trace_";
21088 	int ret = 0, subprog = -1, i;
21089 	const struct btf_type *t;
21090 	bool conservative = true;
21091 	const char *tname;
21092 	struct btf *btf;
21093 	long addr = 0;
21094 	struct module *mod = NULL;
21095 
21096 	if (!btf_id) {
21097 		bpf_log(log, "Tracing programs must provide btf_id\n");
21098 		return -EINVAL;
21099 	}
21100 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
21101 	if (!btf) {
21102 		bpf_log(log,
21103 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
21104 		return -EINVAL;
21105 	}
21106 	t = btf_type_by_id(btf, btf_id);
21107 	if (!t) {
21108 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
21109 		return -EINVAL;
21110 	}
21111 	tname = btf_name_by_offset(btf, t->name_off);
21112 	if (!tname) {
21113 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
21114 		return -EINVAL;
21115 	}
21116 	if (tgt_prog) {
21117 		struct bpf_prog_aux *aux = tgt_prog->aux;
21118 
21119 		if (bpf_prog_is_dev_bound(prog->aux) &&
21120 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
21121 			bpf_log(log, "Target program bound device mismatch");
21122 			return -EINVAL;
21123 		}
21124 
21125 		for (i = 0; i < aux->func_info_cnt; i++)
21126 			if (aux->func_info[i].type_id == btf_id) {
21127 				subprog = i;
21128 				break;
21129 			}
21130 		if (subprog == -1) {
21131 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
21132 			return -EINVAL;
21133 		}
21134 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
21135 			bpf_log(log,
21136 				"%s programs cannot attach to exception callback\n",
21137 				prog_extension ? "Extension" : "FENTRY/FEXIT");
21138 			return -EINVAL;
21139 		}
21140 		conservative = aux->func_info_aux[subprog].unreliable;
21141 		if (prog_extension) {
21142 			if (conservative) {
21143 				bpf_log(log,
21144 					"Cannot replace static functions\n");
21145 				return -EINVAL;
21146 			}
21147 			if (!prog->jit_requested) {
21148 				bpf_log(log,
21149 					"Extension programs should be JITed\n");
21150 				return -EINVAL;
21151 			}
21152 		}
21153 		if (!tgt_prog->jited) {
21154 			bpf_log(log, "Can attach to only JITed progs\n");
21155 			return -EINVAL;
21156 		}
21157 		if (prog_tracing) {
21158 			if (aux->attach_tracing_prog) {
21159 				/*
21160 				 * Target program is an fentry/fexit which is already attached
21161 				 * to another tracing program. More levels of nesting
21162 				 * attachment are not allowed.
21163 				 */
21164 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
21165 				return -EINVAL;
21166 			}
21167 		} else if (tgt_prog->type == prog->type) {
21168 			/*
21169 			 * To avoid potential call chain cycles, prevent attaching of a
21170 			 * program extension to another extension. It's ok to attach
21171 			 * fentry/fexit to extension program.
21172 			 */
21173 			bpf_log(log, "Cannot recursively attach\n");
21174 			return -EINVAL;
21175 		}
21176 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
21177 		    prog_extension &&
21178 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
21179 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
21180 			/* Program extensions can extend all program types
21181 			 * except fentry/fexit. The reason is the following.
21182 			 * The fentry/fexit programs are used for performance
21183 			 * analysis, stats and can be attached to any program
21184 			 * type. When extension program is replacing XDP function
21185 			 * it is necessary to allow performance analysis of all
21186 			 * functions. Both original XDP program and its program
21187 			 * extension. Hence attaching fentry/fexit to
21188 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
21189 			 * fentry/fexit was allowed it would be possible to create
21190 			 * long call chain fentry->extension->fentry->extension
21191 			 * beyond reasonable stack size. Hence extending fentry
21192 			 * is not allowed.
21193 			 */
21194 			bpf_log(log, "Cannot extend fentry/fexit\n");
21195 			return -EINVAL;
21196 		}
21197 	} else {
21198 		if (prog_extension) {
21199 			bpf_log(log, "Cannot replace kernel functions\n");
21200 			return -EINVAL;
21201 		}
21202 	}
21203 
21204 	switch (prog->expected_attach_type) {
21205 	case BPF_TRACE_RAW_TP:
21206 		if (tgt_prog) {
21207 			bpf_log(log,
21208 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
21209 			return -EINVAL;
21210 		}
21211 		if (!btf_type_is_typedef(t)) {
21212 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
21213 				btf_id);
21214 			return -EINVAL;
21215 		}
21216 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
21217 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
21218 				btf_id, tname);
21219 			return -EINVAL;
21220 		}
21221 		tname += sizeof(prefix) - 1;
21222 		t = btf_type_by_id(btf, t->type);
21223 		if (!btf_type_is_ptr(t))
21224 			/* should never happen in valid vmlinux build */
21225 			return -EINVAL;
21226 		t = btf_type_by_id(btf, t->type);
21227 		if (!btf_type_is_func_proto(t))
21228 			/* should never happen in valid vmlinux build */
21229 			return -EINVAL;
21230 
21231 		break;
21232 	case BPF_TRACE_ITER:
21233 		if (!btf_type_is_func(t)) {
21234 			bpf_log(log, "attach_btf_id %u is not a function\n",
21235 				btf_id);
21236 			return -EINVAL;
21237 		}
21238 		t = btf_type_by_id(btf, t->type);
21239 		if (!btf_type_is_func_proto(t))
21240 			return -EINVAL;
21241 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
21242 		if (ret)
21243 			return ret;
21244 		break;
21245 	default:
21246 		if (!prog_extension)
21247 			return -EINVAL;
21248 		fallthrough;
21249 	case BPF_MODIFY_RETURN:
21250 	case BPF_LSM_MAC:
21251 	case BPF_LSM_CGROUP:
21252 	case BPF_TRACE_FENTRY:
21253 	case BPF_TRACE_FEXIT:
21254 		if (!btf_type_is_func(t)) {
21255 			bpf_log(log, "attach_btf_id %u is not a function\n",
21256 				btf_id);
21257 			return -EINVAL;
21258 		}
21259 		if (prog_extension &&
21260 		    btf_check_type_match(log, prog, btf, t))
21261 			return -EINVAL;
21262 		t = btf_type_by_id(btf, t->type);
21263 		if (!btf_type_is_func_proto(t))
21264 			return -EINVAL;
21265 
21266 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
21267 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
21268 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
21269 			return -EINVAL;
21270 
21271 		if (tgt_prog && conservative)
21272 			t = NULL;
21273 
21274 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
21275 		if (ret < 0)
21276 			return ret;
21277 
21278 		if (tgt_prog) {
21279 			if (subprog == 0)
21280 				addr = (long) tgt_prog->bpf_func;
21281 			else
21282 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
21283 		} else {
21284 			if (btf_is_module(btf)) {
21285 				mod = btf_try_get_module(btf);
21286 				if (mod)
21287 					addr = find_kallsyms_symbol_value(mod, tname);
21288 				else
21289 					addr = 0;
21290 			} else {
21291 				addr = kallsyms_lookup_name(tname);
21292 			}
21293 			if (!addr) {
21294 				module_put(mod);
21295 				bpf_log(log,
21296 					"The address of function %s cannot be found\n",
21297 					tname);
21298 				return -ENOENT;
21299 			}
21300 		}
21301 
21302 		if (prog->sleepable) {
21303 			ret = -EINVAL;
21304 			switch (prog->type) {
21305 			case BPF_PROG_TYPE_TRACING:
21306 
21307 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
21308 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
21309 				 */
21310 				if (!check_non_sleepable_error_inject(btf_id) &&
21311 				    within_error_injection_list(addr))
21312 					ret = 0;
21313 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
21314 				 * in the fmodret id set with the KF_SLEEPABLE flag.
21315 				 */
21316 				else {
21317 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
21318 										prog);
21319 
21320 					if (flags && (*flags & KF_SLEEPABLE))
21321 						ret = 0;
21322 				}
21323 				break;
21324 			case BPF_PROG_TYPE_LSM:
21325 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
21326 				 * Only some of them are sleepable.
21327 				 */
21328 				if (bpf_lsm_is_sleepable_hook(btf_id))
21329 					ret = 0;
21330 				break;
21331 			default:
21332 				break;
21333 			}
21334 			if (ret) {
21335 				module_put(mod);
21336 				bpf_log(log, "%s is not sleepable\n", tname);
21337 				return ret;
21338 			}
21339 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
21340 			if (tgt_prog) {
21341 				module_put(mod);
21342 				bpf_log(log, "can't modify return codes of BPF programs\n");
21343 				return -EINVAL;
21344 			}
21345 			ret = -EINVAL;
21346 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
21347 			    !check_attach_modify_return(addr, tname))
21348 				ret = 0;
21349 			if (ret) {
21350 				module_put(mod);
21351 				bpf_log(log, "%s() is not modifiable\n", tname);
21352 				return ret;
21353 			}
21354 		}
21355 
21356 		break;
21357 	}
21358 	tgt_info->tgt_addr = addr;
21359 	tgt_info->tgt_name = tname;
21360 	tgt_info->tgt_type = t;
21361 	tgt_info->tgt_mod = mod;
21362 	return 0;
21363 }
21364 
21365 BTF_SET_START(btf_id_deny)
21366 BTF_ID_UNUSED
21367 #ifdef CONFIG_SMP
21368 BTF_ID(func, migrate_disable)
21369 BTF_ID(func, migrate_enable)
21370 #endif
21371 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
21372 BTF_ID(func, rcu_read_unlock_strict)
21373 #endif
21374 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
21375 BTF_ID(func, preempt_count_add)
21376 BTF_ID(func, preempt_count_sub)
21377 #endif
21378 #ifdef CONFIG_PREEMPT_RCU
21379 BTF_ID(func, __rcu_read_lock)
21380 BTF_ID(func, __rcu_read_unlock)
21381 #endif
21382 BTF_SET_END(btf_id_deny)
21383 
21384 static bool can_be_sleepable(struct bpf_prog *prog)
21385 {
21386 	if (prog->type == BPF_PROG_TYPE_TRACING) {
21387 		switch (prog->expected_attach_type) {
21388 		case BPF_TRACE_FENTRY:
21389 		case BPF_TRACE_FEXIT:
21390 		case BPF_MODIFY_RETURN:
21391 		case BPF_TRACE_ITER:
21392 			return true;
21393 		default:
21394 			return false;
21395 		}
21396 	}
21397 	return prog->type == BPF_PROG_TYPE_LSM ||
21398 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
21399 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
21400 }
21401 
21402 static int check_attach_btf_id(struct bpf_verifier_env *env)
21403 {
21404 	struct bpf_prog *prog = env->prog;
21405 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
21406 	struct bpf_attach_target_info tgt_info = {};
21407 	u32 btf_id = prog->aux->attach_btf_id;
21408 	struct bpf_trampoline *tr;
21409 	int ret;
21410 	u64 key;
21411 
21412 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
21413 		if (prog->sleepable)
21414 			/* attach_btf_id checked to be zero already */
21415 			return 0;
21416 		verbose(env, "Syscall programs can only be sleepable\n");
21417 		return -EINVAL;
21418 	}
21419 
21420 	if (prog->sleepable && !can_be_sleepable(prog)) {
21421 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
21422 		return -EINVAL;
21423 	}
21424 
21425 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
21426 		return check_struct_ops_btf_id(env);
21427 
21428 	if (prog->type != BPF_PROG_TYPE_TRACING &&
21429 	    prog->type != BPF_PROG_TYPE_LSM &&
21430 	    prog->type != BPF_PROG_TYPE_EXT)
21431 		return 0;
21432 
21433 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
21434 	if (ret)
21435 		return ret;
21436 
21437 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
21438 		/* to make freplace equivalent to their targets, they need to
21439 		 * inherit env->ops and expected_attach_type for the rest of the
21440 		 * verification
21441 		 */
21442 		env->ops = bpf_verifier_ops[tgt_prog->type];
21443 		prog->expected_attach_type = tgt_prog->expected_attach_type;
21444 	}
21445 
21446 	/* store info about the attachment target that will be used later */
21447 	prog->aux->attach_func_proto = tgt_info.tgt_type;
21448 	prog->aux->attach_func_name = tgt_info.tgt_name;
21449 	prog->aux->mod = tgt_info.tgt_mod;
21450 
21451 	if (tgt_prog) {
21452 		prog->aux->saved_dst_prog_type = tgt_prog->type;
21453 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
21454 	}
21455 
21456 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
21457 		prog->aux->attach_btf_trace = true;
21458 		return 0;
21459 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
21460 		if (!bpf_iter_prog_supported(prog))
21461 			return -EINVAL;
21462 		return 0;
21463 	}
21464 
21465 	if (prog->type == BPF_PROG_TYPE_LSM) {
21466 		ret = bpf_lsm_verify_prog(&env->log, prog);
21467 		if (ret < 0)
21468 			return ret;
21469 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
21470 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
21471 		return -EINVAL;
21472 	}
21473 
21474 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
21475 	tr = bpf_trampoline_get(key, &tgt_info);
21476 	if (!tr)
21477 		return -ENOMEM;
21478 
21479 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
21480 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
21481 
21482 	prog->aux->dst_trampoline = tr;
21483 	return 0;
21484 }
21485 
21486 struct btf *bpf_get_btf_vmlinux(void)
21487 {
21488 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
21489 		mutex_lock(&bpf_verifier_lock);
21490 		if (!btf_vmlinux)
21491 			btf_vmlinux = btf_parse_vmlinux();
21492 		mutex_unlock(&bpf_verifier_lock);
21493 	}
21494 	return btf_vmlinux;
21495 }
21496 
21497 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
21498 {
21499 	u64 start_time = ktime_get_ns();
21500 	struct bpf_verifier_env *env;
21501 	int i, len, ret = -EINVAL, err;
21502 	u32 log_true_size;
21503 	bool is_priv;
21504 
21505 	/* no program is valid */
21506 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
21507 		return -EINVAL;
21508 
21509 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
21510 	 * allocate/free it every time bpf_check() is called
21511 	 */
21512 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
21513 	if (!env)
21514 		return -ENOMEM;
21515 
21516 	env->bt.env = env;
21517 
21518 	len = (*prog)->len;
21519 	env->insn_aux_data =
21520 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
21521 	ret = -ENOMEM;
21522 	if (!env->insn_aux_data)
21523 		goto err_free_env;
21524 	for (i = 0; i < len; i++)
21525 		env->insn_aux_data[i].orig_idx = i;
21526 	env->prog = *prog;
21527 	env->ops = bpf_verifier_ops[env->prog->type];
21528 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
21529 
21530 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
21531 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
21532 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
21533 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
21534 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
21535 
21536 	bpf_get_btf_vmlinux();
21537 
21538 	/* grab the mutex to protect few globals used by verifier */
21539 	if (!is_priv)
21540 		mutex_lock(&bpf_verifier_lock);
21541 
21542 	/* user could have requested verbose verifier output
21543 	 * and supplied buffer to store the verification trace
21544 	 */
21545 	ret = bpf_vlog_init(&env->log, attr->log_level,
21546 			    (char __user *) (unsigned long) attr->log_buf,
21547 			    attr->log_size);
21548 	if (ret)
21549 		goto err_unlock;
21550 
21551 	mark_verifier_state_clean(env);
21552 
21553 	if (IS_ERR(btf_vmlinux)) {
21554 		/* Either gcc or pahole or kernel are broken. */
21555 		verbose(env, "in-kernel BTF is malformed\n");
21556 		ret = PTR_ERR(btf_vmlinux);
21557 		goto skip_full_check;
21558 	}
21559 
21560 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
21561 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
21562 		env->strict_alignment = true;
21563 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
21564 		env->strict_alignment = false;
21565 
21566 	if (is_priv)
21567 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
21568 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
21569 
21570 	env->explored_states = kvcalloc(state_htab_size(env),
21571 				       sizeof(struct bpf_verifier_state_list *),
21572 				       GFP_USER);
21573 	ret = -ENOMEM;
21574 	if (!env->explored_states)
21575 		goto skip_full_check;
21576 
21577 	ret = check_btf_info_early(env, attr, uattr);
21578 	if (ret < 0)
21579 		goto skip_full_check;
21580 
21581 	ret = add_subprog_and_kfunc(env);
21582 	if (ret < 0)
21583 		goto skip_full_check;
21584 
21585 	ret = check_subprogs(env);
21586 	if (ret < 0)
21587 		goto skip_full_check;
21588 
21589 	ret = check_btf_info(env, attr, uattr);
21590 	if (ret < 0)
21591 		goto skip_full_check;
21592 
21593 	ret = check_attach_btf_id(env);
21594 	if (ret)
21595 		goto skip_full_check;
21596 
21597 	ret = resolve_pseudo_ldimm64(env);
21598 	if (ret < 0)
21599 		goto skip_full_check;
21600 
21601 	if (bpf_prog_is_offloaded(env->prog->aux)) {
21602 		ret = bpf_prog_offload_verifier_prep(env->prog);
21603 		if (ret)
21604 			goto skip_full_check;
21605 	}
21606 
21607 	ret = check_cfg(env);
21608 	if (ret < 0)
21609 		goto skip_full_check;
21610 
21611 	ret = do_check_main(env);
21612 	ret = ret ?: do_check_subprogs(env);
21613 
21614 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
21615 		ret = bpf_prog_offload_finalize(env);
21616 
21617 skip_full_check:
21618 	kvfree(env->explored_states);
21619 
21620 	if (ret == 0)
21621 		ret = check_max_stack_depth(env);
21622 
21623 	/* instruction rewrites happen after this point */
21624 	if (ret == 0)
21625 		ret = optimize_bpf_loop(env);
21626 
21627 	if (is_priv) {
21628 		if (ret == 0)
21629 			opt_hard_wire_dead_code_branches(env);
21630 		if (ret == 0)
21631 			ret = opt_remove_dead_code(env);
21632 		if (ret == 0)
21633 			ret = opt_remove_nops(env);
21634 	} else {
21635 		if (ret == 0)
21636 			sanitize_dead_code(env);
21637 	}
21638 
21639 	if (ret == 0)
21640 		/* program is valid, convert *(u32*)(ctx + off) accesses */
21641 		ret = convert_ctx_accesses(env);
21642 
21643 	if (ret == 0)
21644 		ret = do_misc_fixups(env);
21645 
21646 	/* do 32-bit optimization after insn patching has done so those patched
21647 	 * insns could be handled correctly.
21648 	 */
21649 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
21650 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
21651 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
21652 								     : false;
21653 	}
21654 
21655 	if (ret == 0)
21656 		ret = fixup_call_args(env);
21657 
21658 	env->verification_time = ktime_get_ns() - start_time;
21659 	print_verification_stats(env);
21660 	env->prog->aux->verified_insns = env->insn_processed;
21661 
21662 	/* preserve original error even if log finalization is successful */
21663 	err = bpf_vlog_finalize(&env->log, &log_true_size);
21664 	if (err)
21665 		ret = err;
21666 
21667 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
21668 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
21669 				  &log_true_size, sizeof(log_true_size))) {
21670 		ret = -EFAULT;
21671 		goto err_release_maps;
21672 	}
21673 
21674 	if (ret)
21675 		goto err_release_maps;
21676 
21677 	if (env->used_map_cnt) {
21678 		/* if program passed verifier, update used_maps in bpf_prog_info */
21679 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
21680 							  sizeof(env->used_maps[0]),
21681 							  GFP_KERNEL);
21682 
21683 		if (!env->prog->aux->used_maps) {
21684 			ret = -ENOMEM;
21685 			goto err_release_maps;
21686 		}
21687 
21688 		memcpy(env->prog->aux->used_maps, env->used_maps,
21689 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
21690 		env->prog->aux->used_map_cnt = env->used_map_cnt;
21691 	}
21692 	if (env->used_btf_cnt) {
21693 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
21694 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
21695 							  sizeof(env->used_btfs[0]),
21696 							  GFP_KERNEL);
21697 		if (!env->prog->aux->used_btfs) {
21698 			ret = -ENOMEM;
21699 			goto err_release_maps;
21700 		}
21701 
21702 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
21703 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
21704 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
21705 	}
21706 	if (env->used_map_cnt || env->used_btf_cnt) {
21707 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
21708 		 * bpf_ld_imm64 instructions
21709 		 */
21710 		convert_pseudo_ld_imm64(env);
21711 	}
21712 
21713 	adjust_btf_func(env);
21714 
21715 err_release_maps:
21716 	if (!env->prog->aux->used_maps)
21717 		/* if we didn't copy map pointers into bpf_prog_info, release
21718 		 * them now. Otherwise free_used_maps() will release them.
21719 		 */
21720 		release_maps(env);
21721 	if (!env->prog->aux->used_btfs)
21722 		release_btfs(env);
21723 
21724 	/* extension progs temporarily inherit the attach_type of their targets
21725 	   for verification purposes, so set it back to zero before returning
21726 	 */
21727 	if (env->prog->type == BPF_PROG_TYPE_EXT)
21728 		env->prog->expected_attach_type = 0;
21729 
21730 	*prog = env->prog;
21731 
21732 	module_put(env->attach_btf_mod);
21733 err_unlock:
21734 	if (!is_priv)
21735 		mutex_unlock(&bpf_verifier_lock);
21736 	vfree(env->insn_aux_data);
21737 err_free_env:
21738 	kfree(env);
21739 	return ret;
21740 }
21741