xref: /linux-6.15/kernel/bpf/verifier.c (revision ff4b2bfa)
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 }
2372 
2373 #define DEF_NOT_SUBREG	(0)
2374 static void init_reg_state(struct bpf_verifier_env *env,
2375 			   struct bpf_func_state *state)
2376 {
2377 	struct bpf_reg_state *regs = state->regs;
2378 	int i;
2379 
2380 	for (i = 0; i < MAX_BPF_REG; i++) {
2381 		mark_reg_not_init(env, regs, i);
2382 		regs[i].live = REG_LIVE_NONE;
2383 		regs[i].parent = NULL;
2384 		regs[i].subreg_def = DEF_NOT_SUBREG;
2385 	}
2386 
2387 	/* frame pointer */
2388 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2389 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2390 	regs[BPF_REG_FP].frameno = state->frameno;
2391 }
2392 
2393 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2394 {
2395 	return (struct bpf_retval_range){ minval, maxval };
2396 }
2397 
2398 #define BPF_MAIN_FUNC (-1)
2399 static void init_func_state(struct bpf_verifier_env *env,
2400 			    struct bpf_func_state *state,
2401 			    int callsite, int frameno, int subprogno)
2402 {
2403 	state->callsite = callsite;
2404 	state->frameno = frameno;
2405 	state->subprogno = subprogno;
2406 	state->callback_ret_range = retval_range(0, 0);
2407 	init_reg_state(env, state);
2408 	mark_verifier_state_scratched(env);
2409 }
2410 
2411 /* Similar to push_stack(), but for async callbacks */
2412 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2413 						int insn_idx, int prev_insn_idx,
2414 						int subprog, bool is_sleepable)
2415 {
2416 	struct bpf_verifier_stack_elem *elem;
2417 	struct bpf_func_state *frame;
2418 
2419 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2420 	if (!elem)
2421 		goto err;
2422 
2423 	elem->insn_idx = insn_idx;
2424 	elem->prev_insn_idx = prev_insn_idx;
2425 	elem->next = env->head;
2426 	elem->log_pos = env->log.end_pos;
2427 	env->head = elem;
2428 	env->stack_size++;
2429 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2430 		verbose(env,
2431 			"The sequence of %d jumps is too complex for async cb.\n",
2432 			env->stack_size);
2433 		goto err;
2434 	}
2435 	/* Unlike push_stack() do not copy_verifier_state().
2436 	 * The caller state doesn't matter.
2437 	 * This is async callback. It starts in a fresh stack.
2438 	 * Initialize it similar to do_check_common().
2439 	 */
2440 	elem->st.branches = 1;
2441 	elem->st.in_sleepable = is_sleepable;
2442 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2443 	if (!frame)
2444 		goto err;
2445 	init_func_state(env, frame,
2446 			BPF_MAIN_FUNC /* callsite */,
2447 			0 /* frameno within this callchain */,
2448 			subprog /* subprog number within this prog */);
2449 	elem->st.frame[0] = frame;
2450 	return &elem->st;
2451 err:
2452 	free_verifier_state(env->cur_state, true);
2453 	env->cur_state = NULL;
2454 	/* pop all elements and return */
2455 	while (!pop_stack(env, NULL, NULL, false));
2456 	return NULL;
2457 }
2458 
2459 
2460 enum reg_arg_type {
2461 	SRC_OP,		/* register is used as source operand */
2462 	DST_OP,		/* register is used as destination operand */
2463 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2464 };
2465 
2466 static int cmp_subprogs(const void *a, const void *b)
2467 {
2468 	return ((struct bpf_subprog_info *)a)->start -
2469 	       ((struct bpf_subprog_info *)b)->start;
2470 }
2471 
2472 static int find_subprog(struct bpf_verifier_env *env, int off)
2473 {
2474 	struct bpf_subprog_info *p;
2475 
2476 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2477 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2478 	if (!p)
2479 		return -ENOENT;
2480 	return p - env->subprog_info;
2481 
2482 }
2483 
2484 static int add_subprog(struct bpf_verifier_env *env, int off)
2485 {
2486 	int insn_cnt = env->prog->len;
2487 	int ret;
2488 
2489 	if (off >= insn_cnt || off < 0) {
2490 		verbose(env, "call to invalid destination\n");
2491 		return -EINVAL;
2492 	}
2493 	ret = find_subprog(env, off);
2494 	if (ret >= 0)
2495 		return ret;
2496 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2497 		verbose(env, "too many subprograms\n");
2498 		return -E2BIG;
2499 	}
2500 	/* determine subprog starts. The end is one before the next starts */
2501 	env->subprog_info[env->subprog_cnt++].start = off;
2502 	sort(env->subprog_info, env->subprog_cnt,
2503 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2504 	return env->subprog_cnt - 1;
2505 }
2506 
2507 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2508 {
2509 	struct bpf_prog_aux *aux = env->prog->aux;
2510 	struct btf *btf = aux->btf;
2511 	const struct btf_type *t;
2512 	u32 main_btf_id, id;
2513 	const char *name;
2514 	int ret, i;
2515 
2516 	/* Non-zero func_info_cnt implies valid btf */
2517 	if (!aux->func_info_cnt)
2518 		return 0;
2519 	main_btf_id = aux->func_info[0].type_id;
2520 
2521 	t = btf_type_by_id(btf, main_btf_id);
2522 	if (!t) {
2523 		verbose(env, "invalid btf id for main subprog in func_info\n");
2524 		return -EINVAL;
2525 	}
2526 
2527 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2528 	if (IS_ERR(name)) {
2529 		ret = PTR_ERR(name);
2530 		/* If there is no tag present, there is no exception callback */
2531 		if (ret == -ENOENT)
2532 			ret = 0;
2533 		else if (ret == -EEXIST)
2534 			verbose(env, "multiple exception callback tags for main subprog\n");
2535 		return ret;
2536 	}
2537 
2538 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2539 	if (ret < 0) {
2540 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2541 		return ret;
2542 	}
2543 	id = ret;
2544 	t = btf_type_by_id(btf, id);
2545 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2546 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2547 		return -EINVAL;
2548 	}
2549 	ret = 0;
2550 	for (i = 0; i < aux->func_info_cnt; i++) {
2551 		if (aux->func_info[i].type_id != id)
2552 			continue;
2553 		ret = aux->func_info[i].insn_off;
2554 		/* Further func_info and subprog checks will also happen
2555 		 * later, so assume this is the right insn_off for now.
2556 		 */
2557 		if (!ret) {
2558 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2559 			ret = -EINVAL;
2560 		}
2561 	}
2562 	if (!ret) {
2563 		verbose(env, "exception callback type id not found in func_info\n");
2564 		ret = -EINVAL;
2565 	}
2566 	return ret;
2567 }
2568 
2569 #define MAX_KFUNC_DESCS 256
2570 #define MAX_KFUNC_BTFS	256
2571 
2572 struct bpf_kfunc_desc {
2573 	struct btf_func_model func_model;
2574 	u32 func_id;
2575 	s32 imm;
2576 	u16 offset;
2577 	unsigned long addr;
2578 };
2579 
2580 struct bpf_kfunc_btf {
2581 	struct btf *btf;
2582 	struct module *module;
2583 	u16 offset;
2584 };
2585 
2586 struct bpf_kfunc_desc_tab {
2587 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2588 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2589 	 * available, therefore at the end of verification do_misc_fixups()
2590 	 * sorts this by imm and offset.
2591 	 */
2592 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2593 	u32 nr_descs;
2594 };
2595 
2596 struct bpf_kfunc_btf_tab {
2597 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2598 	u32 nr_descs;
2599 };
2600 
2601 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2602 {
2603 	const struct bpf_kfunc_desc *d0 = a;
2604 	const struct bpf_kfunc_desc *d1 = b;
2605 
2606 	/* func_id is not greater than BTF_MAX_TYPE */
2607 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2608 }
2609 
2610 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2611 {
2612 	const struct bpf_kfunc_btf *d0 = a;
2613 	const struct bpf_kfunc_btf *d1 = b;
2614 
2615 	return d0->offset - d1->offset;
2616 }
2617 
2618 static const struct bpf_kfunc_desc *
2619 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2620 {
2621 	struct bpf_kfunc_desc desc = {
2622 		.func_id = func_id,
2623 		.offset = offset,
2624 	};
2625 	struct bpf_kfunc_desc_tab *tab;
2626 
2627 	tab = prog->aux->kfunc_tab;
2628 	return bsearch(&desc, tab->descs, tab->nr_descs,
2629 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2630 }
2631 
2632 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2633 		       u16 btf_fd_idx, u8 **func_addr)
2634 {
2635 	const struct bpf_kfunc_desc *desc;
2636 
2637 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2638 	if (!desc)
2639 		return -EFAULT;
2640 
2641 	*func_addr = (u8 *)desc->addr;
2642 	return 0;
2643 }
2644 
2645 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2646 					 s16 offset)
2647 {
2648 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2649 	struct bpf_kfunc_btf_tab *tab;
2650 	struct bpf_kfunc_btf *b;
2651 	struct module *mod;
2652 	struct btf *btf;
2653 	int btf_fd;
2654 
2655 	tab = env->prog->aux->kfunc_btf_tab;
2656 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2657 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2658 	if (!b) {
2659 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2660 			verbose(env, "too many different module BTFs\n");
2661 			return ERR_PTR(-E2BIG);
2662 		}
2663 
2664 		if (bpfptr_is_null(env->fd_array)) {
2665 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2666 			return ERR_PTR(-EPROTO);
2667 		}
2668 
2669 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2670 					    offset * sizeof(btf_fd),
2671 					    sizeof(btf_fd)))
2672 			return ERR_PTR(-EFAULT);
2673 
2674 		btf = btf_get_by_fd(btf_fd);
2675 		if (IS_ERR(btf)) {
2676 			verbose(env, "invalid module BTF fd specified\n");
2677 			return btf;
2678 		}
2679 
2680 		if (!btf_is_module(btf)) {
2681 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2682 			btf_put(btf);
2683 			return ERR_PTR(-EINVAL);
2684 		}
2685 
2686 		mod = btf_try_get_module(btf);
2687 		if (!mod) {
2688 			btf_put(btf);
2689 			return ERR_PTR(-ENXIO);
2690 		}
2691 
2692 		b = &tab->descs[tab->nr_descs++];
2693 		b->btf = btf;
2694 		b->module = mod;
2695 		b->offset = offset;
2696 
2697 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2698 		     kfunc_btf_cmp_by_off, NULL);
2699 	}
2700 	return b->btf;
2701 }
2702 
2703 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2704 {
2705 	if (!tab)
2706 		return;
2707 
2708 	while (tab->nr_descs--) {
2709 		module_put(tab->descs[tab->nr_descs].module);
2710 		btf_put(tab->descs[tab->nr_descs].btf);
2711 	}
2712 	kfree(tab);
2713 }
2714 
2715 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2716 {
2717 	if (offset) {
2718 		if (offset < 0) {
2719 			/* In the future, this can be allowed to increase limit
2720 			 * of fd index into fd_array, interpreted as u16.
2721 			 */
2722 			verbose(env, "negative offset disallowed for kernel module function call\n");
2723 			return ERR_PTR(-EINVAL);
2724 		}
2725 
2726 		return __find_kfunc_desc_btf(env, offset);
2727 	}
2728 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2729 }
2730 
2731 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2732 {
2733 	const struct btf_type *func, *func_proto;
2734 	struct bpf_kfunc_btf_tab *btf_tab;
2735 	struct bpf_kfunc_desc_tab *tab;
2736 	struct bpf_prog_aux *prog_aux;
2737 	struct bpf_kfunc_desc *desc;
2738 	const char *func_name;
2739 	struct btf *desc_btf;
2740 	unsigned long call_imm;
2741 	unsigned long addr;
2742 	int err;
2743 
2744 	prog_aux = env->prog->aux;
2745 	tab = prog_aux->kfunc_tab;
2746 	btf_tab = prog_aux->kfunc_btf_tab;
2747 	if (!tab) {
2748 		if (!btf_vmlinux) {
2749 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2750 			return -ENOTSUPP;
2751 		}
2752 
2753 		if (!env->prog->jit_requested) {
2754 			verbose(env, "JIT is required for calling kernel function\n");
2755 			return -ENOTSUPP;
2756 		}
2757 
2758 		if (!bpf_jit_supports_kfunc_call()) {
2759 			verbose(env, "JIT does not support calling kernel function\n");
2760 			return -ENOTSUPP;
2761 		}
2762 
2763 		if (!env->prog->gpl_compatible) {
2764 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2765 			return -EINVAL;
2766 		}
2767 
2768 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2769 		if (!tab)
2770 			return -ENOMEM;
2771 		prog_aux->kfunc_tab = tab;
2772 	}
2773 
2774 	/* func_id == 0 is always invalid, but instead of returning an error, be
2775 	 * conservative and wait until the code elimination pass before returning
2776 	 * error, so that invalid calls that get pruned out can be in BPF programs
2777 	 * loaded from userspace.  It is also required that offset be untouched
2778 	 * for such calls.
2779 	 */
2780 	if (!func_id && !offset)
2781 		return 0;
2782 
2783 	if (!btf_tab && offset) {
2784 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2785 		if (!btf_tab)
2786 			return -ENOMEM;
2787 		prog_aux->kfunc_btf_tab = btf_tab;
2788 	}
2789 
2790 	desc_btf = find_kfunc_desc_btf(env, offset);
2791 	if (IS_ERR(desc_btf)) {
2792 		verbose(env, "failed to find BTF for kernel function\n");
2793 		return PTR_ERR(desc_btf);
2794 	}
2795 
2796 	if (find_kfunc_desc(env->prog, func_id, offset))
2797 		return 0;
2798 
2799 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2800 		verbose(env, "too many different kernel function calls\n");
2801 		return -E2BIG;
2802 	}
2803 
2804 	func = btf_type_by_id(desc_btf, func_id);
2805 	if (!func || !btf_type_is_func(func)) {
2806 		verbose(env, "kernel btf_id %u is not a function\n",
2807 			func_id);
2808 		return -EINVAL;
2809 	}
2810 	func_proto = btf_type_by_id(desc_btf, func->type);
2811 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2812 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2813 			func_id);
2814 		return -EINVAL;
2815 	}
2816 
2817 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2818 	addr = kallsyms_lookup_name(func_name);
2819 	if (!addr) {
2820 		verbose(env, "cannot find address for kernel function %s\n",
2821 			func_name);
2822 		return -EINVAL;
2823 	}
2824 	specialize_kfunc(env, func_id, offset, &addr);
2825 
2826 	if (bpf_jit_supports_far_kfunc_call()) {
2827 		call_imm = func_id;
2828 	} else {
2829 		call_imm = BPF_CALL_IMM(addr);
2830 		/* Check whether the relative offset overflows desc->imm */
2831 		if ((unsigned long)(s32)call_imm != call_imm) {
2832 			verbose(env, "address of kernel function %s is out of range\n",
2833 				func_name);
2834 			return -EINVAL;
2835 		}
2836 	}
2837 
2838 	if (bpf_dev_bound_kfunc_id(func_id)) {
2839 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2840 		if (err)
2841 			return err;
2842 	}
2843 
2844 	desc = &tab->descs[tab->nr_descs++];
2845 	desc->func_id = func_id;
2846 	desc->imm = call_imm;
2847 	desc->offset = offset;
2848 	desc->addr = addr;
2849 	err = btf_distill_func_proto(&env->log, desc_btf,
2850 				     func_proto, func_name,
2851 				     &desc->func_model);
2852 	if (!err)
2853 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2854 		     kfunc_desc_cmp_by_id_off, NULL);
2855 	return err;
2856 }
2857 
2858 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2859 {
2860 	const struct bpf_kfunc_desc *d0 = a;
2861 	const struct bpf_kfunc_desc *d1 = b;
2862 
2863 	if (d0->imm != d1->imm)
2864 		return d0->imm < d1->imm ? -1 : 1;
2865 	if (d0->offset != d1->offset)
2866 		return d0->offset < d1->offset ? -1 : 1;
2867 	return 0;
2868 }
2869 
2870 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2871 {
2872 	struct bpf_kfunc_desc_tab *tab;
2873 
2874 	tab = prog->aux->kfunc_tab;
2875 	if (!tab)
2876 		return;
2877 
2878 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2879 	     kfunc_desc_cmp_by_imm_off, NULL);
2880 }
2881 
2882 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2883 {
2884 	return !!prog->aux->kfunc_tab;
2885 }
2886 
2887 const struct btf_func_model *
2888 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2889 			 const struct bpf_insn *insn)
2890 {
2891 	const struct bpf_kfunc_desc desc = {
2892 		.imm = insn->imm,
2893 		.offset = insn->off,
2894 	};
2895 	const struct bpf_kfunc_desc *res;
2896 	struct bpf_kfunc_desc_tab *tab;
2897 
2898 	tab = prog->aux->kfunc_tab;
2899 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2900 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2901 
2902 	return res ? &res->func_model : NULL;
2903 }
2904 
2905 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2906 {
2907 	struct bpf_subprog_info *subprog = env->subprog_info;
2908 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2909 	struct bpf_insn *insn = env->prog->insnsi;
2910 
2911 	/* Add entry function. */
2912 	ret = add_subprog(env, 0);
2913 	if (ret)
2914 		return ret;
2915 
2916 	for (i = 0; i < insn_cnt; i++, insn++) {
2917 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2918 		    !bpf_pseudo_kfunc_call(insn))
2919 			continue;
2920 
2921 		if (!env->bpf_capable) {
2922 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2923 			return -EPERM;
2924 		}
2925 
2926 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2927 			ret = add_subprog(env, i + insn->imm + 1);
2928 		else
2929 			ret = add_kfunc_call(env, insn->imm, insn->off);
2930 
2931 		if (ret < 0)
2932 			return ret;
2933 	}
2934 
2935 	ret = bpf_find_exception_callback_insn_off(env);
2936 	if (ret < 0)
2937 		return ret;
2938 	ex_cb_insn = ret;
2939 
2940 	/* If ex_cb_insn > 0, this means that the main program has a subprog
2941 	 * marked using BTF decl tag to serve as the exception callback.
2942 	 */
2943 	if (ex_cb_insn) {
2944 		ret = add_subprog(env, ex_cb_insn);
2945 		if (ret < 0)
2946 			return ret;
2947 		for (i = 1; i < env->subprog_cnt; i++) {
2948 			if (env->subprog_info[i].start != ex_cb_insn)
2949 				continue;
2950 			env->exception_callback_subprog = i;
2951 			mark_subprog_exc_cb(env, i);
2952 			break;
2953 		}
2954 	}
2955 
2956 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2957 	 * logic. 'subprog_cnt' should not be increased.
2958 	 */
2959 	subprog[env->subprog_cnt].start = insn_cnt;
2960 
2961 	if (env->log.level & BPF_LOG_LEVEL2)
2962 		for (i = 0; i < env->subprog_cnt; i++)
2963 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2964 
2965 	return 0;
2966 }
2967 
2968 static int check_subprogs(struct bpf_verifier_env *env)
2969 {
2970 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2971 	struct bpf_subprog_info *subprog = env->subprog_info;
2972 	struct bpf_insn *insn = env->prog->insnsi;
2973 	int insn_cnt = env->prog->len;
2974 
2975 	/* now check that all jumps are within the same subprog */
2976 	subprog_start = subprog[cur_subprog].start;
2977 	subprog_end = subprog[cur_subprog + 1].start;
2978 	for (i = 0; i < insn_cnt; i++) {
2979 		u8 code = insn[i].code;
2980 
2981 		if (code == (BPF_JMP | BPF_CALL) &&
2982 		    insn[i].src_reg == 0 &&
2983 		    insn[i].imm == BPF_FUNC_tail_call)
2984 			subprog[cur_subprog].has_tail_call = true;
2985 		if (BPF_CLASS(code) == BPF_LD &&
2986 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2987 			subprog[cur_subprog].has_ld_abs = true;
2988 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2989 			goto next;
2990 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2991 			goto next;
2992 		if (code == (BPF_JMP32 | BPF_JA))
2993 			off = i + insn[i].imm + 1;
2994 		else
2995 			off = i + insn[i].off + 1;
2996 		if (off < subprog_start || off >= subprog_end) {
2997 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2998 			return -EINVAL;
2999 		}
3000 next:
3001 		if (i == subprog_end - 1) {
3002 			/* to avoid fall-through from one subprog into another
3003 			 * the last insn of the subprog should be either exit
3004 			 * or unconditional jump back or bpf_throw call
3005 			 */
3006 			if (code != (BPF_JMP | BPF_EXIT) &&
3007 			    code != (BPF_JMP32 | BPF_JA) &&
3008 			    code != (BPF_JMP | BPF_JA)) {
3009 				verbose(env, "last insn is not an exit or jmp\n");
3010 				return -EINVAL;
3011 			}
3012 			subprog_start = subprog_end;
3013 			cur_subprog++;
3014 			if (cur_subprog < env->subprog_cnt)
3015 				subprog_end = subprog[cur_subprog + 1].start;
3016 		}
3017 	}
3018 	return 0;
3019 }
3020 
3021 /* Parentage chain of this register (or stack slot) should take care of all
3022  * issues like callee-saved registers, stack slot allocation time, etc.
3023  */
3024 static int mark_reg_read(struct bpf_verifier_env *env,
3025 			 const struct bpf_reg_state *state,
3026 			 struct bpf_reg_state *parent, u8 flag)
3027 {
3028 	bool writes = parent == state->parent; /* Observe write marks */
3029 	int cnt = 0;
3030 
3031 	while (parent) {
3032 		/* if read wasn't screened by an earlier write ... */
3033 		if (writes && state->live & REG_LIVE_WRITTEN)
3034 			break;
3035 		if (parent->live & REG_LIVE_DONE) {
3036 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3037 				reg_type_str(env, parent->type),
3038 				parent->var_off.value, parent->off);
3039 			return -EFAULT;
3040 		}
3041 		/* The first condition is more likely to be true than the
3042 		 * second, checked it first.
3043 		 */
3044 		if ((parent->live & REG_LIVE_READ) == flag ||
3045 		    parent->live & REG_LIVE_READ64)
3046 			/* The parentage chain never changes and
3047 			 * this parent was already marked as LIVE_READ.
3048 			 * There is no need to keep walking the chain again and
3049 			 * keep re-marking all parents as LIVE_READ.
3050 			 * This case happens when the same register is read
3051 			 * multiple times without writes into it in-between.
3052 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3053 			 * then no need to set the weak REG_LIVE_READ32.
3054 			 */
3055 			break;
3056 		/* ... then we depend on parent's value */
3057 		parent->live |= flag;
3058 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3059 		if (flag == REG_LIVE_READ64)
3060 			parent->live &= ~REG_LIVE_READ32;
3061 		state = parent;
3062 		parent = state->parent;
3063 		writes = true;
3064 		cnt++;
3065 	}
3066 
3067 	if (env->longest_mark_read_walk < cnt)
3068 		env->longest_mark_read_walk = cnt;
3069 	return 0;
3070 }
3071 
3072 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3073 {
3074 	struct bpf_func_state *state = func(env, reg);
3075 	int spi, ret;
3076 
3077 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3078 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3079 	 * check_kfunc_call.
3080 	 */
3081 	if (reg->type == CONST_PTR_TO_DYNPTR)
3082 		return 0;
3083 	spi = dynptr_get_spi(env, reg);
3084 	if (spi < 0)
3085 		return spi;
3086 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3087 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3088 	 * read.
3089 	 */
3090 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3091 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3092 	if (ret)
3093 		return ret;
3094 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3095 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3096 }
3097 
3098 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3099 			  int spi, int nr_slots)
3100 {
3101 	struct bpf_func_state *state = func(env, reg);
3102 	int err, i;
3103 
3104 	for (i = 0; i < nr_slots; i++) {
3105 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3106 
3107 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3108 		if (err)
3109 			return err;
3110 
3111 		mark_stack_slot_scratched(env, spi - i);
3112 	}
3113 
3114 	return 0;
3115 }
3116 
3117 /* This function is supposed to be used by the following 32-bit optimization
3118  * code only. It returns TRUE if the source or destination register operates
3119  * on 64-bit, otherwise return FALSE.
3120  */
3121 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3122 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3123 {
3124 	u8 code, class, op;
3125 
3126 	code = insn->code;
3127 	class = BPF_CLASS(code);
3128 	op = BPF_OP(code);
3129 	if (class == BPF_JMP) {
3130 		/* BPF_EXIT for "main" will reach here. Return TRUE
3131 		 * conservatively.
3132 		 */
3133 		if (op == BPF_EXIT)
3134 			return true;
3135 		if (op == BPF_CALL) {
3136 			/* BPF to BPF call will reach here because of marking
3137 			 * caller saved clobber with DST_OP_NO_MARK for which we
3138 			 * don't care the register def because they are anyway
3139 			 * marked as NOT_INIT already.
3140 			 */
3141 			if (insn->src_reg == BPF_PSEUDO_CALL)
3142 				return false;
3143 			/* Helper call will reach here because of arg type
3144 			 * check, conservatively return TRUE.
3145 			 */
3146 			if (t == SRC_OP)
3147 				return true;
3148 
3149 			return false;
3150 		}
3151 	}
3152 
3153 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3154 		return false;
3155 
3156 	if (class == BPF_ALU64 || class == BPF_JMP ||
3157 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3158 		return true;
3159 
3160 	if (class == BPF_ALU || class == BPF_JMP32)
3161 		return false;
3162 
3163 	if (class == BPF_LDX) {
3164 		if (t != SRC_OP)
3165 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3166 		/* LDX source must be ptr. */
3167 		return true;
3168 	}
3169 
3170 	if (class == BPF_STX) {
3171 		/* BPF_STX (including atomic variants) has multiple source
3172 		 * operands, one of which is a ptr. Check whether the caller is
3173 		 * asking about it.
3174 		 */
3175 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3176 			return true;
3177 		return BPF_SIZE(code) == BPF_DW;
3178 	}
3179 
3180 	if (class == BPF_LD) {
3181 		u8 mode = BPF_MODE(code);
3182 
3183 		/* LD_IMM64 */
3184 		if (mode == BPF_IMM)
3185 			return true;
3186 
3187 		/* Both LD_IND and LD_ABS return 32-bit data. */
3188 		if (t != SRC_OP)
3189 			return  false;
3190 
3191 		/* Implicit ctx ptr. */
3192 		if (regno == BPF_REG_6)
3193 			return true;
3194 
3195 		/* Explicit source could be any width. */
3196 		return true;
3197 	}
3198 
3199 	if (class == BPF_ST)
3200 		/* The only source register for BPF_ST is a ptr. */
3201 		return true;
3202 
3203 	/* Conservatively return true at default. */
3204 	return true;
3205 }
3206 
3207 /* Return the regno defined by the insn, or -1. */
3208 static int insn_def_regno(const struct bpf_insn *insn)
3209 {
3210 	switch (BPF_CLASS(insn->code)) {
3211 	case BPF_JMP:
3212 	case BPF_JMP32:
3213 	case BPF_ST:
3214 		return -1;
3215 	case BPF_STX:
3216 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3217 		    (insn->imm & BPF_FETCH)) {
3218 			if (insn->imm == BPF_CMPXCHG)
3219 				return BPF_REG_0;
3220 			else
3221 				return insn->src_reg;
3222 		} else {
3223 			return -1;
3224 		}
3225 	default:
3226 		return insn->dst_reg;
3227 	}
3228 }
3229 
3230 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3231 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3232 {
3233 	int dst_reg = insn_def_regno(insn);
3234 
3235 	if (dst_reg == -1)
3236 		return false;
3237 
3238 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3239 }
3240 
3241 static void mark_insn_zext(struct bpf_verifier_env *env,
3242 			   struct bpf_reg_state *reg)
3243 {
3244 	s32 def_idx = reg->subreg_def;
3245 
3246 	if (def_idx == DEF_NOT_SUBREG)
3247 		return;
3248 
3249 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3250 	/* The dst will be zero extended, so won't be sub-register anymore. */
3251 	reg->subreg_def = DEF_NOT_SUBREG;
3252 }
3253 
3254 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3255 			   enum reg_arg_type t)
3256 {
3257 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3258 	struct bpf_reg_state *reg;
3259 	bool rw64;
3260 
3261 	if (regno >= MAX_BPF_REG) {
3262 		verbose(env, "R%d is invalid\n", regno);
3263 		return -EINVAL;
3264 	}
3265 
3266 	mark_reg_scratched(env, regno);
3267 
3268 	reg = &regs[regno];
3269 	rw64 = is_reg64(env, insn, regno, reg, t);
3270 	if (t == SRC_OP) {
3271 		/* check whether register used as source operand can be read */
3272 		if (reg->type == NOT_INIT) {
3273 			verbose(env, "R%d !read_ok\n", regno);
3274 			return -EACCES;
3275 		}
3276 		/* We don't need to worry about FP liveness because it's read-only */
3277 		if (regno == BPF_REG_FP)
3278 			return 0;
3279 
3280 		if (rw64)
3281 			mark_insn_zext(env, reg);
3282 
3283 		return mark_reg_read(env, reg, reg->parent,
3284 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3285 	} else {
3286 		/* check whether register used as dest operand can be written to */
3287 		if (regno == BPF_REG_FP) {
3288 			verbose(env, "frame pointer is read only\n");
3289 			return -EACCES;
3290 		}
3291 		reg->live |= REG_LIVE_WRITTEN;
3292 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3293 		if (t == DST_OP)
3294 			mark_reg_unknown(env, regs, regno);
3295 	}
3296 	return 0;
3297 }
3298 
3299 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3300 			 enum reg_arg_type t)
3301 {
3302 	struct bpf_verifier_state *vstate = env->cur_state;
3303 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3304 
3305 	return __check_reg_arg(env, state->regs, regno, t);
3306 }
3307 
3308 static int insn_stack_access_flags(int frameno, int spi)
3309 {
3310 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3311 }
3312 
3313 static int insn_stack_access_spi(int insn_flags)
3314 {
3315 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3316 }
3317 
3318 static int insn_stack_access_frameno(int insn_flags)
3319 {
3320 	return insn_flags & INSN_F_FRAMENO_MASK;
3321 }
3322 
3323 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3324 {
3325 	env->insn_aux_data[idx].jmp_point = true;
3326 }
3327 
3328 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3329 {
3330 	return env->insn_aux_data[insn_idx].jmp_point;
3331 }
3332 
3333 /* for any branch, call, exit record the history of jmps in the given state */
3334 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3335 			    int insn_flags)
3336 {
3337 	u32 cnt = cur->jmp_history_cnt;
3338 	struct bpf_jmp_history_entry *p;
3339 	size_t alloc_size;
3340 
3341 	/* combine instruction flags if we already recorded this instruction */
3342 	if (env->cur_hist_ent) {
3343 		/* atomic instructions push insn_flags twice, for READ and
3344 		 * WRITE sides, but they should agree on stack slot
3345 		 */
3346 		WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3347 			  (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3348 			  "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3349 			  env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3350 		env->cur_hist_ent->flags |= insn_flags;
3351 		return 0;
3352 	}
3353 
3354 	cnt++;
3355 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3356 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3357 	if (!p)
3358 		return -ENOMEM;
3359 	cur->jmp_history = p;
3360 
3361 	p = &cur->jmp_history[cnt - 1];
3362 	p->idx = env->insn_idx;
3363 	p->prev_idx = env->prev_insn_idx;
3364 	p->flags = insn_flags;
3365 	cur->jmp_history_cnt = cnt;
3366 	env->cur_hist_ent = p;
3367 
3368 	return 0;
3369 }
3370 
3371 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3372 						        u32 hist_end, int insn_idx)
3373 {
3374 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3375 		return &st->jmp_history[hist_end - 1];
3376 	return NULL;
3377 }
3378 
3379 /* Backtrack one insn at a time. If idx is not at the top of recorded
3380  * history then previous instruction came from straight line execution.
3381  * Return -ENOENT if we exhausted all instructions within given state.
3382  *
3383  * It's legal to have a bit of a looping with the same starting and ending
3384  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3385  * instruction index is the same as state's first_idx doesn't mean we are
3386  * done. If there is still some jump history left, we should keep going. We
3387  * need to take into account that we might have a jump history between given
3388  * state's parent and itself, due to checkpointing. In this case, we'll have
3389  * history entry recording a jump from last instruction of parent state and
3390  * first instruction of given state.
3391  */
3392 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3393 			     u32 *history)
3394 {
3395 	u32 cnt = *history;
3396 
3397 	if (i == st->first_insn_idx) {
3398 		if (cnt == 0)
3399 			return -ENOENT;
3400 		if (cnt == 1 && st->jmp_history[0].idx == i)
3401 			return -ENOENT;
3402 	}
3403 
3404 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3405 		i = st->jmp_history[cnt - 1].prev_idx;
3406 		(*history)--;
3407 	} else {
3408 		i--;
3409 	}
3410 	return i;
3411 }
3412 
3413 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3414 {
3415 	const struct btf_type *func;
3416 	struct btf *desc_btf;
3417 
3418 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3419 		return NULL;
3420 
3421 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3422 	if (IS_ERR(desc_btf))
3423 		return "<error>";
3424 
3425 	func = btf_type_by_id(desc_btf, insn->imm);
3426 	return btf_name_by_offset(desc_btf, func->name_off);
3427 }
3428 
3429 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3430 {
3431 	bt->frame = frame;
3432 }
3433 
3434 static inline void bt_reset(struct backtrack_state *bt)
3435 {
3436 	struct bpf_verifier_env *env = bt->env;
3437 
3438 	memset(bt, 0, sizeof(*bt));
3439 	bt->env = env;
3440 }
3441 
3442 static inline u32 bt_empty(struct backtrack_state *bt)
3443 {
3444 	u64 mask = 0;
3445 	int i;
3446 
3447 	for (i = 0; i <= bt->frame; i++)
3448 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3449 
3450 	return mask == 0;
3451 }
3452 
3453 static inline int bt_subprog_enter(struct backtrack_state *bt)
3454 {
3455 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3456 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3457 		WARN_ONCE(1, "verifier backtracking bug");
3458 		return -EFAULT;
3459 	}
3460 	bt->frame++;
3461 	return 0;
3462 }
3463 
3464 static inline int bt_subprog_exit(struct backtrack_state *bt)
3465 {
3466 	if (bt->frame == 0) {
3467 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3468 		WARN_ONCE(1, "verifier backtracking bug");
3469 		return -EFAULT;
3470 	}
3471 	bt->frame--;
3472 	return 0;
3473 }
3474 
3475 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3476 {
3477 	bt->reg_masks[frame] |= 1 << reg;
3478 }
3479 
3480 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3481 {
3482 	bt->reg_masks[frame] &= ~(1 << reg);
3483 }
3484 
3485 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3486 {
3487 	bt_set_frame_reg(bt, bt->frame, reg);
3488 }
3489 
3490 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3491 {
3492 	bt_clear_frame_reg(bt, bt->frame, reg);
3493 }
3494 
3495 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3496 {
3497 	bt->stack_masks[frame] |= 1ull << slot;
3498 }
3499 
3500 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3501 {
3502 	bt->stack_masks[frame] &= ~(1ull << slot);
3503 }
3504 
3505 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3506 {
3507 	return bt->reg_masks[frame];
3508 }
3509 
3510 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3511 {
3512 	return bt->reg_masks[bt->frame];
3513 }
3514 
3515 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3516 {
3517 	return bt->stack_masks[frame];
3518 }
3519 
3520 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3521 {
3522 	return bt->stack_masks[bt->frame];
3523 }
3524 
3525 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3526 {
3527 	return bt->reg_masks[bt->frame] & (1 << reg);
3528 }
3529 
3530 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3531 {
3532 	return bt->stack_masks[frame] & (1ull << slot);
3533 }
3534 
3535 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3536 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3537 {
3538 	DECLARE_BITMAP(mask, 64);
3539 	bool first = true;
3540 	int i, n;
3541 
3542 	buf[0] = '\0';
3543 
3544 	bitmap_from_u64(mask, reg_mask);
3545 	for_each_set_bit(i, mask, 32) {
3546 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3547 		first = false;
3548 		buf += n;
3549 		buf_sz -= n;
3550 		if (buf_sz < 0)
3551 			break;
3552 	}
3553 }
3554 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3555 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3556 {
3557 	DECLARE_BITMAP(mask, 64);
3558 	bool first = true;
3559 	int i, n;
3560 
3561 	buf[0] = '\0';
3562 
3563 	bitmap_from_u64(mask, stack_mask);
3564 	for_each_set_bit(i, mask, 64) {
3565 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3566 		first = false;
3567 		buf += n;
3568 		buf_sz -= n;
3569 		if (buf_sz < 0)
3570 			break;
3571 	}
3572 }
3573 
3574 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3575 
3576 /* For given verifier state backtrack_insn() is called from the last insn to
3577  * the first insn. Its purpose is to compute a bitmask of registers and
3578  * stack slots that needs precision in the parent verifier state.
3579  *
3580  * @idx is an index of the instruction we are currently processing;
3581  * @subseq_idx is an index of the subsequent instruction that:
3582  *   - *would be* executed next, if jump history is viewed in forward order;
3583  *   - *was* processed previously during backtracking.
3584  */
3585 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3586 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
3587 {
3588 	const struct bpf_insn_cbs cbs = {
3589 		.cb_call	= disasm_kfunc_name,
3590 		.cb_print	= verbose,
3591 		.private_data	= env,
3592 	};
3593 	struct bpf_insn *insn = env->prog->insnsi + idx;
3594 	u8 class = BPF_CLASS(insn->code);
3595 	u8 opcode = BPF_OP(insn->code);
3596 	u8 mode = BPF_MODE(insn->code);
3597 	u32 dreg = insn->dst_reg;
3598 	u32 sreg = insn->src_reg;
3599 	u32 spi, i, fr;
3600 
3601 	if (insn->code == 0)
3602 		return 0;
3603 	if (env->log.level & BPF_LOG_LEVEL2) {
3604 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3605 		verbose(env, "mark_precise: frame%d: regs=%s ",
3606 			bt->frame, env->tmp_str_buf);
3607 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3608 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3609 		verbose(env, "%d: ", idx);
3610 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3611 	}
3612 
3613 	if (class == BPF_ALU || class == BPF_ALU64) {
3614 		if (!bt_is_reg_set(bt, dreg))
3615 			return 0;
3616 		if (opcode == BPF_END || opcode == BPF_NEG) {
3617 			/* sreg is reserved and unused
3618 			 * dreg still need precision before this insn
3619 			 */
3620 			return 0;
3621 		} else if (opcode == BPF_MOV) {
3622 			if (BPF_SRC(insn->code) == BPF_X) {
3623 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3624 				 * dreg needs precision after this insn
3625 				 * sreg needs precision before this insn
3626 				 */
3627 				bt_clear_reg(bt, dreg);
3628 				if (sreg != BPF_REG_FP)
3629 					bt_set_reg(bt, sreg);
3630 			} else {
3631 				/* dreg = K
3632 				 * dreg needs precision after this insn.
3633 				 * Corresponding register is already marked
3634 				 * as precise=true in this verifier state.
3635 				 * No further markings in parent are necessary
3636 				 */
3637 				bt_clear_reg(bt, dreg);
3638 			}
3639 		} else {
3640 			if (BPF_SRC(insn->code) == BPF_X) {
3641 				/* dreg += sreg
3642 				 * both dreg and sreg need precision
3643 				 * before this insn
3644 				 */
3645 				if (sreg != BPF_REG_FP)
3646 					bt_set_reg(bt, sreg);
3647 			} /* else dreg += K
3648 			   * dreg still needs precision before this insn
3649 			   */
3650 		}
3651 	} else if (class == BPF_LDX) {
3652 		if (!bt_is_reg_set(bt, dreg))
3653 			return 0;
3654 		bt_clear_reg(bt, dreg);
3655 
3656 		/* scalars can only be spilled into stack w/o losing precision.
3657 		 * Load from any other memory can be zero extended.
3658 		 * The desire to keep that precision is already indicated
3659 		 * by 'precise' mark in corresponding register of this state.
3660 		 * No further tracking necessary.
3661 		 */
3662 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3663 			return 0;
3664 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3665 		 * that [fp - off] slot contains scalar that needs to be
3666 		 * tracked with precision
3667 		 */
3668 		spi = insn_stack_access_spi(hist->flags);
3669 		fr = insn_stack_access_frameno(hist->flags);
3670 		bt_set_frame_slot(bt, fr, spi);
3671 	} else if (class == BPF_STX || class == BPF_ST) {
3672 		if (bt_is_reg_set(bt, dreg))
3673 			/* stx & st shouldn't be using _scalar_ dst_reg
3674 			 * to access memory. It means backtracking
3675 			 * encountered a case of pointer subtraction.
3676 			 */
3677 			return -ENOTSUPP;
3678 		/* scalars can only be spilled into stack */
3679 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3680 			return 0;
3681 		spi = insn_stack_access_spi(hist->flags);
3682 		fr = insn_stack_access_frameno(hist->flags);
3683 		if (!bt_is_frame_slot_set(bt, fr, spi))
3684 			return 0;
3685 		bt_clear_frame_slot(bt, fr, spi);
3686 		if (class == BPF_STX)
3687 			bt_set_reg(bt, sreg);
3688 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3689 		if (bpf_pseudo_call(insn)) {
3690 			int subprog_insn_idx, subprog;
3691 
3692 			subprog_insn_idx = idx + insn->imm + 1;
3693 			subprog = find_subprog(env, subprog_insn_idx);
3694 			if (subprog < 0)
3695 				return -EFAULT;
3696 
3697 			if (subprog_is_global(env, subprog)) {
3698 				/* check that jump history doesn't have any
3699 				 * extra instructions from subprog; the next
3700 				 * instruction after call to global subprog
3701 				 * should be literally next instruction in
3702 				 * caller program
3703 				 */
3704 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3705 				/* r1-r5 are invalidated after subprog call,
3706 				 * so for global func call it shouldn't be set
3707 				 * anymore
3708 				 */
3709 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3710 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3711 					WARN_ONCE(1, "verifier backtracking bug");
3712 					return -EFAULT;
3713 				}
3714 				/* global subprog always sets R0 */
3715 				bt_clear_reg(bt, BPF_REG_0);
3716 				return 0;
3717 			} else {
3718 				/* static subprog call instruction, which
3719 				 * means that we are exiting current subprog,
3720 				 * so only r1-r5 could be still requested as
3721 				 * precise, r0 and r6-r10 or any stack slot in
3722 				 * the current frame should be zero by now
3723 				 */
3724 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3725 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3726 					WARN_ONCE(1, "verifier backtracking bug");
3727 					return -EFAULT;
3728 				}
3729 				/* we are now tracking register spills correctly,
3730 				 * so any instance of leftover slots is a bug
3731 				 */
3732 				if (bt_stack_mask(bt) != 0) {
3733 					verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3734 					WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
3735 					return -EFAULT;
3736 				}
3737 				/* propagate r1-r5 to the caller */
3738 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3739 					if (bt_is_reg_set(bt, i)) {
3740 						bt_clear_reg(bt, i);
3741 						bt_set_frame_reg(bt, bt->frame - 1, i);
3742 					}
3743 				}
3744 				if (bt_subprog_exit(bt))
3745 					return -EFAULT;
3746 				return 0;
3747 			}
3748 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3749 			/* exit from callback subprog to callback-calling helper or
3750 			 * kfunc call. Use idx/subseq_idx check to discern it from
3751 			 * straight line code backtracking.
3752 			 * Unlike the subprog call handling above, we shouldn't
3753 			 * propagate precision of r1-r5 (if any requested), as they are
3754 			 * not actually arguments passed directly to callback subprogs
3755 			 */
3756 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3757 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3758 				WARN_ONCE(1, "verifier backtracking bug");
3759 				return -EFAULT;
3760 			}
3761 			if (bt_stack_mask(bt) != 0) {
3762 				verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3763 				WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
3764 				return -EFAULT;
3765 			}
3766 			/* clear r1-r5 in callback subprog's mask */
3767 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3768 				bt_clear_reg(bt, i);
3769 			if (bt_subprog_exit(bt))
3770 				return -EFAULT;
3771 			return 0;
3772 		} else if (opcode == BPF_CALL) {
3773 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3774 			 * catch this error later. Make backtracking conservative
3775 			 * with ENOTSUPP.
3776 			 */
3777 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3778 				return -ENOTSUPP;
3779 			/* regular helper call sets R0 */
3780 			bt_clear_reg(bt, BPF_REG_0);
3781 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3782 				/* if backtracing was looking for registers R1-R5
3783 				 * they should have been found already.
3784 				 */
3785 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3786 				WARN_ONCE(1, "verifier backtracking bug");
3787 				return -EFAULT;
3788 			}
3789 		} else if (opcode == BPF_EXIT) {
3790 			bool r0_precise;
3791 
3792 			/* Backtracking to a nested function call, 'idx' is a part of
3793 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3794 			 * In case of a regular function call, instructions giving
3795 			 * precision to registers R1-R5 should have been found already.
3796 			 * In case of a callback, it is ok to have R1-R5 marked for
3797 			 * backtracking, as these registers are set by the function
3798 			 * invoking callback.
3799 			 */
3800 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3801 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3802 					bt_clear_reg(bt, i);
3803 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3804 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3805 				WARN_ONCE(1, "verifier backtracking bug");
3806 				return -EFAULT;
3807 			}
3808 
3809 			/* BPF_EXIT in subprog or callback always returns
3810 			 * right after the call instruction, so by checking
3811 			 * whether the instruction at subseq_idx-1 is subprog
3812 			 * call or not we can distinguish actual exit from
3813 			 * *subprog* from exit from *callback*. In the former
3814 			 * case, we need to propagate r0 precision, if
3815 			 * necessary. In the former we never do that.
3816 			 */
3817 			r0_precise = subseq_idx - 1 >= 0 &&
3818 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3819 				     bt_is_reg_set(bt, BPF_REG_0);
3820 
3821 			bt_clear_reg(bt, BPF_REG_0);
3822 			if (bt_subprog_enter(bt))
3823 				return -EFAULT;
3824 
3825 			if (r0_precise)
3826 				bt_set_reg(bt, BPF_REG_0);
3827 			/* r6-r9 and stack slots will stay set in caller frame
3828 			 * bitmasks until we return back from callee(s)
3829 			 */
3830 			return 0;
3831 		} else if (BPF_SRC(insn->code) == BPF_X) {
3832 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3833 				return 0;
3834 			/* dreg <cond> sreg
3835 			 * Both dreg and sreg need precision before
3836 			 * this insn. If only sreg was marked precise
3837 			 * before it would be equally necessary to
3838 			 * propagate it to dreg.
3839 			 */
3840 			bt_set_reg(bt, dreg);
3841 			bt_set_reg(bt, sreg);
3842 			 /* else dreg <cond> K
3843 			  * Only dreg still needs precision before
3844 			  * this insn, so for the K-based conditional
3845 			  * there is nothing new to be marked.
3846 			  */
3847 		}
3848 	} else if (class == BPF_LD) {
3849 		if (!bt_is_reg_set(bt, dreg))
3850 			return 0;
3851 		bt_clear_reg(bt, dreg);
3852 		/* It's ld_imm64 or ld_abs or ld_ind.
3853 		 * For ld_imm64 no further tracking of precision
3854 		 * into parent is necessary
3855 		 */
3856 		if (mode == BPF_IND || mode == BPF_ABS)
3857 			/* to be analyzed */
3858 			return -ENOTSUPP;
3859 	}
3860 	return 0;
3861 }
3862 
3863 /* the scalar precision tracking algorithm:
3864  * . at the start all registers have precise=false.
3865  * . scalar ranges are tracked as normal through alu and jmp insns.
3866  * . once precise value of the scalar register is used in:
3867  *   .  ptr + scalar alu
3868  *   . if (scalar cond K|scalar)
3869  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3870  *   backtrack through the verifier states and mark all registers and
3871  *   stack slots with spilled constants that these scalar regisers
3872  *   should be precise.
3873  * . during state pruning two registers (or spilled stack slots)
3874  *   are equivalent if both are not precise.
3875  *
3876  * Note the verifier cannot simply walk register parentage chain,
3877  * since many different registers and stack slots could have been
3878  * used to compute single precise scalar.
3879  *
3880  * The approach of starting with precise=true for all registers and then
3881  * backtrack to mark a register as not precise when the verifier detects
3882  * that program doesn't care about specific value (e.g., when helper
3883  * takes register as ARG_ANYTHING parameter) is not safe.
3884  *
3885  * It's ok to walk single parentage chain of the verifier states.
3886  * It's possible that this backtracking will go all the way till 1st insn.
3887  * All other branches will be explored for needing precision later.
3888  *
3889  * The backtracking needs to deal with cases like:
3890  *   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)
3891  * r9 -= r8
3892  * r5 = r9
3893  * if r5 > 0x79f goto pc+7
3894  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3895  * r5 += 1
3896  * ...
3897  * call bpf_perf_event_output#25
3898  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3899  *
3900  * and this case:
3901  * r6 = 1
3902  * call foo // uses callee's r6 inside to compute r0
3903  * r0 += r6
3904  * if r0 == 0 goto
3905  *
3906  * to track above reg_mask/stack_mask needs to be independent for each frame.
3907  *
3908  * Also if parent's curframe > frame where backtracking started,
3909  * the verifier need to mark registers in both frames, otherwise callees
3910  * may incorrectly prune callers. This is similar to
3911  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3912  *
3913  * For now backtracking falls back into conservative marking.
3914  */
3915 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3916 				     struct bpf_verifier_state *st)
3917 {
3918 	struct bpf_func_state *func;
3919 	struct bpf_reg_state *reg;
3920 	int i, j;
3921 
3922 	if (env->log.level & BPF_LOG_LEVEL2) {
3923 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3924 			st->curframe);
3925 	}
3926 
3927 	/* big hammer: mark all scalars precise in this path.
3928 	 * pop_stack may still get !precise scalars.
3929 	 * We also skip current state and go straight to first parent state,
3930 	 * because precision markings in current non-checkpointed state are
3931 	 * not needed. See why in the comment in __mark_chain_precision below.
3932 	 */
3933 	for (st = st->parent; st; st = st->parent) {
3934 		for (i = 0; i <= st->curframe; i++) {
3935 			func = st->frame[i];
3936 			for (j = 0; j < BPF_REG_FP; j++) {
3937 				reg = &func->regs[j];
3938 				if (reg->type != SCALAR_VALUE || reg->precise)
3939 					continue;
3940 				reg->precise = true;
3941 				if (env->log.level & BPF_LOG_LEVEL2) {
3942 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3943 						i, j);
3944 				}
3945 			}
3946 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3947 				if (!is_spilled_reg(&func->stack[j]))
3948 					continue;
3949 				reg = &func->stack[j].spilled_ptr;
3950 				if (reg->type != SCALAR_VALUE || reg->precise)
3951 					continue;
3952 				reg->precise = true;
3953 				if (env->log.level & BPF_LOG_LEVEL2) {
3954 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3955 						i, -(j + 1) * 8);
3956 				}
3957 			}
3958 		}
3959 	}
3960 }
3961 
3962 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3963 {
3964 	struct bpf_func_state *func;
3965 	struct bpf_reg_state *reg;
3966 	int i, j;
3967 
3968 	for (i = 0; i <= st->curframe; i++) {
3969 		func = st->frame[i];
3970 		for (j = 0; j < BPF_REG_FP; j++) {
3971 			reg = &func->regs[j];
3972 			if (reg->type != SCALAR_VALUE)
3973 				continue;
3974 			reg->precise = false;
3975 		}
3976 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3977 			if (!is_spilled_reg(&func->stack[j]))
3978 				continue;
3979 			reg = &func->stack[j].spilled_ptr;
3980 			if (reg->type != SCALAR_VALUE)
3981 				continue;
3982 			reg->precise = false;
3983 		}
3984 	}
3985 }
3986 
3987 static bool idset_contains(struct bpf_idset *s, u32 id)
3988 {
3989 	u32 i;
3990 
3991 	for (i = 0; i < s->count; ++i)
3992 		if (s->ids[i] == id)
3993 			return true;
3994 
3995 	return false;
3996 }
3997 
3998 static int idset_push(struct bpf_idset *s, u32 id)
3999 {
4000 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4001 		return -EFAULT;
4002 	s->ids[s->count++] = id;
4003 	return 0;
4004 }
4005 
4006 static void idset_reset(struct bpf_idset *s)
4007 {
4008 	s->count = 0;
4009 }
4010 
4011 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4012  * Mark all registers with these IDs as precise.
4013  */
4014 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4015 {
4016 	struct bpf_idset *precise_ids = &env->idset_scratch;
4017 	struct backtrack_state *bt = &env->bt;
4018 	struct bpf_func_state *func;
4019 	struct bpf_reg_state *reg;
4020 	DECLARE_BITMAP(mask, 64);
4021 	int i, fr;
4022 
4023 	idset_reset(precise_ids);
4024 
4025 	for (fr = bt->frame; fr >= 0; fr--) {
4026 		func = st->frame[fr];
4027 
4028 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4029 		for_each_set_bit(i, mask, 32) {
4030 			reg = &func->regs[i];
4031 			if (!reg->id || reg->type != SCALAR_VALUE)
4032 				continue;
4033 			if (idset_push(precise_ids, reg->id))
4034 				return -EFAULT;
4035 		}
4036 
4037 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4038 		for_each_set_bit(i, mask, 64) {
4039 			if (i >= func->allocated_stack / BPF_REG_SIZE)
4040 				break;
4041 			if (!is_spilled_scalar_reg(&func->stack[i]))
4042 				continue;
4043 			reg = &func->stack[i].spilled_ptr;
4044 			if (!reg->id)
4045 				continue;
4046 			if (idset_push(precise_ids, reg->id))
4047 				return -EFAULT;
4048 		}
4049 	}
4050 
4051 	for (fr = 0; fr <= st->curframe; ++fr) {
4052 		func = st->frame[fr];
4053 
4054 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4055 			reg = &func->regs[i];
4056 			if (!reg->id)
4057 				continue;
4058 			if (!idset_contains(precise_ids, reg->id))
4059 				continue;
4060 			bt_set_frame_reg(bt, fr, i);
4061 		}
4062 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4063 			if (!is_spilled_scalar_reg(&func->stack[i]))
4064 				continue;
4065 			reg = &func->stack[i].spilled_ptr;
4066 			if (!reg->id)
4067 				continue;
4068 			if (!idset_contains(precise_ids, reg->id))
4069 				continue;
4070 			bt_set_frame_slot(bt, fr, i);
4071 		}
4072 	}
4073 
4074 	return 0;
4075 }
4076 
4077 /*
4078  * __mark_chain_precision() backtracks BPF program instruction sequence and
4079  * chain of verifier states making sure that register *regno* (if regno >= 0)
4080  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4081  * SCALARS, as well as any other registers and slots that contribute to
4082  * a tracked state of given registers/stack slots, depending on specific BPF
4083  * assembly instructions (see backtrack_insns() for exact instruction handling
4084  * logic). This backtracking relies on recorded jmp_history and is able to
4085  * traverse entire chain of parent states. This process ends only when all the
4086  * necessary registers/slots and their transitive dependencies are marked as
4087  * precise.
4088  *
4089  * One important and subtle aspect is that precise marks *do not matter* in
4090  * the currently verified state (current state). It is important to understand
4091  * why this is the case.
4092  *
4093  * First, note that current state is the state that is not yet "checkpointed",
4094  * i.e., it is not yet put into env->explored_states, and it has no children
4095  * states as well. It's ephemeral, and can end up either a) being discarded if
4096  * compatible explored state is found at some point or BPF_EXIT instruction is
4097  * reached or b) checkpointed and put into env->explored_states, branching out
4098  * into one or more children states.
4099  *
4100  * In the former case, precise markings in current state are completely
4101  * ignored by state comparison code (see regsafe() for details). Only
4102  * checkpointed ("old") state precise markings are important, and if old
4103  * state's register/slot is precise, regsafe() assumes current state's
4104  * register/slot as precise and checks value ranges exactly and precisely. If
4105  * states turn out to be compatible, current state's necessary precise
4106  * markings and any required parent states' precise markings are enforced
4107  * after the fact with propagate_precision() logic, after the fact. But it's
4108  * important to realize that in this case, even after marking current state
4109  * registers/slots as precise, we immediately discard current state. So what
4110  * actually matters is any of the precise markings propagated into current
4111  * state's parent states, which are always checkpointed (due to b) case above).
4112  * As such, for scenario a) it doesn't matter if current state has precise
4113  * markings set or not.
4114  *
4115  * Now, for the scenario b), checkpointing and forking into child(ren)
4116  * state(s). Note that before current state gets to checkpointing step, any
4117  * processed instruction always assumes precise SCALAR register/slot
4118  * knowledge: if precise value or range is useful to prune jump branch, BPF
4119  * verifier takes this opportunity enthusiastically. Similarly, when
4120  * register's value is used to calculate offset or memory address, exact
4121  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4122  * what we mentioned above about state comparison ignoring precise markings
4123  * during state comparison, BPF verifier ignores and also assumes precise
4124  * markings *at will* during instruction verification process. But as verifier
4125  * assumes precision, it also propagates any precision dependencies across
4126  * parent states, which are not yet finalized, so can be further restricted
4127  * based on new knowledge gained from restrictions enforced by their children
4128  * states. This is so that once those parent states are finalized, i.e., when
4129  * they have no more active children state, state comparison logic in
4130  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4131  * required for correctness.
4132  *
4133  * To build a bit more intuition, note also that once a state is checkpointed,
4134  * the path we took to get to that state is not important. This is crucial
4135  * property for state pruning. When state is checkpointed and finalized at
4136  * some instruction index, it can be correctly and safely used to "short
4137  * circuit" any *compatible* state that reaches exactly the same instruction
4138  * index. I.e., if we jumped to that instruction from a completely different
4139  * code path than original finalized state was derived from, it doesn't
4140  * matter, current state can be discarded because from that instruction
4141  * forward having a compatible state will ensure we will safely reach the
4142  * exit. States describe preconditions for further exploration, but completely
4143  * forget the history of how we got here.
4144  *
4145  * This also means that even if we needed precise SCALAR range to get to
4146  * finalized state, but from that point forward *that same* SCALAR register is
4147  * never used in a precise context (i.e., it's precise value is not needed for
4148  * correctness), it's correct and safe to mark such register as "imprecise"
4149  * (i.e., precise marking set to false). This is what we rely on when we do
4150  * not set precise marking in current state. If no child state requires
4151  * precision for any given SCALAR register, it's safe to dictate that it can
4152  * be imprecise. If any child state does require this register to be precise,
4153  * we'll mark it precise later retroactively during precise markings
4154  * propagation from child state to parent states.
4155  *
4156  * Skipping precise marking setting in current state is a mild version of
4157  * relying on the above observation. But we can utilize this property even
4158  * more aggressively by proactively forgetting any precise marking in the
4159  * current state (which we inherited from the parent state), right before we
4160  * checkpoint it and branch off into new child state. This is done by
4161  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4162  * finalized states which help in short circuiting more future states.
4163  */
4164 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4165 {
4166 	struct backtrack_state *bt = &env->bt;
4167 	struct bpf_verifier_state *st = env->cur_state;
4168 	int first_idx = st->first_insn_idx;
4169 	int last_idx = env->insn_idx;
4170 	int subseq_idx = -1;
4171 	struct bpf_func_state *func;
4172 	struct bpf_reg_state *reg;
4173 	bool skip_first = true;
4174 	int i, fr, err;
4175 
4176 	if (!env->bpf_capable)
4177 		return 0;
4178 
4179 	/* set frame number from which we are starting to backtrack */
4180 	bt_init(bt, env->cur_state->curframe);
4181 
4182 	/* Do sanity checks against current state of register and/or stack
4183 	 * slot, but don't set precise flag in current state, as precision
4184 	 * tracking in the current state is unnecessary.
4185 	 */
4186 	func = st->frame[bt->frame];
4187 	if (regno >= 0) {
4188 		reg = &func->regs[regno];
4189 		if (reg->type != SCALAR_VALUE) {
4190 			WARN_ONCE(1, "backtracing misuse");
4191 			return -EFAULT;
4192 		}
4193 		bt_set_reg(bt, regno);
4194 	}
4195 
4196 	if (bt_empty(bt))
4197 		return 0;
4198 
4199 	for (;;) {
4200 		DECLARE_BITMAP(mask, 64);
4201 		u32 history = st->jmp_history_cnt;
4202 		struct bpf_jmp_history_entry *hist;
4203 
4204 		if (env->log.level & BPF_LOG_LEVEL2) {
4205 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4206 				bt->frame, last_idx, first_idx, subseq_idx);
4207 		}
4208 
4209 		/* If some register with scalar ID is marked as precise,
4210 		 * make sure that all registers sharing this ID are also precise.
4211 		 * This is needed to estimate effect of find_equal_scalars().
4212 		 * Do this at the last instruction of each state,
4213 		 * bpf_reg_state::id fields are valid for these instructions.
4214 		 *
4215 		 * Allows to track precision in situation like below:
4216 		 *
4217 		 *     r2 = unknown value
4218 		 *     ...
4219 		 *   --- state #0 ---
4220 		 *     ...
4221 		 *     r1 = r2                 // r1 and r2 now share the same ID
4222 		 *     ...
4223 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4224 		 *     ...
4225 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4226 		 *     ...
4227 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4228 		 *     r3 = r10
4229 		 *     r3 += r1                // need to mark both r1 and r2
4230 		 */
4231 		if (mark_precise_scalar_ids(env, st))
4232 			return -EFAULT;
4233 
4234 		if (last_idx < 0) {
4235 			/* we are at the entry into subprog, which
4236 			 * is expected for global funcs, but only if
4237 			 * requested precise registers are R1-R5
4238 			 * (which are global func's input arguments)
4239 			 */
4240 			if (st->curframe == 0 &&
4241 			    st->frame[0]->subprogno > 0 &&
4242 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4243 			    bt_stack_mask(bt) == 0 &&
4244 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4245 				bitmap_from_u64(mask, bt_reg_mask(bt));
4246 				for_each_set_bit(i, mask, 32) {
4247 					reg = &st->frame[0]->regs[i];
4248 					bt_clear_reg(bt, i);
4249 					if (reg->type == SCALAR_VALUE)
4250 						reg->precise = true;
4251 				}
4252 				return 0;
4253 			}
4254 
4255 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4256 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4257 			WARN_ONCE(1, "verifier backtracking bug");
4258 			return -EFAULT;
4259 		}
4260 
4261 		for (i = last_idx;;) {
4262 			if (skip_first) {
4263 				err = 0;
4264 				skip_first = false;
4265 			} else {
4266 				hist = get_jmp_hist_entry(st, history, i);
4267 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4268 			}
4269 			if (err == -ENOTSUPP) {
4270 				mark_all_scalars_precise(env, env->cur_state);
4271 				bt_reset(bt);
4272 				return 0;
4273 			} else if (err) {
4274 				return err;
4275 			}
4276 			if (bt_empty(bt))
4277 				/* Found assignment(s) into tracked register in this state.
4278 				 * Since this state is already marked, just return.
4279 				 * Nothing to be tracked further in the parent state.
4280 				 */
4281 				return 0;
4282 			subseq_idx = i;
4283 			i = get_prev_insn_idx(st, i, &history);
4284 			if (i == -ENOENT)
4285 				break;
4286 			if (i >= env->prog->len) {
4287 				/* This can happen if backtracking reached insn 0
4288 				 * and there are still reg_mask or stack_mask
4289 				 * to backtrack.
4290 				 * It means the backtracking missed the spot where
4291 				 * particular register was initialized with a constant.
4292 				 */
4293 				verbose(env, "BUG backtracking idx %d\n", i);
4294 				WARN_ONCE(1, "verifier backtracking bug");
4295 				return -EFAULT;
4296 			}
4297 		}
4298 		st = st->parent;
4299 		if (!st)
4300 			break;
4301 
4302 		for (fr = bt->frame; fr >= 0; fr--) {
4303 			func = st->frame[fr];
4304 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4305 			for_each_set_bit(i, mask, 32) {
4306 				reg = &func->regs[i];
4307 				if (reg->type != SCALAR_VALUE) {
4308 					bt_clear_frame_reg(bt, fr, i);
4309 					continue;
4310 				}
4311 				if (reg->precise)
4312 					bt_clear_frame_reg(bt, fr, i);
4313 				else
4314 					reg->precise = true;
4315 			}
4316 
4317 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4318 			for_each_set_bit(i, mask, 64) {
4319 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4320 					verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4321 						i, func->allocated_stack / BPF_REG_SIZE);
4322 					WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4323 					return -EFAULT;
4324 				}
4325 
4326 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4327 					bt_clear_frame_slot(bt, fr, i);
4328 					continue;
4329 				}
4330 				reg = &func->stack[i].spilled_ptr;
4331 				if (reg->precise)
4332 					bt_clear_frame_slot(bt, fr, i);
4333 				else
4334 					reg->precise = true;
4335 			}
4336 			if (env->log.level & BPF_LOG_LEVEL2) {
4337 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4338 					     bt_frame_reg_mask(bt, fr));
4339 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4340 					fr, env->tmp_str_buf);
4341 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4342 					       bt_frame_stack_mask(bt, fr));
4343 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4344 				print_verifier_state(env, func, true);
4345 			}
4346 		}
4347 
4348 		if (bt_empty(bt))
4349 			return 0;
4350 
4351 		subseq_idx = first_idx;
4352 		last_idx = st->last_insn_idx;
4353 		first_idx = st->first_insn_idx;
4354 	}
4355 
4356 	/* if we still have requested precise regs or slots, we missed
4357 	 * something (e.g., stack access through non-r10 register), so
4358 	 * fallback to marking all precise
4359 	 */
4360 	if (!bt_empty(bt)) {
4361 		mark_all_scalars_precise(env, env->cur_state);
4362 		bt_reset(bt);
4363 	}
4364 
4365 	return 0;
4366 }
4367 
4368 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4369 {
4370 	return __mark_chain_precision(env, regno);
4371 }
4372 
4373 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4374  * desired reg and stack masks across all relevant frames
4375  */
4376 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4377 {
4378 	return __mark_chain_precision(env, -1);
4379 }
4380 
4381 static bool is_spillable_regtype(enum bpf_reg_type type)
4382 {
4383 	switch (base_type(type)) {
4384 	case PTR_TO_MAP_VALUE:
4385 	case PTR_TO_STACK:
4386 	case PTR_TO_CTX:
4387 	case PTR_TO_PACKET:
4388 	case PTR_TO_PACKET_META:
4389 	case PTR_TO_PACKET_END:
4390 	case PTR_TO_FLOW_KEYS:
4391 	case CONST_PTR_TO_MAP:
4392 	case PTR_TO_SOCKET:
4393 	case PTR_TO_SOCK_COMMON:
4394 	case PTR_TO_TCP_SOCK:
4395 	case PTR_TO_XDP_SOCK:
4396 	case PTR_TO_BTF_ID:
4397 	case PTR_TO_BUF:
4398 	case PTR_TO_MEM:
4399 	case PTR_TO_FUNC:
4400 	case PTR_TO_MAP_KEY:
4401 	case PTR_TO_ARENA:
4402 		return true;
4403 	default:
4404 		return false;
4405 	}
4406 }
4407 
4408 /* Does this register contain a constant zero? */
4409 static bool register_is_null(struct bpf_reg_state *reg)
4410 {
4411 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4412 }
4413 
4414 /* check if register is a constant scalar value */
4415 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4416 {
4417 	return reg->type == SCALAR_VALUE &&
4418 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4419 }
4420 
4421 /* assuming is_reg_const() is true, return constant value of a register */
4422 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4423 {
4424 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4425 }
4426 
4427 static bool __is_pointer_value(bool allow_ptr_leaks,
4428 			       const struct bpf_reg_state *reg)
4429 {
4430 	if (allow_ptr_leaks)
4431 		return false;
4432 
4433 	return reg->type != SCALAR_VALUE;
4434 }
4435 
4436 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4437 					struct bpf_reg_state *src_reg)
4438 {
4439 	if (src_reg->type == SCALAR_VALUE && !src_reg->id &&
4440 	    !tnum_is_const(src_reg->var_off))
4441 		/* Ensure that src_reg has a valid ID that will be copied to
4442 		 * dst_reg and then will be used by find_equal_scalars() to
4443 		 * propagate min/max range.
4444 		 */
4445 		src_reg->id = ++env->id_gen;
4446 }
4447 
4448 /* Copy src state preserving dst->parent and dst->live fields */
4449 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4450 {
4451 	struct bpf_reg_state *parent = dst->parent;
4452 	enum bpf_reg_liveness live = dst->live;
4453 
4454 	*dst = *src;
4455 	dst->parent = parent;
4456 	dst->live = live;
4457 }
4458 
4459 static void save_register_state(struct bpf_verifier_env *env,
4460 				struct bpf_func_state *state,
4461 				int spi, struct bpf_reg_state *reg,
4462 				int size)
4463 {
4464 	int i;
4465 
4466 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4467 	if (size == BPF_REG_SIZE)
4468 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4469 
4470 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4471 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4472 
4473 	/* size < 8 bytes spill */
4474 	for (; i; i--)
4475 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4476 }
4477 
4478 static bool is_bpf_st_mem(struct bpf_insn *insn)
4479 {
4480 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4481 }
4482 
4483 static int get_reg_width(struct bpf_reg_state *reg)
4484 {
4485 	return fls64(reg->umax_value);
4486 }
4487 
4488 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4489  * stack boundary and alignment are checked in check_mem_access()
4490  */
4491 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4492 				       /* stack frame we're writing to */
4493 				       struct bpf_func_state *state,
4494 				       int off, int size, int value_regno,
4495 				       int insn_idx)
4496 {
4497 	struct bpf_func_state *cur; /* state of the current function */
4498 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4499 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4500 	struct bpf_reg_state *reg = NULL;
4501 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
4502 
4503 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4504 	 * so it's aligned access and [off, off + size) are within stack limits
4505 	 */
4506 	if (!env->allow_ptr_leaks &&
4507 	    is_spilled_reg(&state->stack[spi]) &&
4508 	    size != BPF_REG_SIZE) {
4509 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4510 		return -EACCES;
4511 	}
4512 
4513 	cur = env->cur_state->frame[env->cur_state->curframe];
4514 	if (value_regno >= 0)
4515 		reg = &cur->regs[value_regno];
4516 	if (!env->bypass_spec_v4) {
4517 		bool sanitize = reg && is_spillable_regtype(reg->type);
4518 
4519 		for (i = 0; i < size; i++) {
4520 			u8 type = state->stack[spi].slot_type[i];
4521 
4522 			if (type != STACK_MISC && type != STACK_ZERO) {
4523 				sanitize = true;
4524 				break;
4525 			}
4526 		}
4527 
4528 		if (sanitize)
4529 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4530 	}
4531 
4532 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4533 	if (err)
4534 		return err;
4535 
4536 	mark_stack_slot_scratched(env, spi);
4537 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
4538 		bool reg_value_fits;
4539 
4540 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
4541 		/* Make sure that reg had an ID to build a relation on spill. */
4542 		if (reg_value_fits)
4543 			assign_scalar_id_before_mov(env, reg);
4544 		save_register_state(env, state, spi, reg, size);
4545 		/* Break the relation on a narrowing spill. */
4546 		if (!reg_value_fits)
4547 			state->stack[spi].spilled_ptr.id = 0;
4548 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4549 		   env->bpf_capable) {
4550 		struct bpf_reg_state fake_reg = {};
4551 
4552 		__mark_reg_known(&fake_reg, insn->imm);
4553 		fake_reg.type = SCALAR_VALUE;
4554 		save_register_state(env, state, spi, &fake_reg, size);
4555 	} else if (reg && is_spillable_regtype(reg->type)) {
4556 		/* register containing pointer is being spilled into stack */
4557 		if (size != BPF_REG_SIZE) {
4558 			verbose_linfo(env, insn_idx, "; ");
4559 			verbose(env, "invalid size of register spill\n");
4560 			return -EACCES;
4561 		}
4562 		if (state != cur && reg->type == PTR_TO_STACK) {
4563 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4564 			return -EINVAL;
4565 		}
4566 		save_register_state(env, state, spi, reg, size);
4567 	} else {
4568 		u8 type = STACK_MISC;
4569 
4570 		/* regular write of data into stack destroys any spilled ptr */
4571 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4572 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4573 		if (is_stack_slot_special(&state->stack[spi]))
4574 			for (i = 0; i < BPF_REG_SIZE; i++)
4575 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4576 
4577 		/* only mark the slot as written if all 8 bytes were written
4578 		 * otherwise read propagation may incorrectly stop too soon
4579 		 * when stack slots are partially written.
4580 		 * This heuristic means that read propagation will be
4581 		 * conservative, since it will add reg_live_read marks
4582 		 * to stack slots all the way to first state when programs
4583 		 * writes+reads less than 8 bytes
4584 		 */
4585 		if (size == BPF_REG_SIZE)
4586 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4587 
4588 		/* when we zero initialize stack slots mark them as such */
4589 		if ((reg && register_is_null(reg)) ||
4590 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4591 			/* STACK_ZERO case happened because register spill
4592 			 * wasn't properly aligned at the stack slot boundary,
4593 			 * so it's not a register spill anymore; force
4594 			 * originating register to be precise to make
4595 			 * STACK_ZERO correct for subsequent states
4596 			 */
4597 			err = mark_chain_precision(env, value_regno);
4598 			if (err)
4599 				return err;
4600 			type = STACK_ZERO;
4601 		}
4602 
4603 		/* Mark slots affected by this stack write. */
4604 		for (i = 0; i < size; i++)
4605 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4606 		insn_flags = 0; /* not a register spill */
4607 	}
4608 
4609 	if (insn_flags)
4610 		return push_jmp_history(env, env->cur_state, insn_flags);
4611 	return 0;
4612 }
4613 
4614 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4615  * known to contain a variable offset.
4616  * This function checks whether the write is permitted and conservatively
4617  * tracks the effects of the write, considering that each stack slot in the
4618  * dynamic range is potentially written to.
4619  *
4620  * 'off' includes 'regno->off'.
4621  * 'value_regno' can be -1, meaning that an unknown value is being written to
4622  * the stack.
4623  *
4624  * Spilled pointers in range are not marked as written because we don't know
4625  * what's going to be actually written. This means that read propagation for
4626  * future reads cannot be terminated by this write.
4627  *
4628  * For privileged programs, uninitialized stack slots are considered
4629  * initialized by this write (even though we don't know exactly what offsets
4630  * are going to be written to). The idea is that we don't want the verifier to
4631  * reject future reads that access slots written to through variable offsets.
4632  */
4633 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4634 				     /* func where register points to */
4635 				     struct bpf_func_state *state,
4636 				     int ptr_regno, int off, int size,
4637 				     int value_regno, int insn_idx)
4638 {
4639 	struct bpf_func_state *cur; /* state of the current function */
4640 	int min_off, max_off;
4641 	int i, err;
4642 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4643 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4644 	bool writing_zero = false;
4645 	/* set if the fact that we're writing a zero is used to let any
4646 	 * stack slots remain STACK_ZERO
4647 	 */
4648 	bool zero_used = false;
4649 
4650 	cur = env->cur_state->frame[env->cur_state->curframe];
4651 	ptr_reg = &cur->regs[ptr_regno];
4652 	min_off = ptr_reg->smin_value + off;
4653 	max_off = ptr_reg->smax_value + off + size;
4654 	if (value_regno >= 0)
4655 		value_reg = &cur->regs[value_regno];
4656 	if ((value_reg && register_is_null(value_reg)) ||
4657 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4658 		writing_zero = true;
4659 
4660 	for (i = min_off; i < max_off; i++) {
4661 		int spi;
4662 
4663 		spi = __get_spi(i);
4664 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4665 		if (err)
4666 			return err;
4667 	}
4668 
4669 	/* Variable offset writes destroy any spilled pointers in range. */
4670 	for (i = min_off; i < max_off; i++) {
4671 		u8 new_type, *stype;
4672 		int slot, spi;
4673 
4674 		slot = -i - 1;
4675 		spi = slot / BPF_REG_SIZE;
4676 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4677 		mark_stack_slot_scratched(env, spi);
4678 
4679 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4680 			/* Reject the write if range we may write to has not
4681 			 * been initialized beforehand. If we didn't reject
4682 			 * here, the ptr status would be erased below (even
4683 			 * though not all slots are actually overwritten),
4684 			 * possibly opening the door to leaks.
4685 			 *
4686 			 * We do however catch STACK_INVALID case below, and
4687 			 * only allow reading possibly uninitialized memory
4688 			 * later for CAP_PERFMON, as the write may not happen to
4689 			 * that slot.
4690 			 */
4691 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4692 				insn_idx, i);
4693 			return -EINVAL;
4694 		}
4695 
4696 		/* If writing_zero and the spi slot contains a spill of value 0,
4697 		 * maintain the spill type.
4698 		 */
4699 		if (writing_zero && *stype == STACK_SPILL &&
4700 		    is_spilled_scalar_reg(&state->stack[spi])) {
4701 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
4702 
4703 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
4704 				zero_used = true;
4705 				continue;
4706 			}
4707 		}
4708 
4709 		/* Erase all other spilled pointers. */
4710 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4711 
4712 		/* Update the slot type. */
4713 		new_type = STACK_MISC;
4714 		if (writing_zero && *stype == STACK_ZERO) {
4715 			new_type = STACK_ZERO;
4716 			zero_used = true;
4717 		}
4718 		/* If the slot is STACK_INVALID, we check whether it's OK to
4719 		 * pretend that it will be initialized by this write. The slot
4720 		 * might not actually be written to, and so if we mark it as
4721 		 * initialized future reads might leak uninitialized memory.
4722 		 * For privileged programs, we will accept such reads to slots
4723 		 * that may or may not be written because, if we're reject
4724 		 * them, the error would be too confusing.
4725 		 */
4726 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4727 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4728 					insn_idx, i);
4729 			return -EINVAL;
4730 		}
4731 		*stype = new_type;
4732 	}
4733 	if (zero_used) {
4734 		/* backtracking doesn't work for STACK_ZERO yet. */
4735 		err = mark_chain_precision(env, value_regno);
4736 		if (err)
4737 			return err;
4738 	}
4739 	return 0;
4740 }
4741 
4742 /* When register 'dst_regno' is assigned some values from stack[min_off,
4743  * max_off), we set the register's type according to the types of the
4744  * respective stack slots. If all the stack values are known to be zeros, then
4745  * so is the destination reg. Otherwise, the register is considered to be
4746  * SCALAR. This function does not deal with register filling; the caller must
4747  * ensure that all spilled registers in the stack range have been marked as
4748  * read.
4749  */
4750 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4751 				/* func where src register points to */
4752 				struct bpf_func_state *ptr_state,
4753 				int min_off, int max_off, int dst_regno)
4754 {
4755 	struct bpf_verifier_state *vstate = env->cur_state;
4756 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4757 	int i, slot, spi;
4758 	u8 *stype;
4759 	int zeros = 0;
4760 
4761 	for (i = min_off; i < max_off; i++) {
4762 		slot = -i - 1;
4763 		spi = slot / BPF_REG_SIZE;
4764 		mark_stack_slot_scratched(env, spi);
4765 		stype = ptr_state->stack[spi].slot_type;
4766 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4767 			break;
4768 		zeros++;
4769 	}
4770 	if (zeros == max_off - min_off) {
4771 		/* Any access_size read into register is zero extended,
4772 		 * so the whole register == const_zero.
4773 		 */
4774 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
4775 	} else {
4776 		/* have read misc data from the stack */
4777 		mark_reg_unknown(env, state->regs, dst_regno);
4778 	}
4779 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4780 }
4781 
4782 /* Read the stack at 'off' and put the results into the register indicated by
4783  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4784  * spilled reg.
4785  *
4786  * 'dst_regno' can be -1, meaning that the read value is not going to a
4787  * register.
4788  *
4789  * The access is assumed to be within the current stack bounds.
4790  */
4791 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4792 				      /* func where src register points to */
4793 				      struct bpf_func_state *reg_state,
4794 				      int off, int size, int dst_regno)
4795 {
4796 	struct bpf_verifier_state *vstate = env->cur_state;
4797 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4798 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4799 	struct bpf_reg_state *reg;
4800 	u8 *stype, type;
4801 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
4802 
4803 	stype = reg_state->stack[spi].slot_type;
4804 	reg = &reg_state->stack[spi].spilled_ptr;
4805 
4806 	mark_stack_slot_scratched(env, spi);
4807 
4808 	if (is_spilled_reg(&reg_state->stack[spi])) {
4809 		u8 spill_size = 1;
4810 
4811 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4812 			spill_size++;
4813 
4814 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4815 			if (reg->type != SCALAR_VALUE) {
4816 				verbose_linfo(env, env->insn_idx, "; ");
4817 				verbose(env, "invalid size of register fill\n");
4818 				return -EACCES;
4819 			}
4820 
4821 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4822 			if (dst_regno < 0)
4823 				return 0;
4824 
4825 			if (size <= spill_size &&
4826 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
4827 				/* The earlier check_reg_arg() has decided the
4828 				 * subreg_def for this insn.  Save it first.
4829 				 */
4830 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4831 
4832 				copy_register_state(&state->regs[dst_regno], reg);
4833 				state->regs[dst_regno].subreg_def = subreg_def;
4834 
4835 				/* Break the relation on a narrowing fill.
4836 				 * coerce_reg_to_size will adjust the boundaries.
4837 				 */
4838 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
4839 					state->regs[dst_regno].id = 0;
4840 			} else {
4841 				int spill_cnt = 0, zero_cnt = 0;
4842 
4843 				for (i = 0; i < size; i++) {
4844 					type = stype[(slot - i) % BPF_REG_SIZE];
4845 					if (type == STACK_SPILL) {
4846 						spill_cnt++;
4847 						continue;
4848 					}
4849 					if (type == STACK_MISC)
4850 						continue;
4851 					if (type == STACK_ZERO) {
4852 						zero_cnt++;
4853 						continue;
4854 					}
4855 					if (type == STACK_INVALID && env->allow_uninit_stack)
4856 						continue;
4857 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4858 						off, i, size);
4859 					return -EACCES;
4860 				}
4861 
4862 				if (spill_cnt == size &&
4863 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4864 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4865 					/* this IS register fill, so keep insn_flags */
4866 				} else if (zero_cnt == size) {
4867 					/* similarly to mark_reg_stack_read(), preserve zeroes */
4868 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4869 					insn_flags = 0; /* not restoring original register state */
4870 				} else {
4871 					mark_reg_unknown(env, state->regs, dst_regno);
4872 					insn_flags = 0; /* not restoring original register state */
4873 				}
4874 			}
4875 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4876 		} else if (dst_regno >= 0) {
4877 			/* restore register state from stack */
4878 			copy_register_state(&state->regs[dst_regno], reg);
4879 			/* mark reg as written since spilled pointer state likely
4880 			 * has its liveness marks cleared by is_state_visited()
4881 			 * which resets stack/reg liveness for state transitions
4882 			 */
4883 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4884 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4885 			/* If dst_regno==-1, the caller is asking us whether
4886 			 * it is acceptable to use this value as a SCALAR_VALUE
4887 			 * (e.g. for XADD).
4888 			 * We must not allow unprivileged callers to do that
4889 			 * with spilled pointers.
4890 			 */
4891 			verbose(env, "leaking pointer from stack off %d\n",
4892 				off);
4893 			return -EACCES;
4894 		}
4895 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4896 	} else {
4897 		for (i = 0; i < size; i++) {
4898 			type = stype[(slot - i) % BPF_REG_SIZE];
4899 			if (type == STACK_MISC)
4900 				continue;
4901 			if (type == STACK_ZERO)
4902 				continue;
4903 			if (type == STACK_INVALID && env->allow_uninit_stack)
4904 				continue;
4905 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4906 				off, i, size);
4907 			return -EACCES;
4908 		}
4909 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4910 		if (dst_regno >= 0)
4911 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4912 		insn_flags = 0; /* we are not restoring spilled register */
4913 	}
4914 	if (insn_flags)
4915 		return push_jmp_history(env, env->cur_state, insn_flags);
4916 	return 0;
4917 }
4918 
4919 enum bpf_access_src {
4920 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4921 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4922 };
4923 
4924 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4925 					 int regno, int off, int access_size,
4926 					 bool zero_size_allowed,
4927 					 enum bpf_access_src type,
4928 					 struct bpf_call_arg_meta *meta);
4929 
4930 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4931 {
4932 	return cur_regs(env) + regno;
4933 }
4934 
4935 /* Read the stack at 'ptr_regno + off' and put the result into the register
4936  * 'dst_regno'.
4937  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4938  * but not its variable offset.
4939  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4940  *
4941  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4942  * filling registers (i.e. reads of spilled register cannot be detected when
4943  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4944  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4945  * offset; for a fixed offset check_stack_read_fixed_off should be used
4946  * instead.
4947  */
4948 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4949 				    int ptr_regno, int off, int size, int dst_regno)
4950 {
4951 	/* The state of the source register. */
4952 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4953 	struct bpf_func_state *ptr_state = func(env, reg);
4954 	int err;
4955 	int min_off, max_off;
4956 
4957 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4958 	 */
4959 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4960 					    false, ACCESS_DIRECT, NULL);
4961 	if (err)
4962 		return err;
4963 
4964 	min_off = reg->smin_value + off;
4965 	max_off = reg->smax_value + off;
4966 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4967 	return 0;
4968 }
4969 
4970 /* check_stack_read dispatches to check_stack_read_fixed_off or
4971  * check_stack_read_var_off.
4972  *
4973  * The caller must ensure that the offset falls within the allocated stack
4974  * bounds.
4975  *
4976  * 'dst_regno' is a register which will receive the value from the stack. It
4977  * can be -1, meaning that the read value is not going to a register.
4978  */
4979 static int check_stack_read(struct bpf_verifier_env *env,
4980 			    int ptr_regno, int off, int size,
4981 			    int dst_regno)
4982 {
4983 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4984 	struct bpf_func_state *state = func(env, reg);
4985 	int err;
4986 	/* Some accesses are only permitted with a static offset. */
4987 	bool var_off = !tnum_is_const(reg->var_off);
4988 
4989 	/* The offset is required to be static when reads don't go to a
4990 	 * register, in order to not leak pointers (see
4991 	 * check_stack_read_fixed_off).
4992 	 */
4993 	if (dst_regno < 0 && var_off) {
4994 		char tn_buf[48];
4995 
4996 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4997 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4998 			tn_buf, off, size);
4999 		return -EACCES;
5000 	}
5001 	/* Variable offset is prohibited for unprivileged mode for simplicity
5002 	 * since it requires corresponding support in Spectre masking for stack
5003 	 * ALU. See also retrieve_ptr_limit(). The check in
5004 	 * check_stack_access_for_ptr_arithmetic() called by
5005 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5006 	 * with variable offsets, therefore no check is required here. Further,
5007 	 * just checking it here would be insufficient as speculative stack
5008 	 * writes could still lead to unsafe speculative behaviour.
5009 	 */
5010 	if (!var_off) {
5011 		off += reg->var_off.value;
5012 		err = check_stack_read_fixed_off(env, state, off, size,
5013 						 dst_regno);
5014 	} else {
5015 		/* Variable offset stack reads need more conservative handling
5016 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5017 		 * branch.
5018 		 */
5019 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5020 					       dst_regno);
5021 	}
5022 	return err;
5023 }
5024 
5025 
5026 /* check_stack_write dispatches to check_stack_write_fixed_off or
5027  * check_stack_write_var_off.
5028  *
5029  * 'ptr_regno' is the register used as a pointer into the stack.
5030  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5031  * 'value_regno' is the register whose value we're writing to the stack. It can
5032  * be -1, meaning that we're not writing from a register.
5033  *
5034  * The caller must ensure that the offset falls within the maximum stack size.
5035  */
5036 static int check_stack_write(struct bpf_verifier_env *env,
5037 			     int ptr_regno, int off, int size,
5038 			     int value_regno, int insn_idx)
5039 {
5040 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5041 	struct bpf_func_state *state = func(env, reg);
5042 	int err;
5043 
5044 	if (tnum_is_const(reg->var_off)) {
5045 		off += reg->var_off.value;
5046 		err = check_stack_write_fixed_off(env, state, off, size,
5047 						  value_regno, insn_idx);
5048 	} else {
5049 		/* Variable offset stack reads need more conservative handling
5050 		 * than fixed offset ones.
5051 		 */
5052 		err = check_stack_write_var_off(env, state,
5053 						ptr_regno, off, size,
5054 						value_regno, insn_idx);
5055 	}
5056 	return err;
5057 }
5058 
5059 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5060 				 int off, int size, enum bpf_access_type type)
5061 {
5062 	struct bpf_reg_state *regs = cur_regs(env);
5063 	struct bpf_map *map = regs[regno].map_ptr;
5064 	u32 cap = bpf_map_flags_to_cap(map);
5065 
5066 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5067 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5068 			map->value_size, off, size);
5069 		return -EACCES;
5070 	}
5071 
5072 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5073 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5074 			map->value_size, off, size);
5075 		return -EACCES;
5076 	}
5077 
5078 	return 0;
5079 }
5080 
5081 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5082 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5083 			      int off, int size, u32 mem_size,
5084 			      bool zero_size_allowed)
5085 {
5086 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5087 	struct bpf_reg_state *reg;
5088 
5089 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5090 		return 0;
5091 
5092 	reg = &cur_regs(env)[regno];
5093 	switch (reg->type) {
5094 	case PTR_TO_MAP_KEY:
5095 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5096 			mem_size, off, size);
5097 		break;
5098 	case PTR_TO_MAP_VALUE:
5099 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5100 			mem_size, off, size);
5101 		break;
5102 	case PTR_TO_PACKET:
5103 	case PTR_TO_PACKET_META:
5104 	case PTR_TO_PACKET_END:
5105 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5106 			off, size, regno, reg->id, off, mem_size);
5107 		break;
5108 	case PTR_TO_MEM:
5109 	default:
5110 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5111 			mem_size, off, size);
5112 	}
5113 
5114 	return -EACCES;
5115 }
5116 
5117 /* check read/write into a memory region with possible variable offset */
5118 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5119 				   int off, int size, u32 mem_size,
5120 				   bool zero_size_allowed)
5121 {
5122 	struct bpf_verifier_state *vstate = env->cur_state;
5123 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5124 	struct bpf_reg_state *reg = &state->regs[regno];
5125 	int err;
5126 
5127 	/* We may have adjusted the register pointing to memory region, so we
5128 	 * need to try adding each of min_value and max_value to off
5129 	 * to make sure our theoretical access will be safe.
5130 	 *
5131 	 * The minimum value is only important with signed
5132 	 * comparisons where we can't assume the floor of a
5133 	 * value is 0.  If we are using signed variables for our
5134 	 * index'es we need to make sure that whatever we use
5135 	 * will have a set floor within our range.
5136 	 */
5137 	if (reg->smin_value < 0 &&
5138 	    (reg->smin_value == S64_MIN ||
5139 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5140 	      reg->smin_value + off < 0)) {
5141 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5142 			regno);
5143 		return -EACCES;
5144 	}
5145 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5146 				 mem_size, zero_size_allowed);
5147 	if (err) {
5148 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5149 			regno);
5150 		return err;
5151 	}
5152 
5153 	/* If we haven't set a max value then we need to bail since we can't be
5154 	 * sure we won't do bad things.
5155 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5156 	 */
5157 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5158 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5159 			regno);
5160 		return -EACCES;
5161 	}
5162 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5163 				 mem_size, zero_size_allowed);
5164 	if (err) {
5165 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5166 			regno);
5167 		return err;
5168 	}
5169 
5170 	return 0;
5171 }
5172 
5173 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5174 			       const struct bpf_reg_state *reg, int regno,
5175 			       bool fixed_off_ok)
5176 {
5177 	/* Access to this pointer-typed register or passing it to a helper
5178 	 * is only allowed in its original, unmodified form.
5179 	 */
5180 
5181 	if (reg->off < 0) {
5182 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5183 			reg_type_str(env, reg->type), regno, reg->off);
5184 		return -EACCES;
5185 	}
5186 
5187 	if (!fixed_off_ok && reg->off) {
5188 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5189 			reg_type_str(env, reg->type), regno, reg->off);
5190 		return -EACCES;
5191 	}
5192 
5193 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5194 		char tn_buf[48];
5195 
5196 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5197 		verbose(env, "variable %s access var_off=%s disallowed\n",
5198 			reg_type_str(env, reg->type), tn_buf);
5199 		return -EACCES;
5200 	}
5201 
5202 	return 0;
5203 }
5204 
5205 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5206 		             const struct bpf_reg_state *reg, int regno)
5207 {
5208 	return __check_ptr_off_reg(env, reg, regno, false);
5209 }
5210 
5211 static int map_kptr_match_type(struct bpf_verifier_env *env,
5212 			       struct btf_field *kptr_field,
5213 			       struct bpf_reg_state *reg, u32 regno)
5214 {
5215 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5216 	int perm_flags;
5217 	const char *reg_name = "";
5218 
5219 	if (btf_is_kernel(reg->btf)) {
5220 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5221 
5222 		/* Only unreferenced case accepts untrusted pointers */
5223 		if (kptr_field->type == BPF_KPTR_UNREF)
5224 			perm_flags |= PTR_UNTRUSTED;
5225 	} else {
5226 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5227 		if (kptr_field->type == BPF_KPTR_PERCPU)
5228 			perm_flags |= MEM_PERCPU;
5229 	}
5230 
5231 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5232 		goto bad_type;
5233 
5234 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5235 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5236 
5237 	/* For ref_ptr case, release function check should ensure we get one
5238 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5239 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5240 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5241 	 * reg->off and reg->ref_obj_id are not needed here.
5242 	 */
5243 	if (__check_ptr_off_reg(env, reg, regno, true))
5244 		return -EACCES;
5245 
5246 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5247 	 * we also need to take into account the reg->off.
5248 	 *
5249 	 * We want to support cases like:
5250 	 *
5251 	 * struct foo {
5252 	 *         struct bar br;
5253 	 *         struct baz bz;
5254 	 * };
5255 	 *
5256 	 * struct foo *v;
5257 	 * v = func();	      // PTR_TO_BTF_ID
5258 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5259 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5260 	 *                    // first member type of struct after comparison fails
5261 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5262 	 *                    // to match type
5263 	 *
5264 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5265 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5266 	 * the struct to match type against first member of struct, i.e. reject
5267 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5268 	 * strict mode to true for type match.
5269 	 */
5270 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5271 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5272 				  kptr_field->type != BPF_KPTR_UNREF))
5273 		goto bad_type;
5274 	return 0;
5275 bad_type:
5276 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5277 		reg_type_str(env, reg->type), reg_name);
5278 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5279 	if (kptr_field->type == BPF_KPTR_UNREF)
5280 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5281 			targ_name);
5282 	else
5283 		verbose(env, "\n");
5284 	return -EINVAL;
5285 }
5286 
5287 static bool in_sleepable(struct bpf_verifier_env *env)
5288 {
5289 	return env->prog->sleepable ||
5290 	       (env->cur_state && env->cur_state->in_sleepable);
5291 }
5292 
5293 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5294  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5295  */
5296 static bool in_rcu_cs(struct bpf_verifier_env *env)
5297 {
5298 	return env->cur_state->active_rcu_lock ||
5299 	       env->cur_state->active_lock.ptr ||
5300 	       !in_sleepable(env);
5301 }
5302 
5303 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5304 BTF_SET_START(rcu_protected_types)
5305 BTF_ID(struct, prog_test_ref_kfunc)
5306 #ifdef CONFIG_CGROUPS
5307 BTF_ID(struct, cgroup)
5308 #endif
5309 #ifdef CONFIG_BPF_JIT
5310 BTF_ID(struct, bpf_cpumask)
5311 #endif
5312 BTF_ID(struct, task_struct)
5313 BTF_ID(struct, bpf_crypto_ctx)
5314 BTF_SET_END(rcu_protected_types)
5315 
5316 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5317 {
5318 	if (!btf_is_kernel(btf))
5319 		return true;
5320 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5321 }
5322 
5323 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5324 {
5325 	struct btf_struct_meta *meta;
5326 
5327 	if (btf_is_kernel(kptr_field->kptr.btf))
5328 		return NULL;
5329 
5330 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5331 				    kptr_field->kptr.btf_id);
5332 
5333 	return meta ? meta->record : NULL;
5334 }
5335 
5336 static bool rcu_safe_kptr(const struct btf_field *field)
5337 {
5338 	const struct btf_field_kptr *kptr = &field->kptr;
5339 
5340 	return field->type == BPF_KPTR_PERCPU ||
5341 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5342 }
5343 
5344 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5345 {
5346 	struct btf_record *rec;
5347 	u32 ret;
5348 
5349 	ret = PTR_MAYBE_NULL;
5350 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5351 		ret |= MEM_RCU;
5352 		if (kptr_field->type == BPF_KPTR_PERCPU)
5353 			ret |= MEM_PERCPU;
5354 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5355 			ret |= MEM_ALLOC;
5356 
5357 		rec = kptr_pointee_btf_record(kptr_field);
5358 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5359 			ret |= NON_OWN_REF;
5360 	} else {
5361 		ret |= PTR_UNTRUSTED;
5362 	}
5363 
5364 	return ret;
5365 }
5366 
5367 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5368 				 int value_regno, int insn_idx,
5369 				 struct btf_field *kptr_field)
5370 {
5371 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5372 	int class = BPF_CLASS(insn->code);
5373 	struct bpf_reg_state *val_reg;
5374 
5375 	/* Things we already checked for in check_map_access and caller:
5376 	 *  - Reject cases where variable offset may touch kptr
5377 	 *  - size of access (must be BPF_DW)
5378 	 *  - tnum_is_const(reg->var_off)
5379 	 *  - kptr_field->offset == off + reg->var_off.value
5380 	 */
5381 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5382 	if (BPF_MODE(insn->code) != BPF_MEM) {
5383 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5384 		return -EACCES;
5385 	}
5386 
5387 	/* We only allow loading referenced kptr, since it will be marked as
5388 	 * untrusted, similar to unreferenced kptr.
5389 	 */
5390 	if (class != BPF_LDX &&
5391 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5392 		verbose(env, "store to referenced kptr disallowed\n");
5393 		return -EACCES;
5394 	}
5395 
5396 	if (class == BPF_LDX) {
5397 		val_reg = reg_state(env, value_regno);
5398 		/* We can simply mark the value_regno receiving the pointer
5399 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5400 		 */
5401 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5402 				kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5403 		/* For mark_ptr_or_null_reg */
5404 		val_reg->id = ++env->id_gen;
5405 	} else if (class == BPF_STX) {
5406 		val_reg = reg_state(env, value_regno);
5407 		if (!register_is_null(val_reg) &&
5408 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5409 			return -EACCES;
5410 	} else if (class == BPF_ST) {
5411 		if (insn->imm) {
5412 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5413 				kptr_field->offset);
5414 			return -EACCES;
5415 		}
5416 	} else {
5417 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5418 		return -EACCES;
5419 	}
5420 	return 0;
5421 }
5422 
5423 /* check read/write into a map element with possible variable offset */
5424 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5425 			    int off, int size, bool zero_size_allowed,
5426 			    enum bpf_access_src src)
5427 {
5428 	struct bpf_verifier_state *vstate = env->cur_state;
5429 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5430 	struct bpf_reg_state *reg = &state->regs[regno];
5431 	struct bpf_map *map = reg->map_ptr;
5432 	struct btf_record *rec;
5433 	int err, i;
5434 
5435 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5436 				      zero_size_allowed);
5437 	if (err)
5438 		return err;
5439 
5440 	if (IS_ERR_OR_NULL(map->record))
5441 		return 0;
5442 	rec = map->record;
5443 	for (i = 0; i < rec->cnt; i++) {
5444 		struct btf_field *field = &rec->fields[i];
5445 		u32 p = field->offset;
5446 
5447 		/* If any part of a field  can be touched by load/store, reject
5448 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5449 		 * it is sufficient to check x1 < y2 && y1 < x2.
5450 		 */
5451 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5452 		    p < reg->umax_value + off + size) {
5453 			switch (field->type) {
5454 			case BPF_KPTR_UNREF:
5455 			case BPF_KPTR_REF:
5456 			case BPF_KPTR_PERCPU:
5457 				if (src != ACCESS_DIRECT) {
5458 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5459 					return -EACCES;
5460 				}
5461 				if (!tnum_is_const(reg->var_off)) {
5462 					verbose(env, "kptr access cannot have variable offset\n");
5463 					return -EACCES;
5464 				}
5465 				if (p != off + reg->var_off.value) {
5466 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5467 						p, off + reg->var_off.value);
5468 					return -EACCES;
5469 				}
5470 				if (size != bpf_size_to_bytes(BPF_DW)) {
5471 					verbose(env, "kptr access size must be BPF_DW\n");
5472 					return -EACCES;
5473 				}
5474 				break;
5475 			default:
5476 				verbose(env, "%s cannot be accessed directly by load/store\n",
5477 					btf_field_type_name(field->type));
5478 				return -EACCES;
5479 			}
5480 		}
5481 	}
5482 	return 0;
5483 }
5484 
5485 #define MAX_PACKET_OFF 0xffff
5486 
5487 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5488 				       const struct bpf_call_arg_meta *meta,
5489 				       enum bpf_access_type t)
5490 {
5491 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5492 
5493 	switch (prog_type) {
5494 	/* Program types only with direct read access go here! */
5495 	case BPF_PROG_TYPE_LWT_IN:
5496 	case BPF_PROG_TYPE_LWT_OUT:
5497 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5498 	case BPF_PROG_TYPE_SK_REUSEPORT:
5499 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5500 	case BPF_PROG_TYPE_CGROUP_SKB:
5501 		if (t == BPF_WRITE)
5502 			return false;
5503 		fallthrough;
5504 
5505 	/* Program types with direct read + write access go here! */
5506 	case BPF_PROG_TYPE_SCHED_CLS:
5507 	case BPF_PROG_TYPE_SCHED_ACT:
5508 	case BPF_PROG_TYPE_XDP:
5509 	case BPF_PROG_TYPE_LWT_XMIT:
5510 	case BPF_PROG_TYPE_SK_SKB:
5511 	case BPF_PROG_TYPE_SK_MSG:
5512 		if (meta)
5513 			return meta->pkt_access;
5514 
5515 		env->seen_direct_write = true;
5516 		return true;
5517 
5518 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5519 		if (t == BPF_WRITE)
5520 			env->seen_direct_write = true;
5521 
5522 		return true;
5523 
5524 	default:
5525 		return false;
5526 	}
5527 }
5528 
5529 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5530 			       int size, bool zero_size_allowed)
5531 {
5532 	struct bpf_reg_state *regs = cur_regs(env);
5533 	struct bpf_reg_state *reg = &regs[regno];
5534 	int err;
5535 
5536 	/* We may have added a variable offset to the packet pointer; but any
5537 	 * reg->range we have comes after that.  We are only checking the fixed
5538 	 * offset.
5539 	 */
5540 
5541 	/* We don't allow negative numbers, because we aren't tracking enough
5542 	 * detail to prove they're safe.
5543 	 */
5544 	if (reg->smin_value < 0) {
5545 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5546 			regno);
5547 		return -EACCES;
5548 	}
5549 
5550 	err = reg->range < 0 ? -EINVAL :
5551 	      __check_mem_access(env, regno, off, size, reg->range,
5552 				 zero_size_allowed);
5553 	if (err) {
5554 		verbose(env, "R%d offset is outside of the packet\n", regno);
5555 		return err;
5556 	}
5557 
5558 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5559 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5560 	 * otherwise find_good_pkt_pointers would have refused to set range info
5561 	 * that __check_mem_access would have rejected this pkt access.
5562 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5563 	 */
5564 	env->prog->aux->max_pkt_offset =
5565 		max_t(u32, env->prog->aux->max_pkt_offset,
5566 		      off + reg->umax_value + size - 1);
5567 
5568 	return err;
5569 }
5570 
5571 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5572 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5573 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5574 			    struct btf **btf, u32 *btf_id)
5575 {
5576 	struct bpf_insn_access_aux info = {
5577 		.reg_type = *reg_type,
5578 		.log = &env->log,
5579 	};
5580 
5581 	if (env->ops->is_valid_access &&
5582 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5583 		/* A non zero info.ctx_field_size indicates that this field is a
5584 		 * candidate for later verifier transformation to load the whole
5585 		 * field and then apply a mask when accessed with a narrower
5586 		 * access than actual ctx access size. A zero info.ctx_field_size
5587 		 * will only allow for whole field access and rejects any other
5588 		 * type of narrower access.
5589 		 */
5590 		*reg_type = info.reg_type;
5591 
5592 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5593 			*btf = info.btf;
5594 			*btf_id = info.btf_id;
5595 		} else {
5596 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5597 		}
5598 		/* remember the offset of last byte accessed in ctx */
5599 		if (env->prog->aux->max_ctx_offset < off + size)
5600 			env->prog->aux->max_ctx_offset = off + size;
5601 		return 0;
5602 	}
5603 
5604 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5605 	return -EACCES;
5606 }
5607 
5608 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5609 				  int size)
5610 {
5611 	if (size < 0 || off < 0 ||
5612 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5613 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5614 			off, size);
5615 		return -EACCES;
5616 	}
5617 	return 0;
5618 }
5619 
5620 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5621 			     u32 regno, int off, int size,
5622 			     enum bpf_access_type t)
5623 {
5624 	struct bpf_reg_state *regs = cur_regs(env);
5625 	struct bpf_reg_state *reg = &regs[regno];
5626 	struct bpf_insn_access_aux info = {};
5627 	bool valid;
5628 
5629 	if (reg->smin_value < 0) {
5630 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5631 			regno);
5632 		return -EACCES;
5633 	}
5634 
5635 	switch (reg->type) {
5636 	case PTR_TO_SOCK_COMMON:
5637 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5638 		break;
5639 	case PTR_TO_SOCKET:
5640 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5641 		break;
5642 	case PTR_TO_TCP_SOCK:
5643 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5644 		break;
5645 	case PTR_TO_XDP_SOCK:
5646 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5647 		break;
5648 	default:
5649 		valid = false;
5650 	}
5651 
5652 
5653 	if (valid) {
5654 		env->insn_aux_data[insn_idx].ctx_field_size =
5655 			info.ctx_field_size;
5656 		return 0;
5657 	}
5658 
5659 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5660 		regno, reg_type_str(env, reg->type), off, size);
5661 
5662 	return -EACCES;
5663 }
5664 
5665 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5666 {
5667 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5668 }
5669 
5670 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5671 {
5672 	const struct bpf_reg_state *reg = reg_state(env, regno);
5673 
5674 	return reg->type == PTR_TO_CTX;
5675 }
5676 
5677 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5678 {
5679 	const struct bpf_reg_state *reg = reg_state(env, regno);
5680 
5681 	return type_is_sk_pointer(reg->type);
5682 }
5683 
5684 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5685 {
5686 	const struct bpf_reg_state *reg = reg_state(env, regno);
5687 
5688 	return type_is_pkt_pointer(reg->type);
5689 }
5690 
5691 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5692 {
5693 	const struct bpf_reg_state *reg = reg_state(env, regno);
5694 
5695 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5696 	return reg->type == PTR_TO_FLOW_KEYS;
5697 }
5698 
5699 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
5700 {
5701 	const struct bpf_reg_state *reg = reg_state(env, regno);
5702 
5703 	return reg->type == PTR_TO_ARENA;
5704 }
5705 
5706 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5707 #ifdef CONFIG_NET
5708 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5709 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5710 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5711 #endif
5712 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5713 };
5714 
5715 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5716 {
5717 	/* A referenced register is always trusted. */
5718 	if (reg->ref_obj_id)
5719 		return true;
5720 
5721 	/* Types listed in the reg2btf_ids are always trusted */
5722 	if (reg2btf_ids[base_type(reg->type)])
5723 		return true;
5724 
5725 	/* If a register is not referenced, it is trusted if it has the
5726 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5727 	 * other type modifiers may be safe, but we elect to take an opt-in
5728 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5729 	 * not.
5730 	 *
5731 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5732 	 * for whether a register is trusted.
5733 	 */
5734 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5735 	       !bpf_type_has_unsafe_modifiers(reg->type);
5736 }
5737 
5738 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5739 {
5740 	return reg->type & MEM_RCU;
5741 }
5742 
5743 static void clear_trusted_flags(enum bpf_type_flag *flag)
5744 {
5745 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5746 }
5747 
5748 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5749 				   const struct bpf_reg_state *reg,
5750 				   int off, int size, bool strict)
5751 {
5752 	struct tnum reg_off;
5753 	int ip_align;
5754 
5755 	/* Byte size accesses are always allowed. */
5756 	if (!strict || size == 1)
5757 		return 0;
5758 
5759 	/* For platforms that do not have a Kconfig enabling
5760 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5761 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5762 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5763 	 * to this code only in strict mode where we want to emulate
5764 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5765 	 * unconditional IP align value of '2'.
5766 	 */
5767 	ip_align = 2;
5768 
5769 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5770 	if (!tnum_is_aligned(reg_off, size)) {
5771 		char tn_buf[48];
5772 
5773 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5774 		verbose(env,
5775 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5776 			ip_align, tn_buf, reg->off, off, size);
5777 		return -EACCES;
5778 	}
5779 
5780 	return 0;
5781 }
5782 
5783 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5784 				       const struct bpf_reg_state *reg,
5785 				       const char *pointer_desc,
5786 				       int off, int size, bool strict)
5787 {
5788 	struct tnum reg_off;
5789 
5790 	/* Byte size accesses are always allowed. */
5791 	if (!strict || size == 1)
5792 		return 0;
5793 
5794 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5795 	if (!tnum_is_aligned(reg_off, size)) {
5796 		char tn_buf[48];
5797 
5798 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5799 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5800 			pointer_desc, tn_buf, reg->off, off, size);
5801 		return -EACCES;
5802 	}
5803 
5804 	return 0;
5805 }
5806 
5807 static int check_ptr_alignment(struct bpf_verifier_env *env,
5808 			       const struct bpf_reg_state *reg, int off,
5809 			       int size, bool strict_alignment_once)
5810 {
5811 	bool strict = env->strict_alignment || strict_alignment_once;
5812 	const char *pointer_desc = "";
5813 
5814 	switch (reg->type) {
5815 	case PTR_TO_PACKET:
5816 	case PTR_TO_PACKET_META:
5817 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5818 		 * right in front, treat it the very same way.
5819 		 */
5820 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5821 	case PTR_TO_FLOW_KEYS:
5822 		pointer_desc = "flow keys ";
5823 		break;
5824 	case PTR_TO_MAP_KEY:
5825 		pointer_desc = "key ";
5826 		break;
5827 	case PTR_TO_MAP_VALUE:
5828 		pointer_desc = "value ";
5829 		break;
5830 	case PTR_TO_CTX:
5831 		pointer_desc = "context ";
5832 		break;
5833 	case PTR_TO_STACK:
5834 		pointer_desc = "stack ";
5835 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5836 		 * and check_stack_read_fixed_off() relies on stack accesses being
5837 		 * aligned.
5838 		 */
5839 		strict = true;
5840 		break;
5841 	case PTR_TO_SOCKET:
5842 		pointer_desc = "sock ";
5843 		break;
5844 	case PTR_TO_SOCK_COMMON:
5845 		pointer_desc = "sock_common ";
5846 		break;
5847 	case PTR_TO_TCP_SOCK:
5848 		pointer_desc = "tcp_sock ";
5849 		break;
5850 	case PTR_TO_XDP_SOCK:
5851 		pointer_desc = "xdp_sock ";
5852 		break;
5853 	case PTR_TO_ARENA:
5854 		return 0;
5855 	default:
5856 		break;
5857 	}
5858 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5859 					   strict);
5860 }
5861 
5862 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5863 {
5864 	if (env->prog->jit_requested)
5865 		return round_up(stack_depth, 16);
5866 
5867 	/* round up to 32-bytes, since this is granularity
5868 	 * of interpreter stack size
5869 	 */
5870 	return round_up(max_t(u32, stack_depth, 1), 32);
5871 }
5872 
5873 /* starting from main bpf function walk all instructions of the function
5874  * and recursively walk all callees that given function can call.
5875  * Ignore jump and exit insns.
5876  * Since recursion is prevented by check_cfg() this algorithm
5877  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5878  */
5879 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5880 {
5881 	struct bpf_subprog_info *subprog = env->subprog_info;
5882 	struct bpf_insn *insn = env->prog->insnsi;
5883 	int depth = 0, frame = 0, i, subprog_end;
5884 	bool tail_call_reachable = false;
5885 	int ret_insn[MAX_CALL_FRAMES];
5886 	int ret_prog[MAX_CALL_FRAMES];
5887 	int j;
5888 
5889 	i = subprog[idx].start;
5890 process_func:
5891 	/* protect against potential stack overflow that might happen when
5892 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5893 	 * depth for such case down to 256 so that the worst case scenario
5894 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5895 	 * 8k).
5896 	 *
5897 	 * To get the idea what might happen, see an example:
5898 	 * func1 -> sub rsp, 128
5899 	 *  subfunc1 -> sub rsp, 256
5900 	 *  tailcall1 -> add rsp, 256
5901 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5902 	 *   subfunc2 -> sub rsp, 64
5903 	 *   subfunc22 -> sub rsp, 128
5904 	 *   tailcall2 -> add rsp, 128
5905 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5906 	 *
5907 	 * tailcall will unwind the current stack frame but it will not get rid
5908 	 * of caller's stack as shown on the example above.
5909 	 */
5910 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5911 		verbose(env,
5912 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5913 			depth);
5914 		return -EACCES;
5915 	}
5916 	depth += round_up_stack_depth(env, subprog[idx].stack_depth);
5917 	if (depth > MAX_BPF_STACK) {
5918 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5919 			frame + 1, depth);
5920 		return -EACCES;
5921 	}
5922 continue_func:
5923 	subprog_end = subprog[idx + 1].start;
5924 	for (; i < subprog_end; i++) {
5925 		int next_insn, sidx;
5926 
5927 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5928 			bool err = false;
5929 
5930 			if (!is_bpf_throw_kfunc(insn + i))
5931 				continue;
5932 			if (subprog[idx].is_cb)
5933 				err = true;
5934 			for (int c = 0; c < frame && !err; c++) {
5935 				if (subprog[ret_prog[c]].is_cb) {
5936 					err = true;
5937 					break;
5938 				}
5939 			}
5940 			if (!err)
5941 				continue;
5942 			verbose(env,
5943 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5944 				i, idx);
5945 			return -EINVAL;
5946 		}
5947 
5948 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5949 			continue;
5950 		/* remember insn and function to return to */
5951 		ret_insn[frame] = i + 1;
5952 		ret_prog[frame] = idx;
5953 
5954 		/* find the callee */
5955 		next_insn = i + insn[i].imm + 1;
5956 		sidx = find_subprog(env, next_insn);
5957 		if (sidx < 0) {
5958 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5959 				  next_insn);
5960 			return -EFAULT;
5961 		}
5962 		if (subprog[sidx].is_async_cb) {
5963 			if (subprog[sidx].has_tail_call) {
5964 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5965 				return -EFAULT;
5966 			}
5967 			/* async callbacks don't increase bpf prog stack size unless called directly */
5968 			if (!bpf_pseudo_call(insn + i))
5969 				continue;
5970 			if (subprog[sidx].is_exception_cb) {
5971 				verbose(env, "insn %d cannot call exception cb directly\n", i);
5972 				return -EINVAL;
5973 			}
5974 		}
5975 		i = next_insn;
5976 		idx = sidx;
5977 
5978 		if (subprog[idx].has_tail_call)
5979 			tail_call_reachable = true;
5980 
5981 		frame++;
5982 		if (frame >= MAX_CALL_FRAMES) {
5983 			verbose(env, "the call stack of %d frames is too deep !\n",
5984 				frame);
5985 			return -E2BIG;
5986 		}
5987 		goto process_func;
5988 	}
5989 	/* if tail call got detected across bpf2bpf calls then mark each of the
5990 	 * currently present subprog frames as tail call reachable subprogs;
5991 	 * this info will be utilized by JIT so that we will be preserving the
5992 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5993 	 */
5994 	if (tail_call_reachable)
5995 		for (j = 0; j < frame; j++) {
5996 			if (subprog[ret_prog[j]].is_exception_cb) {
5997 				verbose(env, "cannot tail call within exception cb\n");
5998 				return -EINVAL;
5999 			}
6000 			subprog[ret_prog[j]].tail_call_reachable = true;
6001 		}
6002 	if (subprog[0].tail_call_reachable)
6003 		env->prog->aux->tail_call_reachable = true;
6004 
6005 	/* end of for() loop means the last insn of the 'subprog'
6006 	 * was reached. Doesn't matter whether it was JA or EXIT
6007 	 */
6008 	if (frame == 0)
6009 		return 0;
6010 	depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6011 	frame--;
6012 	i = ret_insn[frame];
6013 	idx = ret_prog[frame];
6014 	goto continue_func;
6015 }
6016 
6017 static int check_max_stack_depth(struct bpf_verifier_env *env)
6018 {
6019 	struct bpf_subprog_info *si = env->subprog_info;
6020 	int ret;
6021 
6022 	for (int i = 0; i < env->subprog_cnt; i++) {
6023 		if (!i || si[i].is_async_cb) {
6024 			ret = check_max_stack_depth_subprog(env, i);
6025 			if (ret < 0)
6026 				return ret;
6027 		}
6028 		continue;
6029 	}
6030 	return 0;
6031 }
6032 
6033 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6034 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6035 				  const struct bpf_insn *insn, int idx)
6036 {
6037 	int start = idx + insn->imm + 1, subprog;
6038 
6039 	subprog = find_subprog(env, start);
6040 	if (subprog < 0) {
6041 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6042 			  start);
6043 		return -EFAULT;
6044 	}
6045 	return env->subprog_info[subprog].stack_depth;
6046 }
6047 #endif
6048 
6049 static int __check_buffer_access(struct bpf_verifier_env *env,
6050 				 const char *buf_info,
6051 				 const struct bpf_reg_state *reg,
6052 				 int regno, int off, int size)
6053 {
6054 	if (off < 0) {
6055 		verbose(env,
6056 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6057 			regno, buf_info, off, size);
6058 		return -EACCES;
6059 	}
6060 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6061 		char tn_buf[48];
6062 
6063 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6064 		verbose(env,
6065 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6066 			regno, off, tn_buf);
6067 		return -EACCES;
6068 	}
6069 
6070 	return 0;
6071 }
6072 
6073 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6074 				  const struct bpf_reg_state *reg,
6075 				  int regno, int off, int size)
6076 {
6077 	int err;
6078 
6079 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6080 	if (err)
6081 		return err;
6082 
6083 	if (off + size > env->prog->aux->max_tp_access)
6084 		env->prog->aux->max_tp_access = off + size;
6085 
6086 	return 0;
6087 }
6088 
6089 static int check_buffer_access(struct bpf_verifier_env *env,
6090 			       const struct bpf_reg_state *reg,
6091 			       int regno, int off, int size,
6092 			       bool zero_size_allowed,
6093 			       u32 *max_access)
6094 {
6095 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6096 	int err;
6097 
6098 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6099 	if (err)
6100 		return err;
6101 
6102 	if (off + size > *max_access)
6103 		*max_access = off + size;
6104 
6105 	return 0;
6106 }
6107 
6108 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6109 static void zext_32_to_64(struct bpf_reg_state *reg)
6110 {
6111 	reg->var_off = tnum_subreg(reg->var_off);
6112 	__reg_assign_32_into_64(reg);
6113 }
6114 
6115 /* truncate register to smaller size (in bytes)
6116  * must be called with size < BPF_REG_SIZE
6117  */
6118 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6119 {
6120 	u64 mask;
6121 
6122 	/* clear high bits in bit representation */
6123 	reg->var_off = tnum_cast(reg->var_off, size);
6124 
6125 	/* fix arithmetic bounds */
6126 	mask = ((u64)1 << (size * 8)) - 1;
6127 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6128 		reg->umin_value &= mask;
6129 		reg->umax_value &= mask;
6130 	} else {
6131 		reg->umin_value = 0;
6132 		reg->umax_value = mask;
6133 	}
6134 	reg->smin_value = reg->umin_value;
6135 	reg->smax_value = reg->umax_value;
6136 
6137 	/* If size is smaller than 32bit register the 32bit register
6138 	 * values are also truncated so we push 64-bit bounds into
6139 	 * 32-bit bounds. Above were truncated < 32-bits already.
6140 	 */
6141 	if (size < 4)
6142 		__mark_reg32_unbounded(reg);
6143 
6144 	reg_bounds_sync(reg);
6145 }
6146 
6147 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6148 {
6149 	if (size == 1) {
6150 		reg->smin_value = reg->s32_min_value = S8_MIN;
6151 		reg->smax_value = reg->s32_max_value = S8_MAX;
6152 	} else if (size == 2) {
6153 		reg->smin_value = reg->s32_min_value = S16_MIN;
6154 		reg->smax_value = reg->s32_max_value = S16_MAX;
6155 	} else {
6156 		/* size == 4 */
6157 		reg->smin_value = reg->s32_min_value = S32_MIN;
6158 		reg->smax_value = reg->s32_max_value = S32_MAX;
6159 	}
6160 	reg->umin_value = reg->u32_min_value = 0;
6161 	reg->umax_value = U64_MAX;
6162 	reg->u32_max_value = U32_MAX;
6163 	reg->var_off = tnum_unknown;
6164 }
6165 
6166 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6167 {
6168 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6169 	u64 top_smax_value, top_smin_value;
6170 	u64 num_bits = size * 8;
6171 
6172 	if (tnum_is_const(reg->var_off)) {
6173 		u64_cval = reg->var_off.value;
6174 		if (size == 1)
6175 			reg->var_off = tnum_const((s8)u64_cval);
6176 		else if (size == 2)
6177 			reg->var_off = tnum_const((s16)u64_cval);
6178 		else
6179 			/* size == 4 */
6180 			reg->var_off = tnum_const((s32)u64_cval);
6181 
6182 		u64_cval = reg->var_off.value;
6183 		reg->smax_value = reg->smin_value = u64_cval;
6184 		reg->umax_value = reg->umin_value = u64_cval;
6185 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6186 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6187 		return;
6188 	}
6189 
6190 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6191 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6192 
6193 	if (top_smax_value != top_smin_value)
6194 		goto out;
6195 
6196 	/* find the s64_min and s64_min after sign extension */
6197 	if (size == 1) {
6198 		init_s64_max = (s8)reg->smax_value;
6199 		init_s64_min = (s8)reg->smin_value;
6200 	} else if (size == 2) {
6201 		init_s64_max = (s16)reg->smax_value;
6202 		init_s64_min = (s16)reg->smin_value;
6203 	} else {
6204 		init_s64_max = (s32)reg->smax_value;
6205 		init_s64_min = (s32)reg->smin_value;
6206 	}
6207 
6208 	s64_max = max(init_s64_max, init_s64_min);
6209 	s64_min = min(init_s64_max, init_s64_min);
6210 
6211 	/* both of s64_max/s64_min positive or negative */
6212 	if ((s64_max >= 0) == (s64_min >= 0)) {
6213 		reg->smin_value = reg->s32_min_value = s64_min;
6214 		reg->smax_value = reg->s32_max_value = s64_max;
6215 		reg->umin_value = reg->u32_min_value = s64_min;
6216 		reg->umax_value = reg->u32_max_value = s64_max;
6217 		reg->var_off = tnum_range(s64_min, s64_max);
6218 		return;
6219 	}
6220 
6221 out:
6222 	set_sext64_default_val(reg, size);
6223 }
6224 
6225 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6226 {
6227 	if (size == 1) {
6228 		reg->s32_min_value = S8_MIN;
6229 		reg->s32_max_value = S8_MAX;
6230 	} else {
6231 		/* size == 2 */
6232 		reg->s32_min_value = S16_MIN;
6233 		reg->s32_max_value = S16_MAX;
6234 	}
6235 	reg->u32_min_value = 0;
6236 	reg->u32_max_value = U32_MAX;
6237 }
6238 
6239 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6240 {
6241 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6242 	u32 top_smax_value, top_smin_value;
6243 	u32 num_bits = size * 8;
6244 
6245 	if (tnum_is_const(reg->var_off)) {
6246 		u32_val = reg->var_off.value;
6247 		if (size == 1)
6248 			reg->var_off = tnum_const((s8)u32_val);
6249 		else
6250 			reg->var_off = tnum_const((s16)u32_val);
6251 
6252 		u32_val = reg->var_off.value;
6253 		reg->s32_min_value = reg->s32_max_value = u32_val;
6254 		reg->u32_min_value = reg->u32_max_value = u32_val;
6255 		return;
6256 	}
6257 
6258 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6259 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6260 
6261 	if (top_smax_value != top_smin_value)
6262 		goto out;
6263 
6264 	/* find the s32_min and s32_min after sign extension */
6265 	if (size == 1) {
6266 		init_s32_max = (s8)reg->s32_max_value;
6267 		init_s32_min = (s8)reg->s32_min_value;
6268 	} else {
6269 		/* size == 2 */
6270 		init_s32_max = (s16)reg->s32_max_value;
6271 		init_s32_min = (s16)reg->s32_min_value;
6272 	}
6273 	s32_max = max(init_s32_max, init_s32_min);
6274 	s32_min = min(init_s32_max, init_s32_min);
6275 
6276 	if ((s32_min >= 0) == (s32_max >= 0)) {
6277 		reg->s32_min_value = s32_min;
6278 		reg->s32_max_value = s32_max;
6279 		reg->u32_min_value = (u32)s32_min;
6280 		reg->u32_max_value = (u32)s32_max;
6281 		return;
6282 	}
6283 
6284 out:
6285 	set_sext32_default_val(reg, size);
6286 }
6287 
6288 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6289 {
6290 	/* A map is considered read-only if the following condition are true:
6291 	 *
6292 	 * 1) BPF program side cannot change any of the map content. The
6293 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6294 	 *    and was set at map creation time.
6295 	 * 2) The map value(s) have been initialized from user space by a
6296 	 *    loader and then "frozen", such that no new map update/delete
6297 	 *    operations from syscall side are possible for the rest of
6298 	 *    the map's lifetime from that point onwards.
6299 	 * 3) Any parallel/pending map update/delete operations from syscall
6300 	 *    side have been completed. Only after that point, it's safe to
6301 	 *    assume that map value(s) are immutable.
6302 	 */
6303 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6304 	       READ_ONCE(map->frozen) &&
6305 	       !bpf_map_write_active(map);
6306 }
6307 
6308 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6309 			       bool is_ldsx)
6310 {
6311 	void *ptr;
6312 	u64 addr;
6313 	int err;
6314 
6315 	err = map->ops->map_direct_value_addr(map, &addr, off);
6316 	if (err)
6317 		return err;
6318 	ptr = (void *)(long)addr + off;
6319 
6320 	switch (size) {
6321 	case sizeof(u8):
6322 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6323 		break;
6324 	case sizeof(u16):
6325 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6326 		break;
6327 	case sizeof(u32):
6328 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6329 		break;
6330 	case sizeof(u64):
6331 		*val = *(u64 *)ptr;
6332 		break;
6333 	default:
6334 		return -EINVAL;
6335 	}
6336 	return 0;
6337 }
6338 
6339 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6340 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6341 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6342 
6343 /*
6344  * Allow list few fields as RCU trusted or full trusted.
6345  * This logic doesn't allow mix tagging and will be removed once GCC supports
6346  * btf_type_tag.
6347  */
6348 
6349 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6350 BTF_TYPE_SAFE_RCU(struct task_struct) {
6351 	const cpumask_t *cpus_ptr;
6352 	struct css_set __rcu *cgroups;
6353 	struct task_struct __rcu *real_parent;
6354 	struct task_struct *group_leader;
6355 };
6356 
6357 BTF_TYPE_SAFE_RCU(struct cgroup) {
6358 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6359 	struct kernfs_node *kn;
6360 };
6361 
6362 BTF_TYPE_SAFE_RCU(struct css_set) {
6363 	struct cgroup *dfl_cgrp;
6364 };
6365 
6366 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6367 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6368 	struct file __rcu *exe_file;
6369 };
6370 
6371 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6372  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6373  */
6374 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6375 	struct sock *sk;
6376 };
6377 
6378 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6379 	struct sock *sk;
6380 };
6381 
6382 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6383 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6384 	struct seq_file *seq;
6385 };
6386 
6387 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6388 	struct bpf_iter_meta *meta;
6389 	struct task_struct *task;
6390 };
6391 
6392 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6393 	struct file *file;
6394 };
6395 
6396 BTF_TYPE_SAFE_TRUSTED(struct file) {
6397 	struct inode *f_inode;
6398 };
6399 
6400 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6401 	/* no negative dentry-s in places where bpf can see it */
6402 	struct inode *d_inode;
6403 };
6404 
6405 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6406 	struct sock *sk;
6407 };
6408 
6409 static bool type_is_rcu(struct bpf_verifier_env *env,
6410 			struct bpf_reg_state *reg,
6411 			const char *field_name, u32 btf_id)
6412 {
6413 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6414 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6415 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6416 
6417 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6418 }
6419 
6420 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6421 				struct bpf_reg_state *reg,
6422 				const char *field_name, u32 btf_id)
6423 {
6424 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6425 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6426 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6427 
6428 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6429 }
6430 
6431 static bool type_is_trusted(struct bpf_verifier_env *env,
6432 			    struct bpf_reg_state *reg,
6433 			    const char *field_name, u32 btf_id)
6434 {
6435 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6436 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6437 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6438 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6439 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6440 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6441 
6442 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6443 }
6444 
6445 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6446 				   struct bpf_reg_state *regs,
6447 				   int regno, int off, int size,
6448 				   enum bpf_access_type atype,
6449 				   int value_regno)
6450 {
6451 	struct bpf_reg_state *reg = regs + regno;
6452 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6453 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6454 	const char *field_name = NULL;
6455 	enum bpf_type_flag flag = 0;
6456 	u32 btf_id = 0;
6457 	int ret;
6458 
6459 	if (!env->allow_ptr_leaks) {
6460 		verbose(env,
6461 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6462 			tname);
6463 		return -EPERM;
6464 	}
6465 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6466 		verbose(env,
6467 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6468 			tname);
6469 		return -EINVAL;
6470 	}
6471 	if (off < 0) {
6472 		verbose(env,
6473 			"R%d is ptr_%s invalid negative access: off=%d\n",
6474 			regno, tname, off);
6475 		return -EACCES;
6476 	}
6477 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6478 		char tn_buf[48];
6479 
6480 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6481 		verbose(env,
6482 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6483 			regno, tname, off, tn_buf);
6484 		return -EACCES;
6485 	}
6486 
6487 	if (reg->type & MEM_USER) {
6488 		verbose(env,
6489 			"R%d is ptr_%s access user memory: off=%d\n",
6490 			regno, tname, off);
6491 		return -EACCES;
6492 	}
6493 
6494 	if (reg->type & MEM_PERCPU) {
6495 		verbose(env,
6496 			"R%d is ptr_%s access percpu memory: off=%d\n",
6497 			regno, tname, off);
6498 		return -EACCES;
6499 	}
6500 
6501 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6502 		if (!btf_is_kernel(reg->btf)) {
6503 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6504 			return -EFAULT;
6505 		}
6506 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6507 	} else {
6508 		/* Writes are permitted with default btf_struct_access for
6509 		 * program allocated objects (which always have ref_obj_id > 0),
6510 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6511 		 */
6512 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6513 			verbose(env, "only read is supported\n");
6514 			return -EACCES;
6515 		}
6516 
6517 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6518 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6519 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6520 			return -EFAULT;
6521 		}
6522 
6523 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6524 	}
6525 
6526 	if (ret < 0)
6527 		return ret;
6528 
6529 	if (ret != PTR_TO_BTF_ID) {
6530 		/* just mark; */
6531 
6532 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6533 		/* If this is an untrusted pointer, all pointers formed by walking it
6534 		 * also inherit the untrusted flag.
6535 		 */
6536 		flag = PTR_UNTRUSTED;
6537 
6538 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6539 		/* By default any pointer obtained from walking a trusted pointer is no
6540 		 * longer trusted, unless the field being accessed has explicitly been
6541 		 * marked as inheriting its parent's state of trust (either full or RCU).
6542 		 * For example:
6543 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6544 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6545 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6546 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6547 		 *
6548 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6549 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6550 		 */
6551 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6552 			flag |= PTR_TRUSTED;
6553 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6554 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6555 				/* ignore __rcu tag and mark it MEM_RCU */
6556 				flag |= MEM_RCU;
6557 			} else if (flag & MEM_RCU ||
6558 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6559 				/* __rcu tagged pointers can be NULL */
6560 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6561 
6562 				/* We always trust them */
6563 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6564 				    flag & PTR_UNTRUSTED)
6565 					flag &= ~PTR_UNTRUSTED;
6566 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6567 				/* keep as-is */
6568 			} else {
6569 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6570 				clear_trusted_flags(&flag);
6571 			}
6572 		} else {
6573 			/*
6574 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6575 			 * aggressively mark as untrusted otherwise such
6576 			 * pointers will be plain PTR_TO_BTF_ID without flags
6577 			 * and will be allowed to be passed into helpers for
6578 			 * compat reasons.
6579 			 */
6580 			flag = PTR_UNTRUSTED;
6581 		}
6582 	} else {
6583 		/* Old compat. Deprecated */
6584 		clear_trusted_flags(&flag);
6585 	}
6586 
6587 	if (atype == BPF_READ && value_regno >= 0)
6588 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6589 
6590 	return 0;
6591 }
6592 
6593 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6594 				   struct bpf_reg_state *regs,
6595 				   int regno, int off, int size,
6596 				   enum bpf_access_type atype,
6597 				   int value_regno)
6598 {
6599 	struct bpf_reg_state *reg = regs + regno;
6600 	struct bpf_map *map = reg->map_ptr;
6601 	struct bpf_reg_state map_reg;
6602 	enum bpf_type_flag flag = 0;
6603 	const struct btf_type *t;
6604 	const char *tname;
6605 	u32 btf_id;
6606 	int ret;
6607 
6608 	if (!btf_vmlinux) {
6609 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6610 		return -ENOTSUPP;
6611 	}
6612 
6613 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6614 		verbose(env, "map_ptr access not supported for map type %d\n",
6615 			map->map_type);
6616 		return -ENOTSUPP;
6617 	}
6618 
6619 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6620 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6621 
6622 	if (!env->allow_ptr_leaks) {
6623 		verbose(env,
6624 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6625 			tname);
6626 		return -EPERM;
6627 	}
6628 
6629 	if (off < 0) {
6630 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6631 			regno, tname, off);
6632 		return -EACCES;
6633 	}
6634 
6635 	if (atype != BPF_READ) {
6636 		verbose(env, "only read from %s is supported\n", tname);
6637 		return -EACCES;
6638 	}
6639 
6640 	/* Simulate access to a PTR_TO_BTF_ID */
6641 	memset(&map_reg, 0, sizeof(map_reg));
6642 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6643 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6644 	if (ret < 0)
6645 		return ret;
6646 
6647 	if (value_regno >= 0)
6648 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6649 
6650 	return 0;
6651 }
6652 
6653 /* Check that the stack access at the given offset is within bounds. The
6654  * maximum valid offset is -1.
6655  *
6656  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6657  * -state->allocated_stack for reads.
6658  */
6659 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6660                                           s64 off,
6661                                           struct bpf_func_state *state,
6662                                           enum bpf_access_type t)
6663 {
6664 	int min_valid_off;
6665 
6666 	if (t == BPF_WRITE || env->allow_uninit_stack)
6667 		min_valid_off = -MAX_BPF_STACK;
6668 	else
6669 		min_valid_off = -state->allocated_stack;
6670 
6671 	if (off < min_valid_off || off > -1)
6672 		return -EACCES;
6673 	return 0;
6674 }
6675 
6676 /* Check that the stack access at 'regno + off' falls within the maximum stack
6677  * bounds.
6678  *
6679  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6680  */
6681 static int check_stack_access_within_bounds(
6682 		struct bpf_verifier_env *env,
6683 		int regno, int off, int access_size,
6684 		enum bpf_access_src src, enum bpf_access_type type)
6685 {
6686 	struct bpf_reg_state *regs = cur_regs(env);
6687 	struct bpf_reg_state *reg = regs + regno;
6688 	struct bpf_func_state *state = func(env, reg);
6689 	s64 min_off, max_off;
6690 	int err;
6691 	char *err_extra;
6692 
6693 	if (src == ACCESS_HELPER)
6694 		/* We don't know if helpers are reading or writing (or both). */
6695 		err_extra = " indirect access to";
6696 	else if (type == BPF_READ)
6697 		err_extra = " read from";
6698 	else
6699 		err_extra = " write to";
6700 
6701 	if (tnum_is_const(reg->var_off)) {
6702 		min_off = (s64)reg->var_off.value + off;
6703 		max_off = min_off + access_size;
6704 	} else {
6705 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6706 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6707 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6708 				err_extra, regno);
6709 			return -EACCES;
6710 		}
6711 		min_off = reg->smin_value + off;
6712 		max_off = reg->smax_value + off + access_size;
6713 	}
6714 
6715 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6716 	if (!err && max_off > 0)
6717 		err = -EINVAL; /* out of stack access into non-negative offsets */
6718 	if (!err && access_size < 0)
6719 		/* access_size should not be negative (or overflow an int); others checks
6720 		 * along the way should have prevented such an access.
6721 		 */
6722 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6723 
6724 	if (err) {
6725 		if (tnum_is_const(reg->var_off)) {
6726 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6727 				err_extra, regno, off, access_size);
6728 		} else {
6729 			char tn_buf[48];
6730 
6731 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6732 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
6733 				err_extra, regno, tn_buf, off, access_size);
6734 		}
6735 		return err;
6736 	}
6737 
6738 	/* Note that there is no stack access with offset zero, so the needed stack
6739 	 * size is -min_off, not -min_off+1.
6740 	 */
6741 	return grow_stack_state(env, state, -min_off /* size */);
6742 }
6743 
6744 /* check whether memory at (regno + off) is accessible for t = (read | write)
6745  * if t==write, value_regno is a register which value is stored into memory
6746  * if t==read, value_regno is a register which will receive the value from memory
6747  * if t==write && value_regno==-1, some unknown value is stored into memory
6748  * if t==read && value_regno==-1, don't care what we read from memory
6749  */
6750 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6751 			    int off, int bpf_size, enum bpf_access_type t,
6752 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6753 {
6754 	struct bpf_reg_state *regs = cur_regs(env);
6755 	struct bpf_reg_state *reg = regs + regno;
6756 	int size, err = 0;
6757 
6758 	size = bpf_size_to_bytes(bpf_size);
6759 	if (size < 0)
6760 		return size;
6761 
6762 	/* alignment checks will add in reg->off themselves */
6763 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6764 	if (err)
6765 		return err;
6766 
6767 	/* for access checks, reg->off is just part of off */
6768 	off += reg->off;
6769 
6770 	if (reg->type == PTR_TO_MAP_KEY) {
6771 		if (t == BPF_WRITE) {
6772 			verbose(env, "write to change key R%d not allowed\n", regno);
6773 			return -EACCES;
6774 		}
6775 
6776 		err = check_mem_region_access(env, regno, off, size,
6777 					      reg->map_ptr->key_size, false);
6778 		if (err)
6779 			return err;
6780 		if (value_regno >= 0)
6781 			mark_reg_unknown(env, regs, value_regno);
6782 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6783 		struct btf_field *kptr_field = NULL;
6784 
6785 		if (t == BPF_WRITE && value_regno >= 0 &&
6786 		    is_pointer_value(env, value_regno)) {
6787 			verbose(env, "R%d leaks addr into map\n", value_regno);
6788 			return -EACCES;
6789 		}
6790 		err = check_map_access_type(env, regno, off, size, t);
6791 		if (err)
6792 			return err;
6793 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6794 		if (err)
6795 			return err;
6796 		if (tnum_is_const(reg->var_off))
6797 			kptr_field = btf_record_find(reg->map_ptr->record,
6798 						     off + reg->var_off.value, BPF_KPTR);
6799 		if (kptr_field) {
6800 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6801 		} else if (t == BPF_READ && value_regno >= 0) {
6802 			struct bpf_map *map = reg->map_ptr;
6803 
6804 			/* if map is read-only, track its contents as scalars */
6805 			if (tnum_is_const(reg->var_off) &&
6806 			    bpf_map_is_rdonly(map) &&
6807 			    map->ops->map_direct_value_addr) {
6808 				int map_off = off + reg->var_off.value;
6809 				u64 val = 0;
6810 
6811 				err = bpf_map_direct_read(map, map_off, size,
6812 							  &val, is_ldsx);
6813 				if (err)
6814 					return err;
6815 
6816 				regs[value_regno].type = SCALAR_VALUE;
6817 				__mark_reg_known(&regs[value_regno], val);
6818 			} else {
6819 				mark_reg_unknown(env, regs, value_regno);
6820 			}
6821 		}
6822 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6823 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6824 
6825 		if (type_may_be_null(reg->type)) {
6826 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6827 				reg_type_str(env, reg->type));
6828 			return -EACCES;
6829 		}
6830 
6831 		if (t == BPF_WRITE && rdonly_mem) {
6832 			verbose(env, "R%d cannot write into %s\n",
6833 				regno, reg_type_str(env, reg->type));
6834 			return -EACCES;
6835 		}
6836 
6837 		if (t == BPF_WRITE && value_regno >= 0 &&
6838 		    is_pointer_value(env, value_regno)) {
6839 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6840 			return -EACCES;
6841 		}
6842 
6843 		err = check_mem_region_access(env, regno, off, size,
6844 					      reg->mem_size, false);
6845 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6846 			mark_reg_unknown(env, regs, value_regno);
6847 	} else if (reg->type == PTR_TO_CTX) {
6848 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6849 		struct btf *btf = NULL;
6850 		u32 btf_id = 0;
6851 
6852 		if (t == BPF_WRITE && value_regno >= 0 &&
6853 		    is_pointer_value(env, value_regno)) {
6854 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6855 			return -EACCES;
6856 		}
6857 
6858 		err = check_ptr_off_reg(env, reg, regno);
6859 		if (err < 0)
6860 			return err;
6861 
6862 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6863 				       &btf_id);
6864 		if (err)
6865 			verbose_linfo(env, insn_idx, "; ");
6866 		if (!err && t == BPF_READ && value_regno >= 0) {
6867 			/* ctx access returns either a scalar, or a
6868 			 * PTR_TO_PACKET[_META,_END]. In the latter
6869 			 * case, we know the offset is zero.
6870 			 */
6871 			if (reg_type == SCALAR_VALUE) {
6872 				mark_reg_unknown(env, regs, value_regno);
6873 			} else {
6874 				mark_reg_known_zero(env, regs,
6875 						    value_regno);
6876 				if (type_may_be_null(reg_type))
6877 					regs[value_regno].id = ++env->id_gen;
6878 				/* A load of ctx field could have different
6879 				 * actual load size with the one encoded in the
6880 				 * insn. When the dst is PTR, it is for sure not
6881 				 * a sub-register.
6882 				 */
6883 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6884 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6885 					regs[value_regno].btf = btf;
6886 					regs[value_regno].btf_id = btf_id;
6887 				}
6888 			}
6889 			regs[value_regno].type = reg_type;
6890 		}
6891 
6892 	} else if (reg->type == PTR_TO_STACK) {
6893 		/* Basic bounds checks. */
6894 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6895 		if (err)
6896 			return err;
6897 
6898 		if (t == BPF_READ)
6899 			err = check_stack_read(env, regno, off, size,
6900 					       value_regno);
6901 		else
6902 			err = check_stack_write(env, regno, off, size,
6903 						value_regno, insn_idx);
6904 	} else if (reg_is_pkt_pointer(reg)) {
6905 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6906 			verbose(env, "cannot write into packet\n");
6907 			return -EACCES;
6908 		}
6909 		if (t == BPF_WRITE && value_regno >= 0 &&
6910 		    is_pointer_value(env, value_regno)) {
6911 			verbose(env, "R%d leaks addr into packet\n",
6912 				value_regno);
6913 			return -EACCES;
6914 		}
6915 		err = check_packet_access(env, regno, off, size, false);
6916 		if (!err && t == BPF_READ && value_regno >= 0)
6917 			mark_reg_unknown(env, regs, value_regno);
6918 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6919 		if (t == BPF_WRITE && value_regno >= 0 &&
6920 		    is_pointer_value(env, value_regno)) {
6921 			verbose(env, "R%d leaks addr into flow keys\n",
6922 				value_regno);
6923 			return -EACCES;
6924 		}
6925 
6926 		err = check_flow_keys_access(env, off, size);
6927 		if (!err && t == BPF_READ && value_regno >= 0)
6928 			mark_reg_unknown(env, regs, value_regno);
6929 	} else if (type_is_sk_pointer(reg->type)) {
6930 		if (t == BPF_WRITE) {
6931 			verbose(env, "R%d cannot write into %s\n",
6932 				regno, reg_type_str(env, reg->type));
6933 			return -EACCES;
6934 		}
6935 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6936 		if (!err && value_regno >= 0)
6937 			mark_reg_unknown(env, regs, value_regno);
6938 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6939 		err = check_tp_buffer_access(env, reg, regno, off, size);
6940 		if (!err && t == BPF_READ && value_regno >= 0)
6941 			mark_reg_unknown(env, regs, value_regno);
6942 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6943 		   !type_may_be_null(reg->type)) {
6944 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6945 					      value_regno);
6946 	} else if (reg->type == CONST_PTR_TO_MAP) {
6947 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6948 					      value_regno);
6949 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6950 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6951 		u32 *max_access;
6952 
6953 		if (rdonly_mem) {
6954 			if (t == BPF_WRITE) {
6955 				verbose(env, "R%d cannot write into %s\n",
6956 					regno, reg_type_str(env, reg->type));
6957 				return -EACCES;
6958 			}
6959 			max_access = &env->prog->aux->max_rdonly_access;
6960 		} else {
6961 			max_access = &env->prog->aux->max_rdwr_access;
6962 		}
6963 
6964 		err = check_buffer_access(env, reg, regno, off, size, false,
6965 					  max_access);
6966 
6967 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6968 			mark_reg_unknown(env, regs, value_regno);
6969 	} else if (reg->type == PTR_TO_ARENA) {
6970 		if (t == BPF_READ && value_regno >= 0)
6971 			mark_reg_unknown(env, regs, value_regno);
6972 	} else {
6973 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6974 			reg_type_str(env, reg->type));
6975 		return -EACCES;
6976 	}
6977 
6978 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6979 	    regs[value_regno].type == SCALAR_VALUE) {
6980 		if (!is_ldsx)
6981 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6982 			coerce_reg_to_size(&regs[value_regno], size);
6983 		else
6984 			coerce_reg_to_size_sx(&regs[value_regno], size);
6985 	}
6986 	return err;
6987 }
6988 
6989 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
6990 			     bool allow_trust_mismatch);
6991 
6992 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6993 {
6994 	int load_reg;
6995 	int err;
6996 
6997 	switch (insn->imm) {
6998 	case BPF_ADD:
6999 	case BPF_ADD | BPF_FETCH:
7000 	case BPF_AND:
7001 	case BPF_AND | BPF_FETCH:
7002 	case BPF_OR:
7003 	case BPF_OR | BPF_FETCH:
7004 	case BPF_XOR:
7005 	case BPF_XOR | BPF_FETCH:
7006 	case BPF_XCHG:
7007 	case BPF_CMPXCHG:
7008 		break;
7009 	default:
7010 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
7011 		return -EINVAL;
7012 	}
7013 
7014 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7015 		verbose(env, "invalid atomic operand size\n");
7016 		return -EINVAL;
7017 	}
7018 
7019 	/* check src1 operand */
7020 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7021 	if (err)
7022 		return err;
7023 
7024 	/* check src2 operand */
7025 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7026 	if (err)
7027 		return err;
7028 
7029 	if (insn->imm == BPF_CMPXCHG) {
7030 		/* Check comparison of R0 with memory location */
7031 		const u32 aux_reg = BPF_REG_0;
7032 
7033 		err = check_reg_arg(env, aux_reg, SRC_OP);
7034 		if (err)
7035 			return err;
7036 
7037 		if (is_pointer_value(env, aux_reg)) {
7038 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7039 			return -EACCES;
7040 		}
7041 	}
7042 
7043 	if (is_pointer_value(env, insn->src_reg)) {
7044 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7045 		return -EACCES;
7046 	}
7047 
7048 	if (is_ctx_reg(env, insn->dst_reg) ||
7049 	    is_pkt_reg(env, insn->dst_reg) ||
7050 	    is_flow_key_reg(env, insn->dst_reg) ||
7051 	    is_sk_reg(env, insn->dst_reg) ||
7052 	    (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) {
7053 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7054 			insn->dst_reg,
7055 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7056 		return -EACCES;
7057 	}
7058 
7059 	if (insn->imm & BPF_FETCH) {
7060 		if (insn->imm == BPF_CMPXCHG)
7061 			load_reg = BPF_REG_0;
7062 		else
7063 			load_reg = insn->src_reg;
7064 
7065 		/* check and record load of old value */
7066 		err = check_reg_arg(env, load_reg, DST_OP);
7067 		if (err)
7068 			return err;
7069 	} else {
7070 		/* This instruction accesses a memory location but doesn't
7071 		 * actually load it into a register.
7072 		 */
7073 		load_reg = -1;
7074 	}
7075 
7076 	/* Check whether we can read the memory, with second call for fetch
7077 	 * case to simulate the register fill.
7078 	 */
7079 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7080 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7081 	if (!err && load_reg >= 0)
7082 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7083 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7084 				       true, false);
7085 	if (err)
7086 		return err;
7087 
7088 	if (is_arena_reg(env, insn->dst_reg)) {
7089 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7090 		if (err)
7091 			return err;
7092 	}
7093 	/* Check whether we can write into the same memory. */
7094 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7095 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7096 	if (err)
7097 		return err;
7098 	return 0;
7099 }
7100 
7101 /* When register 'regno' is used to read the stack (either directly or through
7102  * a helper function) make sure that it's within stack boundary and, depending
7103  * on the access type and privileges, that all elements of the stack are
7104  * initialized.
7105  *
7106  * 'off' includes 'regno->off', but not its dynamic part (if any).
7107  *
7108  * All registers that have been spilled on the stack in the slots within the
7109  * read offsets are marked as read.
7110  */
7111 static int check_stack_range_initialized(
7112 		struct bpf_verifier_env *env, int regno, int off,
7113 		int access_size, bool zero_size_allowed,
7114 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7115 {
7116 	struct bpf_reg_state *reg = reg_state(env, regno);
7117 	struct bpf_func_state *state = func(env, reg);
7118 	int err, min_off, max_off, i, j, slot, spi;
7119 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7120 	enum bpf_access_type bounds_check_type;
7121 	/* Some accesses can write anything into the stack, others are
7122 	 * read-only.
7123 	 */
7124 	bool clobber = false;
7125 
7126 	if (access_size == 0 && !zero_size_allowed) {
7127 		verbose(env, "invalid zero-sized read\n");
7128 		return -EACCES;
7129 	}
7130 
7131 	if (type == ACCESS_HELPER) {
7132 		/* The bounds checks for writes are more permissive than for
7133 		 * reads. However, if raw_mode is not set, we'll do extra
7134 		 * checks below.
7135 		 */
7136 		bounds_check_type = BPF_WRITE;
7137 		clobber = true;
7138 	} else {
7139 		bounds_check_type = BPF_READ;
7140 	}
7141 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7142 					       type, bounds_check_type);
7143 	if (err)
7144 		return err;
7145 
7146 
7147 	if (tnum_is_const(reg->var_off)) {
7148 		min_off = max_off = reg->var_off.value + off;
7149 	} else {
7150 		/* Variable offset is prohibited for unprivileged mode for
7151 		 * simplicity since it requires corresponding support in
7152 		 * Spectre masking for stack ALU.
7153 		 * See also retrieve_ptr_limit().
7154 		 */
7155 		if (!env->bypass_spec_v1) {
7156 			char tn_buf[48];
7157 
7158 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7159 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7160 				regno, err_extra, tn_buf);
7161 			return -EACCES;
7162 		}
7163 		/* Only initialized buffer on stack is allowed to be accessed
7164 		 * with variable offset. With uninitialized buffer it's hard to
7165 		 * guarantee that whole memory is marked as initialized on
7166 		 * helper return since specific bounds are unknown what may
7167 		 * cause uninitialized stack leaking.
7168 		 */
7169 		if (meta && meta->raw_mode)
7170 			meta = NULL;
7171 
7172 		min_off = reg->smin_value + off;
7173 		max_off = reg->smax_value + off;
7174 	}
7175 
7176 	if (meta && meta->raw_mode) {
7177 		/* Ensure we won't be overwriting dynptrs when simulating byte
7178 		 * by byte access in check_helper_call using meta.access_size.
7179 		 * This would be a problem if we have a helper in the future
7180 		 * which takes:
7181 		 *
7182 		 *	helper(uninit_mem, len, dynptr)
7183 		 *
7184 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7185 		 * may end up writing to dynptr itself when touching memory from
7186 		 * arg 1. This can be relaxed on a case by case basis for known
7187 		 * safe cases, but reject due to the possibilitiy of aliasing by
7188 		 * default.
7189 		 */
7190 		for (i = min_off; i < max_off + access_size; i++) {
7191 			int stack_off = -i - 1;
7192 
7193 			spi = __get_spi(i);
7194 			/* raw_mode may write past allocated_stack */
7195 			if (state->allocated_stack <= stack_off)
7196 				continue;
7197 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7198 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7199 				return -EACCES;
7200 			}
7201 		}
7202 		meta->access_size = access_size;
7203 		meta->regno = regno;
7204 		return 0;
7205 	}
7206 
7207 	for (i = min_off; i < max_off + access_size; i++) {
7208 		u8 *stype;
7209 
7210 		slot = -i - 1;
7211 		spi = slot / BPF_REG_SIZE;
7212 		if (state->allocated_stack <= slot) {
7213 			verbose(env, "verifier bug: allocated_stack too small");
7214 			return -EFAULT;
7215 		}
7216 
7217 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7218 		if (*stype == STACK_MISC)
7219 			goto mark;
7220 		if ((*stype == STACK_ZERO) ||
7221 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7222 			if (clobber) {
7223 				/* helper can write anything into the stack */
7224 				*stype = STACK_MISC;
7225 			}
7226 			goto mark;
7227 		}
7228 
7229 		if (is_spilled_reg(&state->stack[spi]) &&
7230 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7231 		     env->allow_ptr_leaks)) {
7232 			if (clobber) {
7233 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7234 				for (j = 0; j < BPF_REG_SIZE; j++)
7235 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7236 			}
7237 			goto mark;
7238 		}
7239 
7240 		if (tnum_is_const(reg->var_off)) {
7241 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7242 				err_extra, regno, min_off, i - min_off, access_size);
7243 		} else {
7244 			char tn_buf[48];
7245 
7246 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7247 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7248 				err_extra, regno, tn_buf, i - min_off, access_size);
7249 		}
7250 		return -EACCES;
7251 mark:
7252 		/* reading any byte out of 8-byte 'spill_slot' will cause
7253 		 * the whole slot to be marked as 'read'
7254 		 */
7255 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7256 			      state->stack[spi].spilled_ptr.parent,
7257 			      REG_LIVE_READ64);
7258 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7259 		 * be sure that whether stack slot is written to or not. Hence,
7260 		 * we must still conservatively propagate reads upwards even if
7261 		 * helper may write to the entire memory range.
7262 		 */
7263 	}
7264 	return 0;
7265 }
7266 
7267 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7268 				   int access_size, bool zero_size_allowed,
7269 				   struct bpf_call_arg_meta *meta)
7270 {
7271 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7272 	u32 *max_access;
7273 
7274 	switch (base_type(reg->type)) {
7275 	case PTR_TO_PACKET:
7276 	case PTR_TO_PACKET_META:
7277 		return check_packet_access(env, regno, reg->off, access_size,
7278 					   zero_size_allowed);
7279 	case PTR_TO_MAP_KEY:
7280 		if (meta && meta->raw_mode) {
7281 			verbose(env, "R%d cannot write into %s\n", regno,
7282 				reg_type_str(env, reg->type));
7283 			return -EACCES;
7284 		}
7285 		return check_mem_region_access(env, regno, reg->off, access_size,
7286 					       reg->map_ptr->key_size, false);
7287 	case PTR_TO_MAP_VALUE:
7288 		if (check_map_access_type(env, regno, reg->off, access_size,
7289 					  meta && meta->raw_mode ? BPF_WRITE :
7290 					  BPF_READ))
7291 			return -EACCES;
7292 		return check_map_access(env, regno, reg->off, access_size,
7293 					zero_size_allowed, ACCESS_HELPER);
7294 	case PTR_TO_MEM:
7295 		if (type_is_rdonly_mem(reg->type)) {
7296 			if (meta && meta->raw_mode) {
7297 				verbose(env, "R%d cannot write into %s\n", regno,
7298 					reg_type_str(env, reg->type));
7299 				return -EACCES;
7300 			}
7301 		}
7302 		return check_mem_region_access(env, regno, reg->off,
7303 					       access_size, reg->mem_size,
7304 					       zero_size_allowed);
7305 	case PTR_TO_BUF:
7306 		if (type_is_rdonly_mem(reg->type)) {
7307 			if (meta && meta->raw_mode) {
7308 				verbose(env, "R%d cannot write into %s\n", regno,
7309 					reg_type_str(env, reg->type));
7310 				return -EACCES;
7311 			}
7312 
7313 			max_access = &env->prog->aux->max_rdonly_access;
7314 		} else {
7315 			max_access = &env->prog->aux->max_rdwr_access;
7316 		}
7317 		return check_buffer_access(env, reg, regno, reg->off,
7318 					   access_size, zero_size_allowed,
7319 					   max_access);
7320 	case PTR_TO_STACK:
7321 		return check_stack_range_initialized(
7322 				env,
7323 				regno, reg->off, access_size,
7324 				zero_size_allowed, ACCESS_HELPER, meta);
7325 	case PTR_TO_BTF_ID:
7326 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7327 					       access_size, BPF_READ, -1);
7328 	case PTR_TO_CTX:
7329 		/* in case the function doesn't know how to access the context,
7330 		 * (because we are in a program of type SYSCALL for example), we
7331 		 * can not statically check its size.
7332 		 * Dynamically check it now.
7333 		 */
7334 		if (!env->ops->convert_ctx_access) {
7335 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7336 			int offset = access_size - 1;
7337 
7338 			/* Allow zero-byte read from PTR_TO_CTX */
7339 			if (access_size == 0)
7340 				return zero_size_allowed ? 0 : -EACCES;
7341 
7342 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7343 						atype, -1, false, false);
7344 		}
7345 
7346 		fallthrough;
7347 	default: /* scalar_value or invalid ptr */
7348 		/* Allow zero-byte read from NULL, regardless of pointer type */
7349 		if (zero_size_allowed && access_size == 0 &&
7350 		    register_is_null(reg))
7351 			return 0;
7352 
7353 		verbose(env, "R%d type=%s ", regno,
7354 			reg_type_str(env, reg->type));
7355 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7356 		return -EACCES;
7357 	}
7358 }
7359 
7360 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7361  * size.
7362  *
7363  * @regno is the register containing the access size. regno-1 is the register
7364  * containing the pointer.
7365  */
7366 static int check_mem_size_reg(struct bpf_verifier_env *env,
7367 			      struct bpf_reg_state *reg, u32 regno,
7368 			      bool zero_size_allowed,
7369 			      struct bpf_call_arg_meta *meta)
7370 {
7371 	int err;
7372 
7373 	/* This is used to refine r0 return value bounds for helpers
7374 	 * that enforce this value as an upper bound on return values.
7375 	 * See do_refine_retval_range() for helpers that can refine
7376 	 * the return value. C type of helper is u32 so we pull register
7377 	 * bound from umax_value however, if negative verifier errors
7378 	 * out. Only upper bounds can be learned because retval is an
7379 	 * int type and negative retvals are allowed.
7380 	 */
7381 	meta->msize_max_value = reg->umax_value;
7382 
7383 	/* The register is SCALAR_VALUE; the access check
7384 	 * happens using its boundaries.
7385 	 */
7386 	if (!tnum_is_const(reg->var_off))
7387 		/* For unprivileged variable accesses, disable raw
7388 		 * mode so that the program is required to
7389 		 * initialize all the memory that the helper could
7390 		 * just partially fill up.
7391 		 */
7392 		meta = NULL;
7393 
7394 	if (reg->smin_value < 0) {
7395 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7396 			regno);
7397 		return -EACCES;
7398 	}
7399 
7400 	if (reg->umin_value == 0 && !zero_size_allowed) {
7401 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7402 			regno, reg->umin_value, reg->umax_value);
7403 		return -EACCES;
7404 	}
7405 
7406 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7407 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7408 			regno);
7409 		return -EACCES;
7410 	}
7411 	err = check_helper_mem_access(env, regno - 1,
7412 				      reg->umax_value,
7413 				      zero_size_allowed, meta);
7414 	if (!err)
7415 		err = mark_chain_precision(env, regno);
7416 	return err;
7417 }
7418 
7419 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7420 			 u32 regno, u32 mem_size)
7421 {
7422 	bool may_be_null = type_may_be_null(reg->type);
7423 	struct bpf_reg_state saved_reg;
7424 	struct bpf_call_arg_meta meta;
7425 	int err;
7426 
7427 	if (register_is_null(reg))
7428 		return 0;
7429 
7430 	memset(&meta, 0, sizeof(meta));
7431 	/* Assuming that the register contains a value check if the memory
7432 	 * access is safe. Temporarily save and restore the register's state as
7433 	 * the conversion shouldn't be visible to a caller.
7434 	 */
7435 	if (may_be_null) {
7436 		saved_reg = *reg;
7437 		mark_ptr_not_null_reg(reg);
7438 	}
7439 
7440 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7441 	/* Check access for BPF_WRITE */
7442 	meta.raw_mode = true;
7443 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7444 
7445 	if (may_be_null)
7446 		*reg = saved_reg;
7447 
7448 	return err;
7449 }
7450 
7451 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7452 				    u32 regno)
7453 {
7454 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7455 	bool may_be_null = type_may_be_null(mem_reg->type);
7456 	struct bpf_reg_state saved_reg;
7457 	struct bpf_call_arg_meta meta;
7458 	int err;
7459 
7460 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7461 
7462 	memset(&meta, 0, sizeof(meta));
7463 
7464 	if (may_be_null) {
7465 		saved_reg = *mem_reg;
7466 		mark_ptr_not_null_reg(mem_reg);
7467 	}
7468 
7469 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7470 	/* Check access for BPF_WRITE */
7471 	meta.raw_mode = true;
7472 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7473 
7474 	if (may_be_null)
7475 		*mem_reg = saved_reg;
7476 	return err;
7477 }
7478 
7479 /* Implementation details:
7480  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7481  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7482  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7483  * Two separate bpf_obj_new will also have different reg->id.
7484  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7485  * clears reg->id after value_or_null->value transition, since the verifier only
7486  * cares about the range of access to valid map value pointer and doesn't care
7487  * about actual address of the map element.
7488  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7489  * reg->id > 0 after value_or_null->value transition. By doing so
7490  * two bpf_map_lookups will be considered two different pointers that
7491  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7492  * returned from bpf_obj_new.
7493  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7494  * dead-locks.
7495  * Since only one bpf_spin_lock is allowed the checks are simpler than
7496  * reg_is_refcounted() logic. The verifier needs to remember only
7497  * one spin_lock instead of array of acquired_refs.
7498  * cur_state->active_lock remembers which map value element or allocated
7499  * object got locked and clears it after bpf_spin_unlock.
7500  */
7501 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7502 			     bool is_lock)
7503 {
7504 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7505 	struct bpf_verifier_state *cur = env->cur_state;
7506 	bool is_const = tnum_is_const(reg->var_off);
7507 	u64 val = reg->var_off.value;
7508 	struct bpf_map *map = NULL;
7509 	struct btf *btf = NULL;
7510 	struct btf_record *rec;
7511 
7512 	if (!is_const) {
7513 		verbose(env,
7514 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7515 			regno);
7516 		return -EINVAL;
7517 	}
7518 	if (reg->type == PTR_TO_MAP_VALUE) {
7519 		map = reg->map_ptr;
7520 		if (!map->btf) {
7521 			verbose(env,
7522 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7523 				map->name);
7524 			return -EINVAL;
7525 		}
7526 	} else {
7527 		btf = reg->btf;
7528 	}
7529 
7530 	rec = reg_btf_record(reg);
7531 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7532 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7533 			map ? map->name : "kptr");
7534 		return -EINVAL;
7535 	}
7536 	if (rec->spin_lock_off != val + reg->off) {
7537 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7538 			val + reg->off, rec->spin_lock_off);
7539 		return -EINVAL;
7540 	}
7541 	if (is_lock) {
7542 		if (cur->active_lock.ptr) {
7543 			verbose(env,
7544 				"Locking two bpf_spin_locks are not allowed\n");
7545 			return -EINVAL;
7546 		}
7547 		if (map)
7548 			cur->active_lock.ptr = map;
7549 		else
7550 			cur->active_lock.ptr = btf;
7551 		cur->active_lock.id = reg->id;
7552 	} else {
7553 		void *ptr;
7554 
7555 		if (map)
7556 			ptr = map;
7557 		else
7558 			ptr = btf;
7559 
7560 		if (!cur->active_lock.ptr) {
7561 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7562 			return -EINVAL;
7563 		}
7564 		if (cur->active_lock.ptr != ptr ||
7565 		    cur->active_lock.id != reg->id) {
7566 			verbose(env, "bpf_spin_unlock of different lock\n");
7567 			return -EINVAL;
7568 		}
7569 
7570 		invalidate_non_owning_refs(env);
7571 
7572 		cur->active_lock.ptr = NULL;
7573 		cur->active_lock.id = 0;
7574 	}
7575 	return 0;
7576 }
7577 
7578 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7579 			      struct bpf_call_arg_meta *meta)
7580 {
7581 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7582 	bool is_const = tnum_is_const(reg->var_off);
7583 	struct bpf_map *map = reg->map_ptr;
7584 	u64 val = reg->var_off.value;
7585 
7586 	if (!is_const) {
7587 		verbose(env,
7588 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7589 			regno);
7590 		return -EINVAL;
7591 	}
7592 	if (!map->btf) {
7593 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7594 			map->name);
7595 		return -EINVAL;
7596 	}
7597 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7598 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7599 		return -EINVAL;
7600 	}
7601 	if (map->record->timer_off != val + reg->off) {
7602 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7603 			val + reg->off, map->record->timer_off);
7604 		return -EINVAL;
7605 	}
7606 	if (meta->map_ptr) {
7607 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7608 		return -EFAULT;
7609 	}
7610 	meta->map_uid = reg->map_uid;
7611 	meta->map_ptr = map;
7612 	return 0;
7613 }
7614 
7615 static int process_wq_func(struct bpf_verifier_env *env, int regno,
7616 			   struct bpf_kfunc_call_arg_meta *meta)
7617 {
7618 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7619 	struct bpf_map *map = reg->map_ptr;
7620 	u64 val = reg->var_off.value;
7621 
7622 	if (map->record->wq_off != val + reg->off) {
7623 		verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
7624 			val + reg->off, map->record->wq_off);
7625 		return -EINVAL;
7626 	}
7627 	meta->map.uid = reg->map_uid;
7628 	meta->map.ptr = map;
7629 	return 0;
7630 }
7631 
7632 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7633 			     struct bpf_call_arg_meta *meta)
7634 {
7635 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7636 	struct bpf_map *map_ptr = reg->map_ptr;
7637 	struct btf_field *kptr_field;
7638 	u32 kptr_off;
7639 
7640 	if (!tnum_is_const(reg->var_off)) {
7641 		verbose(env,
7642 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7643 			regno);
7644 		return -EINVAL;
7645 	}
7646 	if (!map_ptr->btf) {
7647 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7648 			map_ptr->name);
7649 		return -EINVAL;
7650 	}
7651 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7652 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7653 		return -EINVAL;
7654 	}
7655 
7656 	meta->map_ptr = map_ptr;
7657 	kptr_off = reg->off + reg->var_off.value;
7658 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7659 	if (!kptr_field) {
7660 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7661 		return -EACCES;
7662 	}
7663 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7664 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7665 		return -EACCES;
7666 	}
7667 	meta->kptr_field = kptr_field;
7668 	return 0;
7669 }
7670 
7671 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7672  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7673  *
7674  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7675  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7676  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7677  *
7678  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7679  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7680  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7681  * mutate the view of the dynptr and also possibly destroy it. In the latter
7682  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7683  * memory that dynptr points to.
7684  *
7685  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7686  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7687  * readonly dynptr view yet, hence only the first case is tracked and checked.
7688  *
7689  * This is consistent with how C applies the const modifier to a struct object,
7690  * where the pointer itself inside bpf_dynptr becomes const but not what it
7691  * points to.
7692  *
7693  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7694  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7695  */
7696 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7697 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7698 {
7699 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7700 	int err;
7701 
7702 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7703 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7704 	 */
7705 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7706 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7707 		return -EFAULT;
7708 	}
7709 
7710 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7711 	 *		 constructing a mutable bpf_dynptr object.
7712 	 *
7713 	 *		 Currently, this is only possible with PTR_TO_STACK
7714 	 *		 pointing to a region of at least 16 bytes which doesn't
7715 	 *		 contain an existing bpf_dynptr.
7716 	 *
7717 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7718 	 *		 mutated or destroyed. However, the memory it points to
7719 	 *		 may be mutated.
7720 	 *
7721 	 *  None       - Points to a initialized dynptr that can be mutated and
7722 	 *		 destroyed, including mutation of the memory it points
7723 	 *		 to.
7724 	 */
7725 	if (arg_type & MEM_UNINIT) {
7726 		int i;
7727 
7728 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7729 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7730 			return -EINVAL;
7731 		}
7732 
7733 		/* we write BPF_DW bits (8 bytes) at a time */
7734 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7735 			err = check_mem_access(env, insn_idx, regno,
7736 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7737 			if (err)
7738 				return err;
7739 		}
7740 
7741 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7742 	} else /* MEM_RDONLY and None case from above */ {
7743 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7744 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7745 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7746 			return -EINVAL;
7747 		}
7748 
7749 		if (!is_dynptr_reg_valid_init(env, reg)) {
7750 			verbose(env,
7751 				"Expected an initialized dynptr as arg #%d\n",
7752 				regno);
7753 			return -EINVAL;
7754 		}
7755 
7756 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7757 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7758 			verbose(env,
7759 				"Expected a dynptr of type %s as arg #%d\n",
7760 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7761 			return -EINVAL;
7762 		}
7763 
7764 		err = mark_dynptr_read(env, reg);
7765 	}
7766 	return err;
7767 }
7768 
7769 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7770 {
7771 	struct bpf_func_state *state = func(env, reg);
7772 
7773 	return state->stack[spi].spilled_ptr.ref_obj_id;
7774 }
7775 
7776 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7777 {
7778 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7779 }
7780 
7781 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7782 {
7783 	return meta->kfunc_flags & KF_ITER_NEW;
7784 }
7785 
7786 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7787 {
7788 	return meta->kfunc_flags & KF_ITER_NEXT;
7789 }
7790 
7791 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7792 {
7793 	return meta->kfunc_flags & KF_ITER_DESTROY;
7794 }
7795 
7796 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7797 {
7798 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7799 	 * kfunc is iter state pointer
7800 	 */
7801 	return arg == 0 && is_iter_kfunc(meta);
7802 }
7803 
7804 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7805 			    struct bpf_kfunc_call_arg_meta *meta)
7806 {
7807 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7808 	const struct btf_type *t;
7809 	const struct btf_param *arg;
7810 	int spi, err, i, nr_slots;
7811 	u32 btf_id;
7812 
7813 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7814 	arg = &btf_params(meta->func_proto)[0];
7815 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7816 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7817 	nr_slots = t->size / BPF_REG_SIZE;
7818 
7819 	if (is_iter_new_kfunc(meta)) {
7820 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7821 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7822 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7823 				iter_type_str(meta->btf, btf_id), regno);
7824 			return -EINVAL;
7825 		}
7826 
7827 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7828 			err = check_mem_access(env, insn_idx, regno,
7829 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7830 			if (err)
7831 				return err;
7832 		}
7833 
7834 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7835 		if (err)
7836 			return err;
7837 	} else {
7838 		/* iter_next() or iter_destroy() expect initialized iter state*/
7839 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7840 		switch (err) {
7841 		case 0:
7842 			break;
7843 		case -EINVAL:
7844 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7845 				iter_type_str(meta->btf, btf_id), regno);
7846 			return err;
7847 		case -EPROTO:
7848 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7849 			return err;
7850 		default:
7851 			return err;
7852 		}
7853 
7854 		spi = iter_get_spi(env, reg, nr_slots);
7855 		if (spi < 0)
7856 			return spi;
7857 
7858 		err = mark_iter_read(env, reg, spi, nr_slots);
7859 		if (err)
7860 			return err;
7861 
7862 		/* remember meta->iter info for process_iter_next_call() */
7863 		meta->iter.spi = spi;
7864 		meta->iter.frameno = reg->frameno;
7865 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7866 
7867 		if (is_iter_destroy_kfunc(meta)) {
7868 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7869 			if (err)
7870 				return err;
7871 		}
7872 	}
7873 
7874 	return 0;
7875 }
7876 
7877 /* Look for a previous loop entry at insn_idx: nearest parent state
7878  * stopped at insn_idx with callsites matching those in cur->frame.
7879  */
7880 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7881 						  struct bpf_verifier_state *cur,
7882 						  int insn_idx)
7883 {
7884 	struct bpf_verifier_state_list *sl;
7885 	struct bpf_verifier_state *st;
7886 
7887 	/* Explored states are pushed in stack order, most recent states come first */
7888 	sl = *explored_state(env, insn_idx);
7889 	for (; sl; sl = sl->next) {
7890 		/* If st->branches != 0 state is a part of current DFS verification path,
7891 		 * hence cur & st for a loop.
7892 		 */
7893 		st = &sl->state;
7894 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7895 		    st->dfs_depth < cur->dfs_depth)
7896 			return st;
7897 	}
7898 
7899 	return NULL;
7900 }
7901 
7902 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7903 static bool regs_exact(const struct bpf_reg_state *rold,
7904 		       const struct bpf_reg_state *rcur,
7905 		       struct bpf_idmap *idmap);
7906 
7907 static void maybe_widen_reg(struct bpf_verifier_env *env,
7908 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7909 			    struct bpf_idmap *idmap)
7910 {
7911 	if (rold->type != SCALAR_VALUE)
7912 		return;
7913 	if (rold->type != rcur->type)
7914 		return;
7915 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7916 		return;
7917 	__mark_reg_unknown(env, rcur);
7918 }
7919 
7920 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7921 				   struct bpf_verifier_state *old,
7922 				   struct bpf_verifier_state *cur)
7923 {
7924 	struct bpf_func_state *fold, *fcur;
7925 	int i, fr;
7926 
7927 	reset_idmap_scratch(env);
7928 	for (fr = old->curframe; fr >= 0; fr--) {
7929 		fold = old->frame[fr];
7930 		fcur = cur->frame[fr];
7931 
7932 		for (i = 0; i < MAX_BPF_REG; i++)
7933 			maybe_widen_reg(env,
7934 					&fold->regs[i],
7935 					&fcur->regs[i],
7936 					&env->idmap_scratch);
7937 
7938 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7939 			if (!is_spilled_reg(&fold->stack[i]) ||
7940 			    !is_spilled_reg(&fcur->stack[i]))
7941 				continue;
7942 
7943 			maybe_widen_reg(env,
7944 					&fold->stack[i].spilled_ptr,
7945 					&fcur->stack[i].spilled_ptr,
7946 					&env->idmap_scratch);
7947 		}
7948 	}
7949 	return 0;
7950 }
7951 
7952 /* process_iter_next_call() is called when verifier gets to iterator's next
7953  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7954  * to it as just "iter_next()" in comments below.
7955  *
7956  * BPF verifier relies on a crucial contract for any iter_next()
7957  * implementation: it should *eventually* return NULL, and once that happens
7958  * it should keep returning NULL. That is, once iterator exhausts elements to
7959  * iterate, it should never reset or spuriously return new elements.
7960  *
7961  * With the assumption of such contract, process_iter_next_call() simulates
7962  * a fork in the verifier state to validate loop logic correctness and safety
7963  * without having to simulate infinite amount of iterations.
7964  *
7965  * In current state, we first assume that iter_next() returned NULL and
7966  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7967  * conditions we should not form an infinite loop and should eventually reach
7968  * exit.
7969  *
7970  * Besides that, we also fork current state and enqueue it for later
7971  * verification. In a forked state we keep iterator state as ACTIVE
7972  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7973  * also bump iteration depth to prevent erroneous infinite loop detection
7974  * later on (see iter_active_depths_differ() comment for details). In this
7975  * state we assume that we'll eventually loop back to another iter_next()
7976  * calls (it could be in exactly same location or in some other instruction,
7977  * it doesn't matter, we don't make any unnecessary assumptions about this,
7978  * everything revolves around iterator state in a stack slot, not which
7979  * instruction is calling iter_next()). When that happens, we either will come
7980  * to iter_next() with equivalent state and can conclude that next iteration
7981  * will proceed in exactly the same way as we just verified, so it's safe to
7982  * assume that loop converges. If not, we'll go on another iteration
7983  * simulation with a different input state, until all possible starting states
7984  * are validated or we reach maximum number of instructions limit.
7985  *
7986  * This way, we will either exhaustively discover all possible input states
7987  * that iterator loop can start with and eventually will converge, or we'll
7988  * effectively regress into bounded loop simulation logic and either reach
7989  * maximum number of instructions if loop is not provably convergent, or there
7990  * is some statically known limit on number of iterations (e.g., if there is
7991  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7992  *
7993  * Iteration convergence logic in is_state_visited() relies on exact
7994  * states comparison, which ignores read and precision marks.
7995  * This is necessary because read and precision marks are not finalized
7996  * while in the loop. Exact comparison might preclude convergence for
7997  * simple programs like below:
7998  *
7999  *     i = 0;
8000  *     while(iter_next(&it))
8001  *       i++;
8002  *
8003  * At each iteration step i++ would produce a new distinct state and
8004  * eventually instruction processing limit would be reached.
8005  *
8006  * To avoid such behavior speculatively forget (widen) range for
8007  * imprecise scalar registers, if those registers were not precise at the
8008  * end of the previous iteration and do not match exactly.
8009  *
8010  * This is a conservative heuristic that allows to verify wide range of programs,
8011  * however it precludes verification of programs that conjure an
8012  * imprecise value on the first loop iteration and use it as precise on a second.
8013  * For example, the following safe program would fail to verify:
8014  *
8015  *     struct bpf_num_iter it;
8016  *     int arr[10];
8017  *     int i = 0, a = 0;
8018  *     bpf_iter_num_new(&it, 0, 10);
8019  *     while (bpf_iter_num_next(&it)) {
8020  *       if (a == 0) {
8021  *         a = 1;
8022  *         i = 7; // Because i changed verifier would forget
8023  *                // it's range on second loop entry.
8024  *       } else {
8025  *         arr[i] = 42; // This would fail to verify.
8026  *       }
8027  *     }
8028  *     bpf_iter_num_destroy(&it);
8029  */
8030 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8031 				  struct bpf_kfunc_call_arg_meta *meta)
8032 {
8033 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8034 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8035 	struct bpf_reg_state *cur_iter, *queued_iter;
8036 	int iter_frameno = meta->iter.frameno;
8037 	int iter_spi = meta->iter.spi;
8038 
8039 	BTF_TYPE_EMIT(struct bpf_iter);
8040 
8041 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8042 
8043 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8044 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8045 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
8046 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8047 		return -EFAULT;
8048 	}
8049 
8050 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8051 		/* Because iter_next() call is a checkpoint is_state_visitied()
8052 		 * should guarantee parent state with same call sites and insn_idx.
8053 		 */
8054 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8055 		    !same_callsites(cur_st->parent, cur_st)) {
8056 			verbose(env, "bug: bad parent state for iter next call");
8057 			return -EFAULT;
8058 		}
8059 		/* Note cur_st->parent in the call below, it is necessary to skip
8060 		 * checkpoint created for cur_st by is_state_visited()
8061 		 * right at this instruction.
8062 		 */
8063 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8064 		/* branch out active iter state */
8065 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8066 		if (!queued_st)
8067 			return -ENOMEM;
8068 
8069 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8070 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8071 		queued_iter->iter.depth++;
8072 		if (prev_st)
8073 			widen_imprecise_scalars(env, prev_st, queued_st);
8074 
8075 		queued_fr = queued_st->frame[queued_st->curframe];
8076 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8077 	}
8078 
8079 	/* switch to DRAINED state, but keep the depth unchanged */
8080 	/* mark current iter state as drained and assume returned NULL */
8081 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8082 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8083 
8084 	return 0;
8085 }
8086 
8087 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8088 {
8089 	return type == ARG_CONST_SIZE ||
8090 	       type == ARG_CONST_SIZE_OR_ZERO;
8091 }
8092 
8093 static bool arg_type_is_release(enum bpf_arg_type type)
8094 {
8095 	return type & OBJ_RELEASE;
8096 }
8097 
8098 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8099 {
8100 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8101 }
8102 
8103 static int int_ptr_type_to_size(enum bpf_arg_type type)
8104 {
8105 	if (type == ARG_PTR_TO_INT)
8106 		return sizeof(u32);
8107 	else if (type == ARG_PTR_TO_LONG)
8108 		return sizeof(u64);
8109 
8110 	return -EINVAL;
8111 }
8112 
8113 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8114 				 const struct bpf_call_arg_meta *meta,
8115 				 enum bpf_arg_type *arg_type)
8116 {
8117 	if (!meta->map_ptr) {
8118 		/* kernel subsystem misconfigured verifier */
8119 		verbose(env, "invalid map_ptr to access map->type\n");
8120 		return -EACCES;
8121 	}
8122 
8123 	switch (meta->map_ptr->map_type) {
8124 	case BPF_MAP_TYPE_SOCKMAP:
8125 	case BPF_MAP_TYPE_SOCKHASH:
8126 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8127 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8128 		} else {
8129 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8130 			return -EINVAL;
8131 		}
8132 		break;
8133 	case BPF_MAP_TYPE_BLOOM_FILTER:
8134 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8135 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8136 		break;
8137 	default:
8138 		break;
8139 	}
8140 	return 0;
8141 }
8142 
8143 struct bpf_reg_types {
8144 	const enum bpf_reg_type types[10];
8145 	u32 *btf_id;
8146 };
8147 
8148 static const struct bpf_reg_types sock_types = {
8149 	.types = {
8150 		PTR_TO_SOCK_COMMON,
8151 		PTR_TO_SOCKET,
8152 		PTR_TO_TCP_SOCK,
8153 		PTR_TO_XDP_SOCK,
8154 	},
8155 };
8156 
8157 #ifdef CONFIG_NET
8158 static const struct bpf_reg_types btf_id_sock_common_types = {
8159 	.types = {
8160 		PTR_TO_SOCK_COMMON,
8161 		PTR_TO_SOCKET,
8162 		PTR_TO_TCP_SOCK,
8163 		PTR_TO_XDP_SOCK,
8164 		PTR_TO_BTF_ID,
8165 		PTR_TO_BTF_ID | PTR_TRUSTED,
8166 	},
8167 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8168 };
8169 #endif
8170 
8171 static const struct bpf_reg_types mem_types = {
8172 	.types = {
8173 		PTR_TO_STACK,
8174 		PTR_TO_PACKET,
8175 		PTR_TO_PACKET_META,
8176 		PTR_TO_MAP_KEY,
8177 		PTR_TO_MAP_VALUE,
8178 		PTR_TO_MEM,
8179 		PTR_TO_MEM | MEM_RINGBUF,
8180 		PTR_TO_BUF,
8181 		PTR_TO_BTF_ID | PTR_TRUSTED,
8182 	},
8183 };
8184 
8185 static const struct bpf_reg_types int_ptr_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 	},
8193 };
8194 
8195 static const struct bpf_reg_types spin_lock_types = {
8196 	.types = {
8197 		PTR_TO_MAP_VALUE,
8198 		PTR_TO_BTF_ID | MEM_ALLOC,
8199 	}
8200 };
8201 
8202 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8203 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8204 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8205 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8206 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8207 static const struct bpf_reg_types btf_ptr_types = {
8208 	.types = {
8209 		PTR_TO_BTF_ID,
8210 		PTR_TO_BTF_ID | PTR_TRUSTED,
8211 		PTR_TO_BTF_ID | MEM_RCU,
8212 	},
8213 };
8214 static const struct bpf_reg_types percpu_btf_ptr_types = {
8215 	.types = {
8216 		PTR_TO_BTF_ID | MEM_PERCPU,
8217 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8218 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8219 	}
8220 };
8221 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8222 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8223 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8224 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8225 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8226 static const struct bpf_reg_types dynptr_types = {
8227 	.types = {
8228 		PTR_TO_STACK,
8229 		CONST_PTR_TO_DYNPTR,
8230 	}
8231 };
8232 
8233 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8234 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8235 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8236 	[ARG_CONST_SIZE]		= &scalar_types,
8237 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8238 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8239 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8240 	[ARG_PTR_TO_CTX]		= &context_types,
8241 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8242 #ifdef CONFIG_NET
8243 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8244 #endif
8245 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8246 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8247 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8248 	[ARG_PTR_TO_MEM]		= &mem_types,
8249 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8250 	[ARG_PTR_TO_INT]		= &int_ptr_types,
8251 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
8252 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8253 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8254 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8255 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8256 	[ARG_PTR_TO_TIMER]		= &timer_types,
8257 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8258 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8259 };
8260 
8261 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8262 			  enum bpf_arg_type arg_type,
8263 			  const u32 *arg_btf_id,
8264 			  struct bpf_call_arg_meta *meta)
8265 {
8266 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8267 	enum bpf_reg_type expected, type = reg->type;
8268 	const struct bpf_reg_types *compatible;
8269 	int i, j;
8270 
8271 	compatible = compatible_reg_types[base_type(arg_type)];
8272 	if (!compatible) {
8273 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8274 		return -EFAULT;
8275 	}
8276 
8277 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8278 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8279 	 *
8280 	 * Same for MAYBE_NULL:
8281 	 *
8282 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8283 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8284 	 *
8285 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8286 	 *
8287 	 * Therefore we fold these flags depending on the arg_type before comparison.
8288 	 */
8289 	if (arg_type & MEM_RDONLY)
8290 		type &= ~MEM_RDONLY;
8291 	if (arg_type & PTR_MAYBE_NULL)
8292 		type &= ~PTR_MAYBE_NULL;
8293 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8294 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8295 
8296 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
8297 		type &= ~MEM_ALLOC;
8298 		type &= ~MEM_PERCPU;
8299 	}
8300 
8301 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8302 		expected = compatible->types[i];
8303 		if (expected == NOT_INIT)
8304 			break;
8305 
8306 		if (type == expected)
8307 			goto found;
8308 	}
8309 
8310 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8311 	for (j = 0; j + 1 < i; j++)
8312 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8313 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8314 	return -EACCES;
8315 
8316 found:
8317 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8318 		return 0;
8319 
8320 	if (compatible == &mem_types) {
8321 		if (!(arg_type & MEM_RDONLY)) {
8322 			verbose(env,
8323 				"%s() may write into memory pointed by R%d type=%s\n",
8324 				func_id_name(meta->func_id),
8325 				regno, reg_type_str(env, reg->type));
8326 			return -EACCES;
8327 		}
8328 		return 0;
8329 	}
8330 
8331 	switch ((int)reg->type) {
8332 	case PTR_TO_BTF_ID:
8333 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8334 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
8335 	case PTR_TO_BTF_ID | MEM_RCU:
8336 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8337 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8338 	{
8339 		/* For bpf_sk_release, it needs to match against first member
8340 		 * 'struct sock_common', hence make an exception for it. This
8341 		 * allows bpf_sk_release to work for multiple socket types.
8342 		 */
8343 		bool strict_type_match = arg_type_is_release(arg_type) &&
8344 					 meta->func_id != BPF_FUNC_sk_release;
8345 
8346 		if (type_may_be_null(reg->type) &&
8347 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8348 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8349 			return -EACCES;
8350 		}
8351 
8352 		if (!arg_btf_id) {
8353 			if (!compatible->btf_id) {
8354 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8355 				return -EFAULT;
8356 			}
8357 			arg_btf_id = compatible->btf_id;
8358 		}
8359 
8360 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8361 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8362 				return -EACCES;
8363 		} else {
8364 			if (arg_btf_id == BPF_PTR_POISON) {
8365 				verbose(env, "verifier internal error:");
8366 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8367 					regno);
8368 				return -EACCES;
8369 			}
8370 
8371 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8372 						  btf_vmlinux, *arg_btf_id,
8373 						  strict_type_match)) {
8374 				verbose(env, "R%d is of type %s but %s is expected\n",
8375 					regno, btf_type_name(reg->btf, reg->btf_id),
8376 					btf_type_name(btf_vmlinux, *arg_btf_id));
8377 				return -EACCES;
8378 			}
8379 		}
8380 		break;
8381 	}
8382 	case PTR_TO_BTF_ID | MEM_ALLOC:
8383 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8384 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8385 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8386 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8387 			return -EFAULT;
8388 		}
8389 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8390 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8391 				return -EACCES;
8392 		}
8393 		break;
8394 	case PTR_TO_BTF_ID | MEM_PERCPU:
8395 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8396 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8397 		/* Handled by helper specific checks */
8398 		break;
8399 	default:
8400 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8401 		return -EFAULT;
8402 	}
8403 	return 0;
8404 }
8405 
8406 static struct btf_field *
8407 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8408 {
8409 	struct btf_field *field;
8410 	struct btf_record *rec;
8411 
8412 	rec = reg_btf_record(reg);
8413 	if (!rec)
8414 		return NULL;
8415 
8416 	field = btf_record_find(rec, off, fields);
8417 	if (!field)
8418 		return NULL;
8419 
8420 	return field;
8421 }
8422 
8423 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8424 				  const struct bpf_reg_state *reg, int regno,
8425 				  enum bpf_arg_type arg_type)
8426 {
8427 	u32 type = reg->type;
8428 
8429 	/* When referenced register is passed to release function, its fixed
8430 	 * offset must be 0.
8431 	 *
8432 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8433 	 * meta->release_regno.
8434 	 */
8435 	if (arg_type_is_release(arg_type)) {
8436 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8437 		 * may not directly point to the object being released, but to
8438 		 * dynptr pointing to such object, which might be at some offset
8439 		 * on the stack. In that case, we simply to fallback to the
8440 		 * default handling.
8441 		 */
8442 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8443 			return 0;
8444 
8445 		/* Doing check_ptr_off_reg check for the offset will catch this
8446 		 * because fixed_off_ok is false, but checking here allows us
8447 		 * to give the user a better error message.
8448 		 */
8449 		if (reg->off) {
8450 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8451 				regno);
8452 			return -EINVAL;
8453 		}
8454 		return __check_ptr_off_reg(env, reg, regno, false);
8455 	}
8456 
8457 	switch (type) {
8458 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8459 	case PTR_TO_STACK:
8460 	case PTR_TO_PACKET:
8461 	case PTR_TO_PACKET_META:
8462 	case PTR_TO_MAP_KEY:
8463 	case PTR_TO_MAP_VALUE:
8464 	case PTR_TO_MEM:
8465 	case PTR_TO_MEM | MEM_RDONLY:
8466 	case PTR_TO_MEM | MEM_RINGBUF:
8467 	case PTR_TO_BUF:
8468 	case PTR_TO_BUF | MEM_RDONLY:
8469 	case PTR_TO_ARENA:
8470 	case SCALAR_VALUE:
8471 		return 0;
8472 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8473 	 * fixed offset.
8474 	 */
8475 	case PTR_TO_BTF_ID:
8476 	case PTR_TO_BTF_ID | MEM_ALLOC:
8477 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8478 	case PTR_TO_BTF_ID | MEM_RCU:
8479 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8480 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8481 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8482 		 * its fixed offset must be 0. In the other cases, fixed offset
8483 		 * can be non-zero. This was already checked above. So pass
8484 		 * fixed_off_ok as true to allow fixed offset for all other
8485 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8486 		 * still need to do checks instead of returning.
8487 		 */
8488 		return __check_ptr_off_reg(env, reg, regno, true);
8489 	default:
8490 		return __check_ptr_off_reg(env, reg, regno, false);
8491 	}
8492 }
8493 
8494 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8495 						const struct bpf_func_proto *fn,
8496 						struct bpf_reg_state *regs)
8497 {
8498 	struct bpf_reg_state *state = NULL;
8499 	int i;
8500 
8501 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8502 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8503 			if (state) {
8504 				verbose(env, "verifier internal error: multiple dynptr args\n");
8505 				return NULL;
8506 			}
8507 			state = &regs[BPF_REG_1 + i];
8508 		}
8509 
8510 	if (!state)
8511 		verbose(env, "verifier internal error: no dynptr arg found\n");
8512 
8513 	return state;
8514 }
8515 
8516 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8517 {
8518 	struct bpf_func_state *state = func(env, reg);
8519 	int spi;
8520 
8521 	if (reg->type == CONST_PTR_TO_DYNPTR)
8522 		return reg->id;
8523 	spi = dynptr_get_spi(env, reg);
8524 	if (spi < 0)
8525 		return spi;
8526 	return state->stack[spi].spilled_ptr.id;
8527 }
8528 
8529 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8530 {
8531 	struct bpf_func_state *state = func(env, reg);
8532 	int spi;
8533 
8534 	if (reg->type == CONST_PTR_TO_DYNPTR)
8535 		return reg->ref_obj_id;
8536 	spi = dynptr_get_spi(env, reg);
8537 	if (spi < 0)
8538 		return spi;
8539 	return state->stack[spi].spilled_ptr.ref_obj_id;
8540 }
8541 
8542 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8543 					    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->dynptr.type;
8550 
8551 	spi = __get_spi(reg->off);
8552 	if (spi < 0) {
8553 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8554 		return BPF_DYNPTR_TYPE_INVALID;
8555 	}
8556 
8557 	return state->stack[spi].spilled_ptr.dynptr.type;
8558 }
8559 
8560 static int check_reg_const_str(struct bpf_verifier_env *env,
8561 			       struct bpf_reg_state *reg, u32 regno)
8562 {
8563 	struct bpf_map *map = reg->map_ptr;
8564 	int err;
8565 	int map_off;
8566 	u64 map_addr;
8567 	char *str_ptr;
8568 
8569 	if (reg->type != PTR_TO_MAP_VALUE)
8570 		return -EINVAL;
8571 
8572 	if (!bpf_map_is_rdonly(map)) {
8573 		verbose(env, "R%d does not point to a readonly map'\n", regno);
8574 		return -EACCES;
8575 	}
8576 
8577 	if (!tnum_is_const(reg->var_off)) {
8578 		verbose(env, "R%d is not a constant address'\n", regno);
8579 		return -EACCES;
8580 	}
8581 
8582 	if (!map->ops->map_direct_value_addr) {
8583 		verbose(env, "no direct value access support for this map type\n");
8584 		return -EACCES;
8585 	}
8586 
8587 	err = check_map_access(env, regno, reg->off,
8588 			       map->value_size - reg->off, false,
8589 			       ACCESS_HELPER);
8590 	if (err)
8591 		return err;
8592 
8593 	map_off = reg->off + reg->var_off.value;
8594 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8595 	if (err) {
8596 		verbose(env, "direct value access on string failed\n");
8597 		return err;
8598 	}
8599 
8600 	str_ptr = (char *)(long)(map_addr);
8601 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8602 		verbose(env, "string is not zero-terminated\n");
8603 		return -EINVAL;
8604 	}
8605 	return 0;
8606 }
8607 
8608 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8609 			  struct bpf_call_arg_meta *meta,
8610 			  const struct bpf_func_proto *fn,
8611 			  int insn_idx)
8612 {
8613 	u32 regno = BPF_REG_1 + arg;
8614 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8615 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8616 	enum bpf_reg_type type = reg->type;
8617 	u32 *arg_btf_id = NULL;
8618 	int err = 0;
8619 
8620 	if (arg_type == ARG_DONTCARE)
8621 		return 0;
8622 
8623 	err = check_reg_arg(env, regno, SRC_OP);
8624 	if (err)
8625 		return err;
8626 
8627 	if (arg_type == ARG_ANYTHING) {
8628 		if (is_pointer_value(env, regno)) {
8629 			verbose(env, "R%d leaks addr into helper function\n",
8630 				regno);
8631 			return -EACCES;
8632 		}
8633 		return 0;
8634 	}
8635 
8636 	if (type_is_pkt_pointer(type) &&
8637 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8638 		verbose(env, "helper access to the packet is not allowed\n");
8639 		return -EACCES;
8640 	}
8641 
8642 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8643 		err = resolve_map_arg_type(env, meta, &arg_type);
8644 		if (err)
8645 			return err;
8646 	}
8647 
8648 	if (register_is_null(reg) && type_may_be_null(arg_type))
8649 		/* A NULL register has a SCALAR_VALUE type, so skip
8650 		 * type checking.
8651 		 */
8652 		goto skip_type_check;
8653 
8654 	/* arg_btf_id and arg_size are in a union. */
8655 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8656 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8657 		arg_btf_id = fn->arg_btf_id[arg];
8658 
8659 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8660 	if (err)
8661 		return err;
8662 
8663 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8664 	if (err)
8665 		return err;
8666 
8667 skip_type_check:
8668 	if (arg_type_is_release(arg_type)) {
8669 		if (arg_type_is_dynptr(arg_type)) {
8670 			struct bpf_func_state *state = func(env, reg);
8671 			int spi;
8672 
8673 			/* Only dynptr created on stack can be released, thus
8674 			 * the get_spi and stack state checks for spilled_ptr
8675 			 * should only be done before process_dynptr_func for
8676 			 * PTR_TO_STACK.
8677 			 */
8678 			if (reg->type == PTR_TO_STACK) {
8679 				spi = dynptr_get_spi(env, reg);
8680 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8681 					verbose(env, "arg %d is an unacquired reference\n", regno);
8682 					return -EINVAL;
8683 				}
8684 			} else {
8685 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8686 				return -EINVAL;
8687 			}
8688 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8689 			verbose(env, "R%d must be referenced when passed to release function\n",
8690 				regno);
8691 			return -EINVAL;
8692 		}
8693 		if (meta->release_regno) {
8694 			verbose(env, "verifier internal error: more than one release argument\n");
8695 			return -EFAULT;
8696 		}
8697 		meta->release_regno = regno;
8698 	}
8699 
8700 	if (reg->ref_obj_id) {
8701 		if (meta->ref_obj_id) {
8702 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8703 				regno, reg->ref_obj_id,
8704 				meta->ref_obj_id);
8705 			return -EFAULT;
8706 		}
8707 		meta->ref_obj_id = reg->ref_obj_id;
8708 	}
8709 
8710 	switch (base_type(arg_type)) {
8711 	case ARG_CONST_MAP_PTR:
8712 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8713 		if (meta->map_ptr) {
8714 			/* Use map_uid (which is unique id of inner map) to reject:
8715 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8716 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8717 			 * if (inner_map1 && inner_map2) {
8718 			 *     timer = bpf_map_lookup_elem(inner_map1);
8719 			 *     if (timer)
8720 			 *         // mismatch would have been allowed
8721 			 *         bpf_timer_init(timer, inner_map2);
8722 			 * }
8723 			 *
8724 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8725 			 */
8726 			if (meta->map_ptr != reg->map_ptr ||
8727 			    meta->map_uid != reg->map_uid) {
8728 				verbose(env,
8729 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8730 					meta->map_uid, reg->map_uid);
8731 				return -EINVAL;
8732 			}
8733 		}
8734 		meta->map_ptr = reg->map_ptr;
8735 		meta->map_uid = reg->map_uid;
8736 		break;
8737 	case ARG_PTR_TO_MAP_KEY:
8738 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8739 		 * check that [key, key + map->key_size) are within
8740 		 * stack limits and initialized
8741 		 */
8742 		if (!meta->map_ptr) {
8743 			/* in function declaration map_ptr must come before
8744 			 * map_key, so that it's verified and known before
8745 			 * we have to check map_key here. Otherwise it means
8746 			 * that kernel subsystem misconfigured verifier
8747 			 */
8748 			verbose(env, "invalid map_ptr to access map->key\n");
8749 			return -EACCES;
8750 		}
8751 		err = check_helper_mem_access(env, regno,
8752 					      meta->map_ptr->key_size, false,
8753 					      NULL);
8754 		break;
8755 	case ARG_PTR_TO_MAP_VALUE:
8756 		if (type_may_be_null(arg_type) && register_is_null(reg))
8757 			return 0;
8758 
8759 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8760 		 * check [value, value + map->value_size) validity
8761 		 */
8762 		if (!meta->map_ptr) {
8763 			/* kernel subsystem misconfigured verifier */
8764 			verbose(env, "invalid map_ptr to access map->value\n");
8765 			return -EACCES;
8766 		}
8767 		meta->raw_mode = arg_type & MEM_UNINIT;
8768 		err = check_helper_mem_access(env, regno,
8769 					      meta->map_ptr->value_size, false,
8770 					      meta);
8771 		break;
8772 	case ARG_PTR_TO_PERCPU_BTF_ID:
8773 		if (!reg->btf_id) {
8774 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8775 			return -EACCES;
8776 		}
8777 		meta->ret_btf = reg->btf;
8778 		meta->ret_btf_id = reg->btf_id;
8779 		break;
8780 	case ARG_PTR_TO_SPIN_LOCK:
8781 		if (in_rbtree_lock_required_cb(env)) {
8782 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8783 			return -EACCES;
8784 		}
8785 		if (meta->func_id == BPF_FUNC_spin_lock) {
8786 			err = process_spin_lock(env, regno, true);
8787 			if (err)
8788 				return err;
8789 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8790 			err = process_spin_lock(env, regno, false);
8791 			if (err)
8792 				return err;
8793 		} else {
8794 			verbose(env, "verifier internal error\n");
8795 			return -EFAULT;
8796 		}
8797 		break;
8798 	case ARG_PTR_TO_TIMER:
8799 		err = process_timer_func(env, regno, meta);
8800 		if (err)
8801 			return err;
8802 		break;
8803 	case ARG_PTR_TO_FUNC:
8804 		meta->subprogno = reg->subprogno;
8805 		break;
8806 	case ARG_PTR_TO_MEM:
8807 		/* The access to this pointer is only checked when we hit the
8808 		 * next is_mem_size argument below.
8809 		 */
8810 		meta->raw_mode = arg_type & MEM_UNINIT;
8811 		if (arg_type & MEM_FIXED_SIZE) {
8812 			err = check_helper_mem_access(env, regno,
8813 						      fn->arg_size[arg], false,
8814 						      meta);
8815 		}
8816 		break;
8817 	case ARG_CONST_SIZE:
8818 		err = check_mem_size_reg(env, reg, regno, false, meta);
8819 		break;
8820 	case ARG_CONST_SIZE_OR_ZERO:
8821 		err = check_mem_size_reg(env, reg, regno, true, meta);
8822 		break;
8823 	case ARG_PTR_TO_DYNPTR:
8824 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8825 		if (err)
8826 			return err;
8827 		break;
8828 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8829 		if (!tnum_is_const(reg->var_off)) {
8830 			verbose(env, "R%d is not a known constant'\n",
8831 				regno);
8832 			return -EACCES;
8833 		}
8834 		meta->mem_size = reg->var_off.value;
8835 		err = mark_chain_precision(env, regno);
8836 		if (err)
8837 			return err;
8838 		break;
8839 	case ARG_PTR_TO_INT:
8840 	case ARG_PTR_TO_LONG:
8841 	{
8842 		int size = int_ptr_type_to_size(arg_type);
8843 
8844 		err = check_helper_mem_access(env, regno, size, false, meta);
8845 		if (err)
8846 			return err;
8847 		err = check_ptr_alignment(env, reg, 0, size, true);
8848 		break;
8849 	}
8850 	case ARG_PTR_TO_CONST_STR:
8851 	{
8852 		err = check_reg_const_str(env, reg, regno);
8853 		if (err)
8854 			return err;
8855 		break;
8856 	}
8857 	case ARG_PTR_TO_KPTR:
8858 		err = process_kptr_func(env, regno, meta);
8859 		if (err)
8860 			return err;
8861 		break;
8862 	}
8863 
8864 	return err;
8865 }
8866 
8867 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8868 {
8869 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8870 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8871 
8872 	if (func_id != BPF_FUNC_map_update_elem)
8873 		return false;
8874 
8875 	/* It's not possible to get access to a locked struct sock in these
8876 	 * contexts, so updating is safe.
8877 	 */
8878 	switch (type) {
8879 	case BPF_PROG_TYPE_TRACING:
8880 		if (eatype == BPF_TRACE_ITER)
8881 			return true;
8882 		break;
8883 	case BPF_PROG_TYPE_SOCKET_FILTER:
8884 	case BPF_PROG_TYPE_SCHED_CLS:
8885 	case BPF_PROG_TYPE_SCHED_ACT:
8886 	case BPF_PROG_TYPE_XDP:
8887 	case BPF_PROG_TYPE_SK_REUSEPORT:
8888 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8889 	case BPF_PROG_TYPE_SK_LOOKUP:
8890 		return true;
8891 	default:
8892 		break;
8893 	}
8894 
8895 	verbose(env, "cannot update sockmap in this context\n");
8896 	return false;
8897 }
8898 
8899 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8900 {
8901 	return env->prog->jit_requested &&
8902 	       bpf_jit_supports_subprog_tailcalls();
8903 }
8904 
8905 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8906 					struct bpf_map *map, int func_id)
8907 {
8908 	if (!map)
8909 		return 0;
8910 
8911 	/* We need a two way check, first is from map perspective ... */
8912 	switch (map->map_type) {
8913 	case BPF_MAP_TYPE_PROG_ARRAY:
8914 		if (func_id != BPF_FUNC_tail_call)
8915 			goto error;
8916 		break;
8917 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8918 		if (func_id != BPF_FUNC_perf_event_read &&
8919 		    func_id != BPF_FUNC_perf_event_output &&
8920 		    func_id != BPF_FUNC_skb_output &&
8921 		    func_id != BPF_FUNC_perf_event_read_value &&
8922 		    func_id != BPF_FUNC_xdp_output)
8923 			goto error;
8924 		break;
8925 	case BPF_MAP_TYPE_RINGBUF:
8926 		if (func_id != BPF_FUNC_ringbuf_output &&
8927 		    func_id != BPF_FUNC_ringbuf_reserve &&
8928 		    func_id != BPF_FUNC_ringbuf_query &&
8929 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8930 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8931 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8932 			goto error;
8933 		break;
8934 	case BPF_MAP_TYPE_USER_RINGBUF:
8935 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8936 			goto error;
8937 		break;
8938 	case BPF_MAP_TYPE_STACK_TRACE:
8939 		if (func_id != BPF_FUNC_get_stackid)
8940 			goto error;
8941 		break;
8942 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8943 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8944 		    func_id != BPF_FUNC_current_task_under_cgroup)
8945 			goto error;
8946 		break;
8947 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8948 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8949 		if (func_id != BPF_FUNC_get_local_storage)
8950 			goto error;
8951 		break;
8952 	case BPF_MAP_TYPE_DEVMAP:
8953 	case BPF_MAP_TYPE_DEVMAP_HASH:
8954 		if (func_id != BPF_FUNC_redirect_map &&
8955 		    func_id != BPF_FUNC_map_lookup_elem)
8956 			goto error;
8957 		break;
8958 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8959 	 * appear.
8960 	 */
8961 	case BPF_MAP_TYPE_CPUMAP:
8962 		if (func_id != BPF_FUNC_redirect_map)
8963 			goto error;
8964 		break;
8965 	case BPF_MAP_TYPE_XSKMAP:
8966 		if (func_id != BPF_FUNC_redirect_map &&
8967 		    func_id != BPF_FUNC_map_lookup_elem)
8968 			goto error;
8969 		break;
8970 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8971 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8972 		if (func_id != BPF_FUNC_map_lookup_elem)
8973 			goto error;
8974 		break;
8975 	case BPF_MAP_TYPE_SOCKMAP:
8976 		if (func_id != BPF_FUNC_sk_redirect_map &&
8977 		    func_id != BPF_FUNC_sock_map_update &&
8978 		    func_id != BPF_FUNC_map_delete_elem &&
8979 		    func_id != BPF_FUNC_msg_redirect_map &&
8980 		    func_id != BPF_FUNC_sk_select_reuseport &&
8981 		    func_id != BPF_FUNC_map_lookup_elem &&
8982 		    !may_update_sockmap(env, func_id))
8983 			goto error;
8984 		break;
8985 	case BPF_MAP_TYPE_SOCKHASH:
8986 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8987 		    func_id != BPF_FUNC_sock_hash_update &&
8988 		    func_id != BPF_FUNC_map_delete_elem &&
8989 		    func_id != BPF_FUNC_msg_redirect_hash &&
8990 		    func_id != BPF_FUNC_sk_select_reuseport &&
8991 		    func_id != BPF_FUNC_map_lookup_elem &&
8992 		    !may_update_sockmap(env, func_id))
8993 			goto error;
8994 		break;
8995 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8996 		if (func_id != BPF_FUNC_sk_select_reuseport)
8997 			goto error;
8998 		break;
8999 	case BPF_MAP_TYPE_QUEUE:
9000 	case BPF_MAP_TYPE_STACK:
9001 		if (func_id != BPF_FUNC_map_peek_elem &&
9002 		    func_id != BPF_FUNC_map_pop_elem &&
9003 		    func_id != BPF_FUNC_map_push_elem)
9004 			goto error;
9005 		break;
9006 	case BPF_MAP_TYPE_SK_STORAGE:
9007 		if (func_id != BPF_FUNC_sk_storage_get &&
9008 		    func_id != BPF_FUNC_sk_storage_delete &&
9009 		    func_id != BPF_FUNC_kptr_xchg)
9010 			goto error;
9011 		break;
9012 	case BPF_MAP_TYPE_INODE_STORAGE:
9013 		if (func_id != BPF_FUNC_inode_storage_get &&
9014 		    func_id != BPF_FUNC_inode_storage_delete &&
9015 		    func_id != BPF_FUNC_kptr_xchg)
9016 			goto error;
9017 		break;
9018 	case BPF_MAP_TYPE_TASK_STORAGE:
9019 		if (func_id != BPF_FUNC_task_storage_get &&
9020 		    func_id != BPF_FUNC_task_storage_delete &&
9021 		    func_id != BPF_FUNC_kptr_xchg)
9022 			goto error;
9023 		break;
9024 	case BPF_MAP_TYPE_CGRP_STORAGE:
9025 		if (func_id != BPF_FUNC_cgrp_storage_get &&
9026 		    func_id != BPF_FUNC_cgrp_storage_delete &&
9027 		    func_id != BPF_FUNC_kptr_xchg)
9028 			goto error;
9029 		break;
9030 	case BPF_MAP_TYPE_BLOOM_FILTER:
9031 		if (func_id != BPF_FUNC_map_peek_elem &&
9032 		    func_id != BPF_FUNC_map_push_elem)
9033 			goto error;
9034 		break;
9035 	default:
9036 		break;
9037 	}
9038 
9039 	/* ... and second from the function itself. */
9040 	switch (func_id) {
9041 	case BPF_FUNC_tail_call:
9042 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
9043 			goto error;
9044 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
9045 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
9046 			return -EINVAL;
9047 		}
9048 		break;
9049 	case BPF_FUNC_perf_event_read:
9050 	case BPF_FUNC_perf_event_output:
9051 	case BPF_FUNC_perf_event_read_value:
9052 	case BPF_FUNC_skb_output:
9053 	case BPF_FUNC_xdp_output:
9054 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9055 			goto error;
9056 		break;
9057 	case BPF_FUNC_ringbuf_output:
9058 	case BPF_FUNC_ringbuf_reserve:
9059 	case BPF_FUNC_ringbuf_query:
9060 	case BPF_FUNC_ringbuf_reserve_dynptr:
9061 	case BPF_FUNC_ringbuf_submit_dynptr:
9062 	case BPF_FUNC_ringbuf_discard_dynptr:
9063 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9064 			goto error;
9065 		break;
9066 	case BPF_FUNC_user_ringbuf_drain:
9067 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9068 			goto error;
9069 		break;
9070 	case BPF_FUNC_get_stackid:
9071 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9072 			goto error;
9073 		break;
9074 	case BPF_FUNC_current_task_under_cgroup:
9075 	case BPF_FUNC_skb_under_cgroup:
9076 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9077 			goto error;
9078 		break;
9079 	case BPF_FUNC_redirect_map:
9080 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9081 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9082 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
9083 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
9084 			goto error;
9085 		break;
9086 	case BPF_FUNC_sk_redirect_map:
9087 	case BPF_FUNC_msg_redirect_map:
9088 	case BPF_FUNC_sock_map_update:
9089 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9090 			goto error;
9091 		break;
9092 	case BPF_FUNC_sk_redirect_hash:
9093 	case BPF_FUNC_msg_redirect_hash:
9094 	case BPF_FUNC_sock_hash_update:
9095 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9096 			goto error;
9097 		break;
9098 	case BPF_FUNC_get_local_storage:
9099 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9100 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9101 			goto error;
9102 		break;
9103 	case BPF_FUNC_sk_select_reuseport:
9104 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9105 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9106 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
9107 			goto error;
9108 		break;
9109 	case BPF_FUNC_map_pop_elem:
9110 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9111 		    map->map_type != BPF_MAP_TYPE_STACK)
9112 			goto error;
9113 		break;
9114 	case BPF_FUNC_map_peek_elem:
9115 	case BPF_FUNC_map_push_elem:
9116 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9117 		    map->map_type != BPF_MAP_TYPE_STACK &&
9118 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9119 			goto error;
9120 		break;
9121 	case BPF_FUNC_map_lookup_percpu_elem:
9122 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9123 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9124 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9125 			goto error;
9126 		break;
9127 	case BPF_FUNC_sk_storage_get:
9128 	case BPF_FUNC_sk_storage_delete:
9129 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9130 			goto error;
9131 		break;
9132 	case BPF_FUNC_inode_storage_get:
9133 	case BPF_FUNC_inode_storage_delete:
9134 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9135 			goto error;
9136 		break;
9137 	case BPF_FUNC_task_storage_get:
9138 	case BPF_FUNC_task_storage_delete:
9139 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9140 			goto error;
9141 		break;
9142 	case BPF_FUNC_cgrp_storage_get:
9143 	case BPF_FUNC_cgrp_storage_delete:
9144 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9145 			goto error;
9146 		break;
9147 	default:
9148 		break;
9149 	}
9150 
9151 	return 0;
9152 error:
9153 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9154 		map->map_type, func_id_name(func_id), func_id);
9155 	return -EINVAL;
9156 }
9157 
9158 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9159 {
9160 	int count = 0;
9161 
9162 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9163 		count++;
9164 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9165 		count++;
9166 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9167 		count++;
9168 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9169 		count++;
9170 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9171 		count++;
9172 
9173 	/* We only support one arg being in raw mode at the moment,
9174 	 * which is sufficient for the helper functions we have
9175 	 * right now.
9176 	 */
9177 	return count <= 1;
9178 }
9179 
9180 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9181 {
9182 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9183 	bool has_size = fn->arg_size[arg] != 0;
9184 	bool is_next_size = false;
9185 
9186 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9187 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9188 
9189 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9190 		return is_next_size;
9191 
9192 	return has_size == is_next_size || is_next_size == is_fixed;
9193 }
9194 
9195 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9196 {
9197 	/* bpf_xxx(..., buf, len) call will access 'len'
9198 	 * bytes from memory 'buf'. Both arg types need
9199 	 * to be paired, so make sure there's no buggy
9200 	 * helper function specification.
9201 	 */
9202 	if (arg_type_is_mem_size(fn->arg1_type) ||
9203 	    check_args_pair_invalid(fn, 0) ||
9204 	    check_args_pair_invalid(fn, 1) ||
9205 	    check_args_pair_invalid(fn, 2) ||
9206 	    check_args_pair_invalid(fn, 3) ||
9207 	    check_args_pair_invalid(fn, 4))
9208 		return false;
9209 
9210 	return true;
9211 }
9212 
9213 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9214 {
9215 	int i;
9216 
9217 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9218 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9219 			return !!fn->arg_btf_id[i];
9220 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9221 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9222 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9223 		    /* arg_btf_id and arg_size are in a union. */
9224 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9225 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9226 			return false;
9227 	}
9228 
9229 	return true;
9230 }
9231 
9232 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9233 {
9234 	return check_raw_mode_ok(fn) &&
9235 	       check_arg_pair_ok(fn) &&
9236 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9237 }
9238 
9239 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9240  * are now invalid, so turn them into unknown SCALAR_VALUE.
9241  *
9242  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9243  * since these slices point to packet data.
9244  */
9245 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9246 {
9247 	struct bpf_func_state *state;
9248 	struct bpf_reg_state *reg;
9249 
9250 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9251 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9252 			mark_reg_invalid(env, reg);
9253 	}));
9254 }
9255 
9256 enum {
9257 	AT_PKT_END = -1,
9258 	BEYOND_PKT_END = -2,
9259 };
9260 
9261 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9262 {
9263 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9264 	struct bpf_reg_state *reg = &state->regs[regn];
9265 
9266 	if (reg->type != PTR_TO_PACKET)
9267 		/* PTR_TO_PACKET_META is not supported yet */
9268 		return;
9269 
9270 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9271 	 * How far beyond pkt_end it goes is unknown.
9272 	 * if (!range_open) it's the case of pkt >= pkt_end
9273 	 * if (range_open) it's the case of pkt > pkt_end
9274 	 * hence this pointer is at least 1 byte bigger than pkt_end
9275 	 */
9276 	if (range_open)
9277 		reg->range = BEYOND_PKT_END;
9278 	else
9279 		reg->range = AT_PKT_END;
9280 }
9281 
9282 /* The pointer with the specified id has released its reference to kernel
9283  * resources. Identify all copies of the same pointer and clear the reference.
9284  */
9285 static int release_reference(struct bpf_verifier_env *env,
9286 			     int ref_obj_id)
9287 {
9288 	struct bpf_func_state *state;
9289 	struct bpf_reg_state *reg;
9290 	int err;
9291 
9292 	err = release_reference_state(cur_func(env), ref_obj_id);
9293 	if (err)
9294 		return err;
9295 
9296 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9297 		if (reg->ref_obj_id == ref_obj_id)
9298 			mark_reg_invalid(env, reg);
9299 	}));
9300 
9301 	return 0;
9302 }
9303 
9304 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9305 {
9306 	struct bpf_func_state *unused;
9307 	struct bpf_reg_state *reg;
9308 
9309 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9310 		if (type_is_non_owning_ref(reg->type))
9311 			mark_reg_invalid(env, reg);
9312 	}));
9313 }
9314 
9315 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9316 				    struct bpf_reg_state *regs)
9317 {
9318 	int i;
9319 
9320 	/* after the call registers r0 - r5 were scratched */
9321 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9322 		mark_reg_not_init(env, regs, caller_saved[i]);
9323 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9324 	}
9325 }
9326 
9327 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9328 				   struct bpf_func_state *caller,
9329 				   struct bpf_func_state *callee,
9330 				   int insn_idx);
9331 
9332 static int set_callee_state(struct bpf_verifier_env *env,
9333 			    struct bpf_func_state *caller,
9334 			    struct bpf_func_state *callee, int insn_idx);
9335 
9336 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9337 			    set_callee_state_fn set_callee_state_cb,
9338 			    struct bpf_verifier_state *state)
9339 {
9340 	struct bpf_func_state *caller, *callee;
9341 	int err;
9342 
9343 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9344 		verbose(env, "the call stack of %d frames is too deep\n",
9345 			state->curframe + 2);
9346 		return -E2BIG;
9347 	}
9348 
9349 	if (state->frame[state->curframe + 1]) {
9350 		verbose(env, "verifier bug. Frame %d already allocated\n",
9351 			state->curframe + 1);
9352 		return -EFAULT;
9353 	}
9354 
9355 	caller = state->frame[state->curframe];
9356 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9357 	if (!callee)
9358 		return -ENOMEM;
9359 	state->frame[state->curframe + 1] = callee;
9360 
9361 	/* callee cannot access r0, r6 - r9 for reading and has to write
9362 	 * into its own stack before reading from it.
9363 	 * callee can read/write into caller's stack
9364 	 */
9365 	init_func_state(env, callee,
9366 			/* remember the callsite, it will be used by bpf_exit */
9367 			callsite,
9368 			state->curframe + 1 /* frameno within this callchain */,
9369 			subprog /* subprog number within this prog */);
9370 	/* Transfer references to the callee */
9371 	err = copy_reference_state(callee, caller);
9372 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9373 	if (err)
9374 		goto err_out;
9375 
9376 	/* only increment it after check_reg_arg() finished */
9377 	state->curframe++;
9378 
9379 	return 0;
9380 
9381 err_out:
9382 	free_func_state(callee);
9383 	state->frame[state->curframe + 1] = NULL;
9384 	return err;
9385 }
9386 
9387 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9388 				    const struct btf *btf,
9389 				    struct bpf_reg_state *regs)
9390 {
9391 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
9392 	struct bpf_verifier_log *log = &env->log;
9393 	u32 i;
9394 	int ret;
9395 
9396 	ret = btf_prepare_func_args(env, subprog);
9397 	if (ret)
9398 		return ret;
9399 
9400 	/* check that BTF function arguments match actual types that the
9401 	 * verifier sees.
9402 	 */
9403 	for (i = 0; i < sub->arg_cnt; i++) {
9404 		u32 regno = i + 1;
9405 		struct bpf_reg_state *reg = &regs[regno];
9406 		struct bpf_subprog_arg_info *arg = &sub->args[i];
9407 
9408 		if (arg->arg_type == ARG_ANYTHING) {
9409 			if (reg->type != SCALAR_VALUE) {
9410 				bpf_log(log, "R%d is not a scalar\n", regno);
9411 				return -EINVAL;
9412 			}
9413 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
9414 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9415 			if (ret < 0)
9416 				return ret;
9417 			/* If function expects ctx type in BTF check that caller
9418 			 * is passing PTR_TO_CTX.
9419 			 */
9420 			if (reg->type != PTR_TO_CTX) {
9421 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9422 				return -EINVAL;
9423 			}
9424 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9425 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9426 			if (ret < 0)
9427 				return ret;
9428 			if (check_mem_reg(env, reg, regno, arg->mem_size))
9429 				return -EINVAL;
9430 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9431 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9432 				return -EINVAL;
9433 			}
9434 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
9435 			/*
9436 			 * Can pass any value and the kernel won't crash, but
9437 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
9438 			 * else is a bug in the bpf program. Point it out to
9439 			 * the user at the verification time instead of
9440 			 * run-time debug nightmare.
9441 			 */
9442 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
9443 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
9444 				return -EINVAL;
9445 			}
9446 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
9447 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
9448 			if (ret)
9449 				return ret;
9450 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
9451 			struct bpf_call_arg_meta meta;
9452 			int err;
9453 
9454 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
9455 				continue;
9456 
9457 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
9458 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
9459 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
9460 			if (err)
9461 				return err;
9462 		} else {
9463 			bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
9464 				i, arg->arg_type);
9465 			return -EFAULT;
9466 		}
9467 	}
9468 
9469 	return 0;
9470 }
9471 
9472 /* Compare BTF of a function call with given bpf_reg_state.
9473  * Returns:
9474  * EFAULT - there is a verifier bug. Abort verification.
9475  * EINVAL - there is a type mismatch or BTF is not available.
9476  * 0 - BTF matches with what bpf_reg_state expects.
9477  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9478  */
9479 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9480 				  struct bpf_reg_state *regs)
9481 {
9482 	struct bpf_prog *prog = env->prog;
9483 	struct btf *btf = prog->aux->btf;
9484 	u32 btf_id;
9485 	int err;
9486 
9487 	if (!prog->aux->func_info)
9488 		return -EINVAL;
9489 
9490 	btf_id = prog->aux->func_info[subprog].type_id;
9491 	if (!btf_id)
9492 		return -EFAULT;
9493 
9494 	if (prog->aux->func_info_aux[subprog].unreliable)
9495 		return -EINVAL;
9496 
9497 	err = btf_check_func_arg_match(env, subprog, btf, regs);
9498 	/* Compiler optimizations can remove arguments from static functions
9499 	 * or mismatched type can be passed into a global function.
9500 	 * In such cases mark the function as unreliable from BTF point of view.
9501 	 */
9502 	if (err)
9503 		prog->aux->func_info_aux[subprog].unreliable = true;
9504 	return err;
9505 }
9506 
9507 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9508 			      int insn_idx, int subprog,
9509 			      set_callee_state_fn set_callee_state_cb)
9510 {
9511 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9512 	struct bpf_func_state *caller, *callee;
9513 	int err;
9514 
9515 	caller = state->frame[state->curframe];
9516 	err = btf_check_subprog_call(env, subprog, caller->regs);
9517 	if (err == -EFAULT)
9518 		return err;
9519 
9520 	/* set_callee_state is used for direct subprog calls, but we are
9521 	 * interested in validating only BPF helpers that can call subprogs as
9522 	 * callbacks
9523 	 */
9524 	env->subprog_info[subprog].is_cb = true;
9525 	if (bpf_pseudo_kfunc_call(insn) &&
9526 	    !is_callback_calling_kfunc(insn->imm)) {
9527 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9528 			func_id_name(insn->imm), insn->imm);
9529 		return -EFAULT;
9530 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9531 		   !is_callback_calling_function(insn->imm)) { /* helper */
9532 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9533 			func_id_name(insn->imm), insn->imm);
9534 		return -EFAULT;
9535 	}
9536 
9537 	if (is_async_callback_calling_insn(insn)) {
9538 		struct bpf_verifier_state *async_cb;
9539 
9540 		/* there is no real recursion here. timer and workqueue callbacks are async */
9541 		env->subprog_info[subprog].is_async_cb = true;
9542 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9543 					 insn_idx, subprog,
9544 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm));
9545 		if (!async_cb)
9546 			return -EFAULT;
9547 		callee = async_cb->frame[0];
9548 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9549 
9550 		/* Convert bpf_timer_set_callback() args into timer callback args */
9551 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9552 		if (err)
9553 			return err;
9554 
9555 		return 0;
9556 	}
9557 
9558 	/* for callback functions enqueue entry to callback and
9559 	 * proceed with next instruction within current frame.
9560 	 */
9561 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9562 	if (!callback_state)
9563 		return -ENOMEM;
9564 
9565 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9566 			       callback_state);
9567 	if (err)
9568 		return err;
9569 
9570 	callback_state->callback_unroll_depth++;
9571 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9572 	caller->callback_depth = 0;
9573 	return 0;
9574 }
9575 
9576 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9577 			   int *insn_idx)
9578 {
9579 	struct bpf_verifier_state *state = env->cur_state;
9580 	struct bpf_func_state *caller;
9581 	int err, subprog, target_insn;
9582 
9583 	target_insn = *insn_idx + insn->imm + 1;
9584 	subprog = find_subprog(env, target_insn);
9585 	if (subprog < 0) {
9586 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9587 		return -EFAULT;
9588 	}
9589 
9590 	caller = state->frame[state->curframe];
9591 	err = btf_check_subprog_call(env, subprog, caller->regs);
9592 	if (err == -EFAULT)
9593 		return err;
9594 	if (subprog_is_global(env, subprog)) {
9595 		const char *sub_name = subprog_name(env, subprog);
9596 
9597 		/* Only global subprogs cannot be called with a lock held. */
9598 		if (env->cur_state->active_lock.ptr) {
9599 			verbose(env, "global function calls are not allowed while holding a lock,\n"
9600 				     "use static function instead\n");
9601 			return -EINVAL;
9602 		}
9603 
9604 		/* Only global subprogs cannot be called with preemption disabled. */
9605 		if (env->cur_state->active_preempt_lock) {
9606 			verbose(env, "global function calls are not allowed with preemption disabled,\n"
9607 				     "use static function instead\n");
9608 			return -EINVAL;
9609 		}
9610 
9611 		if (err) {
9612 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9613 				subprog, sub_name);
9614 			return err;
9615 		}
9616 
9617 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9618 			subprog, sub_name);
9619 		/* mark global subprog for verifying after main prog */
9620 		subprog_aux(env, subprog)->called = true;
9621 		clear_caller_saved_regs(env, caller->regs);
9622 
9623 		/* All global functions return a 64-bit SCALAR_VALUE */
9624 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9625 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9626 
9627 		/* continue with next insn after call */
9628 		return 0;
9629 	}
9630 
9631 	/* for regular function entry setup new frame and continue
9632 	 * from that frame.
9633 	 */
9634 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9635 	if (err)
9636 		return err;
9637 
9638 	clear_caller_saved_regs(env, caller->regs);
9639 
9640 	/* and go analyze first insn of the callee */
9641 	*insn_idx = env->subprog_info[subprog].start - 1;
9642 
9643 	if (env->log.level & BPF_LOG_LEVEL) {
9644 		verbose(env, "caller:\n");
9645 		print_verifier_state(env, caller, true);
9646 		verbose(env, "callee:\n");
9647 		print_verifier_state(env, state->frame[state->curframe], true);
9648 	}
9649 
9650 	return 0;
9651 }
9652 
9653 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9654 				   struct bpf_func_state *caller,
9655 				   struct bpf_func_state *callee)
9656 {
9657 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9658 	 *      void *callback_ctx, u64 flags);
9659 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9660 	 *      void *callback_ctx);
9661 	 */
9662 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9663 
9664 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9665 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9666 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9667 
9668 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9669 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9670 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9671 
9672 	/* pointer to stack or null */
9673 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9674 
9675 	/* unused */
9676 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9677 	return 0;
9678 }
9679 
9680 static int set_callee_state(struct bpf_verifier_env *env,
9681 			    struct bpf_func_state *caller,
9682 			    struct bpf_func_state *callee, int insn_idx)
9683 {
9684 	int i;
9685 
9686 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9687 	 * pointers, which connects us up to the liveness chain
9688 	 */
9689 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9690 		callee->regs[i] = caller->regs[i];
9691 	return 0;
9692 }
9693 
9694 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9695 				       struct bpf_func_state *caller,
9696 				       struct bpf_func_state *callee,
9697 				       int insn_idx)
9698 {
9699 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9700 	struct bpf_map *map;
9701 	int err;
9702 
9703 	/* valid map_ptr and poison value does not matter */
9704 	map = insn_aux->map_ptr_state.map_ptr;
9705 	if (!map->ops->map_set_for_each_callback_args ||
9706 	    !map->ops->map_for_each_callback) {
9707 		verbose(env, "callback function not allowed for map\n");
9708 		return -ENOTSUPP;
9709 	}
9710 
9711 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9712 	if (err)
9713 		return err;
9714 
9715 	callee->in_callback_fn = true;
9716 	callee->callback_ret_range = retval_range(0, 1);
9717 	return 0;
9718 }
9719 
9720 static int set_loop_callback_state(struct bpf_verifier_env *env,
9721 				   struct bpf_func_state *caller,
9722 				   struct bpf_func_state *callee,
9723 				   int insn_idx)
9724 {
9725 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9726 	 *	    u64 flags);
9727 	 * callback_fn(u32 index, void *callback_ctx);
9728 	 */
9729 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9730 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9731 
9732 	/* unused */
9733 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9734 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9735 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9736 
9737 	callee->in_callback_fn = true;
9738 	callee->callback_ret_range = retval_range(0, 1);
9739 	return 0;
9740 }
9741 
9742 static int set_timer_callback_state(struct bpf_verifier_env *env,
9743 				    struct bpf_func_state *caller,
9744 				    struct bpf_func_state *callee,
9745 				    int insn_idx)
9746 {
9747 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9748 
9749 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9750 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9751 	 */
9752 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9753 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9754 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9755 
9756 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9757 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9758 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9759 
9760 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9761 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9762 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9763 
9764 	/* unused */
9765 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9766 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9767 	callee->in_async_callback_fn = true;
9768 	callee->callback_ret_range = retval_range(0, 1);
9769 	return 0;
9770 }
9771 
9772 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9773 				       struct bpf_func_state *caller,
9774 				       struct bpf_func_state *callee,
9775 				       int insn_idx)
9776 {
9777 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9778 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9779 	 * (callback_fn)(struct task_struct *task,
9780 	 *               struct vm_area_struct *vma, void *callback_ctx);
9781 	 */
9782 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9783 
9784 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9785 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9786 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9787 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9788 
9789 	/* pointer to stack or null */
9790 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9791 
9792 	/* unused */
9793 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9794 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9795 	callee->in_callback_fn = true;
9796 	callee->callback_ret_range = retval_range(0, 1);
9797 	return 0;
9798 }
9799 
9800 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9801 					   struct bpf_func_state *caller,
9802 					   struct bpf_func_state *callee,
9803 					   int insn_idx)
9804 {
9805 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9806 	 *			  callback_ctx, u64 flags);
9807 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9808 	 */
9809 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9810 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9811 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9812 
9813 	/* unused */
9814 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9815 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9816 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9817 
9818 	callee->in_callback_fn = true;
9819 	callee->callback_ret_range = retval_range(0, 1);
9820 	return 0;
9821 }
9822 
9823 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9824 					 struct bpf_func_state *caller,
9825 					 struct bpf_func_state *callee,
9826 					 int insn_idx)
9827 {
9828 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9829 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9830 	 *
9831 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9832 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9833 	 * by this point, so look at 'root'
9834 	 */
9835 	struct btf_field *field;
9836 
9837 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9838 				      BPF_RB_ROOT);
9839 	if (!field || !field->graph_root.value_btf_id)
9840 		return -EFAULT;
9841 
9842 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9843 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9844 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9845 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9846 
9847 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9848 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9849 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9850 	callee->in_callback_fn = true;
9851 	callee->callback_ret_range = retval_range(0, 1);
9852 	return 0;
9853 }
9854 
9855 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9856 
9857 /* Are we currently verifying the callback for a rbtree helper that must
9858  * be called with lock held? If so, no need to complain about unreleased
9859  * lock
9860  */
9861 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9862 {
9863 	struct bpf_verifier_state *state = env->cur_state;
9864 	struct bpf_insn *insn = env->prog->insnsi;
9865 	struct bpf_func_state *callee;
9866 	int kfunc_btf_id;
9867 
9868 	if (!state->curframe)
9869 		return false;
9870 
9871 	callee = state->frame[state->curframe];
9872 
9873 	if (!callee->in_callback_fn)
9874 		return false;
9875 
9876 	kfunc_btf_id = insn[callee->callsite].imm;
9877 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9878 }
9879 
9880 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
9881 {
9882 	return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
9883 }
9884 
9885 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9886 {
9887 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9888 	struct bpf_func_state *caller, *callee;
9889 	struct bpf_reg_state *r0;
9890 	bool in_callback_fn;
9891 	int err;
9892 
9893 	callee = state->frame[state->curframe];
9894 	r0 = &callee->regs[BPF_REG_0];
9895 	if (r0->type == PTR_TO_STACK) {
9896 		/* technically it's ok to return caller's stack pointer
9897 		 * (or caller's caller's pointer) back to the caller,
9898 		 * since these pointers are valid. Only current stack
9899 		 * pointer will be invalid as soon as function exits,
9900 		 * but let's be conservative
9901 		 */
9902 		verbose(env, "cannot return stack pointer to the caller\n");
9903 		return -EINVAL;
9904 	}
9905 
9906 	caller = state->frame[state->curframe - 1];
9907 	if (callee->in_callback_fn) {
9908 		if (r0->type != SCALAR_VALUE) {
9909 			verbose(env, "R0 not a scalar value\n");
9910 			return -EACCES;
9911 		}
9912 
9913 		/* we are going to rely on register's precise value */
9914 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9915 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9916 		if (err)
9917 			return err;
9918 
9919 		/* enforce R0 return value range */
9920 		if (!retval_range_within(callee->callback_ret_range, r0)) {
9921 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
9922 					       "At callback return", "R0");
9923 			return -EINVAL;
9924 		}
9925 		if (!calls_callback(env, callee->callsite)) {
9926 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9927 				*insn_idx, callee->callsite);
9928 			return -EFAULT;
9929 		}
9930 	} else {
9931 		/* return to the caller whatever r0 had in the callee */
9932 		caller->regs[BPF_REG_0] = *r0;
9933 	}
9934 
9935 	/* callback_fn frame should have released its own additions to parent's
9936 	 * reference state at this point, or check_reference_leak would
9937 	 * complain, hence it must be the same as the caller. There is no need
9938 	 * to copy it back.
9939 	 */
9940 	if (!callee->in_callback_fn) {
9941 		/* Transfer references to the caller */
9942 		err = copy_reference_state(caller, callee);
9943 		if (err)
9944 			return err;
9945 	}
9946 
9947 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9948 	 * there function call logic would reschedule callback visit. If iteration
9949 	 * converges is_state_visited() would prune that visit eventually.
9950 	 */
9951 	in_callback_fn = callee->in_callback_fn;
9952 	if (in_callback_fn)
9953 		*insn_idx = callee->callsite;
9954 	else
9955 		*insn_idx = callee->callsite + 1;
9956 
9957 	if (env->log.level & BPF_LOG_LEVEL) {
9958 		verbose(env, "returning from callee:\n");
9959 		print_verifier_state(env, callee, true);
9960 		verbose(env, "to caller at %d:\n", *insn_idx);
9961 		print_verifier_state(env, caller, true);
9962 	}
9963 	/* clear everything in the callee. In case of exceptional exits using
9964 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9965 	free_func_state(callee);
9966 	state->frame[state->curframe--] = NULL;
9967 
9968 	/* for callbacks widen imprecise scalars to make programs like below verify:
9969 	 *
9970 	 *   struct ctx { int i; }
9971 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9972 	 *   ...
9973 	 *   struct ctx = { .i = 0; }
9974 	 *   bpf_loop(100, cb, &ctx, 0);
9975 	 *
9976 	 * This is similar to what is done in process_iter_next_call() for open
9977 	 * coded iterators.
9978 	 */
9979 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9980 	if (prev_st) {
9981 		err = widen_imprecise_scalars(env, prev_st, state);
9982 		if (err)
9983 			return err;
9984 	}
9985 	return 0;
9986 }
9987 
9988 static int do_refine_retval_range(struct bpf_verifier_env *env,
9989 				  struct bpf_reg_state *regs, int ret_type,
9990 				  int func_id,
9991 				  struct bpf_call_arg_meta *meta)
9992 {
9993 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9994 
9995 	if (ret_type != RET_INTEGER)
9996 		return 0;
9997 
9998 	switch (func_id) {
9999 	case BPF_FUNC_get_stack:
10000 	case BPF_FUNC_get_task_stack:
10001 	case BPF_FUNC_probe_read_str:
10002 	case BPF_FUNC_probe_read_kernel_str:
10003 	case BPF_FUNC_probe_read_user_str:
10004 		ret_reg->smax_value = meta->msize_max_value;
10005 		ret_reg->s32_max_value = meta->msize_max_value;
10006 		ret_reg->smin_value = -MAX_ERRNO;
10007 		ret_reg->s32_min_value = -MAX_ERRNO;
10008 		reg_bounds_sync(ret_reg);
10009 		break;
10010 	case BPF_FUNC_get_smp_processor_id:
10011 		ret_reg->umax_value = nr_cpu_ids - 1;
10012 		ret_reg->u32_max_value = nr_cpu_ids - 1;
10013 		ret_reg->smax_value = nr_cpu_ids - 1;
10014 		ret_reg->s32_max_value = nr_cpu_ids - 1;
10015 		ret_reg->umin_value = 0;
10016 		ret_reg->u32_min_value = 0;
10017 		ret_reg->smin_value = 0;
10018 		ret_reg->s32_min_value = 0;
10019 		reg_bounds_sync(ret_reg);
10020 		break;
10021 	}
10022 
10023 	return reg_bounds_sanity_check(env, ret_reg, "retval");
10024 }
10025 
10026 static int
10027 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10028 		int func_id, int insn_idx)
10029 {
10030 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10031 	struct bpf_map *map = meta->map_ptr;
10032 
10033 	if (func_id != BPF_FUNC_tail_call &&
10034 	    func_id != BPF_FUNC_map_lookup_elem &&
10035 	    func_id != BPF_FUNC_map_update_elem &&
10036 	    func_id != BPF_FUNC_map_delete_elem &&
10037 	    func_id != BPF_FUNC_map_push_elem &&
10038 	    func_id != BPF_FUNC_map_pop_elem &&
10039 	    func_id != BPF_FUNC_map_peek_elem &&
10040 	    func_id != BPF_FUNC_for_each_map_elem &&
10041 	    func_id != BPF_FUNC_redirect_map &&
10042 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
10043 		return 0;
10044 
10045 	if (map == NULL) {
10046 		verbose(env, "kernel subsystem misconfigured verifier\n");
10047 		return -EINVAL;
10048 	}
10049 
10050 	/* In case of read-only, some additional restrictions
10051 	 * need to be applied in order to prevent altering the
10052 	 * state of the map from program side.
10053 	 */
10054 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
10055 	    (func_id == BPF_FUNC_map_delete_elem ||
10056 	     func_id == BPF_FUNC_map_update_elem ||
10057 	     func_id == BPF_FUNC_map_push_elem ||
10058 	     func_id == BPF_FUNC_map_pop_elem)) {
10059 		verbose(env, "write into map forbidden\n");
10060 		return -EACCES;
10061 	}
10062 
10063 	if (!aux->map_ptr_state.map_ptr)
10064 		bpf_map_ptr_store(aux, meta->map_ptr,
10065 				  !meta->map_ptr->bypass_spec_v1, false);
10066 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
10067 		bpf_map_ptr_store(aux, meta->map_ptr,
10068 				  !meta->map_ptr->bypass_spec_v1, true);
10069 	return 0;
10070 }
10071 
10072 static int
10073 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10074 		int func_id, int insn_idx)
10075 {
10076 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10077 	struct bpf_reg_state *regs = cur_regs(env), *reg;
10078 	struct bpf_map *map = meta->map_ptr;
10079 	u64 val, max;
10080 	int err;
10081 
10082 	if (func_id != BPF_FUNC_tail_call)
10083 		return 0;
10084 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
10085 		verbose(env, "kernel subsystem misconfigured verifier\n");
10086 		return -EINVAL;
10087 	}
10088 
10089 	reg = &regs[BPF_REG_3];
10090 	val = reg->var_off.value;
10091 	max = map->max_entries;
10092 
10093 	if (!(is_reg_const(reg, false) && val < max)) {
10094 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10095 		return 0;
10096 	}
10097 
10098 	err = mark_chain_precision(env, BPF_REG_3);
10099 	if (err)
10100 		return err;
10101 	if (bpf_map_key_unseen(aux))
10102 		bpf_map_key_store(aux, val);
10103 	else if (!bpf_map_key_poisoned(aux) &&
10104 		  bpf_map_key_immediate(aux) != val)
10105 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10106 	return 0;
10107 }
10108 
10109 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
10110 {
10111 	struct bpf_func_state *state = cur_func(env);
10112 	bool refs_lingering = false;
10113 	int i;
10114 
10115 	if (!exception_exit && state->frameno && !state->in_callback_fn)
10116 		return 0;
10117 
10118 	for (i = 0; i < state->acquired_refs; i++) {
10119 		if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
10120 			continue;
10121 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10122 			state->refs[i].id, state->refs[i].insn_idx);
10123 		refs_lingering = true;
10124 	}
10125 	return refs_lingering ? -EINVAL : 0;
10126 }
10127 
10128 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10129 				   struct bpf_reg_state *regs)
10130 {
10131 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
10132 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
10133 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
10134 	struct bpf_bprintf_data data = {};
10135 	int err, fmt_map_off, num_args;
10136 	u64 fmt_addr;
10137 	char *fmt;
10138 
10139 	/* data must be an array of u64 */
10140 	if (data_len_reg->var_off.value % 8)
10141 		return -EINVAL;
10142 	num_args = data_len_reg->var_off.value / 8;
10143 
10144 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10145 	 * and map_direct_value_addr is set.
10146 	 */
10147 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10148 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10149 						  fmt_map_off);
10150 	if (err) {
10151 		verbose(env, "verifier bug\n");
10152 		return -EFAULT;
10153 	}
10154 	fmt = (char *)(long)fmt_addr + fmt_map_off;
10155 
10156 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10157 	 * can focus on validating the format specifiers.
10158 	 */
10159 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10160 	if (err < 0)
10161 		verbose(env, "Invalid format string\n");
10162 
10163 	return err;
10164 }
10165 
10166 static int check_get_func_ip(struct bpf_verifier_env *env)
10167 {
10168 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10169 	int func_id = BPF_FUNC_get_func_ip;
10170 
10171 	if (type == BPF_PROG_TYPE_TRACING) {
10172 		if (!bpf_prog_has_trampoline(env->prog)) {
10173 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10174 				func_id_name(func_id), func_id);
10175 			return -ENOTSUPP;
10176 		}
10177 		return 0;
10178 	} else if (type == BPF_PROG_TYPE_KPROBE) {
10179 		return 0;
10180 	}
10181 
10182 	verbose(env, "func %s#%d not supported for program type %d\n",
10183 		func_id_name(func_id), func_id, type);
10184 	return -ENOTSUPP;
10185 }
10186 
10187 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10188 {
10189 	return &env->insn_aux_data[env->insn_idx];
10190 }
10191 
10192 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10193 {
10194 	struct bpf_reg_state *regs = cur_regs(env);
10195 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
10196 	bool reg_is_null = register_is_null(reg);
10197 
10198 	if (reg_is_null)
10199 		mark_chain_precision(env, BPF_REG_4);
10200 
10201 	return reg_is_null;
10202 }
10203 
10204 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10205 {
10206 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10207 
10208 	if (!state->initialized) {
10209 		state->initialized = 1;
10210 		state->fit_for_inline = loop_flag_is_zero(env);
10211 		state->callback_subprogno = subprogno;
10212 		return;
10213 	}
10214 
10215 	if (!state->fit_for_inline)
10216 		return;
10217 
10218 	state->fit_for_inline = (loop_flag_is_zero(env) &&
10219 				 state->callback_subprogno == subprogno);
10220 }
10221 
10222 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10223 			     int *insn_idx_p)
10224 {
10225 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10226 	bool returns_cpu_specific_alloc_ptr = false;
10227 	const struct bpf_func_proto *fn = NULL;
10228 	enum bpf_return_type ret_type;
10229 	enum bpf_type_flag ret_flag;
10230 	struct bpf_reg_state *regs;
10231 	struct bpf_call_arg_meta meta;
10232 	int insn_idx = *insn_idx_p;
10233 	bool changes_data;
10234 	int i, err, func_id;
10235 
10236 	/* find function prototype */
10237 	func_id = insn->imm;
10238 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
10239 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
10240 			func_id);
10241 		return -EINVAL;
10242 	}
10243 
10244 	if (env->ops->get_func_proto)
10245 		fn = env->ops->get_func_proto(func_id, env->prog);
10246 	if (!fn) {
10247 		verbose(env, "program of this type cannot use helper %s#%d\n",
10248 			func_id_name(func_id), func_id);
10249 		return -EINVAL;
10250 	}
10251 
10252 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
10253 	if (!env->prog->gpl_compatible && fn->gpl_only) {
10254 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10255 		return -EINVAL;
10256 	}
10257 
10258 	if (fn->allowed && !fn->allowed(env->prog)) {
10259 		verbose(env, "helper call is not allowed in probe\n");
10260 		return -EINVAL;
10261 	}
10262 
10263 	if (!in_sleepable(env) && fn->might_sleep) {
10264 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
10265 		return -EINVAL;
10266 	}
10267 
10268 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10269 	changes_data = bpf_helper_changes_pkt_data(fn->func);
10270 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10271 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10272 			func_id_name(func_id), func_id);
10273 		return -EINVAL;
10274 	}
10275 
10276 	memset(&meta, 0, sizeof(meta));
10277 	meta.pkt_access = fn->pkt_access;
10278 
10279 	err = check_func_proto(fn, func_id);
10280 	if (err) {
10281 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10282 			func_id_name(func_id), func_id);
10283 		return err;
10284 	}
10285 
10286 	if (env->cur_state->active_rcu_lock) {
10287 		if (fn->might_sleep) {
10288 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10289 				func_id_name(func_id), func_id);
10290 			return -EINVAL;
10291 		}
10292 
10293 		if (in_sleepable(env) && is_storage_get_function(func_id))
10294 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10295 	}
10296 
10297 	if (env->cur_state->active_preempt_lock) {
10298 		if (fn->might_sleep) {
10299 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
10300 				func_id_name(func_id), func_id);
10301 			return -EINVAL;
10302 		}
10303 
10304 		if (in_sleepable(env) && is_storage_get_function(func_id))
10305 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10306 	}
10307 
10308 	meta.func_id = func_id;
10309 	/* check args */
10310 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10311 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10312 		if (err)
10313 			return err;
10314 	}
10315 
10316 	err = record_func_map(env, &meta, func_id, insn_idx);
10317 	if (err)
10318 		return err;
10319 
10320 	err = record_func_key(env, &meta, func_id, insn_idx);
10321 	if (err)
10322 		return err;
10323 
10324 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10325 	 * is inferred from register state.
10326 	 */
10327 	for (i = 0; i < meta.access_size; i++) {
10328 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10329 				       BPF_WRITE, -1, false, false);
10330 		if (err)
10331 			return err;
10332 	}
10333 
10334 	regs = cur_regs(env);
10335 
10336 	if (meta.release_regno) {
10337 		err = -EINVAL;
10338 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10339 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10340 		 * is safe to do directly.
10341 		 */
10342 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10343 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10344 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10345 				return -EFAULT;
10346 			}
10347 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10348 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10349 			u32 ref_obj_id = meta.ref_obj_id;
10350 			bool in_rcu = in_rcu_cs(env);
10351 			struct bpf_func_state *state;
10352 			struct bpf_reg_state *reg;
10353 
10354 			err = release_reference_state(cur_func(env), ref_obj_id);
10355 			if (!err) {
10356 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10357 					if (reg->ref_obj_id == ref_obj_id) {
10358 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10359 							reg->ref_obj_id = 0;
10360 							reg->type &= ~MEM_ALLOC;
10361 							reg->type |= MEM_RCU;
10362 						} else {
10363 							mark_reg_invalid(env, reg);
10364 						}
10365 					}
10366 				}));
10367 			}
10368 		} else if (meta.ref_obj_id) {
10369 			err = release_reference(env, meta.ref_obj_id);
10370 		} else if (register_is_null(&regs[meta.release_regno])) {
10371 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10372 			 * released is NULL, which must be > R0.
10373 			 */
10374 			err = 0;
10375 		}
10376 		if (err) {
10377 			verbose(env, "func %s#%d reference has not been acquired before\n",
10378 				func_id_name(func_id), func_id);
10379 			return err;
10380 		}
10381 	}
10382 
10383 	switch (func_id) {
10384 	case BPF_FUNC_tail_call:
10385 		err = check_reference_leak(env, false);
10386 		if (err) {
10387 			verbose(env, "tail_call would lead to reference leak\n");
10388 			return err;
10389 		}
10390 		break;
10391 	case BPF_FUNC_get_local_storage:
10392 		/* check that flags argument in get_local_storage(map, flags) is 0,
10393 		 * this is required because get_local_storage() can't return an error.
10394 		 */
10395 		if (!register_is_null(&regs[BPF_REG_2])) {
10396 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10397 			return -EINVAL;
10398 		}
10399 		break;
10400 	case BPF_FUNC_for_each_map_elem:
10401 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10402 					 set_map_elem_callback_state);
10403 		break;
10404 	case BPF_FUNC_timer_set_callback:
10405 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10406 					 set_timer_callback_state);
10407 		break;
10408 	case BPF_FUNC_find_vma:
10409 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10410 					 set_find_vma_callback_state);
10411 		break;
10412 	case BPF_FUNC_snprintf:
10413 		err = check_bpf_snprintf_call(env, regs);
10414 		break;
10415 	case BPF_FUNC_loop:
10416 		update_loop_inline_state(env, meta.subprogno);
10417 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10418 		 * is finished, thus mark it precise.
10419 		 */
10420 		err = mark_chain_precision(env, BPF_REG_1);
10421 		if (err)
10422 			return err;
10423 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10424 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10425 						 set_loop_callback_state);
10426 		} else {
10427 			cur_func(env)->callback_depth = 0;
10428 			if (env->log.level & BPF_LOG_LEVEL2)
10429 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10430 					env->cur_state->curframe);
10431 		}
10432 		break;
10433 	case BPF_FUNC_dynptr_from_mem:
10434 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10435 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10436 				reg_type_str(env, regs[BPF_REG_1].type));
10437 			return -EACCES;
10438 		}
10439 		break;
10440 	case BPF_FUNC_set_retval:
10441 		if (prog_type == BPF_PROG_TYPE_LSM &&
10442 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10443 			if (!env->prog->aux->attach_func_proto->type) {
10444 				/* Make sure programs that attach to void
10445 				 * hooks don't try to modify return value.
10446 				 */
10447 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10448 				return -EINVAL;
10449 			}
10450 		}
10451 		break;
10452 	case BPF_FUNC_dynptr_data:
10453 	{
10454 		struct bpf_reg_state *reg;
10455 		int id, ref_obj_id;
10456 
10457 		reg = get_dynptr_arg_reg(env, fn, regs);
10458 		if (!reg)
10459 			return -EFAULT;
10460 
10461 
10462 		if (meta.dynptr_id) {
10463 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10464 			return -EFAULT;
10465 		}
10466 		if (meta.ref_obj_id) {
10467 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10468 			return -EFAULT;
10469 		}
10470 
10471 		id = dynptr_id(env, reg);
10472 		if (id < 0) {
10473 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10474 			return id;
10475 		}
10476 
10477 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10478 		if (ref_obj_id < 0) {
10479 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10480 			return ref_obj_id;
10481 		}
10482 
10483 		meta.dynptr_id = id;
10484 		meta.ref_obj_id = ref_obj_id;
10485 
10486 		break;
10487 	}
10488 	case BPF_FUNC_dynptr_write:
10489 	{
10490 		enum bpf_dynptr_type dynptr_type;
10491 		struct bpf_reg_state *reg;
10492 
10493 		reg = get_dynptr_arg_reg(env, fn, regs);
10494 		if (!reg)
10495 			return -EFAULT;
10496 
10497 		dynptr_type = dynptr_get_type(env, reg);
10498 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10499 			return -EFAULT;
10500 
10501 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10502 			/* this will trigger clear_all_pkt_pointers(), which will
10503 			 * invalidate all dynptr slices associated with the skb
10504 			 */
10505 			changes_data = true;
10506 
10507 		break;
10508 	}
10509 	case BPF_FUNC_per_cpu_ptr:
10510 	case BPF_FUNC_this_cpu_ptr:
10511 	{
10512 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
10513 		const struct btf_type *type;
10514 
10515 		if (reg->type & MEM_RCU) {
10516 			type = btf_type_by_id(reg->btf, reg->btf_id);
10517 			if (!type || !btf_type_is_struct(type)) {
10518 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
10519 				return -EFAULT;
10520 			}
10521 			returns_cpu_specific_alloc_ptr = true;
10522 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10523 		}
10524 		break;
10525 	}
10526 	case BPF_FUNC_user_ringbuf_drain:
10527 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10528 					 set_user_ringbuf_callback_state);
10529 		break;
10530 	}
10531 
10532 	if (err)
10533 		return err;
10534 
10535 	/* reset caller saved regs */
10536 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10537 		mark_reg_not_init(env, regs, caller_saved[i]);
10538 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10539 	}
10540 
10541 	/* helper call returns 64-bit value. */
10542 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10543 
10544 	/* update return register (already marked as written above) */
10545 	ret_type = fn->ret_type;
10546 	ret_flag = type_flag(ret_type);
10547 
10548 	switch (base_type(ret_type)) {
10549 	case RET_INTEGER:
10550 		/* sets type to SCALAR_VALUE */
10551 		mark_reg_unknown(env, regs, BPF_REG_0);
10552 		break;
10553 	case RET_VOID:
10554 		regs[BPF_REG_0].type = NOT_INIT;
10555 		break;
10556 	case RET_PTR_TO_MAP_VALUE:
10557 		/* There is no offset yet applied, variable or fixed */
10558 		mark_reg_known_zero(env, regs, BPF_REG_0);
10559 		/* remember map_ptr, so that check_map_access()
10560 		 * can check 'value_size' boundary of memory access
10561 		 * to map element returned from bpf_map_lookup_elem()
10562 		 */
10563 		if (meta.map_ptr == NULL) {
10564 			verbose(env,
10565 				"kernel subsystem misconfigured verifier\n");
10566 			return -EINVAL;
10567 		}
10568 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10569 		regs[BPF_REG_0].map_uid = meta.map_uid;
10570 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10571 		if (!type_may_be_null(ret_type) &&
10572 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10573 			regs[BPF_REG_0].id = ++env->id_gen;
10574 		}
10575 		break;
10576 	case RET_PTR_TO_SOCKET:
10577 		mark_reg_known_zero(env, regs, BPF_REG_0);
10578 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10579 		break;
10580 	case RET_PTR_TO_SOCK_COMMON:
10581 		mark_reg_known_zero(env, regs, BPF_REG_0);
10582 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10583 		break;
10584 	case RET_PTR_TO_TCP_SOCK:
10585 		mark_reg_known_zero(env, regs, BPF_REG_0);
10586 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10587 		break;
10588 	case RET_PTR_TO_MEM:
10589 		mark_reg_known_zero(env, regs, BPF_REG_0);
10590 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10591 		regs[BPF_REG_0].mem_size = meta.mem_size;
10592 		break;
10593 	case RET_PTR_TO_MEM_OR_BTF_ID:
10594 	{
10595 		const struct btf_type *t;
10596 
10597 		mark_reg_known_zero(env, regs, BPF_REG_0);
10598 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10599 		if (!btf_type_is_struct(t)) {
10600 			u32 tsize;
10601 			const struct btf_type *ret;
10602 			const char *tname;
10603 
10604 			/* resolve the type size of ksym. */
10605 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10606 			if (IS_ERR(ret)) {
10607 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10608 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10609 					tname, PTR_ERR(ret));
10610 				return -EINVAL;
10611 			}
10612 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10613 			regs[BPF_REG_0].mem_size = tsize;
10614 		} else {
10615 			if (returns_cpu_specific_alloc_ptr) {
10616 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10617 			} else {
10618 				/* MEM_RDONLY may be carried from ret_flag, but it
10619 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10620 				 * it will confuse the check of PTR_TO_BTF_ID in
10621 				 * check_mem_access().
10622 				 */
10623 				ret_flag &= ~MEM_RDONLY;
10624 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10625 			}
10626 
10627 			regs[BPF_REG_0].btf = meta.ret_btf;
10628 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10629 		}
10630 		break;
10631 	}
10632 	case RET_PTR_TO_BTF_ID:
10633 	{
10634 		struct btf *ret_btf;
10635 		int ret_btf_id;
10636 
10637 		mark_reg_known_zero(env, regs, BPF_REG_0);
10638 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10639 		if (func_id == BPF_FUNC_kptr_xchg) {
10640 			ret_btf = meta.kptr_field->kptr.btf;
10641 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10642 			if (!btf_is_kernel(ret_btf)) {
10643 				regs[BPF_REG_0].type |= MEM_ALLOC;
10644 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10645 					regs[BPF_REG_0].type |= MEM_PERCPU;
10646 			}
10647 		} else {
10648 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10649 				verbose(env, "verifier internal error:");
10650 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10651 					func_id_name(func_id));
10652 				return -EINVAL;
10653 			}
10654 			ret_btf = btf_vmlinux;
10655 			ret_btf_id = *fn->ret_btf_id;
10656 		}
10657 		if (ret_btf_id == 0) {
10658 			verbose(env, "invalid return type %u of func %s#%d\n",
10659 				base_type(ret_type), func_id_name(func_id),
10660 				func_id);
10661 			return -EINVAL;
10662 		}
10663 		regs[BPF_REG_0].btf = ret_btf;
10664 		regs[BPF_REG_0].btf_id = ret_btf_id;
10665 		break;
10666 	}
10667 	default:
10668 		verbose(env, "unknown return type %u of func %s#%d\n",
10669 			base_type(ret_type), func_id_name(func_id), func_id);
10670 		return -EINVAL;
10671 	}
10672 
10673 	if (type_may_be_null(regs[BPF_REG_0].type))
10674 		regs[BPF_REG_0].id = ++env->id_gen;
10675 
10676 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10677 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10678 			func_id_name(func_id), func_id);
10679 		return -EFAULT;
10680 	}
10681 
10682 	if (is_dynptr_ref_function(func_id))
10683 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10684 
10685 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10686 		/* For release_reference() */
10687 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10688 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10689 		int id = acquire_reference_state(env, insn_idx);
10690 
10691 		if (id < 0)
10692 			return id;
10693 		/* For mark_ptr_or_null_reg() */
10694 		regs[BPF_REG_0].id = id;
10695 		/* For release_reference() */
10696 		regs[BPF_REG_0].ref_obj_id = id;
10697 	}
10698 
10699 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10700 	if (err)
10701 		return err;
10702 
10703 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10704 	if (err)
10705 		return err;
10706 
10707 	if ((func_id == BPF_FUNC_get_stack ||
10708 	     func_id == BPF_FUNC_get_task_stack) &&
10709 	    !env->prog->has_callchain_buf) {
10710 		const char *err_str;
10711 
10712 #ifdef CONFIG_PERF_EVENTS
10713 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10714 		err_str = "cannot get callchain buffer for func %s#%d\n";
10715 #else
10716 		err = -ENOTSUPP;
10717 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10718 #endif
10719 		if (err) {
10720 			verbose(env, err_str, func_id_name(func_id), func_id);
10721 			return err;
10722 		}
10723 
10724 		env->prog->has_callchain_buf = true;
10725 	}
10726 
10727 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10728 		env->prog->call_get_stack = true;
10729 
10730 	if (func_id == BPF_FUNC_get_func_ip) {
10731 		if (check_get_func_ip(env))
10732 			return -ENOTSUPP;
10733 		env->prog->call_get_func_ip = true;
10734 	}
10735 
10736 	if (changes_data)
10737 		clear_all_pkt_pointers(env);
10738 	return 0;
10739 }
10740 
10741 /* mark_btf_func_reg_size() is used when the reg size is determined by
10742  * the BTF func_proto's return value size and argument.
10743  */
10744 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10745 				   size_t reg_size)
10746 {
10747 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10748 
10749 	if (regno == BPF_REG_0) {
10750 		/* Function return value */
10751 		reg->live |= REG_LIVE_WRITTEN;
10752 		reg->subreg_def = reg_size == sizeof(u64) ?
10753 			DEF_NOT_SUBREG : env->insn_idx + 1;
10754 	} else {
10755 		/* Function argument */
10756 		if (reg_size == sizeof(u64)) {
10757 			mark_insn_zext(env, reg);
10758 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10759 		} else {
10760 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10761 		}
10762 	}
10763 }
10764 
10765 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10766 {
10767 	return meta->kfunc_flags & KF_ACQUIRE;
10768 }
10769 
10770 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10771 {
10772 	return meta->kfunc_flags & KF_RELEASE;
10773 }
10774 
10775 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10776 {
10777 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10778 }
10779 
10780 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10781 {
10782 	return meta->kfunc_flags & KF_SLEEPABLE;
10783 }
10784 
10785 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10786 {
10787 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10788 }
10789 
10790 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10791 {
10792 	return meta->kfunc_flags & KF_RCU;
10793 }
10794 
10795 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10796 {
10797 	return meta->kfunc_flags & KF_RCU_PROTECTED;
10798 }
10799 
10800 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10801 				  const struct btf_param *arg,
10802 				  const struct bpf_reg_state *reg)
10803 {
10804 	const struct btf_type *t;
10805 
10806 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10807 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10808 		return false;
10809 
10810 	return btf_param_match_suffix(btf, arg, "__sz");
10811 }
10812 
10813 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10814 					const struct btf_param *arg,
10815 					const struct bpf_reg_state *reg)
10816 {
10817 	const struct btf_type *t;
10818 
10819 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10820 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10821 		return false;
10822 
10823 	return btf_param_match_suffix(btf, arg, "__szk");
10824 }
10825 
10826 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10827 {
10828 	return btf_param_match_suffix(btf, arg, "__opt");
10829 }
10830 
10831 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10832 {
10833 	return btf_param_match_suffix(btf, arg, "__k");
10834 }
10835 
10836 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10837 {
10838 	return btf_param_match_suffix(btf, arg, "__ign");
10839 }
10840 
10841 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
10842 {
10843 	return btf_param_match_suffix(btf, arg, "__map");
10844 }
10845 
10846 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10847 {
10848 	return btf_param_match_suffix(btf, arg, "__alloc");
10849 }
10850 
10851 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10852 {
10853 	return btf_param_match_suffix(btf, arg, "__uninit");
10854 }
10855 
10856 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10857 {
10858 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
10859 }
10860 
10861 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10862 {
10863 	return btf_param_match_suffix(btf, arg, "__nullable");
10864 }
10865 
10866 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
10867 {
10868 	return btf_param_match_suffix(btf, arg, "__str");
10869 }
10870 
10871 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10872 					  const struct btf_param *arg,
10873 					  const char *name)
10874 {
10875 	int len, target_len = strlen(name);
10876 	const char *param_name;
10877 
10878 	param_name = btf_name_by_offset(btf, arg->name_off);
10879 	if (str_is_empty(param_name))
10880 		return false;
10881 	len = strlen(param_name);
10882 	if (len != target_len)
10883 		return false;
10884 	if (strcmp(param_name, name))
10885 		return false;
10886 
10887 	return true;
10888 }
10889 
10890 enum {
10891 	KF_ARG_DYNPTR_ID,
10892 	KF_ARG_LIST_HEAD_ID,
10893 	KF_ARG_LIST_NODE_ID,
10894 	KF_ARG_RB_ROOT_ID,
10895 	KF_ARG_RB_NODE_ID,
10896 	KF_ARG_WORKQUEUE_ID,
10897 };
10898 
10899 BTF_ID_LIST(kf_arg_btf_ids)
10900 BTF_ID(struct, bpf_dynptr_kern)
10901 BTF_ID(struct, bpf_list_head)
10902 BTF_ID(struct, bpf_list_node)
10903 BTF_ID(struct, bpf_rb_root)
10904 BTF_ID(struct, bpf_rb_node)
10905 BTF_ID(struct, bpf_wq)
10906 
10907 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10908 				    const struct btf_param *arg, int type)
10909 {
10910 	const struct btf_type *t;
10911 	u32 res_id;
10912 
10913 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10914 	if (!t)
10915 		return false;
10916 	if (!btf_type_is_ptr(t))
10917 		return false;
10918 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10919 	if (!t)
10920 		return false;
10921 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10922 }
10923 
10924 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10925 {
10926 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10927 }
10928 
10929 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10930 {
10931 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10932 }
10933 
10934 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10935 {
10936 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10937 }
10938 
10939 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10940 {
10941 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10942 }
10943 
10944 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10945 {
10946 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10947 }
10948 
10949 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
10950 {
10951 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
10952 }
10953 
10954 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10955 				  const struct btf_param *arg)
10956 {
10957 	const struct btf_type *t;
10958 
10959 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10960 	if (!t)
10961 		return false;
10962 
10963 	return true;
10964 }
10965 
10966 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10967 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10968 					const struct btf *btf,
10969 					const struct btf_type *t, int rec)
10970 {
10971 	const struct btf_type *member_type;
10972 	const struct btf_member *member;
10973 	u32 i;
10974 
10975 	if (!btf_type_is_struct(t))
10976 		return false;
10977 
10978 	for_each_member(i, t, member) {
10979 		const struct btf_array *array;
10980 
10981 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10982 		if (btf_type_is_struct(member_type)) {
10983 			if (rec >= 3) {
10984 				verbose(env, "max struct nesting depth exceeded\n");
10985 				return false;
10986 			}
10987 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10988 				return false;
10989 			continue;
10990 		}
10991 		if (btf_type_is_array(member_type)) {
10992 			array = btf_array(member_type);
10993 			if (!array->nelems)
10994 				return false;
10995 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10996 			if (!btf_type_is_scalar(member_type))
10997 				return false;
10998 			continue;
10999 		}
11000 		if (!btf_type_is_scalar(member_type))
11001 			return false;
11002 	}
11003 	return true;
11004 }
11005 
11006 enum kfunc_ptr_arg_type {
11007 	KF_ARG_PTR_TO_CTX,
11008 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
11009 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
11010 	KF_ARG_PTR_TO_DYNPTR,
11011 	KF_ARG_PTR_TO_ITER,
11012 	KF_ARG_PTR_TO_LIST_HEAD,
11013 	KF_ARG_PTR_TO_LIST_NODE,
11014 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
11015 	KF_ARG_PTR_TO_MEM,
11016 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
11017 	KF_ARG_PTR_TO_CALLBACK,
11018 	KF_ARG_PTR_TO_RB_ROOT,
11019 	KF_ARG_PTR_TO_RB_NODE,
11020 	KF_ARG_PTR_TO_NULL,
11021 	KF_ARG_PTR_TO_CONST_STR,
11022 	KF_ARG_PTR_TO_MAP,
11023 	KF_ARG_PTR_TO_WORKQUEUE,
11024 };
11025 
11026 enum special_kfunc_type {
11027 	KF_bpf_obj_new_impl,
11028 	KF_bpf_obj_drop_impl,
11029 	KF_bpf_refcount_acquire_impl,
11030 	KF_bpf_list_push_front_impl,
11031 	KF_bpf_list_push_back_impl,
11032 	KF_bpf_list_pop_front,
11033 	KF_bpf_list_pop_back,
11034 	KF_bpf_cast_to_kern_ctx,
11035 	KF_bpf_rdonly_cast,
11036 	KF_bpf_rcu_read_lock,
11037 	KF_bpf_rcu_read_unlock,
11038 	KF_bpf_rbtree_remove,
11039 	KF_bpf_rbtree_add_impl,
11040 	KF_bpf_rbtree_first,
11041 	KF_bpf_dynptr_from_skb,
11042 	KF_bpf_dynptr_from_xdp,
11043 	KF_bpf_dynptr_slice,
11044 	KF_bpf_dynptr_slice_rdwr,
11045 	KF_bpf_dynptr_clone,
11046 	KF_bpf_percpu_obj_new_impl,
11047 	KF_bpf_percpu_obj_drop_impl,
11048 	KF_bpf_throw,
11049 	KF_bpf_wq_set_callback_impl,
11050 	KF_bpf_preempt_disable,
11051 	KF_bpf_preempt_enable,
11052 	KF_bpf_iter_css_task_new,
11053 };
11054 
11055 BTF_SET_START(special_kfunc_set)
11056 BTF_ID(func, bpf_obj_new_impl)
11057 BTF_ID(func, bpf_obj_drop_impl)
11058 BTF_ID(func, bpf_refcount_acquire_impl)
11059 BTF_ID(func, bpf_list_push_front_impl)
11060 BTF_ID(func, bpf_list_push_back_impl)
11061 BTF_ID(func, bpf_list_pop_front)
11062 BTF_ID(func, bpf_list_pop_back)
11063 BTF_ID(func, bpf_cast_to_kern_ctx)
11064 BTF_ID(func, bpf_rdonly_cast)
11065 BTF_ID(func, bpf_rbtree_remove)
11066 BTF_ID(func, bpf_rbtree_add_impl)
11067 BTF_ID(func, bpf_rbtree_first)
11068 BTF_ID(func, bpf_dynptr_from_skb)
11069 BTF_ID(func, bpf_dynptr_from_xdp)
11070 BTF_ID(func, bpf_dynptr_slice)
11071 BTF_ID(func, bpf_dynptr_slice_rdwr)
11072 BTF_ID(func, bpf_dynptr_clone)
11073 BTF_ID(func, bpf_percpu_obj_new_impl)
11074 BTF_ID(func, bpf_percpu_obj_drop_impl)
11075 BTF_ID(func, bpf_throw)
11076 BTF_ID(func, bpf_wq_set_callback_impl)
11077 #ifdef CONFIG_CGROUPS
11078 BTF_ID(func, bpf_iter_css_task_new)
11079 #endif
11080 BTF_SET_END(special_kfunc_set)
11081 
11082 BTF_ID_LIST(special_kfunc_list)
11083 BTF_ID(func, bpf_obj_new_impl)
11084 BTF_ID(func, bpf_obj_drop_impl)
11085 BTF_ID(func, bpf_refcount_acquire_impl)
11086 BTF_ID(func, bpf_list_push_front_impl)
11087 BTF_ID(func, bpf_list_push_back_impl)
11088 BTF_ID(func, bpf_list_pop_front)
11089 BTF_ID(func, bpf_list_pop_back)
11090 BTF_ID(func, bpf_cast_to_kern_ctx)
11091 BTF_ID(func, bpf_rdonly_cast)
11092 BTF_ID(func, bpf_rcu_read_lock)
11093 BTF_ID(func, bpf_rcu_read_unlock)
11094 BTF_ID(func, bpf_rbtree_remove)
11095 BTF_ID(func, bpf_rbtree_add_impl)
11096 BTF_ID(func, bpf_rbtree_first)
11097 BTF_ID(func, bpf_dynptr_from_skb)
11098 BTF_ID(func, bpf_dynptr_from_xdp)
11099 BTF_ID(func, bpf_dynptr_slice)
11100 BTF_ID(func, bpf_dynptr_slice_rdwr)
11101 BTF_ID(func, bpf_dynptr_clone)
11102 BTF_ID(func, bpf_percpu_obj_new_impl)
11103 BTF_ID(func, bpf_percpu_obj_drop_impl)
11104 BTF_ID(func, bpf_throw)
11105 BTF_ID(func, bpf_wq_set_callback_impl)
11106 BTF_ID(func, bpf_preempt_disable)
11107 BTF_ID(func, bpf_preempt_enable)
11108 #ifdef CONFIG_CGROUPS
11109 BTF_ID(func, bpf_iter_css_task_new)
11110 #else
11111 BTF_ID_UNUSED
11112 #endif
11113 
11114 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
11115 {
11116 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
11117 	    meta->arg_owning_ref) {
11118 		return false;
11119 	}
11120 
11121 	return meta->kfunc_flags & KF_RET_NULL;
11122 }
11123 
11124 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
11125 {
11126 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11127 }
11128 
11129 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11130 {
11131 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11132 }
11133 
11134 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
11135 {
11136 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
11137 }
11138 
11139 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
11140 {
11141 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
11142 }
11143 
11144 static enum kfunc_ptr_arg_type
11145 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
11146 		       struct bpf_kfunc_call_arg_meta *meta,
11147 		       const struct btf_type *t, const struct btf_type *ref_t,
11148 		       const char *ref_tname, const struct btf_param *args,
11149 		       int argno, int nargs)
11150 {
11151 	u32 regno = argno + 1;
11152 	struct bpf_reg_state *regs = cur_regs(env);
11153 	struct bpf_reg_state *reg = &regs[regno];
11154 	bool arg_mem_size = false;
11155 
11156 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11157 		return KF_ARG_PTR_TO_CTX;
11158 
11159 	/* In this function, we verify the kfunc's BTF as per the argument type,
11160 	 * leaving the rest of the verification with respect to the register
11161 	 * type to our caller. When a set of conditions hold in the BTF type of
11162 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11163 	 */
11164 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11165 		return KF_ARG_PTR_TO_CTX;
11166 
11167 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11168 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11169 
11170 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11171 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11172 
11173 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11174 		return KF_ARG_PTR_TO_DYNPTR;
11175 
11176 	if (is_kfunc_arg_iter(meta, argno))
11177 		return KF_ARG_PTR_TO_ITER;
11178 
11179 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11180 		return KF_ARG_PTR_TO_LIST_HEAD;
11181 
11182 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11183 		return KF_ARG_PTR_TO_LIST_NODE;
11184 
11185 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11186 		return KF_ARG_PTR_TO_RB_ROOT;
11187 
11188 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11189 		return KF_ARG_PTR_TO_RB_NODE;
11190 
11191 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11192 		return KF_ARG_PTR_TO_CONST_STR;
11193 
11194 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
11195 		return KF_ARG_PTR_TO_MAP;
11196 
11197 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
11198 		return KF_ARG_PTR_TO_WORKQUEUE;
11199 
11200 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11201 		if (!btf_type_is_struct(ref_t)) {
11202 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11203 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11204 			return -EINVAL;
11205 		}
11206 		return KF_ARG_PTR_TO_BTF_ID;
11207 	}
11208 
11209 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11210 		return KF_ARG_PTR_TO_CALLBACK;
11211 
11212 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11213 		return KF_ARG_PTR_TO_NULL;
11214 
11215 	if (argno + 1 < nargs &&
11216 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
11217 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
11218 		arg_mem_size = true;
11219 
11220 	/* This is the catch all argument type of register types supported by
11221 	 * check_helper_mem_access. However, we only allow when argument type is
11222 	 * pointer to scalar, or struct composed (recursively) of scalars. When
11223 	 * arg_mem_size is true, the pointer can be void *.
11224 	 */
11225 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11226 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11227 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11228 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11229 		return -EINVAL;
11230 	}
11231 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11232 }
11233 
11234 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11235 					struct bpf_reg_state *reg,
11236 					const struct btf_type *ref_t,
11237 					const char *ref_tname, u32 ref_id,
11238 					struct bpf_kfunc_call_arg_meta *meta,
11239 					int argno)
11240 {
11241 	const struct btf_type *reg_ref_t;
11242 	bool strict_type_match = false;
11243 	const struct btf *reg_btf;
11244 	const char *reg_ref_tname;
11245 	u32 reg_ref_id;
11246 
11247 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
11248 		reg_btf = reg->btf;
11249 		reg_ref_id = reg->btf_id;
11250 	} else {
11251 		reg_btf = btf_vmlinux;
11252 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11253 	}
11254 
11255 	/* Enforce strict type matching for calls to kfuncs that are acquiring
11256 	 * or releasing a reference, or are no-cast aliases. We do _not_
11257 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11258 	 * as we want to enable BPF programs to pass types that are bitwise
11259 	 * equivalent without forcing them to explicitly cast with something
11260 	 * like bpf_cast_to_kern_ctx().
11261 	 *
11262 	 * For example, say we had a type like the following:
11263 	 *
11264 	 * struct bpf_cpumask {
11265 	 *	cpumask_t cpumask;
11266 	 *	refcount_t usage;
11267 	 * };
11268 	 *
11269 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11270 	 * to a struct cpumask, so it would be safe to pass a struct
11271 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11272 	 *
11273 	 * The philosophy here is similar to how we allow scalars of different
11274 	 * types to be passed to kfuncs as long as the size is the same. The
11275 	 * only difference here is that we're simply allowing
11276 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11277 	 * resolve types.
11278 	 */
11279 	if (is_kfunc_acquire(meta) ||
11280 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
11281 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11282 		strict_type_match = true;
11283 
11284 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
11285 
11286 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
11287 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11288 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
11289 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11290 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11291 			btf_type_str(reg_ref_t), reg_ref_tname);
11292 		return -EINVAL;
11293 	}
11294 	return 0;
11295 }
11296 
11297 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11298 {
11299 	struct bpf_verifier_state *state = env->cur_state;
11300 	struct btf_record *rec = reg_btf_record(reg);
11301 
11302 	if (!state->active_lock.ptr) {
11303 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11304 		return -EFAULT;
11305 	}
11306 
11307 	if (type_flag(reg->type) & NON_OWN_REF) {
11308 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11309 		return -EFAULT;
11310 	}
11311 
11312 	reg->type |= NON_OWN_REF;
11313 	if (rec->refcount_off >= 0)
11314 		reg->type |= MEM_RCU;
11315 
11316 	return 0;
11317 }
11318 
11319 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11320 {
11321 	struct bpf_func_state *state, *unused;
11322 	struct bpf_reg_state *reg;
11323 	int i;
11324 
11325 	state = cur_func(env);
11326 
11327 	if (!ref_obj_id) {
11328 		verbose(env, "verifier internal error: ref_obj_id is zero for "
11329 			     "owning -> non-owning conversion\n");
11330 		return -EFAULT;
11331 	}
11332 
11333 	for (i = 0; i < state->acquired_refs; i++) {
11334 		if (state->refs[i].id != ref_obj_id)
11335 			continue;
11336 
11337 		/* Clear ref_obj_id here so release_reference doesn't clobber
11338 		 * the whole reg
11339 		 */
11340 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11341 			if (reg->ref_obj_id == ref_obj_id) {
11342 				reg->ref_obj_id = 0;
11343 				ref_set_non_owning(env, reg);
11344 			}
11345 		}));
11346 		return 0;
11347 	}
11348 
11349 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11350 	return -EFAULT;
11351 }
11352 
11353 /* Implementation details:
11354  *
11355  * Each register points to some region of memory, which we define as an
11356  * allocation. Each allocation may embed a bpf_spin_lock which protects any
11357  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11358  * allocation. The lock and the data it protects are colocated in the same
11359  * memory region.
11360  *
11361  * Hence, everytime a register holds a pointer value pointing to such
11362  * allocation, the verifier preserves a unique reg->id for it.
11363  *
11364  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11365  * bpf_spin_lock is called.
11366  *
11367  * To enable this, lock state in the verifier captures two values:
11368  *	active_lock.ptr = Register's type specific pointer
11369  *	active_lock.id  = A unique ID for each register pointer value
11370  *
11371  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11372  * supported register types.
11373  *
11374  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11375  * allocated objects is the reg->btf pointer.
11376  *
11377  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11378  * can establish the provenance of the map value statically for each distinct
11379  * lookup into such maps. They always contain a single map value hence unique
11380  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11381  *
11382  * So, in case of global variables, they use array maps with max_entries = 1,
11383  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11384  * into the same map value as max_entries is 1, as described above).
11385  *
11386  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11387  * outer map pointer (in verifier context), but each lookup into an inner map
11388  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11389  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11390  * will get different reg->id assigned to each lookup, hence different
11391  * active_lock.id.
11392  *
11393  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11394  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11395  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11396  */
11397 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11398 {
11399 	void *ptr;
11400 	u32 id;
11401 
11402 	switch ((int)reg->type) {
11403 	case PTR_TO_MAP_VALUE:
11404 		ptr = reg->map_ptr;
11405 		break;
11406 	case PTR_TO_BTF_ID | MEM_ALLOC:
11407 		ptr = reg->btf;
11408 		break;
11409 	default:
11410 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11411 		return -EFAULT;
11412 	}
11413 	id = reg->id;
11414 
11415 	if (!env->cur_state->active_lock.ptr)
11416 		return -EINVAL;
11417 	if (env->cur_state->active_lock.ptr != ptr ||
11418 	    env->cur_state->active_lock.id != id) {
11419 		verbose(env, "held lock and object are not in the same allocation\n");
11420 		return -EINVAL;
11421 	}
11422 	return 0;
11423 }
11424 
11425 static bool is_bpf_list_api_kfunc(u32 btf_id)
11426 {
11427 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11428 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11429 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11430 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11431 }
11432 
11433 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11434 {
11435 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11436 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11437 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11438 }
11439 
11440 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11441 {
11442 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11443 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11444 }
11445 
11446 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11447 {
11448 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11449 }
11450 
11451 static bool is_async_callback_calling_kfunc(u32 btf_id)
11452 {
11453 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
11454 }
11455 
11456 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11457 {
11458 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11459 	       insn->imm == special_kfunc_list[KF_bpf_throw];
11460 }
11461 
11462 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
11463 {
11464 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
11465 }
11466 
11467 static bool is_callback_calling_kfunc(u32 btf_id)
11468 {
11469 	return is_sync_callback_calling_kfunc(btf_id) ||
11470 	       is_async_callback_calling_kfunc(btf_id);
11471 }
11472 
11473 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11474 {
11475 	return is_bpf_rbtree_api_kfunc(btf_id);
11476 }
11477 
11478 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11479 					  enum btf_field_type head_field_type,
11480 					  u32 kfunc_btf_id)
11481 {
11482 	bool ret;
11483 
11484 	switch (head_field_type) {
11485 	case BPF_LIST_HEAD:
11486 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11487 		break;
11488 	case BPF_RB_ROOT:
11489 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11490 		break;
11491 	default:
11492 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11493 			btf_field_type_name(head_field_type));
11494 		return false;
11495 	}
11496 
11497 	if (!ret)
11498 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11499 			btf_field_type_name(head_field_type));
11500 	return ret;
11501 }
11502 
11503 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11504 					  enum btf_field_type node_field_type,
11505 					  u32 kfunc_btf_id)
11506 {
11507 	bool ret;
11508 
11509 	switch (node_field_type) {
11510 	case BPF_LIST_NODE:
11511 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11512 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11513 		break;
11514 	case BPF_RB_NODE:
11515 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11516 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11517 		break;
11518 	default:
11519 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11520 			btf_field_type_name(node_field_type));
11521 		return false;
11522 	}
11523 
11524 	if (!ret)
11525 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11526 			btf_field_type_name(node_field_type));
11527 	return ret;
11528 }
11529 
11530 static int
11531 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11532 				   struct bpf_reg_state *reg, u32 regno,
11533 				   struct bpf_kfunc_call_arg_meta *meta,
11534 				   enum btf_field_type head_field_type,
11535 				   struct btf_field **head_field)
11536 {
11537 	const char *head_type_name;
11538 	struct btf_field *field;
11539 	struct btf_record *rec;
11540 	u32 head_off;
11541 
11542 	if (meta->btf != btf_vmlinux) {
11543 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11544 		return -EFAULT;
11545 	}
11546 
11547 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11548 		return -EFAULT;
11549 
11550 	head_type_name = btf_field_type_name(head_field_type);
11551 	if (!tnum_is_const(reg->var_off)) {
11552 		verbose(env,
11553 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11554 			regno, head_type_name);
11555 		return -EINVAL;
11556 	}
11557 
11558 	rec = reg_btf_record(reg);
11559 	head_off = reg->off + reg->var_off.value;
11560 	field = btf_record_find(rec, head_off, head_field_type);
11561 	if (!field) {
11562 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11563 		return -EINVAL;
11564 	}
11565 
11566 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11567 	if (check_reg_allocation_locked(env, reg)) {
11568 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11569 			rec->spin_lock_off, head_type_name);
11570 		return -EINVAL;
11571 	}
11572 
11573 	if (*head_field) {
11574 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11575 		return -EFAULT;
11576 	}
11577 	*head_field = field;
11578 	return 0;
11579 }
11580 
11581 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11582 					   struct bpf_reg_state *reg, u32 regno,
11583 					   struct bpf_kfunc_call_arg_meta *meta)
11584 {
11585 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11586 							  &meta->arg_list_head.field);
11587 }
11588 
11589 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11590 					     struct bpf_reg_state *reg, u32 regno,
11591 					     struct bpf_kfunc_call_arg_meta *meta)
11592 {
11593 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11594 							  &meta->arg_rbtree_root.field);
11595 }
11596 
11597 static int
11598 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11599 				   struct bpf_reg_state *reg, u32 regno,
11600 				   struct bpf_kfunc_call_arg_meta *meta,
11601 				   enum btf_field_type head_field_type,
11602 				   enum btf_field_type node_field_type,
11603 				   struct btf_field **node_field)
11604 {
11605 	const char *node_type_name;
11606 	const struct btf_type *et, *t;
11607 	struct btf_field *field;
11608 	u32 node_off;
11609 
11610 	if (meta->btf != btf_vmlinux) {
11611 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11612 		return -EFAULT;
11613 	}
11614 
11615 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11616 		return -EFAULT;
11617 
11618 	node_type_name = btf_field_type_name(node_field_type);
11619 	if (!tnum_is_const(reg->var_off)) {
11620 		verbose(env,
11621 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11622 			regno, node_type_name);
11623 		return -EINVAL;
11624 	}
11625 
11626 	node_off = reg->off + reg->var_off.value;
11627 	field = reg_find_field_offset(reg, node_off, node_field_type);
11628 	if (!field || field->offset != node_off) {
11629 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11630 		return -EINVAL;
11631 	}
11632 
11633 	field = *node_field;
11634 
11635 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11636 	t = btf_type_by_id(reg->btf, reg->btf_id);
11637 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11638 				  field->graph_root.value_btf_id, true)) {
11639 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11640 			"in struct %s, but arg is at offset=%d in struct %s\n",
11641 			btf_field_type_name(head_field_type),
11642 			btf_field_type_name(node_field_type),
11643 			field->graph_root.node_offset,
11644 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11645 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11646 		return -EINVAL;
11647 	}
11648 	meta->arg_btf = reg->btf;
11649 	meta->arg_btf_id = reg->btf_id;
11650 
11651 	if (node_off != field->graph_root.node_offset) {
11652 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11653 			node_off, btf_field_type_name(node_field_type),
11654 			field->graph_root.node_offset,
11655 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11656 		return -EINVAL;
11657 	}
11658 
11659 	return 0;
11660 }
11661 
11662 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11663 					   struct bpf_reg_state *reg, u32 regno,
11664 					   struct bpf_kfunc_call_arg_meta *meta)
11665 {
11666 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11667 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11668 						  &meta->arg_list_head.field);
11669 }
11670 
11671 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11672 					     struct bpf_reg_state *reg, u32 regno,
11673 					     struct bpf_kfunc_call_arg_meta *meta)
11674 {
11675 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11676 						  BPF_RB_ROOT, BPF_RB_NODE,
11677 						  &meta->arg_rbtree_root.field);
11678 }
11679 
11680 /*
11681  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11682  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11683  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11684  * them can only be attached to some specific hook points.
11685  */
11686 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11687 {
11688 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11689 
11690 	switch (prog_type) {
11691 	case BPF_PROG_TYPE_LSM:
11692 		return true;
11693 	case BPF_PROG_TYPE_TRACING:
11694 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11695 			return true;
11696 		fallthrough;
11697 	default:
11698 		return in_sleepable(env);
11699 	}
11700 }
11701 
11702 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11703 			    int insn_idx)
11704 {
11705 	const char *func_name = meta->func_name, *ref_tname;
11706 	const struct btf *btf = meta->btf;
11707 	const struct btf_param *args;
11708 	struct btf_record *rec;
11709 	u32 i, nargs;
11710 	int ret;
11711 
11712 	args = (const struct btf_param *)(meta->func_proto + 1);
11713 	nargs = btf_type_vlen(meta->func_proto);
11714 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11715 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11716 			MAX_BPF_FUNC_REG_ARGS);
11717 		return -EINVAL;
11718 	}
11719 
11720 	/* Check that BTF function arguments match actual types that the
11721 	 * verifier sees.
11722 	 */
11723 	for (i = 0; i < nargs; i++) {
11724 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11725 		const struct btf_type *t, *ref_t, *resolve_ret;
11726 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11727 		u32 regno = i + 1, ref_id, type_size;
11728 		bool is_ret_buf_sz = false;
11729 		int kf_arg_type;
11730 
11731 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11732 
11733 		if (is_kfunc_arg_ignore(btf, &args[i]))
11734 			continue;
11735 
11736 		if (btf_type_is_scalar(t)) {
11737 			if (reg->type != SCALAR_VALUE) {
11738 				verbose(env, "R%d is not a scalar\n", regno);
11739 				return -EINVAL;
11740 			}
11741 
11742 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11743 				if (meta->arg_constant.found) {
11744 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11745 					return -EFAULT;
11746 				}
11747 				if (!tnum_is_const(reg->var_off)) {
11748 					verbose(env, "R%d must be a known constant\n", regno);
11749 					return -EINVAL;
11750 				}
11751 				ret = mark_chain_precision(env, regno);
11752 				if (ret < 0)
11753 					return ret;
11754 				meta->arg_constant.found = true;
11755 				meta->arg_constant.value = reg->var_off.value;
11756 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11757 				meta->r0_rdonly = true;
11758 				is_ret_buf_sz = true;
11759 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11760 				is_ret_buf_sz = true;
11761 			}
11762 
11763 			if (is_ret_buf_sz) {
11764 				if (meta->r0_size) {
11765 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11766 					return -EINVAL;
11767 				}
11768 
11769 				if (!tnum_is_const(reg->var_off)) {
11770 					verbose(env, "R%d is not a const\n", regno);
11771 					return -EINVAL;
11772 				}
11773 
11774 				meta->r0_size = reg->var_off.value;
11775 				ret = mark_chain_precision(env, regno);
11776 				if (ret)
11777 					return ret;
11778 			}
11779 			continue;
11780 		}
11781 
11782 		if (!btf_type_is_ptr(t)) {
11783 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11784 			return -EINVAL;
11785 		}
11786 
11787 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11788 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
11789 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
11790 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11791 			return -EACCES;
11792 		}
11793 
11794 		if (reg->ref_obj_id) {
11795 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11796 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11797 					regno, reg->ref_obj_id,
11798 					meta->ref_obj_id);
11799 				return -EFAULT;
11800 			}
11801 			meta->ref_obj_id = reg->ref_obj_id;
11802 			if (is_kfunc_release(meta))
11803 				meta->release_regno = regno;
11804 		}
11805 
11806 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11807 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11808 
11809 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11810 		if (kf_arg_type < 0)
11811 			return kf_arg_type;
11812 
11813 		switch (kf_arg_type) {
11814 		case KF_ARG_PTR_TO_NULL:
11815 			continue;
11816 		case KF_ARG_PTR_TO_MAP:
11817 			if (!reg->map_ptr) {
11818 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
11819 				return -EINVAL;
11820 			}
11821 			if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) {
11822 				/* Use map_uid (which is unique id of inner map) to reject:
11823 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
11824 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
11825 				 * if (inner_map1 && inner_map2) {
11826 				 *     wq = bpf_map_lookup_elem(inner_map1);
11827 				 *     if (wq)
11828 				 *         // mismatch would have been allowed
11829 				 *         bpf_wq_init(wq, inner_map2);
11830 				 * }
11831 				 *
11832 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
11833 				 */
11834 				if (meta->map.ptr != reg->map_ptr ||
11835 				    meta->map.uid != reg->map_uid) {
11836 					verbose(env,
11837 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
11838 						meta->map.uid, reg->map_uid);
11839 					return -EINVAL;
11840 				}
11841 			}
11842 			meta->map.ptr = reg->map_ptr;
11843 			meta->map.uid = reg->map_uid;
11844 			fallthrough;
11845 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11846 		case KF_ARG_PTR_TO_BTF_ID:
11847 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11848 				break;
11849 
11850 			if (!is_trusted_reg(reg)) {
11851 				if (!is_kfunc_rcu(meta)) {
11852 					verbose(env, "R%d must be referenced or trusted\n", regno);
11853 					return -EINVAL;
11854 				}
11855 				if (!is_rcu_reg(reg)) {
11856 					verbose(env, "R%d must be a rcu pointer\n", regno);
11857 					return -EINVAL;
11858 				}
11859 			}
11860 
11861 			fallthrough;
11862 		case KF_ARG_PTR_TO_CTX:
11863 			/* Trusted arguments have the same offset checks as release arguments */
11864 			arg_type |= OBJ_RELEASE;
11865 			break;
11866 		case KF_ARG_PTR_TO_DYNPTR:
11867 		case KF_ARG_PTR_TO_ITER:
11868 		case KF_ARG_PTR_TO_LIST_HEAD:
11869 		case KF_ARG_PTR_TO_LIST_NODE:
11870 		case KF_ARG_PTR_TO_RB_ROOT:
11871 		case KF_ARG_PTR_TO_RB_NODE:
11872 		case KF_ARG_PTR_TO_MEM:
11873 		case KF_ARG_PTR_TO_MEM_SIZE:
11874 		case KF_ARG_PTR_TO_CALLBACK:
11875 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11876 		case KF_ARG_PTR_TO_CONST_STR:
11877 		case KF_ARG_PTR_TO_WORKQUEUE:
11878 			/* Trusted by default */
11879 			break;
11880 		default:
11881 			WARN_ON_ONCE(1);
11882 			return -EFAULT;
11883 		}
11884 
11885 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11886 			arg_type |= OBJ_RELEASE;
11887 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11888 		if (ret < 0)
11889 			return ret;
11890 
11891 		switch (kf_arg_type) {
11892 		case KF_ARG_PTR_TO_CTX:
11893 			if (reg->type != PTR_TO_CTX) {
11894 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11895 				return -EINVAL;
11896 			}
11897 
11898 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11899 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11900 				if (ret < 0)
11901 					return -EINVAL;
11902 				meta->ret_btf_id  = ret;
11903 			}
11904 			break;
11905 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11906 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11907 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11908 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11909 					return -EINVAL;
11910 				}
11911 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11912 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11913 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11914 					return -EINVAL;
11915 				}
11916 			} else {
11917 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11918 				return -EINVAL;
11919 			}
11920 			if (!reg->ref_obj_id) {
11921 				verbose(env, "allocated object must be referenced\n");
11922 				return -EINVAL;
11923 			}
11924 			if (meta->btf == btf_vmlinux) {
11925 				meta->arg_btf = reg->btf;
11926 				meta->arg_btf_id = reg->btf_id;
11927 			}
11928 			break;
11929 		case KF_ARG_PTR_TO_DYNPTR:
11930 		{
11931 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11932 			int clone_ref_obj_id = 0;
11933 
11934 			if (reg->type != PTR_TO_STACK &&
11935 			    reg->type != CONST_PTR_TO_DYNPTR) {
11936 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11937 				return -EINVAL;
11938 			}
11939 
11940 			if (reg->type == CONST_PTR_TO_DYNPTR)
11941 				dynptr_arg_type |= MEM_RDONLY;
11942 
11943 			if (is_kfunc_arg_uninit(btf, &args[i]))
11944 				dynptr_arg_type |= MEM_UNINIT;
11945 
11946 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11947 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11948 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11949 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11950 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11951 				   (dynptr_arg_type & MEM_UNINIT)) {
11952 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11953 
11954 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11955 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11956 					return -EFAULT;
11957 				}
11958 
11959 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11960 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11961 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11962 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11963 					return -EFAULT;
11964 				}
11965 			}
11966 
11967 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11968 			if (ret < 0)
11969 				return ret;
11970 
11971 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11972 				int id = dynptr_id(env, reg);
11973 
11974 				if (id < 0) {
11975 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11976 					return id;
11977 				}
11978 				meta->initialized_dynptr.id = id;
11979 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11980 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11981 			}
11982 
11983 			break;
11984 		}
11985 		case KF_ARG_PTR_TO_ITER:
11986 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
11987 				if (!check_css_task_iter_allowlist(env)) {
11988 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
11989 					return -EINVAL;
11990 				}
11991 			}
11992 			ret = process_iter_arg(env, regno, insn_idx, meta);
11993 			if (ret < 0)
11994 				return ret;
11995 			break;
11996 		case KF_ARG_PTR_TO_LIST_HEAD:
11997 			if (reg->type != PTR_TO_MAP_VALUE &&
11998 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11999 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12000 				return -EINVAL;
12001 			}
12002 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12003 				verbose(env, "allocated object must be referenced\n");
12004 				return -EINVAL;
12005 			}
12006 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
12007 			if (ret < 0)
12008 				return ret;
12009 			break;
12010 		case KF_ARG_PTR_TO_RB_ROOT:
12011 			if (reg->type != PTR_TO_MAP_VALUE &&
12012 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12013 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12014 				return -EINVAL;
12015 			}
12016 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12017 				verbose(env, "allocated object must be referenced\n");
12018 				return -EINVAL;
12019 			}
12020 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
12021 			if (ret < 0)
12022 				return ret;
12023 			break;
12024 		case KF_ARG_PTR_TO_LIST_NODE:
12025 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12026 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
12027 				return -EINVAL;
12028 			}
12029 			if (!reg->ref_obj_id) {
12030 				verbose(env, "allocated object must be referenced\n");
12031 				return -EINVAL;
12032 			}
12033 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
12034 			if (ret < 0)
12035 				return ret;
12036 			break;
12037 		case KF_ARG_PTR_TO_RB_NODE:
12038 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
12039 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
12040 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
12041 					return -EINVAL;
12042 				}
12043 				if (in_rbtree_lock_required_cb(env)) {
12044 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
12045 					return -EINVAL;
12046 				}
12047 			} else {
12048 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12049 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
12050 					return -EINVAL;
12051 				}
12052 				if (!reg->ref_obj_id) {
12053 					verbose(env, "allocated object must be referenced\n");
12054 					return -EINVAL;
12055 				}
12056 			}
12057 
12058 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
12059 			if (ret < 0)
12060 				return ret;
12061 			break;
12062 		case KF_ARG_PTR_TO_MAP:
12063 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
12064 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
12065 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
12066 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12067 			fallthrough;
12068 		case KF_ARG_PTR_TO_BTF_ID:
12069 			/* Only base_type is checked, further checks are done here */
12070 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
12071 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
12072 			    !reg2btf_ids[base_type(reg->type)]) {
12073 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
12074 				verbose(env, "expected %s or socket\n",
12075 					reg_type_str(env, base_type(reg->type) |
12076 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
12077 				return -EINVAL;
12078 			}
12079 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
12080 			if (ret < 0)
12081 				return ret;
12082 			break;
12083 		case KF_ARG_PTR_TO_MEM:
12084 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
12085 			if (IS_ERR(resolve_ret)) {
12086 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
12087 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
12088 				return -EINVAL;
12089 			}
12090 			ret = check_mem_reg(env, reg, regno, type_size);
12091 			if (ret < 0)
12092 				return ret;
12093 			break;
12094 		case KF_ARG_PTR_TO_MEM_SIZE:
12095 		{
12096 			struct bpf_reg_state *buff_reg = &regs[regno];
12097 			const struct btf_param *buff_arg = &args[i];
12098 			struct bpf_reg_state *size_reg = &regs[regno + 1];
12099 			const struct btf_param *size_arg = &args[i + 1];
12100 
12101 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
12102 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
12103 				if (ret < 0) {
12104 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
12105 					return ret;
12106 				}
12107 			}
12108 
12109 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
12110 				if (meta->arg_constant.found) {
12111 					verbose(env, "verifier internal error: only one constant argument permitted\n");
12112 					return -EFAULT;
12113 				}
12114 				if (!tnum_is_const(size_reg->var_off)) {
12115 					verbose(env, "R%d must be a known constant\n", regno + 1);
12116 					return -EINVAL;
12117 				}
12118 				meta->arg_constant.found = true;
12119 				meta->arg_constant.value = size_reg->var_off.value;
12120 			}
12121 
12122 			/* Skip next '__sz' or '__szk' argument */
12123 			i++;
12124 			break;
12125 		}
12126 		case KF_ARG_PTR_TO_CALLBACK:
12127 			if (reg->type != PTR_TO_FUNC) {
12128 				verbose(env, "arg%d expected pointer to func\n", i);
12129 				return -EINVAL;
12130 			}
12131 			meta->subprogno = reg->subprogno;
12132 			break;
12133 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12134 			if (!type_is_ptr_alloc_obj(reg->type)) {
12135 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
12136 				return -EINVAL;
12137 			}
12138 			if (!type_is_non_owning_ref(reg->type))
12139 				meta->arg_owning_ref = true;
12140 
12141 			rec = reg_btf_record(reg);
12142 			if (!rec) {
12143 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
12144 				return -EFAULT;
12145 			}
12146 
12147 			if (rec->refcount_off < 0) {
12148 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
12149 				return -EINVAL;
12150 			}
12151 
12152 			meta->arg_btf = reg->btf;
12153 			meta->arg_btf_id = reg->btf_id;
12154 			break;
12155 		case KF_ARG_PTR_TO_CONST_STR:
12156 			if (reg->type != PTR_TO_MAP_VALUE) {
12157 				verbose(env, "arg#%d doesn't point to a const string\n", i);
12158 				return -EINVAL;
12159 			}
12160 			ret = check_reg_const_str(env, reg, regno);
12161 			if (ret)
12162 				return ret;
12163 			break;
12164 		case KF_ARG_PTR_TO_WORKQUEUE:
12165 			if (reg->type != PTR_TO_MAP_VALUE) {
12166 				verbose(env, "arg#%d doesn't point to a map value\n", i);
12167 				return -EINVAL;
12168 			}
12169 			ret = process_wq_func(env, regno, meta);
12170 			if (ret < 0)
12171 				return ret;
12172 			break;
12173 		}
12174 	}
12175 
12176 	if (is_kfunc_release(meta) && !meta->release_regno) {
12177 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
12178 			func_name);
12179 		return -EINVAL;
12180 	}
12181 
12182 	return 0;
12183 }
12184 
12185 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
12186 			    struct bpf_insn *insn,
12187 			    struct bpf_kfunc_call_arg_meta *meta,
12188 			    const char **kfunc_name)
12189 {
12190 	const struct btf_type *func, *func_proto;
12191 	u32 func_id, *kfunc_flags;
12192 	const char *func_name;
12193 	struct btf *desc_btf;
12194 
12195 	if (kfunc_name)
12196 		*kfunc_name = NULL;
12197 
12198 	if (!insn->imm)
12199 		return -EINVAL;
12200 
12201 	desc_btf = find_kfunc_desc_btf(env, insn->off);
12202 	if (IS_ERR(desc_btf))
12203 		return PTR_ERR(desc_btf);
12204 
12205 	func_id = insn->imm;
12206 	func = btf_type_by_id(desc_btf, func_id);
12207 	func_name = btf_name_by_offset(desc_btf, func->name_off);
12208 	if (kfunc_name)
12209 		*kfunc_name = func_name;
12210 	func_proto = btf_type_by_id(desc_btf, func->type);
12211 
12212 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
12213 	if (!kfunc_flags) {
12214 		return -EACCES;
12215 	}
12216 
12217 	memset(meta, 0, sizeof(*meta));
12218 	meta->btf = desc_btf;
12219 	meta->func_id = func_id;
12220 	meta->kfunc_flags = *kfunc_flags;
12221 	meta->func_proto = func_proto;
12222 	meta->func_name = func_name;
12223 
12224 	return 0;
12225 }
12226 
12227 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12228 
12229 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12230 			    int *insn_idx_p)
12231 {
12232 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
12233 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
12234 	struct bpf_reg_state *regs = cur_regs(env);
12235 	const char *func_name, *ptr_type_name;
12236 	const struct btf_type *t, *ptr_type;
12237 	struct bpf_kfunc_call_arg_meta meta;
12238 	struct bpf_insn_aux_data *insn_aux;
12239 	int err, insn_idx = *insn_idx_p;
12240 	const struct btf_param *args;
12241 	const struct btf_type *ret_t;
12242 	struct btf *desc_btf;
12243 
12244 	/* skip for now, but return error when we find this in fixup_kfunc_call */
12245 	if (!insn->imm)
12246 		return 0;
12247 
12248 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
12249 	if (err == -EACCES && func_name)
12250 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
12251 	if (err)
12252 		return err;
12253 	desc_btf = meta.btf;
12254 	insn_aux = &env->insn_aux_data[insn_idx];
12255 
12256 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
12257 
12258 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12259 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12260 		return -EACCES;
12261 	}
12262 
12263 	sleepable = is_kfunc_sleepable(&meta);
12264 	if (sleepable && !in_sleepable(env)) {
12265 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12266 		return -EACCES;
12267 	}
12268 
12269 	/* Check the arguments */
12270 	err = check_kfunc_args(env, &meta, insn_idx);
12271 	if (err < 0)
12272 		return err;
12273 
12274 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12275 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12276 					 set_rbtree_add_callback_state);
12277 		if (err) {
12278 			verbose(env, "kfunc %s#%d failed callback verification\n",
12279 				func_name, meta.func_id);
12280 			return err;
12281 		}
12282 	}
12283 
12284 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
12285 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12286 					 set_timer_callback_state);
12287 		if (err) {
12288 			verbose(env, "kfunc %s#%d failed callback verification\n",
12289 				func_name, meta.func_id);
12290 			return err;
12291 		}
12292 	}
12293 
12294 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12295 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
12296 
12297 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
12298 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
12299 
12300 	if (env->cur_state->active_rcu_lock) {
12301 		struct bpf_func_state *state;
12302 		struct bpf_reg_state *reg;
12303 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
12304 
12305 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12306 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12307 			return -EACCES;
12308 		}
12309 
12310 		if (rcu_lock) {
12311 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12312 			return -EINVAL;
12313 		} else if (rcu_unlock) {
12314 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
12315 				if (reg->type & MEM_RCU) {
12316 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
12317 					reg->type |= PTR_UNTRUSTED;
12318 				}
12319 			}));
12320 			env->cur_state->active_rcu_lock = false;
12321 		} else if (sleepable) {
12322 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12323 			return -EACCES;
12324 		}
12325 	} else if (rcu_lock) {
12326 		env->cur_state->active_rcu_lock = true;
12327 	} else if (rcu_unlock) {
12328 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12329 		return -EINVAL;
12330 	}
12331 
12332 	if (env->cur_state->active_preempt_lock) {
12333 		if (preempt_disable) {
12334 			env->cur_state->active_preempt_lock++;
12335 		} else if (preempt_enable) {
12336 			env->cur_state->active_preempt_lock--;
12337 		} else if (sleepable) {
12338 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
12339 			return -EACCES;
12340 		}
12341 	} else if (preempt_disable) {
12342 		env->cur_state->active_preempt_lock++;
12343 	} else if (preempt_enable) {
12344 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
12345 		return -EINVAL;
12346 	}
12347 
12348 	/* In case of release function, we get register number of refcounted
12349 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
12350 	 */
12351 	if (meta.release_regno) {
12352 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
12353 		if (err) {
12354 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12355 				func_name, meta.func_id);
12356 			return err;
12357 		}
12358 	}
12359 
12360 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12361 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12362 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12363 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
12364 		insn_aux->insert_off = regs[BPF_REG_2].off;
12365 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
12366 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12367 		if (err) {
12368 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
12369 				func_name, meta.func_id);
12370 			return err;
12371 		}
12372 
12373 		err = release_reference(env, release_ref_obj_id);
12374 		if (err) {
12375 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12376 				func_name, meta.func_id);
12377 			return err;
12378 		}
12379 	}
12380 
12381 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12382 		if (!bpf_jit_supports_exceptions()) {
12383 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
12384 				func_name, meta.func_id);
12385 			return -ENOTSUPP;
12386 		}
12387 		env->seen_exception = true;
12388 
12389 		/* In the case of the default callback, the cookie value passed
12390 		 * to bpf_throw becomes the return value of the program.
12391 		 */
12392 		if (!env->exception_callback_subprog) {
12393 			err = check_return_code(env, BPF_REG_1, "R1");
12394 			if (err < 0)
12395 				return err;
12396 		}
12397 	}
12398 
12399 	for (i = 0; i < CALLER_SAVED_REGS; i++)
12400 		mark_reg_not_init(env, regs, caller_saved[i]);
12401 
12402 	/* Check return type */
12403 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12404 
12405 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12406 		/* Only exception is bpf_obj_new_impl */
12407 		if (meta.btf != btf_vmlinux ||
12408 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12409 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12410 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12411 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12412 			return -EINVAL;
12413 		}
12414 	}
12415 
12416 	if (btf_type_is_scalar(t)) {
12417 		mark_reg_unknown(env, regs, BPF_REG_0);
12418 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12419 	} else if (btf_type_is_ptr(t)) {
12420 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12421 
12422 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12423 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12424 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12425 				struct btf_struct_meta *struct_meta;
12426 				struct btf *ret_btf;
12427 				u32 ret_btf_id;
12428 
12429 				if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12430 					return -ENOMEM;
12431 
12432 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12433 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12434 					return -EINVAL;
12435 				}
12436 
12437 				ret_btf = env->prog->aux->btf;
12438 				ret_btf_id = meta.arg_constant.value;
12439 
12440 				/* This may be NULL due to user not supplying a BTF */
12441 				if (!ret_btf) {
12442 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12443 					return -EINVAL;
12444 				}
12445 
12446 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12447 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
12448 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12449 					return -EINVAL;
12450 				}
12451 
12452 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12453 					if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12454 						verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12455 							ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12456 						return -EINVAL;
12457 					}
12458 
12459 					if (!bpf_global_percpu_ma_set) {
12460 						mutex_lock(&bpf_percpu_ma_lock);
12461 						if (!bpf_global_percpu_ma_set) {
12462 							/* Charge memory allocated with bpf_global_percpu_ma to
12463 							 * root memcg. The obj_cgroup for root memcg is NULL.
12464 							 */
12465 							err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12466 							if (!err)
12467 								bpf_global_percpu_ma_set = true;
12468 						}
12469 						mutex_unlock(&bpf_percpu_ma_lock);
12470 						if (err)
12471 							return err;
12472 					}
12473 
12474 					mutex_lock(&bpf_percpu_ma_lock);
12475 					err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12476 					mutex_unlock(&bpf_percpu_ma_lock);
12477 					if (err)
12478 						return err;
12479 				}
12480 
12481 				struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12482 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12483 					if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12484 						verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12485 						return -EINVAL;
12486 					}
12487 
12488 					if (struct_meta) {
12489 						verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12490 						return -EINVAL;
12491 					}
12492 				}
12493 
12494 				mark_reg_known_zero(env, regs, BPF_REG_0);
12495 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12496 				regs[BPF_REG_0].btf = ret_btf;
12497 				regs[BPF_REG_0].btf_id = ret_btf_id;
12498 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12499 					regs[BPF_REG_0].type |= MEM_PERCPU;
12500 
12501 				insn_aux->obj_new_size = ret_t->size;
12502 				insn_aux->kptr_struct_meta = struct_meta;
12503 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12504 				mark_reg_known_zero(env, regs, BPF_REG_0);
12505 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12506 				regs[BPF_REG_0].btf = meta.arg_btf;
12507 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12508 
12509 				insn_aux->kptr_struct_meta =
12510 					btf_find_struct_meta(meta.arg_btf,
12511 							     meta.arg_btf_id);
12512 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12513 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12514 				struct btf_field *field = meta.arg_list_head.field;
12515 
12516 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12517 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12518 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12519 				struct btf_field *field = meta.arg_rbtree_root.field;
12520 
12521 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12522 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12523 				mark_reg_known_zero(env, regs, BPF_REG_0);
12524 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12525 				regs[BPF_REG_0].btf = desc_btf;
12526 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12527 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12528 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12529 				if (!ret_t || !btf_type_is_struct(ret_t)) {
12530 					verbose(env,
12531 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12532 					return -EINVAL;
12533 				}
12534 
12535 				mark_reg_known_zero(env, regs, BPF_REG_0);
12536 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12537 				regs[BPF_REG_0].btf = desc_btf;
12538 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12539 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12540 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12541 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12542 
12543 				mark_reg_known_zero(env, regs, BPF_REG_0);
12544 
12545 				if (!meta.arg_constant.found) {
12546 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12547 					return -EFAULT;
12548 				}
12549 
12550 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12551 
12552 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12553 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12554 
12555 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12556 					regs[BPF_REG_0].type |= MEM_RDONLY;
12557 				} else {
12558 					/* this will set env->seen_direct_write to true */
12559 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12560 						verbose(env, "the prog does not allow writes to packet data\n");
12561 						return -EINVAL;
12562 					}
12563 				}
12564 
12565 				if (!meta.initialized_dynptr.id) {
12566 					verbose(env, "verifier internal error: no dynptr id\n");
12567 					return -EFAULT;
12568 				}
12569 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12570 
12571 				/* we don't need to set BPF_REG_0's ref obj id
12572 				 * because packet slices are not refcounted (see
12573 				 * dynptr_type_refcounted)
12574 				 */
12575 			} else {
12576 				verbose(env, "kernel function %s unhandled dynamic return type\n",
12577 					meta.func_name);
12578 				return -EFAULT;
12579 			}
12580 		} else if (btf_type_is_void(ptr_type)) {
12581 			/* kfunc returning 'void *' is equivalent to returning scalar */
12582 			mark_reg_unknown(env, regs, BPF_REG_0);
12583 		} else if (!__btf_type_is_struct(ptr_type)) {
12584 			if (!meta.r0_size) {
12585 				__u32 sz;
12586 
12587 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12588 					meta.r0_size = sz;
12589 					meta.r0_rdonly = true;
12590 				}
12591 			}
12592 			if (!meta.r0_size) {
12593 				ptr_type_name = btf_name_by_offset(desc_btf,
12594 								   ptr_type->name_off);
12595 				verbose(env,
12596 					"kernel function %s returns pointer type %s %s is not supported\n",
12597 					func_name,
12598 					btf_type_str(ptr_type),
12599 					ptr_type_name);
12600 				return -EINVAL;
12601 			}
12602 
12603 			mark_reg_known_zero(env, regs, BPF_REG_0);
12604 			regs[BPF_REG_0].type = PTR_TO_MEM;
12605 			regs[BPF_REG_0].mem_size = meta.r0_size;
12606 
12607 			if (meta.r0_rdonly)
12608 				regs[BPF_REG_0].type |= MEM_RDONLY;
12609 
12610 			/* Ensures we don't access the memory after a release_reference() */
12611 			if (meta.ref_obj_id)
12612 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12613 		} else {
12614 			mark_reg_known_zero(env, regs, BPF_REG_0);
12615 			regs[BPF_REG_0].btf = desc_btf;
12616 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12617 			regs[BPF_REG_0].btf_id = ptr_type_id;
12618 		}
12619 
12620 		if (is_kfunc_ret_null(&meta)) {
12621 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12622 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12623 			regs[BPF_REG_0].id = ++env->id_gen;
12624 		}
12625 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12626 		if (is_kfunc_acquire(&meta)) {
12627 			int id = acquire_reference_state(env, insn_idx);
12628 
12629 			if (id < 0)
12630 				return id;
12631 			if (is_kfunc_ret_null(&meta))
12632 				regs[BPF_REG_0].id = id;
12633 			regs[BPF_REG_0].ref_obj_id = id;
12634 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12635 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12636 		}
12637 
12638 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12639 			regs[BPF_REG_0].id = ++env->id_gen;
12640 	} else if (btf_type_is_void(t)) {
12641 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12642 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12643 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12644 				insn_aux->kptr_struct_meta =
12645 					btf_find_struct_meta(meta.arg_btf,
12646 							     meta.arg_btf_id);
12647 			}
12648 		}
12649 	}
12650 
12651 	nargs = btf_type_vlen(meta.func_proto);
12652 	args = (const struct btf_param *)(meta.func_proto + 1);
12653 	for (i = 0; i < nargs; i++) {
12654 		u32 regno = i + 1;
12655 
12656 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12657 		if (btf_type_is_ptr(t))
12658 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12659 		else
12660 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12661 			mark_btf_func_reg_size(env, regno, t->size);
12662 	}
12663 
12664 	if (is_iter_next_kfunc(&meta)) {
12665 		err = process_iter_next_call(env, insn_idx, &meta);
12666 		if (err)
12667 			return err;
12668 	}
12669 
12670 	return 0;
12671 }
12672 
12673 static bool signed_add_overflows(s64 a, s64 b)
12674 {
12675 	/* Do the add in u64, where overflow is well-defined */
12676 	s64 res = (s64)((u64)a + (u64)b);
12677 
12678 	if (b < 0)
12679 		return res > a;
12680 	return res < a;
12681 }
12682 
12683 static bool signed_add32_overflows(s32 a, s32 b)
12684 {
12685 	/* Do the add in u32, where overflow is well-defined */
12686 	s32 res = (s32)((u32)a + (u32)b);
12687 
12688 	if (b < 0)
12689 		return res > a;
12690 	return res < a;
12691 }
12692 
12693 static bool signed_sub_overflows(s64 a, s64 b)
12694 {
12695 	/* Do the sub in u64, where overflow is well-defined */
12696 	s64 res = (s64)((u64)a - (u64)b);
12697 
12698 	if (b < 0)
12699 		return res < a;
12700 	return res > a;
12701 }
12702 
12703 static bool signed_sub32_overflows(s32 a, s32 b)
12704 {
12705 	/* Do the sub in u32, where overflow is well-defined */
12706 	s32 res = (s32)((u32)a - (u32)b);
12707 
12708 	if (b < 0)
12709 		return res < a;
12710 	return res > a;
12711 }
12712 
12713 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12714 				  const struct bpf_reg_state *reg,
12715 				  enum bpf_reg_type type)
12716 {
12717 	bool known = tnum_is_const(reg->var_off);
12718 	s64 val = reg->var_off.value;
12719 	s64 smin = reg->smin_value;
12720 
12721 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12722 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12723 			reg_type_str(env, type), val);
12724 		return false;
12725 	}
12726 
12727 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12728 		verbose(env, "%s pointer offset %d is not allowed\n",
12729 			reg_type_str(env, type), reg->off);
12730 		return false;
12731 	}
12732 
12733 	if (smin == S64_MIN) {
12734 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12735 			reg_type_str(env, type));
12736 		return false;
12737 	}
12738 
12739 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12740 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12741 			smin, reg_type_str(env, type));
12742 		return false;
12743 	}
12744 
12745 	return true;
12746 }
12747 
12748 enum {
12749 	REASON_BOUNDS	= -1,
12750 	REASON_TYPE	= -2,
12751 	REASON_PATHS	= -3,
12752 	REASON_LIMIT	= -4,
12753 	REASON_STACK	= -5,
12754 };
12755 
12756 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12757 			      u32 *alu_limit, bool mask_to_left)
12758 {
12759 	u32 max = 0, ptr_limit = 0;
12760 
12761 	switch (ptr_reg->type) {
12762 	case PTR_TO_STACK:
12763 		/* Offset 0 is out-of-bounds, but acceptable start for the
12764 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12765 		 * offset where we would need to deal with min/max bounds is
12766 		 * currently prohibited for unprivileged.
12767 		 */
12768 		max = MAX_BPF_STACK + mask_to_left;
12769 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12770 		break;
12771 	case PTR_TO_MAP_VALUE:
12772 		max = ptr_reg->map_ptr->value_size;
12773 		ptr_limit = (mask_to_left ?
12774 			     ptr_reg->smin_value :
12775 			     ptr_reg->umax_value) + ptr_reg->off;
12776 		break;
12777 	default:
12778 		return REASON_TYPE;
12779 	}
12780 
12781 	if (ptr_limit >= max)
12782 		return REASON_LIMIT;
12783 	*alu_limit = ptr_limit;
12784 	return 0;
12785 }
12786 
12787 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12788 				    const struct bpf_insn *insn)
12789 {
12790 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12791 }
12792 
12793 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12794 				       u32 alu_state, u32 alu_limit)
12795 {
12796 	/* If we arrived here from different branches with different
12797 	 * state or limits to sanitize, then this won't work.
12798 	 */
12799 	if (aux->alu_state &&
12800 	    (aux->alu_state != alu_state ||
12801 	     aux->alu_limit != alu_limit))
12802 		return REASON_PATHS;
12803 
12804 	/* Corresponding fixup done in do_misc_fixups(). */
12805 	aux->alu_state = alu_state;
12806 	aux->alu_limit = alu_limit;
12807 	return 0;
12808 }
12809 
12810 static int sanitize_val_alu(struct bpf_verifier_env *env,
12811 			    struct bpf_insn *insn)
12812 {
12813 	struct bpf_insn_aux_data *aux = cur_aux(env);
12814 
12815 	if (can_skip_alu_sanitation(env, insn))
12816 		return 0;
12817 
12818 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12819 }
12820 
12821 static bool sanitize_needed(u8 opcode)
12822 {
12823 	return opcode == BPF_ADD || opcode == BPF_SUB;
12824 }
12825 
12826 struct bpf_sanitize_info {
12827 	struct bpf_insn_aux_data aux;
12828 	bool mask_to_left;
12829 };
12830 
12831 static struct bpf_verifier_state *
12832 sanitize_speculative_path(struct bpf_verifier_env *env,
12833 			  const struct bpf_insn *insn,
12834 			  u32 next_idx, u32 curr_idx)
12835 {
12836 	struct bpf_verifier_state *branch;
12837 	struct bpf_reg_state *regs;
12838 
12839 	branch = push_stack(env, next_idx, curr_idx, true);
12840 	if (branch && insn) {
12841 		regs = branch->frame[branch->curframe]->regs;
12842 		if (BPF_SRC(insn->code) == BPF_K) {
12843 			mark_reg_unknown(env, regs, insn->dst_reg);
12844 		} else if (BPF_SRC(insn->code) == BPF_X) {
12845 			mark_reg_unknown(env, regs, insn->dst_reg);
12846 			mark_reg_unknown(env, regs, insn->src_reg);
12847 		}
12848 	}
12849 	return branch;
12850 }
12851 
12852 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12853 			    struct bpf_insn *insn,
12854 			    const struct bpf_reg_state *ptr_reg,
12855 			    const struct bpf_reg_state *off_reg,
12856 			    struct bpf_reg_state *dst_reg,
12857 			    struct bpf_sanitize_info *info,
12858 			    const bool commit_window)
12859 {
12860 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12861 	struct bpf_verifier_state *vstate = env->cur_state;
12862 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12863 	bool off_is_neg = off_reg->smin_value < 0;
12864 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12865 	u8 opcode = BPF_OP(insn->code);
12866 	u32 alu_state, alu_limit;
12867 	struct bpf_reg_state tmp;
12868 	bool ret;
12869 	int err;
12870 
12871 	if (can_skip_alu_sanitation(env, insn))
12872 		return 0;
12873 
12874 	/* We already marked aux for masking from non-speculative
12875 	 * paths, thus we got here in the first place. We only care
12876 	 * to explore bad access from here.
12877 	 */
12878 	if (vstate->speculative)
12879 		goto do_sim;
12880 
12881 	if (!commit_window) {
12882 		if (!tnum_is_const(off_reg->var_off) &&
12883 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12884 			return REASON_BOUNDS;
12885 
12886 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12887 				     (opcode == BPF_SUB && !off_is_neg);
12888 	}
12889 
12890 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12891 	if (err < 0)
12892 		return err;
12893 
12894 	if (commit_window) {
12895 		/* In commit phase we narrow the masking window based on
12896 		 * the observed pointer move after the simulated operation.
12897 		 */
12898 		alu_state = info->aux.alu_state;
12899 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12900 	} else {
12901 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12902 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12903 		alu_state |= ptr_is_dst_reg ?
12904 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12905 
12906 		/* Limit pruning on unknown scalars to enable deep search for
12907 		 * potential masking differences from other program paths.
12908 		 */
12909 		if (!off_is_imm)
12910 			env->explore_alu_limits = true;
12911 	}
12912 
12913 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12914 	if (err < 0)
12915 		return err;
12916 do_sim:
12917 	/* If we're in commit phase, we're done here given we already
12918 	 * pushed the truncated dst_reg into the speculative verification
12919 	 * stack.
12920 	 *
12921 	 * Also, when register is a known constant, we rewrite register-based
12922 	 * operation to immediate-based, and thus do not need masking (and as
12923 	 * a consequence, do not need to simulate the zero-truncation either).
12924 	 */
12925 	if (commit_window || off_is_imm)
12926 		return 0;
12927 
12928 	/* Simulate and find potential out-of-bounds access under
12929 	 * speculative execution from truncation as a result of
12930 	 * masking when off was not within expected range. If off
12931 	 * sits in dst, then we temporarily need to move ptr there
12932 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12933 	 * for cases where we use K-based arithmetic in one direction
12934 	 * and truncated reg-based in the other in order to explore
12935 	 * bad access.
12936 	 */
12937 	if (!ptr_is_dst_reg) {
12938 		tmp = *dst_reg;
12939 		copy_register_state(dst_reg, ptr_reg);
12940 	}
12941 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12942 					env->insn_idx);
12943 	if (!ptr_is_dst_reg && ret)
12944 		*dst_reg = tmp;
12945 	return !ret ? REASON_STACK : 0;
12946 }
12947 
12948 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12949 {
12950 	struct bpf_verifier_state *vstate = env->cur_state;
12951 
12952 	/* If we simulate paths under speculation, we don't update the
12953 	 * insn as 'seen' such that when we verify unreachable paths in
12954 	 * the non-speculative domain, sanitize_dead_code() can still
12955 	 * rewrite/sanitize them.
12956 	 */
12957 	if (!vstate->speculative)
12958 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12959 }
12960 
12961 static int sanitize_err(struct bpf_verifier_env *env,
12962 			const struct bpf_insn *insn, int reason,
12963 			const struct bpf_reg_state *off_reg,
12964 			const struct bpf_reg_state *dst_reg)
12965 {
12966 	static const char *err = "pointer arithmetic with it prohibited for !root";
12967 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12968 	u32 dst = insn->dst_reg, src = insn->src_reg;
12969 
12970 	switch (reason) {
12971 	case REASON_BOUNDS:
12972 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12973 			off_reg == dst_reg ? dst : src, err);
12974 		break;
12975 	case REASON_TYPE:
12976 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12977 			off_reg == dst_reg ? src : dst, err);
12978 		break;
12979 	case REASON_PATHS:
12980 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12981 			dst, op, err);
12982 		break;
12983 	case REASON_LIMIT:
12984 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12985 			dst, op, err);
12986 		break;
12987 	case REASON_STACK:
12988 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12989 			dst, err);
12990 		break;
12991 	default:
12992 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12993 			reason);
12994 		break;
12995 	}
12996 
12997 	return -EACCES;
12998 }
12999 
13000 /* check that stack access falls within stack limits and that 'reg' doesn't
13001  * have a variable offset.
13002  *
13003  * Variable offset is prohibited for unprivileged mode for simplicity since it
13004  * requires corresponding support in Spectre masking for stack ALU.  See also
13005  * retrieve_ptr_limit().
13006  *
13007  *
13008  * 'off' includes 'reg->off'.
13009  */
13010 static int check_stack_access_for_ptr_arithmetic(
13011 				struct bpf_verifier_env *env,
13012 				int regno,
13013 				const struct bpf_reg_state *reg,
13014 				int off)
13015 {
13016 	if (!tnum_is_const(reg->var_off)) {
13017 		char tn_buf[48];
13018 
13019 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
13020 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
13021 			regno, tn_buf, off);
13022 		return -EACCES;
13023 	}
13024 
13025 	if (off >= 0 || off < -MAX_BPF_STACK) {
13026 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
13027 			"prohibited for !root; off=%d\n", regno, off);
13028 		return -EACCES;
13029 	}
13030 
13031 	return 0;
13032 }
13033 
13034 static int sanitize_check_bounds(struct bpf_verifier_env *env,
13035 				 const struct bpf_insn *insn,
13036 				 const struct bpf_reg_state *dst_reg)
13037 {
13038 	u32 dst = insn->dst_reg;
13039 
13040 	/* For unprivileged we require that resulting offset must be in bounds
13041 	 * in order to be able to sanitize access later on.
13042 	 */
13043 	if (env->bypass_spec_v1)
13044 		return 0;
13045 
13046 	switch (dst_reg->type) {
13047 	case PTR_TO_STACK:
13048 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
13049 					dst_reg->off + dst_reg->var_off.value))
13050 			return -EACCES;
13051 		break;
13052 	case PTR_TO_MAP_VALUE:
13053 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
13054 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
13055 				"prohibited for !root\n", dst);
13056 			return -EACCES;
13057 		}
13058 		break;
13059 	default:
13060 		break;
13061 	}
13062 
13063 	return 0;
13064 }
13065 
13066 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
13067  * Caller should also handle BPF_MOV case separately.
13068  * If we return -EACCES, caller may want to try again treating pointer as a
13069  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
13070  */
13071 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
13072 				   struct bpf_insn *insn,
13073 				   const struct bpf_reg_state *ptr_reg,
13074 				   const struct bpf_reg_state *off_reg)
13075 {
13076 	struct bpf_verifier_state *vstate = env->cur_state;
13077 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13078 	struct bpf_reg_state *regs = state->regs, *dst_reg;
13079 	bool known = tnum_is_const(off_reg->var_off);
13080 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
13081 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
13082 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
13083 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
13084 	struct bpf_sanitize_info info = {};
13085 	u8 opcode = BPF_OP(insn->code);
13086 	u32 dst = insn->dst_reg;
13087 	int ret;
13088 
13089 	dst_reg = &regs[dst];
13090 
13091 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
13092 	    smin_val > smax_val || umin_val > umax_val) {
13093 		/* Taint dst register if offset had invalid bounds derived from
13094 		 * e.g. dead branches.
13095 		 */
13096 		__mark_reg_unknown(env, dst_reg);
13097 		return 0;
13098 	}
13099 
13100 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
13101 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
13102 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13103 			__mark_reg_unknown(env, dst_reg);
13104 			return 0;
13105 		}
13106 
13107 		verbose(env,
13108 			"R%d 32-bit pointer arithmetic prohibited\n",
13109 			dst);
13110 		return -EACCES;
13111 	}
13112 
13113 	if (ptr_reg->type & PTR_MAYBE_NULL) {
13114 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
13115 			dst, reg_type_str(env, ptr_reg->type));
13116 		return -EACCES;
13117 	}
13118 
13119 	switch (base_type(ptr_reg->type)) {
13120 	case PTR_TO_CTX:
13121 	case PTR_TO_MAP_VALUE:
13122 	case PTR_TO_MAP_KEY:
13123 	case PTR_TO_STACK:
13124 	case PTR_TO_PACKET_META:
13125 	case PTR_TO_PACKET:
13126 	case PTR_TO_TP_BUFFER:
13127 	case PTR_TO_BTF_ID:
13128 	case PTR_TO_MEM:
13129 	case PTR_TO_BUF:
13130 	case PTR_TO_FUNC:
13131 	case CONST_PTR_TO_DYNPTR:
13132 		break;
13133 	case PTR_TO_FLOW_KEYS:
13134 		if (known)
13135 			break;
13136 		fallthrough;
13137 	case CONST_PTR_TO_MAP:
13138 		/* smin_val represents the known value */
13139 		if (known && smin_val == 0 && opcode == BPF_ADD)
13140 			break;
13141 		fallthrough;
13142 	default:
13143 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
13144 			dst, reg_type_str(env, ptr_reg->type));
13145 		return -EACCES;
13146 	}
13147 
13148 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
13149 	 * The id may be overwritten later if we create a new variable offset.
13150 	 */
13151 	dst_reg->type = ptr_reg->type;
13152 	dst_reg->id = ptr_reg->id;
13153 
13154 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
13155 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
13156 		return -EINVAL;
13157 
13158 	/* pointer types do not carry 32-bit bounds at the moment. */
13159 	__mark_reg32_unbounded(dst_reg);
13160 
13161 	if (sanitize_needed(opcode)) {
13162 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
13163 				       &info, false);
13164 		if (ret < 0)
13165 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13166 	}
13167 
13168 	switch (opcode) {
13169 	case BPF_ADD:
13170 		/* We can take a fixed offset as long as it doesn't overflow
13171 		 * the s32 'off' field
13172 		 */
13173 		if (known && (ptr_reg->off + smin_val ==
13174 			      (s64)(s32)(ptr_reg->off + smin_val))) {
13175 			/* pointer += K.  Accumulate it into fixed offset */
13176 			dst_reg->smin_value = smin_ptr;
13177 			dst_reg->smax_value = smax_ptr;
13178 			dst_reg->umin_value = umin_ptr;
13179 			dst_reg->umax_value = umax_ptr;
13180 			dst_reg->var_off = ptr_reg->var_off;
13181 			dst_reg->off = ptr_reg->off + smin_val;
13182 			dst_reg->raw = ptr_reg->raw;
13183 			break;
13184 		}
13185 		/* A new variable offset is created.  Note that off_reg->off
13186 		 * == 0, since it's a scalar.
13187 		 * dst_reg gets the pointer type and since some positive
13188 		 * integer value was added to the pointer, give it a new 'id'
13189 		 * if it's a PTR_TO_PACKET.
13190 		 * this creates a new 'base' pointer, off_reg (variable) gets
13191 		 * added into the variable offset, and we copy the fixed offset
13192 		 * from ptr_reg.
13193 		 */
13194 		if (signed_add_overflows(smin_ptr, smin_val) ||
13195 		    signed_add_overflows(smax_ptr, smax_val)) {
13196 			dst_reg->smin_value = S64_MIN;
13197 			dst_reg->smax_value = S64_MAX;
13198 		} else {
13199 			dst_reg->smin_value = smin_ptr + smin_val;
13200 			dst_reg->smax_value = smax_ptr + smax_val;
13201 		}
13202 		if (umin_ptr + umin_val < umin_ptr ||
13203 		    umax_ptr + umax_val < umax_ptr) {
13204 			dst_reg->umin_value = 0;
13205 			dst_reg->umax_value = U64_MAX;
13206 		} else {
13207 			dst_reg->umin_value = umin_ptr + umin_val;
13208 			dst_reg->umax_value = umax_ptr + umax_val;
13209 		}
13210 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
13211 		dst_reg->off = ptr_reg->off;
13212 		dst_reg->raw = ptr_reg->raw;
13213 		if (reg_is_pkt_pointer(ptr_reg)) {
13214 			dst_reg->id = ++env->id_gen;
13215 			/* something was added to pkt_ptr, set range to zero */
13216 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13217 		}
13218 		break;
13219 	case BPF_SUB:
13220 		if (dst_reg == off_reg) {
13221 			/* scalar -= pointer.  Creates an unknown scalar */
13222 			verbose(env, "R%d tried to subtract pointer from scalar\n",
13223 				dst);
13224 			return -EACCES;
13225 		}
13226 		/* We don't allow subtraction from FP, because (according to
13227 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
13228 		 * be able to deal with it.
13229 		 */
13230 		if (ptr_reg->type == PTR_TO_STACK) {
13231 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
13232 				dst);
13233 			return -EACCES;
13234 		}
13235 		if (known && (ptr_reg->off - smin_val ==
13236 			      (s64)(s32)(ptr_reg->off - smin_val))) {
13237 			/* pointer -= K.  Subtract it from fixed offset */
13238 			dst_reg->smin_value = smin_ptr;
13239 			dst_reg->smax_value = smax_ptr;
13240 			dst_reg->umin_value = umin_ptr;
13241 			dst_reg->umax_value = umax_ptr;
13242 			dst_reg->var_off = ptr_reg->var_off;
13243 			dst_reg->id = ptr_reg->id;
13244 			dst_reg->off = ptr_reg->off - smin_val;
13245 			dst_reg->raw = ptr_reg->raw;
13246 			break;
13247 		}
13248 		/* A new variable offset is created.  If the subtrahend is known
13249 		 * nonnegative, then any reg->range we had before is still good.
13250 		 */
13251 		if (signed_sub_overflows(smin_ptr, smax_val) ||
13252 		    signed_sub_overflows(smax_ptr, smin_val)) {
13253 			/* Overflow possible, we know nothing */
13254 			dst_reg->smin_value = S64_MIN;
13255 			dst_reg->smax_value = S64_MAX;
13256 		} else {
13257 			dst_reg->smin_value = smin_ptr - smax_val;
13258 			dst_reg->smax_value = smax_ptr - smin_val;
13259 		}
13260 		if (umin_ptr < umax_val) {
13261 			/* Overflow possible, we know nothing */
13262 			dst_reg->umin_value = 0;
13263 			dst_reg->umax_value = U64_MAX;
13264 		} else {
13265 			/* Cannot overflow (as long as bounds are consistent) */
13266 			dst_reg->umin_value = umin_ptr - umax_val;
13267 			dst_reg->umax_value = umax_ptr - umin_val;
13268 		}
13269 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13270 		dst_reg->off = ptr_reg->off;
13271 		dst_reg->raw = ptr_reg->raw;
13272 		if (reg_is_pkt_pointer(ptr_reg)) {
13273 			dst_reg->id = ++env->id_gen;
13274 			/* something was added to pkt_ptr, set range to zero */
13275 			if (smin_val < 0)
13276 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13277 		}
13278 		break;
13279 	case BPF_AND:
13280 	case BPF_OR:
13281 	case BPF_XOR:
13282 		/* bitwise ops on pointers are troublesome, prohibit. */
13283 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13284 			dst, bpf_alu_string[opcode >> 4]);
13285 		return -EACCES;
13286 	default:
13287 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
13288 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13289 			dst, bpf_alu_string[opcode >> 4]);
13290 		return -EACCES;
13291 	}
13292 
13293 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
13294 		return -EINVAL;
13295 	reg_bounds_sync(dst_reg);
13296 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13297 		return -EACCES;
13298 	if (sanitize_needed(opcode)) {
13299 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13300 				       &info, true);
13301 		if (ret < 0)
13302 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13303 	}
13304 
13305 	return 0;
13306 }
13307 
13308 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13309 				 struct bpf_reg_state *src_reg)
13310 {
13311 	s32 smin_val = src_reg->s32_min_value;
13312 	s32 smax_val = src_reg->s32_max_value;
13313 	u32 umin_val = src_reg->u32_min_value;
13314 	u32 umax_val = src_reg->u32_max_value;
13315 
13316 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
13317 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
13318 		dst_reg->s32_min_value = S32_MIN;
13319 		dst_reg->s32_max_value = S32_MAX;
13320 	} else {
13321 		dst_reg->s32_min_value += smin_val;
13322 		dst_reg->s32_max_value += smax_val;
13323 	}
13324 	if (dst_reg->u32_min_value + umin_val < umin_val ||
13325 	    dst_reg->u32_max_value + umax_val < umax_val) {
13326 		dst_reg->u32_min_value = 0;
13327 		dst_reg->u32_max_value = U32_MAX;
13328 	} else {
13329 		dst_reg->u32_min_value += umin_val;
13330 		dst_reg->u32_max_value += umax_val;
13331 	}
13332 }
13333 
13334 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13335 			       struct bpf_reg_state *src_reg)
13336 {
13337 	s64 smin_val = src_reg->smin_value;
13338 	s64 smax_val = src_reg->smax_value;
13339 	u64 umin_val = src_reg->umin_value;
13340 	u64 umax_val = src_reg->umax_value;
13341 
13342 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
13343 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
13344 		dst_reg->smin_value = S64_MIN;
13345 		dst_reg->smax_value = S64_MAX;
13346 	} else {
13347 		dst_reg->smin_value += smin_val;
13348 		dst_reg->smax_value += smax_val;
13349 	}
13350 	if (dst_reg->umin_value + umin_val < umin_val ||
13351 	    dst_reg->umax_value + umax_val < umax_val) {
13352 		dst_reg->umin_value = 0;
13353 		dst_reg->umax_value = U64_MAX;
13354 	} else {
13355 		dst_reg->umin_value += umin_val;
13356 		dst_reg->umax_value += umax_val;
13357 	}
13358 }
13359 
13360 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13361 				 struct bpf_reg_state *src_reg)
13362 {
13363 	s32 smin_val = src_reg->s32_min_value;
13364 	s32 smax_val = src_reg->s32_max_value;
13365 	u32 umin_val = src_reg->u32_min_value;
13366 	u32 umax_val = src_reg->u32_max_value;
13367 
13368 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
13369 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
13370 		/* Overflow possible, we know nothing */
13371 		dst_reg->s32_min_value = S32_MIN;
13372 		dst_reg->s32_max_value = S32_MAX;
13373 	} else {
13374 		dst_reg->s32_min_value -= smax_val;
13375 		dst_reg->s32_max_value -= smin_val;
13376 	}
13377 	if (dst_reg->u32_min_value < umax_val) {
13378 		/* Overflow possible, we know nothing */
13379 		dst_reg->u32_min_value = 0;
13380 		dst_reg->u32_max_value = U32_MAX;
13381 	} else {
13382 		/* Cannot overflow (as long as bounds are consistent) */
13383 		dst_reg->u32_min_value -= umax_val;
13384 		dst_reg->u32_max_value -= umin_val;
13385 	}
13386 }
13387 
13388 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13389 			       struct bpf_reg_state *src_reg)
13390 {
13391 	s64 smin_val = src_reg->smin_value;
13392 	s64 smax_val = src_reg->smax_value;
13393 	u64 umin_val = src_reg->umin_value;
13394 	u64 umax_val = src_reg->umax_value;
13395 
13396 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
13397 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
13398 		/* Overflow possible, we know nothing */
13399 		dst_reg->smin_value = S64_MIN;
13400 		dst_reg->smax_value = S64_MAX;
13401 	} else {
13402 		dst_reg->smin_value -= smax_val;
13403 		dst_reg->smax_value -= smin_val;
13404 	}
13405 	if (dst_reg->umin_value < umax_val) {
13406 		/* Overflow possible, we know nothing */
13407 		dst_reg->umin_value = 0;
13408 		dst_reg->umax_value = U64_MAX;
13409 	} else {
13410 		/* Cannot overflow (as long as bounds are consistent) */
13411 		dst_reg->umin_value -= umax_val;
13412 		dst_reg->umax_value -= umin_val;
13413 	}
13414 }
13415 
13416 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13417 				 struct bpf_reg_state *src_reg)
13418 {
13419 	s32 smin_val = src_reg->s32_min_value;
13420 	u32 umin_val = src_reg->u32_min_value;
13421 	u32 umax_val = src_reg->u32_max_value;
13422 
13423 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13424 		/* Ain't nobody got time to multiply that sign */
13425 		__mark_reg32_unbounded(dst_reg);
13426 		return;
13427 	}
13428 	/* Both values are positive, so we can work with unsigned and
13429 	 * copy the result to signed (unless it exceeds S32_MAX).
13430 	 */
13431 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13432 		/* Potential overflow, we know nothing */
13433 		__mark_reg32_unbounded(dst_reg);
13434 		return;
13435 	}
13436 	dst_reg->u32_min_value *= umin_val;
13437 	dst_reg->u32_max_value *= umax_val;
13438 	if (dst_reg->u32_max_value > S32_MAX) {
13439 		/* Overflow possible, we know nothing */
13440 		dst_reg->s32_min_value = S32_MIN;
13441 		dst_reg->s32_max_value = S32_MAX;
13442 	} else {
13443 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13444 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13445 	}
13446 }
13447 
13448 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13449 			       struct bpf_reg_state *src_reg)
13450 {
13451 	s64 smin_val = src_reg->smin_value;
13452 	u64 umin_val = src_reg->umin_value;
13453 	u64 umax_val = src_reg->umax_value;
13454 
13455 	if (smin_val < 0 || dst_reg->smin_value < 0) {
13456 		/* Ain't nobody got time to multiply that sign */
13457 		__mark_reg64_unbounded(dst_reg);
13458 		return;
13459 	}
13460 	/* Both values are positive, so we can work with unsigned and
13461 	 * copy the result to signed (unless it exceeds S64_MAX).
13462 	 */
13463 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13464 		/* Potential overflow, we know nothing */
13465 		__mark_reg64_unbounded(dst_reg);
13466 		return;
13467 	}
13468 	dst_reg->umin_value *= umin_val;
13469 	dst_reg->umax_value *= umax_val;
13470 	if (dst_reg->umax_value > S64_MAX) {
13471 		/* Overflow possible, we know nothing */
13472 		dst_reg->smin_value = S64_MIN;
13473 		dst_reg->smax_value = S64_MAX;
13474 	} else {
13475 		dst_reg->smin_value = dst_reg->umin_value;
13476 		dst_reg->smax_value = dst_reg->umax_value;
13477 	}
13478 }
13479 
13480 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13481 				 struct bpf_reg_state *src_reg)
13482 {
13483 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13484 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13485 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13486 	u32 umax_val = src_reg->u32_max_value;
13487 
13488 	if (src_known && dst_known) {
13489 		__mark_reg32_known(dst_reg, var32_off.value);
13490 		return;
13491 	}
13492 
13493 	/* We get our minimum from the var_off, since that's inherently
13494 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13495 	 */
13496 	dst_reg->u32_min_value = var32_off.value;
13497 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13498 
13499 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
13500 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13501 	 */
13502 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13503 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13504 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13505 	} else {
13506 		dst_reg->s32_min_value = S32_MIN;
13507 		dst_reg->s32_max_value = S32_MAX;
13508 	}
13509 }
13510 
13511 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13512 			       struct bpf_reg_state *src_reg)
13513 {
13514 	bool src_known = tnum_is_const(src_reg->var_off);
13515 	bool dst_known = tnum_is_const(dst_reg->var_off);
13516 	u64 umax_val = src_reg->umax_value;
13517 
13518 	if (src_known && dst_known) {
13519 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13520 		return;
13521 	}
13522 
13523 	/* We get our minimum from the var_off, since that's inherently
13524 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13525 	 */
13526 	dst_reg->umin_value = dst_reg->var_off.value;
13527 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13528 
13529 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
13530 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13531 	 */
13532 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13533 		dst_reg->smin_value = dst_reg->umin_value;
13534 		dst_reg->smax_value = dst_reg->umax_value;
13535 	} else {
13536 		dst_reg->smin_value = S64_MIN;
13537 		dst_reg->smax_value = S64_MAX;
13538 	}
13539 	/* We may learn something more from the var_off */
13540 	__update_reg_bounds(dst_reg);
13541 }
13542 
13543 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13544 				struct bpf_reg_state *src_reg)
13545 {
13546 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13547 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13548 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13549 	u32 umin_val = src_reg->u32_min_value;
13550 
13551 	if (src_known && dst_known) {
13552 		__mark_reg32_known(dst_reg, var32_off.value);
13553 		return;
13554 	}
13555 
13556 	/* We get our maximum from the var_off, and our minimum is the
13557 	 * maximum of the operands' minima
13558 	 */
13559 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13560 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13561 
13562 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
13563 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13564 	 */
13565 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13566 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13567 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13568 	} else {
13569 		dst_reg->s32_min_value = S32_MIN;
13570 		dst_reg->s32_max_value = S32_MAX;
13571 	}
13572 }
13573 
13574 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13575 			      struct bpf_reg_state *src_reg)
13576 {
13577 	bool src_known = tnum_is_const(src_reg->var_off);
13578 	bool dst_known = tnum_is_const(dst_reg->var_off);
13579 	u64 umin_val = src_reg->umin_value;
13580 
13581 	if (src_known && dst_known) {
13582 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13583 		return;
13584 	}
13585 
13586 	/* We get our maximum from the var_off, and our minimum is the
13587 	 * maximum of the operands' minima
13588 	 */
13589 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13590 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13591 
13592 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
13593 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13594 	 */
13595 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13596 		dst_reg->smin_value = dst_reg->umin_value;
13597 		dst_reg->smax_value = dst_reg->umax_value;
13598 	} else {
13599 		dst_reg->smin_value = S64_MIN;
13600 		dst_reg->smax_value = S64_MAX;
13601 	}
13602 	/* We may learn something more from the var_off */
13603 	__update_reg_bounds(dst_reg);
13604 }
13605 
13606 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13607 				 struct bpf_reg_state *src_reg)
13608 {
13609 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13610 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13611 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13612 
13613 	if (src_known && dst_known) {
13614 		__mark_reg32_known(dst_reg, var32_off.value);
13615 		return;
13616 	}
13617 
13618 	/* We get both minimum and maximum from the var32_off. */
13619 	dst_reg->u32_min_value = var32_off.value;
13620 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13621 
13622 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
13623 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13624 	 */
13625 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13626 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13627 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13628 	} else {
13629 		dst_reg->s32_min_value = S32_MIN;
13630 		dst_reg->s32_max_value = S32_MAX;
13631 	}
13632 }
13633 
13634 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13635 			       struct bpf_reg_state *src_reg)
13636 {
13637 	bool src_known = tnum_is_const(src_reg->var_off);
13638 	bool dst_known = tnum_is_const(dst_reg->var_off);
13639 
13640 	if (src_known && dst_known) {
13641 		/* dst_reg->var_off.value has been updated earlier */
13642 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13643 		return;
13644 	}
13645 
13646 	/* We get both minimum and maximum from the var_off. */
13647 	dst_reg->umin_value = dst_reg->var_off.value;
13648 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13649 
13650 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
13651 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13652 	 */
13653 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13654 		dst_reg->smin_value = dst_reg->umin_value;
13655 		dst_reg->smax_value = dst_reg->umax_value;
13656 	} else {
13657 		dst_reg->smin_value = S64_MIN;
13658 		dst_reg->smax_value = S64_MAX;
13659 	}
13660 
13661 	__update_reg_bounds(dst_reg);
13662 }
13663 
13664 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13665 				   u64 umin_val, u64 umax_val)
13666 {
13667 	/* We lose all sign bit information (except what we can pick
13668 	 * up from var_off)
13669 	 */
13670 	dst_reg->s32_min_value = S32_MIN;
13671 	dst_reg->s32_max_value = S32_MAX;
13672 	/* If we might shift our top bit out, then we know nothing */
13673 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13674 		dst_reg->u32_min_value = 0;
13675 		dst_reg->u32_max_value = U32_MAX;
13676 	} else {
13677 		dst_reg->u32_min_value <<= umin_val;
13678 		dst_reg->u32_max_value <<= umax_val;
13679 	}
13680 }
13681 
13682 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13683 				 struct bpf_reg_state *src_reg)
13684 {
13685 	u32 umax_val = src_reg->u32_max_value;
13686 	u32 umin_val = src_reg->u32_min_value;
13687 	/* u32 alu operation will zext upper bits */
13688 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13689 
13690 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13691 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13692 	/* Not required but being careful mark reg64 bounds as unknown so
13693 	 * that we are forced to pick them up from tnum and zext later and
13694 	 * if some path skips this step we are still safe.
13695 	 */
13696 	__mark_reg64_unbounded(dst_reg);
13697 	__update_reg32_bounds(dst_reg);
13698 }
13699 
13700 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13701 				   u64 umin_val, u64 umax_val)
13702 {
13703 	/* Special case <<32 because it is a common compiler pattern to sign
13704 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13705 	 * positive we know this shift will also be positive so we can track
13706 	 * bounds correctly. Otherwise we lose all sign bit information except
13707 	 * what we can pick up from var_off. Perhaps we can generalize this
13708 	 * later to shifts of any length.
13709 	 */
13710 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13711 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13712 	else
13713 		dst_reg->smax_value = S64_MAX;
13714 
13715 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13716 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13717 	else
13718 		dst_reg->smin_value = S64_MIN;
13719 
13720 	/* If we might shift our top bit out, then we know nothing */
13721 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13722 		dst_reg->umin_value = 0;
13723 		dst_reg->umax_value = U64_MAX;
13724 	} else {
13725 		dst_reg->umin_value <<= umin_val;
13726 		dst_reg->umax_value <<= umax_val;
13727 	}
13728 }
13729 
13730 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13731 			       struct bpf_reg_state *src_reg)
13732 {
13733 	u64 umax_val = src_reg->umax_value;
13734 	u64 umin_val = src_reg->umin_value;
13735 
13736 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13737 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13738 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13739 
13740 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13741 	/* We may learn something more from the var_off */
13742 	__update_reg_bounds(dst_reg);
13743 }
13744 
13745 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13746 				 struct bpf_reg_state *src_reg)
13747 {
13748 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13749 	u32 umax_val = src_reg->u32_max_value;
13750 	u32 umin_val = src_reg->u32_min_value;
13751 
13752 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13753 	 * be negative, then either:
13754 	 * 1) src_reg might be zero, so the sign bit of the result is
13755 	 *    unknown, so we lose our signed bounds
13756 	 * 2) it's known negative, thus the unsigned bounds capture the
13757 	 *    signed bounds
13758 	 * 3) the signed bounds cross zero, so they tell us nothing
13759 	 *    about the result
13760 	 * If the value in dst_reg is known nonnegative, then again the
13761 	 * unsigned bounds capture the signed bounds.
13762 	 * Thus, in all cases it suffices to blow away our signed bounds
13763 	 * and rely on inferring new ones from the unsigned bounds and
13764 	 * var_off of the result.
13765 	 */
13766 	dst_reg->s32_min_value = S32_MIN;
13767 	dst_reg->s32_max_value = S32_MAX;
13768 
13769 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13770 	dst_reg->u32_min_value >>= umax_val;
13771 	dst_reg->u32_max_value >>= umin_val;
13772 
13773 	__mark_reg64_unbounded(dst_reg);
13774 	__update_reg32_bounds(dst_reg);
13775 }
13776 
13777 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13778 			       struct bpf_reg_state *src_reg)
13779 {
13780 	u64 umax_val = src_reg->umax_value;
13781 	u64 umin_val = src_reg->umin_value;
13782 
13783 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13784 	 * be negative, then either:
13785 	 * 1) src_reg might be zero, so the sign bit of the result is
13786 	 *    unknown, so we lose our signed bounds
13787 	 * 2) it's known negative, thus the unsigned bounds capture the
13788 	 *    signed bounds
13789 	 * 3) the signed bounds cross zero, so they tell us nothing
13790 	 *    about the result
13791 	 * If the value in dst_reg is known nonnegative, then again the
13792 	 * unsigned bounds capture the signed bounds.
13793 	 * Thus, in all cases it suffices to blow away our signed bounds
13794 	 * and rely on inferring new ones from the unsigned bounds and
13795 	 * var_off of the result.
13796 	 */
13797 	dst_reg->smin_value = S64_MIN;
13798 	dst_reg->smax_value = S64_MAX;
13799 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13800 	dst_reg->umin_value >>= umax_val;
13801 	dst_reg->umax_value >>= umin_val;
13802 
13803 	/* Its not easy to operate on alu32 bounds here because it depends
13804 	 * on bits being shifted in. Take easy way out and mark unbounded
13805 	 * so we can recalculate later from tnum.
13806 	 */
13807 	__mark_reg32_unbounded(dst_reg);
13808 	__update_reg_bounds(dst_reg);
13809 }
13810 
13811 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13812 				  struct bpf_reg_state *src_reg)
13813 {
13814 	u64 umin_val = src_reg->u32_min_value;
13815 
13816 	/* Upon reaching here, src_known is true and
13817 	 * umax_val is equal to umin_val.
13818 	 */
13819 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13820 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13821 
13822 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13823 
13824 	/* blow away the dst_reg umin_value/umax_value and rely on
13825 	 * dst_reg var_off to refine the result.
13826 	 */
13827 	dst_reg->u32_min_value = 0;
13828 	dst_reg->u32_max_value = U32_MAX;
13829 
13830 	__mark_reg64_unbounded(dst_reg);
13831 	__update_reg32_bounds(dst_reg);
13832 }
13833 
13834 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13835 				struct bpf_reg_state *src_reg)
13836 {
13837 	u64 umin_val = src_reg->umin_value;
13838 
13839 	/* Upon reaching here, src_known is true and umax_val is equal
13840 	 * to umin_val.
13841 	 */
13842 	dst_reg->smin_value >>= umin_val;
13843 	dst_reg->smax_value >>= umin_val;
13844 
13845 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13846 
13847 	/* blow away the dst_reg umin_value/umax_value and rely on
13848 	 * dst_reg var_off to refine the result.
13849 	 */
13850 	dst_reg->umin_value = 0;
13851 	dst_reg->umax_value = U64_MAX;
13852 
13853 	/* Its not easy to operate on alu32 bounds here because it depends
13854 	 * on bits being shifted in from upper 32-bits. Take easy way out
13855 	 * and mark unbounded so we can recalculate later from tnum.
13856 	 */
13857 	__mark_reg32_unbounded(dst_reg);
13858 	__update_reg_bounds(dst_reg);
13859 }
13860 
13861 /* WARNING: This function does calculations on 64-bit values, but the actual
13862  * execution may occur on 32-bit values. Therefore, things like bitshifts
13863  * need extra checks in the 32-bit case.
13864  */
13865 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13866 				      struct bpf_insn *insn,
13867 				      struct bpf_reg_state *dst_reg,
13868 				      struct bpf_reg_state src_reg)
13869 {
13870 	struct bpf_reg_state *regs = cur_regs(env);
13871 	u8 opcode = BPF_OP(insn->code);
13872 	bool src_known;
13873 	s64 smin_val, smax_val;
13874 	u64 umin_val, umax_val;
13875 	s32 s32_min_val, s32_max_val;
13876 	u32 u32_min_val, u32_max_val;
13877 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13878 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13879 	int ret;
13880 
13881 	smin_val = src_reg.smin_value;
13882 	smax_val = src_reg.smax_value;
13883 	umin_val = src_reg.umin_value;
13884 	umax_val = src_reg.umax_value;
13885 
13886 	s32_min_val = src_reg.s32_min_value;
13887 	s32_max_val = src_reg.s32_max_value;
13888 	u32_min_val = src_reg.u32_min_value;
13889 	u32_max_val = src_reg.u32_max_value;
13890 
13891 	if (alu32) {
13892 		src_known = tnum_subreg_is_const(src_reg.var_off);
13893 		if ((src_known &&
13894 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13895 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13896 			/* Taint dst register if offset had invalid bounds
13897 			 * derived from e.g. dead branches.
13898 			 */
13899 			__mark_reg_unknown(env, dst_reg);
13900 			return 0;
13901 		}
13902 	} else {
13903 		src_known = tnum_is_const(src_reg.var_off);
13904 		if ((src_known &&
13905 		     (smin_val != smax_val || umin_val != umax_val)) ||
13906 		    smin_val > smax_val || umin_val > umax_val) {
13907 			/* Taint dst register if offset had invalid bounds
13908 			 * derived from e.g. dead branches.
13909 			 */
13910 			__mark_reg_unknown(env, dst_reg);
13911 			return 0;
13912 		}
13913 	}
13914 
13915 	if (!src_known &&
13916 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13917 		__mark_reg_unknown(env, dst_reg);
13918 		return 0;
13919 	}
13920 
13921 	if (sanitize_needed(opcode)) {
13922 		ret = sanitize_val_alu(env, insn);
13923 		if (ret < 0)
13924 			return sanitize_err(env, insn, ret, NULL, NULL);
13925 	}
13926 
13927 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13928 	 * There are two classes of instructions: The first class we track both
13929 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13930 	 * greatest amount of precision when alu operations are mixed with jmp32
13931 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13932 	 * and BPF_OR. This is possible because these ops have fairly easy to
13933 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13934 	 * See alu32 verifier tests for examples. The second class of
13935 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13936 	 * with regards to tracking sign/unsigned bounds because the bits may
13937 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13938 	 * the reg unbounded in the subreg bound space and use the resulting
13939 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13940 	 */
13941 	switch (opcode) {
13942 	case BPF_ADD:
13943 		scalar32_min_max_add(dst_reg, &src_reg);
13944 		scalar_min_max_add(dst_reg, &src_reg);
13945 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13946 		break;
13947 	case BPF_SUB:
13948 		scalar32_min_max_sub(dst_reg, &src_reg);
13949 		scalar_min_max_sub(dst_reg, &src_reg);
13950 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13951 		break;
13952 	case BPF_MUL:
13953 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13954 		scalar32_min_max_mul(dst_reg, &src_reg);
13955 		scalar_min_max_mul(dst_reg, &src_reg);
13956 		break;
13957 	case BPF_AND:
13958 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13959 		scalar32_min_max_and(dst_reg, &src_reg);
13960 		scalar_min_max_and(dst_reg, &src_reg);
13961 		break;
13962 	case BPF_OR:
13963 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13964 		scalar32_min_max_or(dst_reg, &src_reg);
13965 		scalar_min_max_or(dst_reg, &src_reg);
13966 		break;
13967 	case BPF_XOR:
13968 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13969 		scalar32_min_max_xor(dst_reg, &src_reg);
13970 		scalar_min_max_xor(dst_reg, &src_reg);
13971 		break;
13972 	case BPF_LSH:
13973 		if (umax_val >= insn_bitness) {
13974 			/* Shifts greater than 31 or 63 are undefined.
13975 			 * This includes shifts by a negative number.
13976 			 */
13977 			mark_reg_unknown(env, regs, insn->dst_reg);
13978 			break;
13979 		}
13980 		if (alu32)
13981 			scalar32_min_max_lsh(dst_reg, &src_reg);
13982 		else
13983 			scalar_min_max_lsh(dst_reg, &src_reg);
13984 		break;
13985 	case BPF_RSH:
13986 		if (umax_val >= insn_bitness) {
13987 			/* Shifts greater than 31 or 63 are undefined.
13988 			 * This includes shifts by a negative number.
13989 			 */
13990 			mark_reg_unknown(env, regs, insn->dst_reg);
13991 			break;
13992 		}
13993 		if (alu32)
13994 			scalar32_min_max_rsh(dst_reg, &src_reg);
13995 		else
13996 			scalar_min_max_rsh(dst_reg, &src_reg);
13997 		break;
13998 	case BPF_ARSH:
13999 		if (umax_val >= insn_bitness) {
14000 			/* Shifts greater than 31 or 63 are undefined.
14001 			 * This includes shifts by a negative number.
14002 			 */
14003 			mark_reg_unknown(env, regs, insn->dst_reg);
14004 			break;
14005 		}
14006 		if (alu32)
14007 			scalar32_min_max_arsh(dst_reg, &src_reg);
14008 		else
14009 			scalar_min_max_arsh(dst_reg, &src_reg);
14010 		break;
14011 	default:
14012 		mark_reg_unknown(env, regs, insn->dst_reg);
14013 		break;
14014 	}
14015 
14016 	/* ALU32 ops are zero extended into 64bit register */
14017 	if (alu32)
14018 		zext_32_to_64(dst_reg);
14019 	reg_bounds_sync(dst_reg);
14020 	return 0;
14021 }
14022 
14023 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
14024  * and var_off.
14025  */
14026 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
14027 				   struct bpf_insn *insn)
14028 {
14029 	struct bpf_verifier_state *vstate = env->cur_state;
14030 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14031 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
14032 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
14033 	u8 opcode = BPF_OP(insn->code);
14034 	int err;
14035 
14036 	dst_reg = &regs[insn->dst_reg];
14037 	src_reg = NULL;
14038 
14039 	if (dst_reg->type == PTR_TO_ARENA) {
14040 		struct bpf_insn_aux_data *aux = cur_aux(env);
14041 
14042 		if (BPF_CLASS(insn->code) == BPF_ALU64)
14043 			/*
14044 			 * 32-bit operations zero upper bits automatically.
14045 			 * 64-bit operations need to be converted to 32.
14046 			 */
14047 			aux->needs_zext = true;
14048 
14049 		/* Any arithmetic operations are allowed on arena pointers */
14050 		return 0;
14051 	}
14052 
14053 	if (dst_reg->type != SCALAR_VALUE)
14054 		ptr_reg = dst_reg;
14055 	else
14056 		/* Make sure ID is cleared otherwise dst_reg min/max could be
14057 		 * incorrectly propagated into other registers by find_equal_scalars()
14058 		 */
14059 		dst_reg->id = 0;
14060 	if (BPF_SRC(insn->code) == BPF_X) {
14061 		src_reg = &regs[insn->src_reg];
14062 		if (src_reg->type != SCALAR_VALUE) {
14063 			if (dst_reg->type != SCALAR_VALUE) {
14064 				/* Combining two pointers by any ALU op yields
14065 				 * an arbitrary scalar. Disallow all math except
14066 				 * pointer subtraction
14067 				 */
14068 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14069 					mark_reg_unknown(env, regs, insn->dst_reg);
14070 					return 0;
14071 				}
14072 				verbose(env, "R%d pointer %s pointer prohibited\n",
14073 					insn->dst_reg,
14074 					bpf_alu_string[opcode >> 4]);
14075 				return -EACCES;
14076 			} else {
14077 				/* scalar += pointer
14078 				 * This is legal, but we have to reverse our
14079 				 * src/dest handling in computing the range
14080 				 */
14081 				err = mark_chain_precision(env, insn->dst_reg);
14082 				if (err)
14083 					return err;
14084 				return adjust_ptr_min_max_vals(env, insn,
14085 							       src_reg, dst_reg);
14086 			}
14087 		} else if (ptr_reg) {
14088 			/* pointer += scalar */
14089 			err = mark_chain_precision(env, insn->src_reg);
14090 			if (err)
14091 				return err;
14092 			return adjust_ptr_min_max_vals(env, insn,
14093 						       dst_reg, src_reg);
14094 		} else if (dst_reg->precise) {
14095 			/* if dst_reg is precise, src_reg should be precise as well */
14096 			err = mark_chain_precision(env, insn->src_reg);
14097 			if (err)
14098 				return err;
14099 		}
14100 	} else {
14101 		/* Pretend the src is a reg with a known value, since we only
14102 		 * need to be able to read from this state.
14103 		 */
14104 		off_reg.type = SCALAR_VALUE;
14105 		__mark_reg_known(&off_reg, insn->imm);
14106 		src_reg = &off_reg;
14107 		if (ptr_reg) /* pointer += K */
14108 			return adjust_ptr_min_max_vals(env, insn,
14109 						       ptr_reg, src_reg);
14110 	}
14111 
14112 	/* Got here implies adding two SCALAR_VALUEs */
14113 	if (WARN_ON_ONCE(ptr_reg)) {
14114 		print_verifier_state(env, state, true);
14115 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
14116 		return -EINVAL;
14117 	}
14118 	if (WARN_ON(!src_reg)) {
14119 		print_verifier_state(env, state, true);
14120 		verbose(env, "verifier internal error: no src_reg\n");
14121 		return -EINVAL;
14122 	}
14123 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
14124 }
14125 
14126 /* check validity of 32-bit and 64-bit arithmetic operations */
14127 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
14128 {
14129 	struct bpf_reg_state *regs = cur_regs(env);
14130 	u8 opcode = BPF_OP(insn->code);
14131 	int err;
14132 
14133 	if (opcode == BPF_END || opcode == BPF_NEG) {
14134 		if (opcode == BPF_NEG) {
14135 			if (BPF_SRC(insn->code) != BPF_K ||
14136 			    insn->src_reg != BPF_REG_0 ||
14137 			    insn->off != 0 || insn->imm != 0) {
14138 				verbose(env, "BPF_NEG uses reserved fields\n");
14139 				return -EINVAL;
14140 			}
14141 		} else {
14142 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
14143 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
14144 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
14145 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
14146 				verbose(env, "BPF_END uses reserved fields\n");
14147 				return -EINVAL;
14148 			}
14149 		}
14150 
14151 		/* check src operand */
14152 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14153 		if (err)
14154 			return err;
14155 
14156 		if (is_pointer_value(env, insn->dst_reg)) {
14157 			verbose(env, "R%d pointer arithmetic prohibited\n",
14158 				insn->dst_reg);
14159 			return -EACCES;
14160 		}
14161 
14162 		/* check dest operand */
14163 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
14164 		if (err)
14165 			return err;
14166 
14167 	} else if (opcode == BPF_MOV) {
14168 
14169 		if (BPF_SRC(insn->code) == BPF_X) {
14170 			if (BPF_CLASS(insn->code) == BPF_ALU) {
14171 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
14172 				    insn->imm) {
14173 					verbose(env, "BPF_MOV uses reserved fields\n");
14174 					return -EINVAL;
14175 				}
14176 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
14177 				if (insn->imm != 1 && insn->imm != 1u << 16) {
14178 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
14179 					return -EINVAL;
14180 				}
14181 				if (!env->prog->aux->arena) {
14182 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
14183 					return -EINVAL;
14184 				}
14185 			} else {
14186 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
14187 				     insn->off != 32) || insn->imm) {
14188 					verbose(env, "BPF_MOV uses reserved fields\n");
14189 					return -EINVAL;
14190 				}
14191 			}
14192 
14193 			/* check src operand */
14194 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14195 			if (err)
14196 				return err;
14197 		} else {
14198 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
14199 				verbose(env, "BPF_MOV uses reserved fields\n");
14200 				return -EINVAL;
14201 			}
14202 		}
14203 
14204 		/* check dest operand, mark as required later */
14205 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14206 		if (err)
14207 			return err;
14208 
14209 		if (BPF_SRC(insn->code) == BPF_X) {
14210 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
14211 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
14212 
14213 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14214 				if (insn->imm) {
14215 					/* off == BPF_ADDR_SPACE_CAST */
14216 					mark_reg_unknown(env, regs, insn->dst_reg);
14217 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
14218 						dst_reg->type = PTR_TO_ARENA;
14219 						/* PTR_TO_ARENA is 32-bit */
14220 						dst_reg->subreg_def = env->insn_idx + 1;
14221 					}
14222 				} else if (insn->off == 0) {
14223 					/* case: R1 = R2
14224 					 * copy register state to dest reg
14225 					 */
14226 					assign_scalar_id_before_mov(env, src_reg);
14227 					copy_register_state(dst_reg, src_reg);
14228 					dst_reg->live |= REG_LIVE_WRITTEN;
14229 					dst_reg->subreg_def = DEF_NOT_SUBREG;
14230 				} else {
14231 					/* case: R1 = (s8, s16 s32)R2 */
14232 					if (is_pointer_value(env, insn->src_reg)) {
14233 						verbose(env,
14234 							"R%d sign-extension part of pointer\n",
14235 							insn->src_reg);
14236 						return -EACCES;
14237 					} else if (src_reg->type == SCALAR_VALUE) {
14238 						bool no_sext;
14239 
14240 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14241 						if (no_sext)
14242 							assign_scalar_id_before_mov(env, src_reg);
14243 						copy_register_state(dst_reg, src_reg);
14244 						if (!no_sext)
14245 							dst_reg->id = 0;
14246 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
14247 						dst_reg->live |= REG_LIVE_WRITTEN;
14248 						dst_reg->subreg_def = DEF_NOT_SUBREG;
14249 					} else {
14250 						mark_reg_unknown(env, regs, insn->dst_reg);
14251 					}
14252 				}
14253 			} else {
14254 				/* R1 = (u32) R2 */
14255 				if (is_pointer_value(env, insn->src_reg)) {
14256 					verbose(env,
14257 						"R%d partial copy of pointer\n",
14258 						insn->src_reg);
14259 					return -EACCES;
14260 				} else if (src_reg->type == SCALAR_VALUE) {
14261 					if (insn->off == 0) {
14262 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
14263 
14264 						if (is_src_reg_u32)
14265 							assign_scalar_id_before_mov(env, src_reg);
14266 						copy_register_state(dst_reg, src_reg);
14267 						/* Make sure ID is cleared if src_reg is not in u32
14268 						 * range otherwise dst_reg min/max could be incorrectly
14269 						 * propagated into src_reg by find_equal_scalars()
14270 						 */
14271 						if (!is_src_reg_u32)
14272 							dst_reg->id = 0;
14273 						dst_reg->live |= REG_LIVE_WRITTEN;
14274 						dst_reg->subreg_def = env->insn_idx + 1;
14275 					} else {
14276 						/* case: W1 = (s8, s16)W2 */
14277 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14278 
14279 						if (no_sext)
14280 							assign_scalar_id_before_mov(env, src_reg);
14281 						copy_register_state(dst_reg, src_reg);
14282 						if (!no_sext)
14283 							dst_reg->id = 0;
14284 						dst_reg->live |= REG_LIVE_WRITTEN;
14285 						dst_reg->subreg_def = env->insn_idx + 1;
14286 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
14287 					}
14288 				} else {
14289 					mark_reg_unknown(env, regs,
14290 							 insn->dst_reg);
14291 				}
14292 				zext_32_to_64(dst_reg);
14293 				reg_bounds_sync(dst_reg);
14294 			}
14295 		} else {
14296 			/* case: R = imm
14297 			 * remember the value we stored into this reg
14298 			 */
14299 			/* clear any state __mark_reg_known doesn't set */
14300 			mark_reg_unknown(env, regs, insn->dst_reg);
14301 			regs[insn->dst_reg].type = SCALAR_VALUE;
14302 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14303 				__mark_reg_known(regs + insn->dst_reg,
14304 						 insn->imm);
14305 			} else {
14306 				__mark_reg_known(regs + insn->dst_reg,
14307 						 (u32)insn->imm);
14308 			}
14309 		}
14310 
14311 	} else if (opcode > BPF_END) {
14312 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14313 		return -EINVAL;
14314 
14315 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
14316 
14317 		if (BPF_SRC(insn->code) == BPF_X) {
14318 			if (insn->imm != 0 || insn->off > 1 ||
14319 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14320 				verbose(env, "BPF_ALU uses reserved fields\n");
14321 				return -EINVAL;
14322 			}
14323 			/* check src1 operand */
14324 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14325 			if (err)
14326 				return err;
14327 		} else {
14328 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14329 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14330 				verbose(env, "BPF_ALU uses reserved fields\n");
14331 				return -EINVAL;
14332 			}
14333 		}
14334 
14335 		/* check src2 operand */
14336 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14337 		if (err)
14338 			return err;
14339 
14340 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14341 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14342 			verbose(env, "div by zero\n");
14343 			return -EINVAL;
14344 		}
14345 
14346 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14347 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14348 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14349 
14350 			if (insn->imm < 0 || insn->imm >= size) {
14351 				verbose(env, "invalid shift %d\n", insn->imm);
14352 				return -EINVAL;
14353 			}
14354 		}
14355 
14356 		/* check dest operand */
14357 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14358 		err = err ?: adjust_reg_min_max_vals(env, insn);
14359 		if (err)
14360 			return err;
14361 	}
14362 
14363 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
14364 }
14365 
14366 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14367 				   struct bpf_reg_state *dst_reg,
14368 				   enum bpf_reg_type type,
14369 				   bool range_right_open)
14370 {
14371 	struct bpf_func_state *state;
14372 	struct bpf_reg_state *reg;
14373 	int new_range;
14374 
14375 	if (dst_reg->off < 0 ||
14376 	    (dst_reg->off == 0 && range_right_open))
14377 		/* This doesn't give us any range */
14378 		return;
14379 
14380 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
14381 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14382 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
14383 		 * than pkt_end, but that's because it's also less than pkt.
14384 		 */
14385 		return;
14386 
14387 	new_range = dst_reg->off;
14388 	if (range_right_open)
14389 		new_range++;
14390 
14391 	/* Examples for register markings:
14392 	 *
14393 	 * pkt_data in dst register:
14394 	 *
14395 	 *   r2 = r3;
14396 	 *   r2 += 8;
14397 	 *   if (r2 > pkt_end) goto <handle exception>
14398 	 *   <access okay>
14399 	 *
14400 	 *   r2 = r3;
14401 	 *   r2 += 8;
14402 	 *   if (r2 < pkt_end) goto <access okay>
14403 	 *   <handle exception>
14404 	 *
14405 	 *   Where:
14406 	 *     r2 == dst_reg, pkt_end == src_reg
14407 	 *     r2=pkt(id=n,off=8,r=0)
14408 	 *     r3=pkt(id=n,off=0,r=0)
14409 	 *
14410 	 * pkt_data in src register:
14411 	 *
14412 	 *   r2 = r3;
14413 	 *   r2 += 8;
14414 	 *   if (pkt_end >= r2) goto <access okay>
14415 	 *   <handle exception>
14416 	 *
14417 	 *   r2 = r3;
14418 	 *   r2 += 8;
14419 	 *   if (pkt_end <= r2) goto <handle exception>
14420 	 *   <access okay>
14421 	 *
14422 	 *   Where:
14423 	 *     pkt_end == dst_reg, r2 == src_reg
14424 	 *     r2=pkt(id=n,off=8,r=0)
14425 	 *     r3=pkt(id=n,off=0,r=0)
14426 	 *
14427 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14428 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14429 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
14430 	 * the check.
14431 	 */
14432 
14433 	/* If our ids match, then we must have the same max_value.  And we
14434 	 * don't care about the other reg's fixed offset, since if it's too big
14435 	 * the range won't allow anything.
14436 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14437 	 */
14438 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14439 		if (reg->type == type && reg->id == dst_reg->id)
14440 			/* keep the maximum range already checked */
14441 			reg->range = max(reg->range, new_range);
14442 	}));
14443 }
14444 
14445 /*
14446  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14447  */
14448 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14449 				  u8 opcode, bool is_jmp32)
14450 {
14451 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14452 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14453 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14454 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14455 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14456 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14457 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14458 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14459 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14460 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14461 
14462 	switch (opcode) {
14463 	case BPF_JEQ:
14464 		/* constants, umin/umax and smin/smax checks would be
14465 		 * redundant in this case because they all should match
14466 		 */
14467 		if (tnum_is_const(t1) && tnum_is_const(t2))
14468 			return t1.value == t2.value;
14469 		/* non-overlapping ranges */
14470 		if (umin1 > umax2 || umax1 < umin2)
14471 			return 0;
14472 		if (smin1 > smax2 || smax1 < smin2)
14473 			return 0;
14474 		if (!is_jmp32) {
14475 			/* if 64-bit ranges are inconclusive, see if we can
14476 			 * utilize 32-bit subrange knowledge to eliminate
14477 			 * branches that can't be taken a priori
14478 			 */
14479 			if (reg1->u32_min_value > reg2->u32_max_value ||
14480 			    reg1->u32_max_value < reg2->u32_min_value)
14481 				return 0;
14482 			if (reg1->s32_min_value > reg2->s32_max_value ||
14483 			    reg1->s32_max_value < reg2->s32_min_value)
14484 				return 0;
14485 		}
14486 		break;
14487 	case BPF_JNE:
14488 		/* constants, umin/umax and smin/smax checks would be
14489 		 * redundant in this case because they all should match
14490 		 */
14491 		if (tnum_is_const(t1) && tnum_is_const(t2))
14492 			return t1.value != t2.value;
14493 		/* non-overlapping ranges */
14494 		if (umin1 > umax2 || umax1 < umin2)
14495 			return 1;
14496 		if (smin1 > smax2 || smax1 < smin2)
14497 			return 1;
14498 		if (!is_jmp32) {
14499 			/* if 64-bit ranges are inconclusive, see if we can
14500 			 * utilize 32-bit subrange knowledge to eliminate
14501 			 * branches that can't be taken a priori
14502 			 */
14503 			if (reg1->u32_min_value > reg2->u32_max_value ||
14504 			    reg1->u32_max_value < reg2->u32_min_value)
14505 				return 1;
14506 			if (reg1->s32_min_value > reg2->s32_max_value ||
14507 			    reg1->s32_max_value < reg2->s32_min_value)
14508 				return 1;
14509 		}
14510 		break;
14511 	case BPF_JSET:
14512 		if (!is_reg_const(reg2, is_jmp32)) {
14513 			swap(reg1, reg2);
14514 			swap(t1, t2);
14515 		}
14516 		if (!is_reg_const(reg2, is_jmp32))
14517 			return -1;
14518 		if ((~t1.mask & t1.value) & t2.value)
14519 			return 1;
14520 		if (!((t1.mask | t1.value) & t2.value))
14521 			return 0;
14522 		break;
14523 	case BPF_JGT:
14524 		if (umin1 > umax2)
14525 			return 1;
14526 		else if (umax1 <= umin2)
14527 			return 0;
14528 		break;
14529 	case BPF_JSGT:
14530 		if (smin1 > smax2)
14531 			return 1;
14532 		else if (smax1 <= smin2)
14533 			return 0;
14534 		break;
14535 	case BPF_JLT:
14536 		if (umax1 < umin2)
14537 			return 1;
14538 		else if (umin1 >= umax2)
14539 			return 0;
14540 		break;
14541 	case BPF_JSLT:
14542 		if (smax1 < smin2)
14543 			return 1;
14544 		else if (smin1 >= smax2)
14545 			return 0;
14546 		break;
14547 	case BPF_JGE:
14548 		if (umin1 >= umax2)
14549 			return 1;
14550 		else if (umax1 < umin2)
14551 			return 0;
14552 		break;
14553 	case BPF_JSGE:
14554 		if (smin1 >= smax2)
14555 			return 1;
14556 		else if (smax1 < smin2)
14557 			return 0;
14558 		break;
14559 	case BPF_JLE:
14560 		if (umax1 <= umin2)
14561 			return 1;
14562 		else if (umin1 > umax2)
14563 			return 0;
14564 		break;
14565 	case BPF_JSLE:
14566 		if (smax1 <= smin2)
14567 			return 1;
14568 		else if (smin1 > smax2)
14569 			return 0;
14570 		break;
14571 	}
14572 
14573 	return -1;
14574 }
14575 
14576 static int flip_opcode(u32 opcode)
14577 {
14578 	/* How can we transform "a <op> b" into "b <op> a"? */
14579 	static const u8 opcode_flip[16] = {
14580 		/* these stay the same */
14581 		[BPF_JEQ  >> 4] = BPF_JEQ,
14582 		[BPF_JNE  >> 4] = BPF_JNE,
14583 		[BPF_JSET >> 4] = BPF_JSET,
14584 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14585 		[BPF_JGE  >> 4] = BPF_JLE,
14586 		[BPF_JGT  >> 4] = BPF_JLT,
14587 		[BPF_JLE  >> 4] = BPF_JGE,
14588 		[BPF_JLT  >> 4] = BPF_JGT,
14589 		[BPF_JSGE >> 4] = BPF_JSLE,
14590 		[BPF_JSGT >> 4] = BPF_JSLT,
14591 		[BPF_JSLE >> 4] = BPF_JSGE,
14592 		[BPF_JSLT >> 4] = BPF_JSGT
14593 	};
14594 	return opcode_flip[opcode >> 4];
14595 }
14596 
14597 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14598 				   struct bpf_reg_state *src_reg,
14599 				   u8 opcode)
14600 {
14601 	struct bpf_reg_state *pkt;
14602 
14603 	if (src_reg->type == PTR_TO_PACKET_END) {
14604 		pkt = dst_reg;
14605 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14606 		pkt = src_reg;
14607 		opcode = flip_opcode(opcode);
14608 	} else {
14609 		return -1;
14610 	}
14611 
14612 	if (pkt->range >= 0)
14613 		return -1;
14614 
14615 	switch (opcode) {
14616 	case BPF_JLE:
14617 		/* pkt <= pkt_end */
14618 		fallthrough;
14619 	case BPF_JGT:
14620 		/* pkt > pkt_end */
14621 		if (pkt->range == BEYOND_PKT_END)
14622 			/* pkt has at last one extra byte beyond pkt_end */
14623 			return opcode == BPF_JGT;
14624 		break;
14625 	case BPF_JLT:
14626 		/* pkt < pkt_end */
14627 		fallthrough;
14628 	case BPF_JGE:
14629 		/* pkt >= pkt_end */
14630 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14631 			return opcode == BPF_JGE;
14632 		break;
14633 	}
14634 	return -1;
14635 }
14636 
14637 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14638  * and return:
14639  *  1 - branch will be taken and "goto target" will be executed
14640  *  0 - branch will not be taken and fall-through to next insn
14641  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14642  *      range [0,10]
14643  */
14644 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14645 			   u8 opcode, bool is_jmp32)
14646 {
14647 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14648 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14649 
14650 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14651 		u64 val;
14652 
14653 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
14654 		if (!is_reg_const(reg2, is_jmp32)) {
14655 			opcode = flip_opcode(opcode);
14656 			swap(reg1, reg2);
14657 		}
14658 		/* and ensure that reg2 is a constant */
14659 		if (!is_reg_const(reg2, is_jmp32))
14660 			return -1;
14661 
14662 		if (!reg_not_null(reg1))
14663 			return -1;
14664 
14665 		/* If pointer is valid tests against zero will fail so we can
14666 		 * use this to direct branch taken.
14667 		 */
14668 		val = reg_const_value(reg2, is_jmp32);
14669 		if (val != 0)
14670 			return -1;
14671 
14672 		switch (opcode) {
14673 		case BPF_JEQ:
14674 			return 0;
14675 		case BPF_JNE:
14676 			return 1;
14677 		default:
14678 			return -1;
14679 		}
14680 	}
14681 
14682 	/* now deal with two scalars, but not necessarily constants */
14683 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14684 }
14685 
14686 /* Opcode that corresponds to a *false* branch condition.
14687  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14688  */
14689 static u8 rev_opcode(u8 opcode)
14690 {
14691 	switch (opcode) {
14692 	case BPF_JEQ:		return BPF_JNE;
14693 	case BPF_JNE:		return BPF_JEQ;
14694 	/* JSET doesn't have it's reverse opcode in BPF, so add
14695 	 * BPF_X flag to denote the reverse of that operation
14696 	 */
14697 	case BPF_JSET:		return BPF_JSET | BPF_X;
14698 	case BPF_JSET | BPF_X:	return BPF_JSET;
14699 	case BPF_JGE:		return BPF_JLT;
14700 	case BPF_JGT:		return BPF_JLE;
14701 	case BPF_JLE:		return BPF_JGT;
14702 	case BPF_JLT:		return BPF_JGE;
14703 	case BPF_JSGE:		return BPF_JSLT;
14704 	case BPF_JSGT:		return BPF_JSLE;
14705 	case BPF_JSLE:		return BPF_JSGT;
14706 	case BPF_JSLT:		return BPF_JSGE;
14707 	default:		return 0;
14708 	}
14709 }
14710 
14711 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
14712 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14713 				u8 opcode, bool is_jmp32)
14714 {
14715 	struct tnum t;
14716 	u64 val;
14717 
14718 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
14719 	switch (opcode) {
14720 	case BPF_JGE:
14721 	case BPF_JGT:
14722 	case BPF_JSGE:
14723 	case BPF_JSGT:
14724 		opcode = flip_opcode(opcode);
14725 		swap(reg1, reg2);
14726 		break;
14727 	default:
14728 		break;
14729 	}
14730 
14731 	switch (opcode) {
14732 	case BPF_JEQ:
14733 		if (is_jmp32) {
14734 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14735 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14736 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14737 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14738 			reg2->u32_min_value = reg1->u32_min_value;
14739 			reg2->u32_max_value = reg1->u32_max_value;
14740 			reg2->s32_min_value = reg1->s32_min_value;
14741 			reg2->s32_max_value = reg1->s32_max_value;
14742 
14743 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14744 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14745 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14746 		} else {
14747 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14748 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14749 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14750 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14751 			reg2->umin_value = reg1->umin_value;
14752 			reg2->umax_value = reg1->umax_value;
14753 			reg2->smin_value = reg1->smin_value;
14754 			reg2->smax_value = reg1->smax_value;
14755 
14756 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14757 			reg2->var_off = reg1->var_off;
14758 		}
14759 		break;
14760 	case BPF_JNE:
14761 		if (!is_reg_const(reg2, is_jmp32))
14762 			swap(reg1, reg2);
14763 		if (!is_reg_const(reg2, is_jmp32))
14764 			break;
14765 
14766 		/* try to recompute the bound of reg1 if reg2 is a const and
14767 		 * is exactly the edge of reg1.
14768 		 */
14769 		val = reg_const_value(reg2, is_jmp32);
14770 		if (is_jmp32) {
14771 			/* u32_min_value is not equal to 0xffffffff at this point,
14772 			 * because otherwise u32_max_value is 0xffffffff as well,
14773 			 * in such a case both reg1 and reg2 would be constants,
14774 			 * jump would be predicted and reg_set_min_max() won't
14775 			 * be called.
14776 			 *
14777 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
14778 			 * below.
14779 			 */
14780 			if (reg1->u32_min_value == (u32)val)
14781 				reg1->u32_min_value++;
14782 			if (reg1->u32_max_value == (u32)val)
14783 				reg1->u32_max_value--;
14784 			if (reg1->s32_min_value == (s32)val)
14785 				reg1->s32_min_value++;
14786 			if (reg1->s32_max_value == (s32)val)
14787 				reg1->s32_max_value--;
14788 		} else {
14789 			if (reg1->umin_value == (u64)val)
14790 				reg1->umin_value++;
14791 			if (reg1->umax_value == (u64)val)
14792 				reg1->umax_value--;
14793 			if (reg1->smin_value == (s64)val)
14794 				reg1->smin_value++;
14795 			if (reg1->smax_value == (s64)val)
14796 				reg1->smax_value--;
14797 		}
14798 		break;
14799 	case BPF_JSET:
14800 		if (!is_reg_const(reg2, is_jmp32))
14801 			swap(reg1, reg2);
14802 		if (!is_reg_const(reg2, is_jmp32))
14803 			break;
14804 		val = reg_const_value(reg2, is_jmp32);
14805 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14806 		 * requires single bit to learn something useful. E.g., if we
14807 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14808 		 * are actually set? We can learn something definite only if
14809 		 * it's a single-bit value to begin with.
14810 		 *
14811 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14812 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14813 		 * bit 1 is set, which we can readily use in adjustments.
14814 		 */
14815 		if (!is_power_of_2(val))
14816 			break;
14817 		if (is_jmp32) {
14818 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14819 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14820 		} else {
14821 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
14822 		}
14823 		break;
14824 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
14825 		if (!is_reg_const(reg2, is_jmp32))
14826 			swap(reg1, reg2);
14827 		if (!is_reg_const(reg2, is_jmp32))
14828 			break;
14829 		val = reg_const_value(reg2, is_jmp32);
14830 		if (is_jmp32) {
14831 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
14832 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14833 		} else {
14834 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
14835 		}
14836 		break;
14837 	case BPF_JLE:
14838 		if (is_jmp32) {
14839 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14840 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14841 		} else {
14842 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14843 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
14844 		}
14845 		break;
14846 	case BPF_JLT:
14847 		if (is_jmp32) {
14848 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
14849 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
14850 		} else {
14851 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
14852 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
14853 		}
14854 		break;
14855 	case BPF_JSLE:
14856 		if (is_jmp32) {
14857 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14858 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14859 		} else {
14860 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14861 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
14862 		}
14863 		break;
14864 	case BPF_JSLT:
14865 		if (is_jmp32) {
14866 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
14867 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
14868 		} else {
14869 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
14870 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
14871 		}
14872 		break;
14873 	default:
14874 		return;
14875 	}
14876 }
14877 
14878 /* Adjusts the register min/max values in the case that the dst_reg and
14879  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
14880  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
14881  * Technically we can do similar adjustments for pointers to the same object,
14882  * but we don't support that right now.
14883  */
14884 static int reg_set_min_max(struct bpf_verifier_env *env,
14885 			   struct bpf_reg_state *true_reg1,
14886 			   struct bpf_reg_state *true_reg2,
14887 			   struct bpf_reg_state *false_reg1,
14888 			   struct bpf_reg_state *false_reg2,
14889 			   u8 opcode, bool is_jmp32)
14890 {
14891 	int err;
14892 
14893 	/* If either register is a pointer, we can't learn anything about its
14894 	 * variable offset from the compare (unless they were a pointer into
14895 	 * the same object, but we don't bother with that).
14896 	 */
14897 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
14898 		return 0;
14899 
14900 	/* fallthrough (FALSE) branch */
14901 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
14902 	reg_bounds_sync(false_reg1);
14903 	reg_bounds_sync(false_reg2);
14904 
14905 	/* jump (TRUE) branch */
14906 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
14907 	reg_bounds_sync(true_reg1);
14908 	reg_bounds_sync(true_reg2);
14909 
14910 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
14911 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
14912 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
14913 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
14914 	return err;
14915 }
14916 
14917 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14918 				 struct bpf_reg_state *reg, u32 id,
14919 				 bool is_null)
14920 {
14921 	if (type_may_be_null(reg->type) && reg->id == id &&
14922 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14923 		/* Old offset (both fixed and variable parts) should have been
14924 		 * known-zero, because we don't allow pointer arithmetic on
14925 		 * pointers that might be NULL. If we see this happening, don't
14926 		 * convert the register.
14927 		 *
14928 		 * But in some cases, some helpers that return local kptrs
14929 		 * advance offset for the returned pointer. In those cases, it
14930 		 * is fine to expect to see reg->off.
14931 		 */
14932 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14933 			return;
14934 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14935 		    WARN_ON_ONCE(reg->off))
14936 			return;
14937 
14938 		if (is_null) {
14939 			reg->type = SCALAR_VALUE;
14940 			/* We don't need id and ref_obj_id from this point
14941 			 * onwards anymore, thus we should better reset it,
14942 			 * so that state pruning has chances to take effect.
14943 			 */
14944 			reg->id = 0;
14945 			reg->ref_obj_id = 0;
14946 
14947 			return;
14948 		}
14949 
14950 		mark_ptr_not_null_reg(reg);
14951 
14952 		if (!reg_may_point_to_spin_lock(reg)) {
14953 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14954 			 * in release_reference().
14955 			 *
14956 			 * reg->id is still used by spin_lock ptr. Other
14957 			 * than spin_lock ptr type, reg->id can be reset.
14958 			 */
14959 			reg->id = 0;
14960 		}
14961 	}
14962 }
14963 
14964 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14965  * be folded together at some point.
14966  */
14967 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14968 				  bool is_null)
14969 {
14970 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14971 	struct bpf_reg_state *regs = state->regs, *reg;
14972 	u32 ref_obj_id = regs[regno].ref_obj_id;
14973 	u32 id = regs[regno].id;
14974 
14975 	if (ref_obj_id && ref_obj_id == id && is_null)
14976 		/* regs[regno] is in the " == NULL" branch.
14977 		 * No one could have freed the reference state before
14978 		 * doing the NULL check.
14979 		 */
14980 		WARN_ON_ONCE(release_reference_state(state, id));
14981 
14982 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14983 		mark_ptr_or_null_reg(state, reg, id, is_null);
14984 	}));
14985 }
14986 
14987 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14988 				   struct bpf_reg_state *dst_reg,
14989 				   struct bpf_reg_state *src_reg,
14990 				   struct bpf_verifier_state *this_branch,
14991 				   struct bpf_verifier_state *other_branch)
14992 {
14993 	if (BPF_SRC(insn->code) != BPF_X)
14994 		return false;
14995 
14996 	/* Pointers are always 64-bit. */
14997 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14998 		return false;
14999 
15000 	switch (BPF_OP(insn->code)) {
15001 	case BPF_JGT:
15002 		if ((dst_reg->type == PTR_TO_PACKET &&
15003 		     src_reg->type == PTR_TO_PACKET_END) ||
15004 		    (dst_reg->type == PTR_TO_PACKET_META &&
15005 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15006 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
15007 			find_good_pkt_pointers(this_branch, dst_reg,
15008 					       dst_reg->type, false);
15009 			mark_pkt_end(other_branch, insn->dst_reg, true);
15010 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15011 			    src_reg->type == PTR_TO_PACKET) ||
15012 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15013 			    src_reg->type == PTR_TO_PACKET_META)) {
15014 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
15015 			find_good_pkt_pointers(other_branch, src_reg,
15016 					       src_reg->type, true);
15017 			mark_pkt_end(this_branch, insn->src_reg, false);
15018 		} else {
15019 			return false;
15020 		}
15021 		break;
15022 	case BPF_JLT:
15023 		if ((dst_reg->type == PTR_TO_PACKET &&
15024 		     src_reg->type == PTR_TO_PACKET_END) ||
15025 		    (dst_reg->type == PTR_TO_PACKET_META &&
15026 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15027 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
15028 			find_good_pkt_pointers(other_branch, dst_reg,
15029 					       dst_reg->type, true);
15030 			mark_pkt_end(this_branch, insn->dst_reg, false);
15031 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15032 			    src_reg->type == PTR_TO_PACKET) ||
15033 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15034 			    src_reg->type == PTR_TO_PACKET_META)) {
15035 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
15036 			find_good_pkt_pointers(this_branch, src_reg,
15037 					       src_reg->type, false);
15038 			mark_pkt_end(other_branch, insn->src_reg, true);
15039 		} else {
15040 			return false;
15041 		}
15042 		break;
15043 	case BPF_JGE:
15044 		if ((dst_reg->type == PTR_TO_PACKET &&
15045 		     src_reg->type == PTR_TO_PACKET_END) ||
15046 		    (dst_reg->type == PTR_TO_PACKET_META &&
15047 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15048 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
15049 			find_good_pkt_pointers(this_branch, dst_reg,
15050 					       dst_reg->type, true);
15051 			mark_pkt_end(other_branch, insn->dst_reg, false);
15052 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15053 			    src_reg->type == PTR_TO_PACKET) ||
15054 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15055 			    src_reg->type == PTR_TO_PACKET_META)) {
15056 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
15057 			find_good_pkt_pointers(other_branch, src_reg,
15058 					       src_reg->type, false);
15059 			mark_pkt_end(this_branch, insn->src_reg, true);
15060 		} else {
15061 			return false;
15062 		}
15063 		break;
15064 	case BPF_JLE:
15065 		if ((dst_reg->type == PTR_TO_PACKET &&
15066 		     src_reg->type == PTR_TO_PACKET_END) ||
15067 		    (dst_reg->type == PTR_TO_PACKET_META &&
15068 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15069 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
15070 			find_good_pkt_pointers(other_branch, dst_reg,
15071 					       dst_reg->type, false);
15072 			mark_pkt_end(this_branch, insn->dst_reg, true);
15073 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15074 			    src_reg->type == PTR_TO_PACKET) ||
15075 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15076 			    src_reg->type == PTR_TO_PACKET_META)) {
15077 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
15078 			find_good_pkt_pointers(this_branch, src_reg,
15079 					       src_reg->type, true);
15080 			mark_pkt_end(other_branch, insn->src_reg, false);
15081 		} else {
15082 			return false;
15083 		}
15084 		break;
15085 	default:
15086 		return false;
15087 	}
15088 
15089 	return true;
15090 }
15091 
15092 static void find_equal_scalars(struct bpf_verifier_state *vstate,
15093 			       struct bpf_reg_state *known_reg)
15094 {
15095 	struct bpf_func_state *state;
15096 	struct bpf_reg_state *reg;
15097 
15098 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15099 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
15100 			copy_register_state(reg, known_reg);
15101 	}));
15102 }
15103 
15104 static int check_cond_jmp_op(struct bpf_verifier_env *env,
15105 			     struct bpf_insn *insn, int *insn_idx)
15106 {
15107 	struct bpf_verifier_state *this_branch = env->cur_state;
15108 	struct bpf_verifier_state *other_branch;
15109 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
15110 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
15111 	struct bpf_reg_state *eq_branch_regs;
15112 	struct bpf_reg_state fake_reg = {};
15113 	u8 opcode = BPF_OP(insn->code);
15114 	bool is_jmp32;
15115 	int pred = -1;
15116 	int err;
15117 
15118 	/* Only conditional jumps are expected to reach here. */
15119 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
15120 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
15121 		return -EINVAL;
15122 	}
15123 
15124 	if (opcode == BPF_JCOND) {
15125 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
15126 		int idx = *insn_idx;
15127 
15128 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
15129 		    insn->src_reg != BPF_MAY_GOTO ||
15130 		    insn->dst_reg || insn->imm || insn->off == 0) {
15131 			verbose(env, "invalid may_goto off %d imm %d\n",
15132 				insn->off, insn->imm);
15133 			return -EINVAL;
15134 		}
15135 		prev_st = find_prev_entry(env, cur_st->parent, idx);
15136 
15137 		/* branch out 'fallthrough' insn as a new state to explore */
15138 		queued_st = push_stack(env, idx + 1, idx, false);
15139 		if (!queued_st)
15140 			return -ENOMEM;
15141 
15142 		queued_st->may_goto_depth++;
15143 		if (prev_st)
15144 			widen_imprecise_scalars(env, prev_st, queued_st);
15145 		*insn_idx += insn->off;
15146 		return 0;
15147 	}
15148 
15149 	/* check src2 operand */
15150 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15151 	if (err)
15152 		return err;
15153 
15154 	dst_reg = &regs[insn->dst_reg];
15155 	if (BPF_SRC(insn->code) == BPF_X) {
15156 		if (insn->imm != 0) {
15157 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15158 			return -EINVAL;
15159 		}
15160 
15161 		/* check src1 operand */
15162 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15163 		if (err)
15164 			return err;
15165 
15166 		src_reg = &regs[insn->src_reg];
15167 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
15168 		    is_pointer_value(env, insn->src_reg)) {
15169 			verbose(env, "R%d pointer comparison prohibited\n",
15170 				insn->src_reg);
15171 			return -EACCES;
15172 		}
15173 	} else {
15174 		if (insn->src_reg != BPF_REG_0) {
15175 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15176 			return -EINVAL;
15177 		}
15178 		src_reg = &fake_reg;
15179 		src_reg->type = SCALAR_VALUE;
15180 		__mark_reg_known(src_reg, insn->imm);
15181 	}
15182 
15183 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
15184 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
15185 	if (pred >= 0) {
15186 		/* If we get here with a dst_reg pointer type it is because
15187 		 * above is_branch_taken() special cased the 0 comparison.
15188 		 */
15189 		if (!__is_pointer_value(false, dst_reg))
15190 			err = mark_chain_precision(env, insn->dst_reg);
15191 		if (BPF_SRC(insn->code) == BPF_X && !err &&
15192 		    !__is_pointer_value(false, src_reg))
15193 			err = mark_chain_precision(env, insn->src_reg);
15194 		if (err)
15195 			return err;
15196 	}
15197 
15198 	if (pred == 1) {
15199 		/* Only follow the goto, ignore fall-through. If needed, push
15200 		 * the fall-through branch for simulation under speculative
15201 		 * execution.
15202 		 */
15203 		if (!env->bypass_spec_v1 &&
15204 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
15205 					       *insn_idx))
15206 			return -EFAULT;
15207 		if (env->log.level & BPF_LOG_LEVEL)
15208 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
15209 		*insn_idx += insn->off;
15210 		return 0;
15211 	} else if (pred == 0) {
15212 		/* Only follow the fall-through branch, since that's where the
15213 		 * program will go. If needed, push the goto branch for
15214 		 * simulation under speculative execution.
15215 		 */
15216 		if (!env->bypass_spec_v1 &&
15217 		    !sanitize_speculative_path(env, insn,
15218 					       *insn_idx + insn->off + 1,
15219 					       *insn_idx))
15220 			return -EFAULT;
15221 		if (env->log.level & BPF_LOG_LEVEL)
15222 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
15223 		return 0;
15224 	}
15225 
15226 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
15227 				  false);
15228 	if (!other_branch)
15229 		return -EFAULT;
15230 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
15231 
15232 	if (BPF_SRC(insn->code) == BPF_X) {
15233 		err = reg_set_min_max(env,
15234 				      &other_branch_regs[insn->dst_reg],
15235 				      &other_branch_regs[insn->src_reg],
15236 				      dst_reg, src_reg, opcode, is_jmp32);
15237 	} else /* BPF_SRC(insn->code) == BPF_K */ {
15238 		err = reg_set_min_max(env,
15239 				      &other_branch_regs[insn->dst_reg],
15240 				      src_reg /* fake one */,
15241 				      dst_reg, src_reg /* same fake one */,
15242 				      opcode, is_jmp32);
15243 	}
15244 	if (err)
15245 		return err;
15246 
15247 	if (BPF_SRC(insn->code) == BPF_X &&
15248 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
15249 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
15250 		find_equal_scalars(this_branch, src_reg);
15251 		find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
15252 	}
15253 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
15254 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
15255 		find_equal_scalars(this_branch, dst_reg);
15256 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
15257 	}
15258 
15259 	/* if one pointer register is compared to another pointer
15260 	 * register check if PTR_MAYBE_NULL could be lifted.
15261 	 * E.g. register A - maybe null
15262 	 *      register B - not null
15263 	 * for JNE A, B, ... - A is not null in the false branch;
15264 	 * for JEQ A, B, ... - A is not null in the true branch.
15265 	 *
15266 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
15267 	 * not need to be null checked by the BPF program, i.e.,
15268 	 * could be null even without PTR_MAYBE_NULL marking, so
15269 	 * only propagate nullness when neither reg is that type.
15270 	 */
15271 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
15272 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
15273 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
15274 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
15275 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
15276 		eq_branch_regs = NULL;
15277 		switch (opcode) {
15278 		case BPF_JEQ:
15279 			eq_branch_regs = other_branch_regs;
15280 			break;
15281 		case BPF_JNE:
15282 			eq_branch_regs = regs;
15283 			break;
15284 		default:
15285 			/* do nothing */
15286 			break;
15287 		}
15288 		if (eq_branch_regs) {
15289 			if (type_may_be_null(src_reg->type))
15290 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
15291 			else
15292 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
15293 		}
15294 	}
15295 
15296 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
15297 	 * NOTE: these optimizations below are related with pointer comparison
15298 	 *       which will never be JMP32.
15299 	 */
15300 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
15301 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
15302 	    type_may_be_null(dst_reg->type)) {
15303 		/* Mark all identical registers in each branch as either
15304 		 * safe or unknown depending R == 0 or R != 0 conditional.
15305 		 */
15306 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
15307 				      opcode == BPF_JNE);
15308 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
15309 				      opcode == BPF_JEQ);
15310 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
15311 					   this_branch, other_branch) &&
15312 		   is_pointer_value(env, insn->dst_reg)) {
15313 		verbose(env, "R%d pointer comparison prohibited\n",
15314 			insn->dst_reg);
15315 		return -EACCES;
15316 	}
15317 	if (env->log.level & BPF_LOG_LEVEL)
15318 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
15319 	return 0;
15320 }
15321 
15322 /* verify BPF_LD_IMM64 instruction */
15323 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
15324 {
15325 	struct bpf_insn_aux_data *aux = cur_aux(env);
15326 	struct bpf_reg_state *regs = cur_regs(env);
15327 	struct bpf_reg_state *dst_reg;
15328 	struct bpf_map *map;
15329 	int err;
15330 
15331 	if (BPF_SIZE(insn->code) != BPF_DW) {
15332 		verbose(env, "invalid BPF_LD_IMM insn\n");
15333 		return -EINVAL;
15334 	}
15335 	if (insn->off != 0) {
15336 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
15337 		return -EINVAL;
15338 	}
15339 
15340 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
15341 	if (err)
15342 		return err;
15343 
15344 	dst_reg = &regs[insn->dst_reg];
15345 	if (insn->src_reg == 0) {
15346 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15347 
15348 		dst_reg->type = SCALAR_VALUE;
15349 		__mark_reg_known(&regs[insn->dst_reg], imm);
15350 		return 0;
15351 	}
15352 
15353 	/* All special src_reg cases are listed below. From this point onwards
15354 	 * we either succeed and assign a corresponding dst_reg->type after
15355 	 * zeroing the offset, or fail and reject the program.
15356 	 */
15357 	mark_reg_known_zero(env, regs, insn->dst_reg);
15358 
15359 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15360 		dst_reg->type = aux->btf_var.reg_type;
15361 		switch (base_type(dst_reg->type)) {
15362 		case PTR_TO_MEM:
15363 			dst_reg->mem_size = aux->btf_var.mem_size;
15364 			break;
15365 		case PTR_TO_BTF_ID:
15366 			dst_reg->btf = aux->btf_var.btf;
15367 			dst_reg->btf_id = aux->btf_var.btf_id;
15368 			break;
15369 		default:
15370 			verbose(env, "bpf verifier is misconfigured\n");
15371 			return -EFAULT;
15372 		}
15373 		return 0;
15374 	}
15375 
15376 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
15377 		struct bpf_prog_aux *aux = env->prog->aux;
15378 		u32 subprogno = find_subprog(env,
15379 					     env->insn_idx + insn->imm + 1);
15380 
15381 		if (!aux->func_info) {
15382 			verbose(env, "missing btf func_info\n");
15383 			return -EINVAL;
15384 		}
15385 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15386 			verbose(env, "callback function not static\n");
15387 			return -EINVAL;
15388 		}
15389 
15390 		dst_reg->type = PTR_TO_FUNC;
15391 		dst_reg->subprogno = subprogno;
15392 		return 0;
15393 	}
15394 
15395 	map = env->used_maps[aux->map_index];
15396 	dst_reg->map_ptr = map;
15397 
15398 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15399 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15400 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
15401 			__mark_reg_unknown(env, dst_reg);
15402 			return 0;
15403 		}
15404 		dst_reg->type = PTR_TO_MAP_VALUE;
15405 		dst_reg->off = aux->map_off;
15406 		WARN_ON_ONCE(map->max_entries != 1);
15407 		/* We want reg->id to be same (0) as map_value is not distinct */
15408 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15409 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15410 		dst_reg->type = CONST_PTR_TO_MAP;
15411 	} else {
15412 		verbose(env, "bpf verifier is misconfigured\n");
15413 		return -EINVAL;
15414 	}
15415 
15416 	return 0;
15417 }
15418 
15419 static bool may_access_skb(enum bpf_prog_type type)
15420 {
15421 	switch (type) {
15422 	case BPF_PROG_TYPE_SOCKET_FILTER:
15423 	case BPF_PROG_TYPE_SCHED_CLS:
15424 	case BPF_PROG_TYPE_SCHED_ACT:
15425 		return true;
15426 	default:
15427 		return false;
15428 	}
15429 }
15430 
15431 /* verify safety of LD_ABS|LD_IND instructions:
15432  * - they can only appear in the programs where ctx == skb
15433  * - since they are wrappers of function calls, they scratch R1-R5 registers,
15434  *   preserve R6-R9, and store return value into R0
15435  *
15436  * Implicit input:
15437  *   ctx == skb == R6 == CTX
15438  *
15439  * Explicit input:
15440  *   SRC == any register
15441  *   IMM == 32-bit immediate
15442  *
15443  * Output:
15444  *   R0 - 8/16/32-bit skb data converted to cpu endianness
15445  */
15446 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15447 {
15448 	struct bpf_reg_state *regs = cur_regs(env);
15449 	static const int ctx_reg = BPF_REG_6;
15450 	u8 mode = BPF_MODE(insn->code);
15451 	int i, err;
15452 
15453 	if (!may_access_skb(resolve_prog_type(env->prog))) {
15454 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15455 		return -EINVAL;
15456 	}
15457 
15458 	if (!env->ops->gen_ld_abs) {
15459 		verbose(env, "bpf verifier is misconfigured\n");
15460 		return -EINVAL;
15461 	}
15462 
15463 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15464 	    BPF_SIZE(insn->code) == BPF_DW ||
15465 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15466 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15467 		return -EINVAL;
15468 	}
15469 
15470 	/* check whether implicit source operand (register R6) is readable */
15471 	err = check_reg_arg(env, ctx_reg, SRC_OP);
15472 	if (err)
15473 		return err;
15474 
15475 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15476 	 * gen_ld_abs() may terminate the program at runtime, leading to
15477 	 * reference leak.
15478 	 */
15479 	err = check_reference_leak(env, false);
15480 	if (err) {
15481 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15482 		return err;
15483 	}
15484 
15485 	if (env->cur_state->active_lock.ptr) {
15486 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15487 		return -EINVAL;
15488 	}
15489 
15490 	if (env->cur_state->active_rcu_lock) {
15491 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15492 		return -EINVAL;
15493 	}
15494 
15495 	if (env->cur_state->active_preempt_lock) {
15496 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_preempt_disable-ed region\n");
15497 		return -EINVAL;
15498 	}
15499 
15500 	if (regs[ctx_reg].type != PTR_TO_CTX) {
15501 		verbose(env,
15502 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15503 		return -EINVAL;
15504 	}
15505 
15506 	if (mode == BPF_IND) {
15507 		/* check explicit source operand */
15508 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15509 		if (err)
15510 			return err;
15511 	}
15512 
15513 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
15514 	if (err < 0)
15515 		return err;
15516 
15517 	/* reset caller saved regs to unreadable */
15518 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
15519 		mark_reg_not_init(env, regs, caller_saved[i]);
15520 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15521 	}
15522 
15523 	/* mark destination R0 register as readable, since it contains
15524 	 * the value fetched from the packet.
15525 	 * Already marked as written above.
15526 	 */
15527 	mark_reg_unknown(env, regs, BPF_REG_0);
15528 	/* ld_abs load up to 32-bit skb data. */
15529 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15530 	return 0;
15531 }
15532 
15533 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
15534 {
15535 	const char *exit_ctx = "At program exit";
15536 	struct tnum enforce_attach_type_range = tnum_unknown;
15537 	const struct bpf_prog *prog = env->prog;
15538 	struct bpf_reg_state *reg;
15539 	struct bpf_retval_range range = retval_range(0, 1);
15540 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15541 	int err;
15542 	struct bpf_func_state *frame = env->cur_state->frame[0];
15543 	const bool is_subprog = frame->subprogno;
15544 
15545 	/* LSM and struct_ops func-ptr's return type could be "void" */
15546 	if (!is_subprog || frame->in_exception_callback_fn) {
15547 		switch (prog_type) {
15548 		case BPF_PROG_TYPE_LSM:
15549 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
15550 				/* See below, can be 0 or 0-1 depending on hook. */
15551 				break;
15552 			fallthrough;
15553 		case BPF_PROG_TYPE_STRUCT_OPS:
15554 			if (!prog->aux->attach_func_proto->type)
15555 				return 0;
15556 			break;
15557 		default:
15558 			break;
15559 		}
15560 	}
15561 
15562 	/* eBPF calling convention is such that R0 is used
15563 	 * to return the value from eBPF program.
15564 	 * Make sure that it's readable at this time
15565 	 * of bpf_exit, which means that program wrote
15566 	 * something into it earlier
15567 	 */
15568 	err = check_reg_arg(env, regno, SRC_OP);
15569 	if (err)
15570 		return err;
15571 
15572 	if (is_pointer_value(env, regno)) {
15573 		verbose(env, "R%d leaks addr as return value\n", regno);
15574 		return -EACCES;
15575 	}
15576 
15577 	reg = cur_regs(env) + regno;
15578 
15579 	if (frame->in_async_callback_fn) {
15580 		/* enforce return zero from async callbacks like timer */
15581 		exit_ctx = "At async callback return";
15582 		range = retval_range(0, 0);
15583 		goto enforce_retval;
15584 	}
15585 
15586 	if (is_subprog && !frame->in_exception_callback_fn) {
15587 		if (reg->type != SCALAR_VALUE) {
15588 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15589 				regno, reg_type_str(env, reg->type));
15590 			return -EINVAL;
15591 		}
15592 		return 0;
15593 	}
15594 
15595 	switch (prog_type) {
15596 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15597 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15598 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15599 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15600 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15601 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15602 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15603 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15604 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15605 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15606 			range = retval_range(1, 1);
15607 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15608 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15609 			range = retval_range(0, 3);
15610 		break;
15611 	case BPF_PROG_TYPE_CGROUP_SKB:
15612 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15613 			range = retval_range(0, 3);
15614 			enforce_attach_type_range = tnum_range(2, 3);
15615 		}
15616 		break;
15617 	case BPF_PROG_TYPE_CGROUP_SOCK:
15618 	case BPF_PROG_TYPE_SOCK_OPS:
15619 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15620 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15621 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15622 		break;
15623 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15624 		if (!env->prog->aux->attach_btf_id)
15625 			return 0;
15626 		range = retval_range(0, 0);
15627 		break;
15628 	case BPF_PROG_TYPE_TRACING:
15629 		switch (env->prog->expected_attach_type) {
15630 		case BPF_TRACE_FENTRY:
15631 		case BPF_TRACE_FEXIT:
15632 			range = retval_range(0, 0);
15633 			break;
15634 		case BPF_TRACE_RAW_TP:
15635 		case BPF_MODIFY_RETURN:
15636 			return 0;
15637 		case BPF_TRACE_ITER:
15638 			break;
15639 		default:
15640 			return -ENOTSUPP;
15641 		}
15642 		break;
15643 	case BPF_PROG_TYPE_SK_LOOKUP:
15644 		range = retval_range(SK_DROP, SK_PASS);
15645 		break;
15646 
15647 	case BPF_PROG_TYPE_LSM:
15648 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15649 			/* Regular BPF_PROG_TYPE_LSM programs can return
15650 			 * any value.
15651 			 */
15652 			return 0;
15653 		}
15654 		if (!env->prog->aux->attach_func_proto->type) {
15655 			/* Make sure programs that attach to void
15656 			 * hooks don't try to modify return value.
15657 			 */
15658 			range = retval_range(1, 1);
15659 		}
15660 		break;
15661 
15662 	case BPF_PROG_TYPE_NETFILTER:
15663 		range = retval_range(NF_DROP, NF_ACCEPT);
15664 		break;
15665 	case BPF_PROG_TYPE_EXT:
15666 		/* freplace program can return anything as its return value
15667 		 * depends on the to-be-replaced kernel func or bpf program.
15668 		 */
15669 	default:
15670 		return 0;
15671 	}
15672 
15673 enforce_retval:
15674 	if (reg->type != SCALAR_VALUE) {
15675 		verbose(env, "%s the register R%d is not a known value (%s)\n",
15676 			exit_ctx, regno, reg_type_str(env, reg->type));
15677 		return -EINVAL;
15678 	}
15679 
15680 	err = mark_chain_precision(env, regno);
15681 	if (err)
15682 		return err;
15683 
15684 	if (!retval_range_within(range, reg)) {
15685 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
15686 		if (!is_subprog &&
15687 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
15688 		    prog_type == BPF_PROG_TYPE_LSM &&
15689 		    !prog->aux->attach_func_proto->type)
15690 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15691 		return -EINVAL;
15692 	}
15693 
15694 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15695 	    tnum_in(enforce_attach_type_range, reg->var_off))
15696 		env->prog->enforce_expected_attach_type = 1;
15697 	return 0;
15698 }
15699 
15700 /* non-recursive DFS pseudo code
15701  * 1  procedure DFS-iterative(G,v):
15702  * 2      label v as discovered
15703  * 3      let S be a stack
15704  * 4      S.push(v)
15705  * 5      while S is not empty
15706  * 6            t <- S.peek()
15707  * 7            if t is what we're looking for:
15708  * 8                return t
15709  * 9            for all edges e in G.adjacentEdges(t) do
15710  * 10               if edge e is already labelled
15711  * 11                   continue with the next edge
15712  * 12               w <- G.adjacentVertex(t,e)
15713  * 13               if vertex w is not discovered and not explored
15714  * 14                   label e as tree-edge
15715  * 15                   label w as discovered
15716  * 16                   S.push(w)
15717  * 17                   continue at 5
15718  * 18               else if vertex w is discovered
15719  * 19                   label e as back-edge
15720  * 20               else
15721  * 21                   // vertex w is explored
15722  * 22                   label e as forward- or cross-edge
15723  * 23           label t as explored
15724  * 24           S.pop()
15725  *
15726  * convention:
15727  * 0x10 - discovered
15728  * 0x11 - discovered and fall-through edge labelled
15729  * 0x12 - discovered and fall-through and branch edges labelled
15730  * 0x20 - explored
15731  */
15732 
15733 enum {
15734 	DISCOVERED = 0x10,
15735 	EXPLORED = 0x20,
15736 	FALLTHROUGH = 1,
15737 	BRANCH = 2,
15738 };
15739 
15740 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15741 {
15742 	env->insn_aux_data[idx].prune_point = true;
15743 }
15744 
15745 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15746 {
15747 	return env->insn_aux_data[insn_idx].prune_point;
15748 }
15749 
15750 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15751 {
15752 	env->insn_aux_data[idx].force_checkpoint = true;
15753 }
15754 
15755 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15756 {
15757 	return env->insn_aux_data[insn_idx].force_checkpoint;
15758 }
15759 
15760 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15761 {
15762 	env->insn_aux_data[idx].calls_callback = true;
15763 }
15764 
15765 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15766 {
15767 	return env->insn_aux_data[insn_idx].calls_callback;
15768 }
15769 
15770 enum {
15771 	DONE_EXPLORING = 0,
15772 	KEEP_EXPLORING = 1,
15773 };
15774 
15775 /* t, w, e - match pseudo-code above:
15776  * t - index of current instruction
15777  * w - next instruction
15778  * e - edge
15779  */
15780 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15781 {
15782 	int *insn_stack = env->cfg.insn_stack;
15783 	int *insn_state = env->cfg.insn_state;
15784 
15785 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15786 		return DONE_EXPLORING;
15787 
15788 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15789 		return DONE_EXPLORING;
15790 
15791 	if (w < 0 || w >= env->prog->len) {
15792 		verbose_linfo(env, t, "%d: ", t);
15793 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15794 		return -EINVAL;
15795 	}
15796 
15797 	if (e == BRANCH) {
15798 		/* mark branch target for state pruning */
15799 		mark_prune_point(env, w);
15800 		mark_jmp_point(env, w);
15801 	}
15802 
15803 	if (insn_state[w] == 0) {
15804 		/* tree-edge */
15805 		insn_state[t] = DISCOVERED | e;
15806 		insn_state[w] = DISCOVERED;
15807 		if (env->cfg.cur_stack >= env->prog->len)
15808 			return -E2BIG;
15809 		insn_stack[env->cfg.cur_stack++] = w;
15810 		return KEEP_EXPLORING;
15811 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15812 		if (env->bpf_capable)
15813 			return DONE_EXPLORING;
15814 		verbose_linfo(env, t, "%d: ", t);
15815 		verbose_linfo(env, w, "%d: ", w);
15816 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15817 		return -EINVAL;
15818 	} else if (insn_state[w] == EXPLORED) {
15819 		/* forward- or cross-edge */
15820 		insn_state[t] = DISCOVERED | e;
15821 	} else {
15822 		verbose(env, "insn state internal bug\n");
15823 		return -EFAULT;
15824 	}
15825 	return DONE_EXPLORING;
15826 }
15827 
15828 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15829 				struct bpf_verifier_env *env,
15830 				bool visit_callee)
15831 {
15832 	int ret, insn_sz;
15833 
15834 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15835 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15836 	if (ret)
15837 		return ret;
15838 
15839 	mark_prune_point(env, t + insn_sz);
15840 	/* when we exit from subprog, we need to record non-linear history */
15841 	mark_jmp_point(env, t + insn_sz);
15842 
15843 	if (visit_callee) {
15844 		mark_prune_point(env, t);
15845 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15846 	}
15847 	return ret;
15848 }
15849 
15850 /* Visits the instruction at index t and returns one of the following:
15851  *  < 0 - an error occurred
15852  *  DONE_EXPLORING - the instruction was fully explored
15853  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15854  */
15855 static int visit_insn(int t, struct bpf_verifier_env *env)
15856 {
15857 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15858 	int ret, off, insn_sz;
15859 
15860 	if (bpf_pseudo_func(insn))
15861 		return visit_func_call_insn(t, insns, env, true);
15862 
15863 	/* All non-branch instructions have a single fall-through edge. */
15864 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15865 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15866 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15867 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15868 	}
15869 
15870 	switch (BPF_OP(insn->code)) {
15871 	case BPF_EXIT:
15872 		return DONE_EXPLORING;
15873 
15874 	case BPF_CALL:
15875 		if (is_async_callback_calling_insn(insn))
15876 			/* Mark this call insn as a prune point to trigger
15877 			 * is_state_visited() check before call itself is
15878 			 * processed by __check_func_call(). Otherwise new
15879 			 * async state will be pushed for further exploration.
15880 			 */
15881 			mark_prune_point(env, t);
15882 		/* For functions that invoke callbacks it is not known how many times
15883 		 * callback would be called. Verifier models callback calling functions
15884 		 * by repeatedly visiting callback bodies and returning to origin call
15885 		 * instruction.
15886 		 * In order to stop such iteration verifier needs to identify when a
15887 		 * state identical some state from a previous iteration is reached.
15888 		 * Check below forces creation of checkpoint before callback calling
15889 		 * instruction to allow search for such identical states.
15890 		 */
15891 		if (is_sync_callback_calling_insn(insn)) {
15892 			mark_calls_callback(env, t);
15893 			mark_force_checkpoint(env, t);
15894 			mark_prune_point(env, t);
15895 			mark_jmp_point(env, t);
15896 		}
15897 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15898 			struct bpf_kfunc_call_arg_meta meta;
15899 
15900 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15901 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15902 				mark_prune_point(env, t);
15903 				/* Checking and saving state checkpoints at iter_next() call
15904 				 * is crucial for fast convergence of open-coded iterator loop
15905 				 * logic, so we need to force it. If we don't do that,
15906 				 * is_state_visited() might skip saving a checkpoint, causing
15907 				 * unnecessarily long sequence of not checkpointed
15908 				 * instructions and jumps, leading to exhaustion of jump
15909 				 * history buffer, and potentially other undesired outcomes.
15910 				 * It is expected that with correct open-coded iterators
15911 				 * convergence will happen quickly, so we don't run a risk of
15912 				 * exhausting memory.
15913 				 */
15914 				mark_force_checkpoint(env, t);
15915 			}
15916 		}
15917 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15918 
15919 	case BPF_JA:
15920 		if (BPF_SRC(insn->code) != BPF_K)
15921 			return -EINVAL;
15922 
15923 		if (BPF_CLASS(insn->code) == BPF_JMP)
15924 			off = insn->off;
15925 		else
15926 			off = insn->imm;
15927 
15928 		/* unconditional jump with single edge */
15929 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15930 		if (ret)
15931 			return ret;
15932 
15933 		mark_prune_point(env, t + off + 1);
15934 		mark_jmp_point(env, t + off + 1);
15935 
15936 		return ret;
15937 
15938 	default:
15939 		/* conditional jump with two edges */
15940 		mark_prune_point(env, t);
15941 		if (is_may_goto_insn(insn))
15942 			mark_force_checkpoint(env, t);
15943 
15944 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15945 		if (ret)
15946 			return ret;
15947 
15948 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15949 	}
15950 }
15951 
15952 /* non-recursive depth-first-search to detect loops in BPF program
15953  * loop == back-edge in directed graph
15954  */
15955 static int check_cfg(struct bpf_verifier_env *env)
15956 {
15957 	int insn_cnt = env->prog->len;
15958 	int *insn_stack, *insn_state;
15959 	int ex_insn_beg, i, ret = 0;
15960 	bool ex_done = false;
15961 
15962 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15963 	if (!insn_state)
15964 		return -ENOMEM;
15965 
15966 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15967 	if (!insn_stack) {
15968 		kvfree(insn_state);
15969 		return -ENOMEM;
15970 	}
15971 
15972 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15973 	insn_stack[0] = 0; /* 0 is the first instruction */
15974 	env->cfg.cur_stack = 1;
15975 
15976 walk_cfg:
15977 	while (env->cfg.cur_stack > 0) {
15978 		int t = insn_stack[env->cfg.cur_stack - 1];
15979 
15980 		ret = visit_insn(t, env);
15981 		switch (ret) {
15982 		case DONE_EXPLORING:
15983 			insn_state[t] = EXPLORED;
15984 			env->cfg.cur_stack--;
15985 			break;
15986 		case KEEP_EXPLORING:
15987 			break;
15988 		default:
15989 			if (ret > 0) {
15990 				verbose(env, "visit_insn internal bug\n");
15991 				ret = -EFAULT;
15992 			}
15993 			goto err_free;
15994 		}
15995 	}
15996 
15997 	if (env->cfg.cur_stack < 0) {
15998 		verbose(env, "pop stack internal bug\n");
15999 		ret = -EFAULT;
16000 		goto err_free;
16001 	}
16002 
16003 	if (env->exception_callback_subprog && !ex_done) {
16004 		ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
16005 
16006 		insn_state[ex_insn_beg] = DISCOVERED;
16007 		insn_stack[0] = ex_insn_beg;
16008 		env->cfg.cur_stack = 1;
16009 		ex_done = true;
16010 		goto walk_cfg;
16011 	}
16012 
16013 	for (i = 0; i < insn_cnt; i++) {
16014 		struct bpf_insn *insn = &env->prog->insnsi[i];
16015 
16016 		if (insn_state[i] != EXPLORED) {
16017 			verbose(env, "unreachable insn %d\n", i);
16018 			ret = -EINVAL;
16019 			goto err_free;
16020 		}
16021 		if (bpf_is_ldimm64(insn)) {
16022 			if (insn_state[i + 1] != 0) {
16023 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
16024 				ret = -EINVAL;
16025 				goto err_free;
16026 			}
16027 			i++; /* skip second half of ldimm64 */
16028 		}
16029 	}
16030 	ret = 0; /* cfg looks good */
16031 
16032 err_free:
16033 	kvfree(insn_state);
16034 	kvfree(insn_stack);
16035 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
16036 	return ret;
16037 }
16038 
16039 static int check_abnormal_return(struct bpf_verifier_env *env)
16040 {
16041 	int i;
16042 
16043 	for (i = 1; i < env->subprog_cnt; i++) {
16044 		if (env->subprog_info[i].has_ld_abs) {
16045 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
16046 			return -EINVAL;
16047 		}
16048 		if (env->subprog_info[i].has_tail_call) {
16049 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
16050 			return -EINVAL;
16051 		}
16052 	}
16053 	return 0;
16054 }
16055 
16056 /* The minimum supported BTF func info size */
16057 #define MIN_BPF_FUNCINFO_SIZE	8
16058 #define MAX_FUNCINFO_REC_SIZE	252
16059 
16060 static int check_btf_func_early(struct bpf_verifier_env *env,
16061 				const union bpf_attr *attr,
16062 				bpfptr_t uattr)
16063 {
16064 	u32 krec_size = sizeof(struct bpf_func_info);
16065 	const struct btf_type *type, *func_proto;
16066 	u32 i, nfuncs, urec_size, min_size;
16067 	struct bpf_func_info *krecord;
16068 	struct bpf_prog *prog;
16069 	const struct btf *btf;
16070 	u32 prev_offset = 0;
16071 	bpfptr_t urecord;
16072 	int ret = -ENOMEM;
16073 
16074 	nfuncs = attr->func_info_cnt;
16075 	if (!nfuncs) {
16076 		if (check_abnormal_return(env))
16077 			return -EINVAL;
16078 		return 0;
16079 	}
16080 
16081 	urec_size = attr->func_info_rec_size;
16082 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
16083 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
16084 	    urec_size % sizeof(u32)) {
16085 		verbose(env, "invalid func info rec size %u\n", urec_size);
16086 		return -EINVAL;
16087 	}
16088 
16089 	prog = env->prog;
16090 	btf = prog->aux->btf;
16091 
16092 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16093 	min_size = min_t(u32, krec_size, urec_size);
16094 
16095 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
16096 	if (!krecord)
16097 		return -ENOMEM;
16098 
16099 	for (i = 0; i < nfuncs; i++) {
16100 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
16101 		if (ret) {
16102 			if (ret == -E2BIG) {
16103 				verbose(env, "nonzero tailing record in func info");
16104 				/* set the size kernel expects so loader can zero
16105 				 * out the rest of the record.
16106 				 */
16107 				if (copy_to_bpfptr_offset(uattr,
16108 							  offsetof(union bpf_attr, func_info_rec_size),
16109 							  &min_size, sizeof(min_size)))
16110 					ret = -EFAULT;
16111 			}
16112 			goto err_free;
16113 		}
16114 
16115 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
16116 			ret = -EFAULT;
16117 			goto err_free;
16118 		}
16119 
16120 		/* check insn_off */
16121 		ret = -EINVAL;
16122 		if (i == 0) {
16123 			if (krecord[i].insn_off) {
16124 				verbose(env,
16125 					"nonzero insn_off %u for the first func info record",
16126 					krecord[i].insn_off);
16127 				goto err_free;
16128 			}
16129 		} else if (krecord[i].insn_off <= prev_offset) {
16130 			verbose(env,
16131 				"same or smaller insn offset (%u) than previous func info record (%u)",
16132 				krecord[i].insn_off, prev_offset);
16133 			goto err_free;
16134 		}
16135 
16136 		/* check type_id */
16137 		type = btf_type_by_id(btf, krecord[i].type_id);
16138 		if (!type || !btf_type_is_func(type)) {
16139 			verbose(env, "invalid type id %d in func info",
16140 				krecord[i].type_id);
16141 			goto err_free;
16142 		}
16143 
16144 		func_proto = btf_type_by_id(btf, type->type);
16145 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
16146 			/* btf_func_check() already verified it during BTF load */
16147 			goto err_free;
16148 
16149 		prev_offset = krecord[i].insn_off;
16150 		bpfptr_add(&urecord, urec_size);
16151 	}
16152 
16153 	prog->aux->func_info = krecord;
16154 	prog->aux->func_info_cnt = nfuncs;
16155 	return 0;
16156 
16157 err_free:
16158 	kvfree(krecord);
16159 	return ret;
16160 }
16161 
16162 static int check_btf_func(struct bpf_verifier_env *env,
16163 			  const union bpf_attr *attr,
16164 			  bpfptr_t uattr)
16165 {
16166 	const struct btf_type *type, *func_proto, *ret_type;
16167 	u32 i, nfuncs, urec_size;
16168 	struct bpf_func_info *krecord;
16169 	struct bpf_func_info_aux *info_aux = NULL;
16170 	struct bpf_prog *prog;
16171 	const struct btf *btf;
16172 	bpfptr_t urecord;
16173 	bool scalar_return;
16174 	int ret = -ENOMEM;
16175 
16176 	nfuncs = attr->func_info_cnt;
16177 	if (!nfuncs) {
16178 		if (check_abnormal_return(env))
16179 			return -EINVAL;
16180 		return 0;
16181 	}
16182 	if (nfuncs != env->subprog_cnt) {
16183 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
16184 		return -EINVAL;
16185 	}
16186 
16187 	urec_size = attr->func_info_rec_size;
16188 
16189 	prog = env->prog;
16190 	btf = prog->aux->btf;
16191 
16192 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16193 
16194 	krecord = prog->aux->func_info;
16195 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
16196 	if (!info_aux)
16197 		return -ENOMEM;
16198 
16199 	for (i = 0; i < nfuncs; i++) {
16200 		/* check insn_off */
16201 		ret = -EINVAL;
16202 
16203 		if (env->subprog_info[i].start != krecord[i].insn_off) {
16204 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
16205 			goto err_free;
16206 		}
16207 
16208 		/* Already checked type_id */
16209 		type = btf_type_by_id(btf, krecord[i].type_id);
16210 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
16211 		/* Already checked func_proto */
16212 		func_proto = btf_type_by_id(btf, type->type);
16213 
16214 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
16215 		scalar_return =
16216 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
16217 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
16218 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
16219 			goto err_free;
16220 		}
16221 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
16222 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
16223 			goto err_free;
16224 		}
16225 
16226 		bpfptr_add(&urecord, urec_size);
16227 	}
16228 
16229 	prog->aux->func_info_aux = info_aux;
16230 	return 0;
16231 
16232 err_free:
16233 	kfree(info_aux);
16234 	return ret;
16235 }
16236 
16237 static void adjust_btf_func(struct bpf_verifier_env *env)
16238 {
16239 	struct bpf_prog_aux *aux = env->prog->aux;
16240 	int i;
16241 
16242 	if (!aux->func_info)
16243 		return;
16244 
16245 	/* func_info is not available for hidden subprogs */
16246 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
16247 		aux->func_info[i].insn_off = env->subprog_info[i].start;
16248 }
16249 
16250 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
16251 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
16252 
16253 static int check_btf_line(struct bpf_verifier_env *env,
16254 			  const union bpf_attr *attr,
16255 			  bpfptr_t uattr)
16256 {
16257 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
16258 	struct bpf_subprog_info *sub;
16259 	struct bpf_line_info *linfo;
16260 	struct bpf_prog *prog;
16261 	const struct btf *btf;
16262 	bpfptr_t ulinfo;
16263 	int err;
16264 
16265 	nr_linfo = attr->line_info_cnt;
16266 	if (!nr_linfo)
16267 		return 0;
16268 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
16269 		return -EINVAL;
16270 
16271 	rec_size = attr->line_info_rec_size;
16272 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
16273 	    rec_size > MAX_LINEINFO_REC_SIZE ||
16274 	    rec_size & (sizeof(u32) - 1))
16275 		return -EINVAL;
16276 
16277 	/* Need to zero it in case the userspace may
16278 	 * pass in a smaller bpf_line_info object.
16279 	 */
16280 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
16281 			 GFP_KERNEL | __GFP_NOWARN);
16282 	if (!linfo)
16283 		return -ENOMEM;
16284 
16285 	prog = env->prog;
16286 	btf = prog->aux->btf;
16287 
16288 	s = 0;
16289 	sub = env->subprog_info;
16290 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
16291 	expected_size = sizeof(struct bpf_line_info);
16292 	ncopy = min_t(u32, expected_size, rec_size);
16293 	for (i = 0; i < nr_linfo; i++) {
16294 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
16295 		if (err) {
16296 			if (err == -E2BIG) {
16297 				verbose(env, "nonzero tailing record in line_info");
16298 				if (copy_to_bpfptr_offset(uattr,
16299 							  offsetof(union bpf_attr, line_info_rec_size),
16300 							  &expected_size, sizeof(expected_size)))
16301 					err = -EFAULT;
16302 			}
16303 			goto err_free;
16304 		}
16305 
16306 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
16307 			err = -EFAULT;
16308 			goto err_free;
16309 		}
16310 
16311 		/*
16312 		 * Check insn_off to ensure
16313 		 * 1) strictly increasing AND
16314 		 * 2) bounded by prog->len
16315 		 *
16316 		 * The linfo[0].insn_off == 0 check logically falls into
16317 		 * the later "missing bpf_line_info for func..." case
16318 		 * because the first linfo[0].insn_off must be the
16319 		 * first sub also and the first sub must have
16320 		 * subprog_info[0].start == 0.
16321 		 */
16322 		if ((i && linfo[i].insn_off <= prev_offset) ||
16323 		    linfo[i].insn_off >= prog->len) {
16324 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
16325 				i, linfo[i].insn_off, prev_offset,
16326 				prog->len);
16327 			err = -EINVAL;
16328 			goto err_free;
16329 		}
16330 
16331 		if (!prog->insnsi[linfo[i].insn_off].code) {
16332 			verbose(env,
16333 				"Invalid insn code at line_info[%u].insn_off\n",
16334 				i);
16335 			err = -EINVAL;
16336 			goto err_free;
16337 		}
16338 
16339 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
16340 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
16341 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
16342 			err = -EINVAL;
16343 			goto err_free;
16344 		}
16345 
16346 		if (s != env->subprog_cnt) {
16347 			if (linfo[i].insn_off == sub[s].start) {
16348 				sub[s].linfo_idx = i;
16349 				s++;
16350 			} else if (sub[s].start < linfo[i].insn_off) {
16351 				verbose(env, "missing bpf_line_info for func#%u\n", s);
16352 				err = -EINVAL;
16353 				goto err_free;
16354 			}
16355 		}
16356 
16357 		prev_offset = linfo[i].insn_off;
16358 		bpfptr_add(&ulinfo, rec_size);
16359 	}
16360 
16361 	if (s != env->subprog_cnt) {
16362 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
16363 			env->subprog_cnt - s, s);
16364 		err = -EINVAL;
16365 		goto err_free;
16366 	}
16367 
16368 	prog->aux->linfo = linfo;
16369 	prog->aux->nr_linfo = nr_linfo;
16370 
16371 	return 0;
16372 
16373 err_free:
16374 	kvfree(linfo);
16375 	return err;
16376 }
16377 
16378 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
16379 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
16380 
16381 static int check_core_relo(struct bpf_verifier_env *env,
16382 			   const union bpf_attr *attr,
16383 			   bpfptr_t uattr)
16384 {
16385 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16386 	struct bpf_core_relo core_relo = {};
16387 	struct bpf_prog *prog = env->prog;
16388 	const struct btf *btf = prog->aux->btf;
16389 	struct bpf_core_ctx ctx = {
16390 		.log = &env->log,
16391 		.btf = btf,
16392 	};
16393 	bpfptr_t u_core_relo;
16394 	int err;
16395 
16396 	nr_core_relo = attr->core_relo_cnt;
16397 	if (!nr_core_relo)
16398 		return 0;
16399 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16400 		return -EINVAL;
16401 
16402 	rec_size = attr->core_relo_rec_size;
16403 	if (rec_size < MIN_CORE_RELO_SIZE ||
16404 	    rec_size > MAX_CORE_RELO_SIZE ||
16405 	    rec_size % sizeof(u32))
16406 		return -EINVAL;
16407 
16408 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16409 	expected_size = sizeof(struct bpf_core_relo);
16410 	ncopy = min_t(u32, expected_size, rec_size);
16411 
16412 	/* Unlike func_info and line_info, copy and apply each CO-RE
16413 	 * relocation record one at a time.
16414 	 */
16415 	for (i = 0; i < nr_core_relo; i++) {
16416 		/* future proofing when sizeof(bpf_core_relo) changes */
16417 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16418 		if (err) {
16419 			if (err == -E2BIG) {
16420 				verbose(env, "nonzero tailing record in core_relo");
16421 				if (copy_to_bpfptr_offset(uattr,
16422 							  offsetof(union bpf_attr, core_relo_rec_size),
16423 							  &expected_size, sizeof(expected_size)))
16424 					err = -EFAULT;
16425 			}
16426 			break;
16427 		}
16428 
16429 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16430 			err = -EFAULT;
16431 			break;
16432 		}
16433 
16434 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16435 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16436 				i, core_relo.insn_off, prog->len);
16437 			err = -EINVAL;
16438 			break;
16439 		}
16440 
16441 		err = bpf_core_apply(&ctx, &core_relo, i,
16442 				     &prog->insnsi[core_relo.insn_off / 8]);
16443 		if (err)
16444 			break;
16445 		bpfptr_add(&u_core_relo, rec_size);
16446 	}
16447 	return err;
16448 }
16449 
16450 static int check_btf_info_early(struct bpf_verifier_env *env,
16451 				const union bpf_attr *attr,
16452 				bpfptr_t uattr)
16453 {
16454 	struct btf *btf;
16455 	int err;
16456 
16457 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
16458 		if (check_abnormal_return(env))
16459 			return -EINVAL;
16460 		return 0;
16461 	}
16462 
16463 	btf = btf_get_by_fd(attr->prog_btf_fd);
16464 	if (IS_ERR(btf))
16465 		return PTR_ERR(btf);
16466 	if (btf_is_kernel(btf)) {
16467 		btf_put(btf);
16468 		return -EACCES;
16469 	}
16470 	env->prog->aux->btf = btf;
16471 
16472 	err = check_btf_func_early(env, attr, uattr);
16473 	if (err)
16474 		return err;
16475 	return 0;
16476 }
16477 
16478 static int check_btf_info(struct bpf_verifier_env *env,
16479 			  const union bpf_attr *attr,
16480 			  bpfptr_t uattr)
16481 {
16482 	int err;
16483 
16484 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
16485 		if (check_abnormal_return(env))
16486 			return -EINVAL;
16487 		return 0;
16488 	}
16489 
16490 	err = check_btf_func(env, attr, uattr);
16491 	if (err)
16492 		return err;
16493 
16494 	err = check_btf_line(env, attr, uattr);
16495 	if (err)
16496 		return err;
16497 
16498 	err = check_core_relo(env, attr, uattr);
16499 	if (err)
16500 		return err;
16501 
16502 	return 0;
16503 }
16504 
16505 /* check %cur's range satisfies %old's */
16506 static bool range_within(const struct bpf_reg_state *old,
16507 			 const struct bpf_reg_state *cur)
16508 {
16509 	return old->umin_value <= cur->umin_value &&
16510 	       old->umax_value >= cur->umax_value &&
16511 	       old->smin_value <= cur->smin_value &&
16512 	       old->smax_value >= cur->smax_value &&
16513 	       old->u32_min_value <= cur->u32_min_value &&
16514 	       old->u32_max_value >= cur->u32_max_value &&
16515 	       old->s32_min_value <= cur->s32_min_value &&
16516 	       old->s32_max_value >= cur->s32_max_value;
16517 }
16518 
16519 /* If in the old state two registers had the same id, then they need to have
16520  * the same id in the new state as well.  But that id could be different from
16521  * the old state, so we need to track the mapping from old to new ids.
16522  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16523  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
16524  * regs with a different old id could still have new id 9, we don't care about
16525  * that.
16526  * So we look through our idmap to see if this old id has been seen before.  If
16527  * so, we require the new id to match; otherwise, we add the id pair to the map.
16528  */
16529 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16530 {
16531 	struct bpf_id_pair *map = idmap->map;
16532 	unsigned int i;
16533 
16534 	/* either both IDs should be set or both should be zero */
16535 	if (!!old_id != !!cur_id)
16536 		return false;
16537 
16538 	if (old_id == 0) /* cur_id == 0 as well */
16539 		return true;
16540 
16541 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
16542 		if (!map[i].old) {
16543 			/* Reached an empty slot; haven't seen this id before */
16544 			map[i].old = old_id;
16545 			map[i].cur = cur_id;
16546 			return true;
16547 		}
16548 		if (map[i].old == old_id)
16549 			return map[i].cur == cur_id;
16550 		if (map[i].cur == cur_id)
16551 			return false;
16552 	}
16553 	/* We ran out of idmap slots, which should be impossible */
16554 	WARN_ON_ONCE(1);
16555 	return false;
16556 }
16557 
16558 /* Similar to check_ids(), but allocate a unique temporary ID
16559  * for 'old_id' or 'cur_id' of zero.
16560  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16561  */
16562 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16563 {
16564 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16565 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16566 
16567 	return check_ids(old_id, cur_id, idmap);
16568 }
16569 
16570 static void clean_func_state(struct bpf_verifier_env *env,
16571 			     struct bpf_func_state *st)
16572 {
16573 	enum bpf_reg_liveness live;
16574 	int i, j;
16575 
16576 	for (i = 0; i < BPF_REG_FP; i++) {
16577 		live = st->regs[i].live;
16578 		/* liveness must not touch this register anymore */
16579 		st->regs[i].live |= REG_LIVE_DONE;
16580 		if (!(live & REG_LIVE_READ))
16581 			/* since the register is unused, clear its state
16582 			 * to make further comparison simpler
16583 			 */
16584 			__mark_reg_not_init(env, &st->regs[i]);
16585 	}
16586 
16587 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16588 		live = st->stack[i].spilled_ptr.live;
16589 		/* liveness must not touch this stack slot anymore */
16590 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16591 		if (!(live & REG_LIVE_READ)) {
16592 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16593 			for (j = 0; j < BPF_REG_SIZE; j++)
16594 				st->stack[i].slot_type[j] = STACK_INVALID;
16595 		}
16596 	}
16597 }
16598 
16599 static void clean_verifier_state(struct bpf_verifier_env *env,
16600 				 struct bpf_verifier_state *st)
16601 {
16602 	int i;
16603 
16604 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16605 		/* all regs in this state in all frames were already marked */
16606 		return;
16607 
16608 	for (i = 0; i <= st->curframe; i++)
16609 		clean_func_state(env, st->frame[i]);
16610 }
16611 
16612 /* the parentage chains form a tree.
16613  * the verifier states are added to state lists at given insn and
16614  * pushed into state stack for future exploration.
16615  * when the verifier reaches bpf_exit insn some of the verifer states
16616  * stored in the state lists have their final liveness state already,
16617  * but a lot of states will get revised from liveness point of view when
16618  * the verifier explores other branches.
16619  * Example:
16620  * 1: r0 = 1
16621  * 2: if r1 == 100 goto pc+1
16622  * 3: r0 = 2
16623  * 4: exit
16624  * when the verifier reaches exit insn the register r0 in the state list of
16625  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16626  * of insn 2 and goes exploring further. At the insn 4 it will walk the
16627  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16628  *
16629  * Since the verifier pushes the branch states as it sees them while exploring
16630  * the program the condition of walking the branch instruction for the second
16631  * time means that all states below this branch were already explored and
16632  * their final liveness marks are already propagated.
16633  * Hence when the verifier completes the search of state list in is_state_visited()
16634  * we can call this clean_live_states() function to mark all liveness states
16635  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16636  * will not be used.
16637  * This function also clears the registers and stack for states that !READ
16638  * to simplify state merging.
16639  *
16640  * Important note here that walking the same branch instruction in the callee
16641  * doesn't meant that the states are DONE. The verifier has to compare
16642  * the callsites
16643  */
16644 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16645 			      struct bpf_verifier_state *cur)
16646 {
16647 	struct bpf_verifier_state_list *sl;
16648 
16649 	sl = *explored_state(env, insn);
16650 	while (sl) {
16651 		if (sl->state.branches)
16652 			goto next;
16653 		if (sl->state.insn_idx != insn ||
16654 		    !same_callsites(&sl->state, cur))
16655 			goto next;
16656 		clean_verifier_state(env, &sl->state);
16657 next:
16658 		sl = sl->next;
16659 	}
16660 }
16661 
16662 static bool regs_exact(const struct bpf_reg_state *rold,
16663 		       const struct bpf_reg_state *rcur,
16664 		       struct bpf_idmap *idmap)
16665 {
16666 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16667 	       check_ids(rold->id, rcur->id, idmap) &&
16668 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16669 }
16670 
16671 enum exact_level {
16672 	NOT_EXACT,
16673 	EXACT,
16674 	RANGE_WITHIN
16675 };
16676 
16677 /* Returns true if (rold safe implies rcur safe) */
16678 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16679 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
16680 		    enum exact_level exact)
16681 {
16682 	if (exact == EXACT)
16683 		return regs_exact(rold, rcur, idmap);
16684 
16685 	if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
16686 		/* explored state didn't use this */
16687 		return true;
16688 	if (rold->type == NOT_INIT) {
16689 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
16690 			/* explored state can't have used this */
16691 			return true;
16692 	}
16693 
16694 	/* Enforce that register types have to match exactly, including their
16695 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16696 	 * rule.
16697 	 *
16698 	 * One can make a point that using a pointer register as unbounded
16699 	 * SCALAR would be technically acceptable, but this could lead to
16700 	 * pointer leaks because scalars are allowed to leak while pointers
16701 	 * are not. We could make this safe in special cases if root is
16702 	 * calling us, but it's probably not worth the hassle.
16703 	 *
16704 	 * Also, register types that are *not* MAYBE_NULL could technically be
16705 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16706 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16707 	 * to the same map).
16708 	 * However, if the old MAYBE_NULL register then got NULL checked,
16709 	 * doing so could have affected others with the same id, and we can't
16710 	 * check for that because we lost the id when we converted to
16711 	 * a non-MAYBE_NULL variant.
16712 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16713 	 * non-MAYBE_NULL registers as well.
16714 	 */
16715 	if (rold->type != rcur->type)
16716 		return false;
16717 
16718 	switch (base_type(rold->type)) {
16719 	case SCALAR_VALUE:
16720 		if (env->explore_alu_limits) {
16721 			/* explore_alu_limits disables tnum_in() and range_within()
16722 			 * logic and requires everything to be strict
16723 			 */
16724 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16725 			       check_scalar_ids(rold->id, rcur->id, idmap);
16726 		}
16727 		if (!rold->precise && exact == NOT_EXACT)
16728 			return true;
16729 		/* Why check_ids() for scalar registers?
16730 		 *
16731 		 * Consider the following BPF code:
16732 		 *   1: r6 = ... unbound scalar, ID=a ...
16733 		 *   2: r7 = ... unbound scalar, ID=b ...
16734 		 *   3: if (r6 > r7) goto +1
16735 		 *   4: r6 = r7
16736 		 *   5: if (r6 > X) goto ...
16737 		 *   6: ... memory operation using r7 ...
16738 		 *
16739 		 * First verification path is [1-6]:
16740 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16741 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16742 		 *   r7 <= X, because r6 and r7 share same id.
16743 		 * Next verification path is [1-4, 6].
16744 		 *
16745 		 * Instruction (6) would be reached in two states:
16746 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16747 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16748 		 *
16749 		 * Use check_ids() to distinguish these states.
16750 		 * ---
16751 		 * Also verify that new value satisfies old value range knowledge.
16752 		 */
16753 		return range_within(rold, rcur) &&
16754 		       tnum_in(rold->var_off, rcur->var_off) &&
16755 		       check_scalar_ids(rold->id, rcur->id, idmap);
16756 	case PTR_TO_MAP_KEY:
16757 	case PTR_TO_MAP_VALUE:
16758 	case PTR_TO_MEM:
16759 	case PTR_TO_BUF:
16760 	case PTR_TO_TP_BUFFER:
16761 		/* If the new min/max/var_off satisfy the old ones and
16762 		 * everything else matches, we are OK.
16763 		 */
16764 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16765 		       range_within(rold, rcur) &&
16766 		       tnum_in(rold->var_off, rcur->var_off) &&
16767 		       check_ids(rold->id, rcur->id, idmap) &&
16768 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16769 	case PTR_TO_PACKET_META:
16770 	case PTR_TO_PACKET:
16771 		/* We must have at least as much range as the old ptr
16772 		 * did, so that any accesses which were safe before are
16773 		 * still safe.  This is true even if old range < old off,
16774 		 * since someone could have accessed through (ptr - k), or
16775 		 * even done ptr -= k in a register, to get a safe access.
16776 		 */
16777 		if (rold->range > rcur->range)
16778 			return false;
16779 		/* If the offsets don't match, we can't trust our alignment;
16780 		 * nor can we be sure that we won't fall out of range.
16781 		 */
16782 		if (rold->off != rcur->off)
16783 			return false;
16784 		/* id relations must be preserved */
16785 		if (!check_ids(rold->id, rcur->id, idmap))
16786 			return false;
16787 		/* new val must satisfy old val knowledge */
16788 		return range_within(rold, rcur) &&
16789 		       tnum_in(rold->var_off, rcur->var_off);
16790 	case PTR_TO_STACK:
16791 		/* two stack pointers are equal only if they're pointing to
16792 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16793 		 */
16794 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16795 	case PTR_TO_ARENA:
16796 		return true;
16797 	default:
16798 		return regs_exact(rold, rcur, idmap);
16799 	}
16800 }
16801 
16802 static struct bpf_reg_state unbound_reg;
16803 
16804 static __init int unbound_reg_init(void)
16805 {
16806 	__mark_reg_unknown_imprecise(&unbound_reg);
16807 	unbound_reg.live |= REG_LIVE_READ;
16808 	return 0;
16809 }
16810 late_initcall(unbound_reg_init);
16811 
16812 static bool is_stack_all_misc(struct bpf_verifier_env *env,
16813 			      struct bpf_stack_state *stack)
16814 {
16815 	u32 i;
16816 
16817 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
16818 		if ((stack->slot_type[i] == STACK_MISC) ||
16819 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
16820 			continue;
16821 		return false;
16822 	}
16823 
16824 	return true;
16825 }
16826 
16827 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
16828 						  struct bpf_stack_state *stack)
16829 {
16830 	if (is_spilled_scalar_reg64(stack))
16831 		return &stack->spilled_ptr;
16832 
16833 	if (is_stack_all_misc(env, stack))
16834 		return &unbound_reg;
16835 
16836 	return NULL;
16837 }
16838 
16839 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16840 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
16841 		      enum exact_level exact)
16842 {
16843 	int i, spi;
16844 
16845 	/* walk slots of the explored stack and ignore any additional
16846 	 * slots in the current stack, since explored(safe) state
16847 	 * didn't use them
16848 	 */
16849 	for (i = 0; i < old->allocated_stack; i++) {
16850 		struct bpf_reg_state *old_reg, *cur_reg;
16851 
16852 		spi = i / BPF_REG_SIZE;
16853 
16854 		if (exact != NOT_EXACT &&
16855 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16856 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16857 			return false;
16858 
16859 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
16860 		    && exact == NOT_EXACT) {
16861 			i += BPF_REG_SIZE - 1;
16862 			/* explored state didn't use this */
16863 			continue;
16864 		}
16865 
16866 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16867 			continue;
16868 
16869 		if (env->allow_uninit_stack &&
16870 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16871 			continue;
16872 
16873 		/* explored stack has more populated slots than current stack
16874 		 * and these slots were used
16875 		 */
16876 		if (i >= cur->allocated_stack)
16877 			return false;
16878 
16879 		/* 64-bit scalar spill vs all slots MISC and vice versa.
16880 		 * Load from all slots MISC produces unbound scalar.
16881 		 * Construct a fake register for such stack and call
16882 		 * regsafe() to ensure scalar ids are compared.
16883 		 */
16884 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
16885 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
16886 		if (old_reg && cur_reg) {
16887 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
16888 				return false;
16889 			i += BPF_REG_SIZE - 1;
16890 			continue;
16891 		}
16892 
16893 		/* if old state was safe with misc data in the stack
16894 		 * it will be safe with zero-initialized stack.
16895 		 * The opposite is not true
16896 		 */
16897 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16898 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16899 			continue;
16900 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16901 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16902 			/* Ex: old explored (safe) state has STACK_SPILL in
16903 			 * this stack slot, but current has STACK_MISC ->
16904 			 * this verifier states are not equivalent,
16905 			 * return false to continue verification of this path
16906 			 */
16907 			return false;
16908 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16909 			continue;
16910 		/* Both old and cur are having same slot_type */
16911 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16912 		case STACK_SPILL:
16913 			/* when explored and current stack slot are both storing
16914 			 * spilled registers, check that stored pointers types
16915 			 * are the same as well.
16916 			 * Ex: explored safe path could have stored
16917 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16918 			 * but current path has stored:
16919 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16920 			 * such verifier states are not equivalent.
16921 			 * return false to continue verification of this path
16922 			 */
16923 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16924 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16925 				return false;
16926 			break;
16927 		case STACK_DYNPTR:
16928 			old_reg = &old->stack[spi].spilled_ptr;
16929 			cur_reg = &cur->stack[spi].spilled_ptr;
16930 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16931 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16932 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16933 				return false;
16934 			break;
16935 		case STACK_ITER:
16936 			old_reg = &old->stack[spi].spilled_ptr;
16937 			cur_reg = &cur->stack[spi].spilled_ptr;
16938 			/* iter.depth is not compared between states as it
16939 			 * doesn't matter for correctness and would otherwise
16940 			 * prevent convergence; we maintain it only to prevent
16941 			 * infinite loop check triggering, see
16942 			 * iter_active_depths_differ()
16943 			 */
16944 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16945 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16946 			    old_reg->iter.state != cur_reg->iter.state ||
16947 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16948 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16949 				return false;
16950 			break;
16951 		case STACK_MISC:
16952 		case STACK_ZERO:
16953 		case STACK_INVALID:
16954 			continue;
16955 		/* Ensure that new unhandled slot types return false by default */
16956 		default:
16957 			return false;
16958 		}
16959 	}
16960 	return true;
16961 }
16962 
16963 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16964 		    struct bpf_idmap *idmap)
16965 {
16966 	int i;
16967 
16968 	if (old->acquired_refs != cur->acquired_refs)
16969 		return false;
16970 
16971 	for (i = 0; i < old->acquired_refs; i++) {
16972 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16973 			return false;
16974 	}
16975 
16976 	return true;
16977 }
16978 
16979 /* compare two verifier states
16980  *
16981  * all states stored in state_list are known to be valid, since
16982  * verifier reached 'bpf_exit' instruction through them
16983  *
16984  * this function is called when verifier exploring different branches of
16985  * execution popped from the state stack. If it sees an old state that has
16986  * more strict register state and more strict stack state then this execution
16987  * branch doesn't need to be explored further, since verifier already
16988  * concluded that more strict state leads to valid finish.
16989  *
16990  * Therefore two states are equivalent if register state is more conservative
16991  * and explored stack state is more conservative than the current one.
16992  * Example:
16993  *       explored                   current
16994  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16995  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16996  *
16997  * In other words if current stack state (one being explored) has more
16998  * valid slots than old one that already passed validation, it means
16999  * the verifier can stop exploring and conclude that current state is valid too
17000  *
17001  * Similarly with registers. If explored state has register type as invalid
17002  * whereas register type in current state is meaningful, it means that
17003  * the current state will reach 'bpf_exit' instruction safely
17004  */
17005 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
17006 			      struct bpf_func_state *cur, enum exact_level exact)
17007 {
17008 	int i;
17009 
17010 	if (old->callback_depth > cur->callback_depth)
17011 		return false;
17012 
17013 	for (i = 0; i < MAX_BPF_REG; i++)
17014 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
17015 			     &env->idmap_scratch, exact))
17016 			return false;
17017 
17018 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
17019 		return false;
17020 
17021 	if (!refsafe(old, cur, &env->idmap_scratch))
17022 		return false;
17023 
17024 	return true;
17025 }
17026 
17027 static void reset_idmap_scratch(struct bpf_verifier_env *env)
17028 {
17029 	env->idmap_scratch.tmp_id_gen = env->id_gen;
17030 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
17031 }
17032 
17033 static bool states_equal(struct bpf_verifier_env *env,
17034 			 struct bpf_verifier_state *old,
17035 			 struct bpf_verifier_state *cur,
17036 			 enum exact_level exact)
17037 {
17038 	int i;
17039 
17040 	if (old->curframe != cur->curframe)
17041 		return false;
17042 
17043 	reset_idmap_scratch(env);
17044 
17045 	/* Verification state from speculative execution simulation
17046 	 * must never prune a non-speculative execution one.
17047 	 */
17048 	if (old->speculative && !cur->speculative)
17049 		return false;
17050 
17051 	if (old->active_lock.ptr != cur->active_lock.ptr)
17052 		return false;
17053 
17054 	/* Old and cur active_lock's have to be either both present
17055 	 * or both absent.
17056 	 */
17057 	if (!!old->active_lock.id != !!cur->active_lock.id)
17058 		return false;
17059 
17060 	if (old->active_lock.id &&
17061 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
17062 		return false;
17063 
17064 	if (old->active_rcu_lock != cur->active_rcu_lock)
17065 		return false;
17066 
17067 	if (old->active_preempt_lock != cur->active_preempt_lock)
17068 		return false;
17069 
17070 	if (old->in_sleepable != cur->in_sleepable)
17071 		return false;
17072 
17073 	/* for states to be equal callsites have to be the same
17074 	 * and all frame states need to be equivalent
17075 	 */
17076 	for (i = 0; i <= old->curframe; i++) {
17077 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
17078 			return false;
17079 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
17080 			return false;
17081 	}
17082 	return true;
17083 }
17084 
17085 /* Return 0 if no propagation happened. Return negative error code if error
17086  * happened. Otherwise, return the propagated bit.
17087  */
17088 static int propagate_liveness_reg(struct bpf_verifier_env *env,
17089 				  struct bpf_reg_state *reg,
17090 				  struct bpf_reg_state *parent_reg)
17091 {
17092 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
17093 	u8 flag = reg->live & REG_LIVE_READ;
17094 	int err;
17095 
17096 	/* When comes here, read flags of PARENT_REG or REG could be any of
17097 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
17098 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
17099 	 */
17100 	if (parent_flag == REG_LIVE_READ64 ||
17101 	    /* Or if there is no read flag from REG. */
17102 	    !flag ||
17103 	    /* Or if the read flag from REG is the same as PARENT_REG. */
17104 	    parent_flag == flag)
17105 		return 0;
17106 
17107 	err = mark_reg_read(env, reg, parent_reg, flag);
17108 	if (err)
17109 		return err;
17110 
17111 	return flag;
17112 }
17113 
17114 /* A write screens off any subsequent reads; but write marks come from the
17115  * straight-line code between a state and its parent.  When we arrive at an
17116  * equivalent state (jump target or such) we didn't arrive by the straight-line
17117  * code, so read marks in the state must propagate to the parent regardless
17118  * of the state's write marks. That's what 'parent == state->parent' comparison
17119  * in mark_reg_read() is for.
17120  */
17121 static int propagate_liveness(struct bpf_verifier_env *env,
17122 			      const struct bpf_verifier_state *vstate,
17123 			      struct bpf_verifier_state *vparent)
17124 {
17125 	struct bpf_reg_state *state_reg, *parent_reg;
17126 	struct bpf_func_state *state, *parent;
17127 	int i, frame, err = 0;
17128 
17129 	if (vparent->curframe != vstate->curframe) {
17130 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
17131 		     vparent->curframe, vstate->curframe);
17132 		return -EFAULT;
17133 	}
17134 	/* Propagate read liveness of registers... */
17135 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
17136 	for (frame = 0; frame <= vstate->curframe; frame++) {
17137 		parent = vparent->frame[frame];
17138 		state = vstate->frame[frame];
17139 		parent_reg = parent->regs;
17140 		state_reg = state->regs;
17141 		/* We don't need to worry about FP liveness, it's read-only */
17142 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
17143 			err = propagate_liveness_reg(env, &state_reg[i],
17144 						     &parent_reg[i]);
17145 			if (err < 0)
17146 				return err;
17147 			if (err == REG_LIVE_READ64)
17148 				mark_insn_zext(env, &parent_reg[i]);
17149 		}
17150 
17151 		/* Propagate stack slots. */
17152 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
17153 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
17154 			parent_reg = &parent->stack[i].spilled_ptr;
17155 			state_reg = &state->stack[i].spilled_ptr;
17156 			err = propagate_liveness_reg(env, state_reg,
17157 						     parent_reg);
17158 			if (err < 0)
17159 				return err;
17160 		}
17161 	}
17162 	return 0;
17163 }
17164 
17165 /* find precise scalars in the previous equivalent state and
17166  * propagate them into the current state
17167  */
17168 static int propagate_precision(struct bpf_verifier_env *env,
17169 			       const struct bpf_verifier_state *old)
17170 {
17171 	struct bpf_reg_state *state_reg;
17172 	struct bpf_func_state *state;
17173 	int i, err = 0, fr;
17174 	bool first;
17175 
17176 	for (fr = old->curframe; fr >= 0; fr--) {
17177 		state = old->frame[fr];
17178 		state_reg = state->regs;
17179 		first = true;
17180 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
17181 			if (state_reg->type != SCALAR_VALUE ||
17182 			    !state_reg->precise ||
17183 			    !(state_reg->live & REG_LIVE_READ))
17184 				continue;
17185 			if (env->log.level & BPF_LOG_LEVEL2) {
17186 				if (first)
17187 					verbose(env, "frame %d: propagating r%d", fr, i);
17188 				else
17189 					verbose(env, ",r%d", i);
17190 			}
17191 			bt_set_frame_reg(&env->bt, fr, i);
17192 			first = false;
17193 		}
17194 
17195 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17196 			if (!is_spilled_reg(&state->stack[i]))
17197 				continue;
17198 			state_reg = &state->stack[i].spilled_ptr;
17199 			if (state_reg->type != SCALAR_VALUE ||
17200 			    !state_reg->precise ||
17201 			    !(state_reg->live & REG_LIVE_READ))
17202 				continue;
17203 			if (env->log.level & BPF_LOG_LEVEL2) {
17204 				if (first)
17205 					verbose(env, "frame %d: propagating fp%d",
17206 						fr, (-i - 1) * BPF_REG_SIZE);
17207 				else
17208 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
17209 			}
17210 			bt_set_frame_slot(&env->bt, fr, i);
17211 			first = false;
17212 		}
17213 		if (!first)
17214 			verbose(env, "\n");
17215 	}
17216 
17217 	err = mark_chain_precision_batch(env);
17218 	if (err < 0)
17219 		return err;
17220 
17221 	return 0;
17222 }
17223 
17224 static bool states_maybe_looping(struct bpf_verifier_state *old,
17225 				 struct bpf_verifier_state *cur)
17226 {
17227 	struct bpf_func_state *fold, *fcur;
17228 	int i, fr = cur->curframe;
17229 
17230 	if (old->curframe != fr)
17231 		return false;
17232 
17233 	fold = old->frame[fr];
17234 	fcur = cur->frame[fr];
17235 	for (i = 0; i < MAX_BPF_REG; i++)
17236 		if (memcmp(&fold->regs[i], &fcur->regs[i],
17237 			   offsetof(struct bpf_reg_state, parent)))
17238 			return false;
17239 	return true;
17240 }
17241 
17242 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
17243 {
17244 	return env->insn_aux_data[insn_idx].is_iter_next;
17245 }
17246 
17247 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
17248  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
17249  * states to match, which otherwise would look like an infinite loop. So while
17250  * iter_next() calls are taken care of, we still need to be careful and
17251  * prevent erroneous and too eager declaration of "ininite loop", when
17252  * iterators are involved.
17253  *
17254  * Here's a situation in pseudo-BPF assembly form:
17255  *
17256  *   0: again:                          ; set up iter_next() call args
17257  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
17258  *   2:   call bpf_iter_num_next        ; this is iter_next() call
17259  *   3:   if r0 == 0 goto done
17260  *   4:   ... something useful here ...
17261  *   5:   goto again                    ; another iteration
17262  *   6: done:
17263  *   7:   r1 = &it
17264  *   8:   call bpf_iter_num_destroy     ; clean up iter state
17265  *   9:   exit
17266  *
17267  * This is a typical loop. Let's assume that we have a prune point at 1:,
17268  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
17269  * again`, assuming other heuristics don't get in a way).
17270  *
17271  * When we first time come to 1:, let's say we have some state X. We proceed
17272  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
17273  * Now we come back to validate that forked ACTIVE state. We proceed through
17274  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
17275  * are converging. But the problem is that we don't know that yet, as this
17276  * convergence has to happen at iter_next() call site only. So if nothing is
17277  * done, at 1: verifier will use bounded loop logic and declare infinite
17278  * looping (and would be *technically* correct, if not for iterator's
17279  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
17280  * don't want that. So what we do in process_iter_next_call() when we go on
17281  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
17282  * a different iteration. So when we suspect an infinite loop, we additionally
17283  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
17284  * pretend we are not looping and wait for next iter_next() call.
17285  *
17286  * This only applies to ACTIVE state. In DRAINED state we don't expect to
17287  * loop, because that would actually mean infinite loop, as DRAINED state is
17288  * "sticky", and so we'll keep returning into the same instruction with the
17289  * same state (at least in one of possible code paths).
17290  *
17291  * This approach allows to keep infinite loop heuristic even in the face of
17292  * active iterator. E.g., C snippet below is and will be detected as
17293  * inifintely looping:
17294  *
17295  *   struct bpf_iter_num it;
17296  *   int *p, x;
17297  *
17298  *   bpf_iter_num_new(&it, 0, 10);
17299  *   while ((p = bpf_iter_num_next(&t))) {
17300  *       x = p;
17301  *       while (x--) {} // <<-- infinite loop here
17302  *   }
17303  *
17304  */
17305 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
17306 {
17307 	struct bpf_reg_state *slot, *cur_slot;
17308 	struct bpf_func_state *state;
17309 	int i, fr;
17310 
17311 	for (fr = old->curframe; fr >= 0; fr--) {
17312 		state = old->frame[fr];
17313 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17314 			if (state->stack[i].slot_type[0] != STACK_ITER)
17315 				continue;
17316 
17317 			slot = &state->stack[i].spilled_ptr;
17318 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
17319 				continue;
17320 
17321 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
17322 			if (cur_slot->iter.depth != slot->iter.depth)
17323 				return true;
17324 		}
17325 	}
17326 	return false;
17327 }
17328 
17329 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
17330 {
17331 	struct bpf_verifier_state_list *new_sl;
17332 	struct bpf_verifier_state_list *sl, **pprev;
17333 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
17334 	int i, j, n, err, states_cnt = 0;
17335 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
17336 	bool add_new_state = force_new_state;
17337 	bool force_exact;
17338 
17339 	/* bpf progs typically have pruning point every 4 instructions
17340 	 * http://vger.kernel.org/bpfconf2019.html#session-1
17341 	 * Do not add new state for future pruning if the verifier hasn't seen
17342 	 * at least 2 jumps and at least 8 instructions.
17343 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
17344 	 * In tests that amounts to up to 50% reduction into total verifier
17345 	 * memory consumption and 20% verifier time speedup.
17346 	 */
17347 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
17348 	    env->insn_processed - env->prev_insn_processed >= 8)
17349 		add_new_state = true;
17350 
17351 	pprev = explored_state(env, insn_idx);
17352 	sl = *pprev;
17353 
17354 	clean_live_states(env, insn_idx, cur);
17355 
17356 	while (sl) {
17357 		states_cnt++;
17358 		if (sl->state.insn_idx != insn_idx)
17359 			goto next;
17360 
17361 		if (sl->state.branches) {
17362 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
17363 
17364 			if (frame->in_async_callback_fn &&
17365 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
17366 				/* Different async_entry_cnt means that the verifier is
17367 				 * processing another entry into async callback.
17368 				 * Seeing the same state is not an indication of infinite
17369 				 * loop or infinite recursion.
17370 				 * But finding the same state doesn't mean that it's safe
17371 				 * to stop processing the current state. The previous state
17372 				 * hasn't yet reached bpf_exit, since state.branches > 0.
17373 				 * Checking in_async_callback_fn alone is not enough either.
17374 				 * Since the verifier still needs to catch infinite loops
17375 				 * inside async callbacks.
17376 				 */
17377 				goto skip_inf_loop_check;
17378 			}
17379 			/* BPF open-coded iterators loop detection is special.
17380 			 * states_maybe_looping() logic is too simplistic in detecting
17381 			 * states that *might* be equivalent, because it doesn't know
17382 			 * about ID remapping, so don't even perform it.
17383 			 * See process_iter_next_call() and iter_active_depths_differ()
17384 			 * for overview of the logic. When current and one of parent
17385 			 * states are detected as equivalent, it's a good thing: we prove
17386 			 * convergence and can stop simulating further iterations.
17387 			 * It's safe to assume that iterator loop will finish, taking into
17388 			 * account iter_next() contract of eventually returning
17389 			 * sticky NULL result.
17390 			 *
17391 			 * Note, that states have to be compared exactly in this case because
17392 			 * read and precision marks might not be finalized inside the loop.
17393 			 * E.g. as in the program below:
17394 			 *
17395 			 *     1. r7 = -16
17396 			 *     2. r6 = bpf_get_prandom_u32()
17397 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
17398 			 *     4.   if (r6 != 42) {
17399 			 *     5.     r7 = -32
17400 			 *     6.     r6 = bpf_get_prandom_u32()
17401 			 *     7.     continue
17402 			 *     8.   }
17403 			 *     9.   r0 = r10
17404 			 *    10.   r0 += r7
17405 			 *    11.   r8 = *(u64 *)(r0 + 0)
17406 			 *    12.   r6 = bpf_get_prandom_u32()
17407 			 *    13. }
17408 			 *
17409 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
17410 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
17411 			 * not have read or precision mark for r7 yet, thus inexact states
17412 			 * comparison would discard current state with r7=-32
17413 			 * => unsafe memory access at 11 would not be caught.
17414 			 */
17415 			if (is_iter_next_insn(env, insn_idx)) {
17416 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17417 					struct bpf_func_state *cur_frame;
17418 					struct bpf_reg_state *iter_state, *iter_reg;
17419 					int spi;
17420 
17421 					cur_frame = cur->frame[cur->curframe];
17422 					/* btf_check_iter_kfuncs() enforces that
17423 					 * iter state pointer is always the first arg
17424 					 */
17425 					iter_reg = &cur_frame->regs[BPF_REG_1];
17426 					/* current state is valid due to states_equal(),
17427 					 * so we can assume valid iter and reg state,
17428 					 * no need for extra (re-)validations
17429 					 */
17430 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
17431 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
17432 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
17433 						update_loop_entry(cur, &sl->state);
17434 						goto hit;
17435 					}
17436 				}
17437 				goto skip_inf_loop_check;
17438 			}
17439 			if (is_may_goto_insn_at(env, insn_idx)) {
17440 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17441 					update_loop_entry(cur, &sl->state);
17442 					goto hit;
17443 				}
17444 				goto skip_inf_loop_check;
17445 			}
17446 			if (calls_callback(env, insn_idx)) {
17447 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
17448 					goto hit;
17449 				goto skip_inf_loop_check;
17450 			}
17451 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
17452 			if (states_maybe_looping(&sl->state, cur) &&
17453 			    states_equal(env, &sl->state, cur, EXACT) &&
17454 			    !iter_active_depths_differ(&sl->state, cur) &&
17455 			    sl->state.may_goto_depth == cur->may_goto_depth &&
17456 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
17457 				verbose_linfo(env, insn_idx, "; ");
17458 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
17459 				verbose(env, "cur state:");
17460 				print_verifier_state(env, cur->frame[cur->curframe], true);
17461 				verbose(env, "old state:");
17462 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
17463 				return -EINVAL;
17464 			}
17465 			/* if the verifier is processing a loop, avoid adding new state
17466 			 * too often, since different loop iterations have distinct
17467 			 * states and may not help future pruning.
17468 			 * This threshold shouldn't be too low to make sure that
17469 			 * a loop with large bound will be rejected quickly.
17470 			 * The most abusive loop will be:
17471 			 * r1 += 1
17472 			 * if r1 < 1000000 goto pc-2
17473 			 * 1M insn_procssed limit / 100 == 10k peak states.
17474 			 * This threshold shouldn't be too high either, since states
17475 			 * at the end of the loop are likely to be useful in pruning.
17476 			 */
17477 skip_inf_loop_check:
17478 			if (!force_new_state &&
17479 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
17480 			    env->insn_processed - env->prev_insn_processed < 100)
17481 				add_new_state = false;
17482 			goto miss;
17483 		}
17484 		/* If sl->state is a part of a loop and this loop's entry is a part of
17485 		 * current verification path then states have to be compared exactly.
17486 		 * 'force_exact' is needed to catch the following case:
17487 		 *
17488 		 *                initial     Here state 'succ' was processed first,
17489 		 *                  |         it was eventually tracked to produce a
17490 		 *                  V         state identical to 'hdr'.
17491 		 *     .---------> hdr        All branches from 'succ' had been explored
17492 		 *     |            |         and thus 'succ' has its .branches == 0.
17493 		 *     |            V
17494 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
17495 		 *     |    |       |         to the same instruction + callsites.
17496 		 *     |    V       V         In such case it is necessary to check
17497 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
17498 		 *     |    |       |         If 'succ' and 'cur' are a part of the
17499 		 *     |    V       V         same loop exact flag has to be set.
17500 		 *     |   succ <- cur        To check if that is the case, verify
17501 		 *     |    |                 if loop entry of 'succ' is in current
17502 		 *     |    V                 DFS path.
17503 		 *     |   ...
17504 		 *     |    |
17505 		 *     '----'
17506 		 *
17507 		 * Additional details are in the comment before get_loop_entry().
17508 		 */
17509 		loop_entry = get_loop_entry(&sl->state);
17510 		force_exact = loop_entry && loop_entry->branches > 0;
17511 		if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) {
17512 			if (force_exact)
17513 				update_loop_entry(cur, loop_entry);
17514 hit:
17515 			sl->hit_cnt++;
17516 			/* reached equivalent register/stack state,
17517 			 * prune the search.
17518 			 * Registers read by the continuation are read by us.
17519 			 * If we have any write marks in env->cur_state, they
17520 			 * will prevent corresponding reads in the continuation
17521 			 * from reaching our parent (an explored_state).  Our
17522 			 * own state will get the read marks recorded, but
17523 			 * they'll be immediately forgotten as we're pruning
17524 			 * this state and will pop a new one.
17525 			 */
17526 			err = propagate_liveness(env, &sl->state, cur);
17527 
17528 			/* if previous state reached the exit with precision and
17529 			 * current state is equivalent to it (except precision marks)
17530 			 * the precision needs to be propagated back in
17531 			 * the current state.
17532 			 */
17533 			if (is_jmp_point(env, env->insn_idx))
17534 				err = err ? : push_jmp_history(env, cur, 0);
17535 			err = err ? : propagate_precision(env, &sl->state);
17536 			if (err)
17537 				return err;
17538 			return 1;
17539 		}
17540 miss:
17541 		/* when new state is not going to be added do not increase miss count.
17542 		 * Otherwise several loop iterations will remove the state
17543 		 * recorded earlier. The goal of these heuristics is to have
17544 		 * states from some iterations of the loop (some in the beginning
17545 		 * and some at the end) to help pruning.
17546 		 */
17547 		if (add_new_state)
17548 			sl->miss_cnt++;
17549 		/* heuristic to determine whether this state is beneficial
17550 		 * to keep checking from state equivalence point of view.
17551 		 * Higher numbers increase max_states_per_insn and verification time,
17552 		 * but do not meaningfully decrease insn_processed.
17553 		 * 'n' controls how many times state could miss before eviction.
17554 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
17555 		 * too early would hinder iterator convergence.
17556 		 */
17557 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17558 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
17559 			/* the state is unlikely to be useful. Remove it to
17560 			 * speed up verification
17561 			 */
17562 			*pprev = sl->next;
17563 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17564 			    !sl->state.used_as_loop_entry) {
17565 				u32 br = sl->state.branches;
17566 
17567 				WARN_ONCE(br,
17568 					  "BUG live_done but branches_to_explore %d\n",
17569 					  br);
17570 				free_verifier_state(&sl->state, false);
17571 				kfree(sl);
17572 				env->peak_states--;
17573 			} else {
17574 				/* cannot free this state, since parentage chain may
17575 				 * walk it later. Add it for free_list instead to
17576 				 * be freed at the end of verification
17577 				 */
17578 				sl->next = env->free_list;
17579 				env->free_list = sl;
17580 			}
17581 			sl = *pprev;
17582 			continue;
17583 		}
17584 next:
17585 		pprev = &sl->next;
17586 		sl = *pprev;
17587 	}
17588 
17589 	if (env->max_states_per_insn < states_cnt)
17590 		env->max_states_per_insn = states_cnt;
17591 
17592 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
17593 		return 0;
17594 
17595 	if (!add_new_state)
17596 		return 0;
17597 
17598 	/* There were no equivalent states, remember the current one.
17599 	 * Technically the current state is not proven to be safe yet,
17600 	 * but it will either reach outer most bpf_exit (which means it's safe)
17601 	 * or it will be rejected. When there are no loops the verifier won't be
17602 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
17603 	 * again on the way to bpf_exit.
17604 	 * When looping the sl->state.branches will be > 0 and this state
17605 	 * will not be considered for equivalence until branches == 0.
17606 	 */
17607 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
17608 	if (!new_sl)
17609 		return -ENOMEM;
17610 	env->total_states++;
17611 	env->peak_states++;
17612 	env->prev_jmps_processed = env->jmps_processed;
17613 	env->prev_insn_processed = env->insn_processed;
17614 
17615 	/* forget precise markings we inherited, see __mark_chain_precision */
17616 	if (env->bpf_capable)
17617 		mark_all_scalars_imprecise(env, cur);
17618 
17619 	/* add new state to the head of linked list */
17620 	new = &new_sl->state;
17621 	err = copy_verifier_state(new, cur);
17622 	if (err) {
17623 		free_verifier_state(new, false);
17624 		kfree(new_sl);
17625 		return err;
17626 	}
17627 	new->insn_idx = insn_idx;
17628 	WARN_ONCE(new->branches != 1,
17629 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
17630 
17631 	cur->parent = new;
17632 	cur->first_insn_idx = insn_idx;
17633 	cur->dfs_depth = new->dfs_depth + 1;
17634 	clear_jmp_history(cur);
17635 	new_sl->next = *explored_state(env, insn_idx);
17636 	*explored_state(env, insn_idx) = new_sl;
17637 	/* connect new state to parentage chain. Current frame needs all
17638 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
17639 	 * to the stack implicitly by JITs) so in callers' frames connect just
17640 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17641 	 * the state of the call instruction (with WRITTEN set), and r0 comes
17642 	 * from callee with its full parentage chain, anyway.
17643 	 */
17644 	/* clear write marks in current state: the writes we did are not writes
17645 	 * our child did, so they don't screen off its reads from us.
17646 	 * (There are no read marks in current state, because reads always mark
17647 	 * their parent and current state never has children yet.  Only
17648 	 * explored_states can get read marks.)
17649 	 */
17650 	for (j = 0; j <= cur->curframe; j++) {
17651 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17652 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17653 		for (i = 0; i < BPF_REG_FP; i++)
17654 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17655 	}
17656 
17657 	/* all stack frames are accessible from callee, clear them all */
17658 	for (j = 0; j <= cur->curframe; j++) {
17659 		struct bpf_func_state *frame = cur->frame[j];
17660 		struct bpf_func_state *newframe = new->frame[j];
17661 
17662 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17663 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17664 			frame->stack[i].spilled_ptr.parent =
17665 						&newframe->stack[i].spilled_ptr;
17666 		}
17667 	}
17668 	return 0;
17669 }
17670 
17671 /* Return true if it's OK to have the same insn return a different type. */
17672 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17673 {
17674 	switch (base_type(type)) {
17675 	case PTR_TO_CTX:
17676 	case PTR_TO_SOCKET:
17677 	case PTR_TO_SOCK_COMMON:
17678 	case PTR_TO_TCP_SOCK:
17679 	case PTR_TO_XDP_SOCK:
17680 	case PTR_TO_BTF_ID:
17681 	case PTR_TO_ARENA:
17682 		return false;
17683 	default:
17684 		return true;
17685 	}
17686 }
17687 
17688 /* If an instruction was previously used with particular pointer types, then we
17689  * need to be careful to avoid cases such as the below, where it may be ok
17690  * for one branch accessing the pointer, but not ok for the other branch:
17691  *
17692  * R1 = sock_ptr
17693  * goto X;
17694  * ...
17695  * R1 = some_other_valid_ptr;
17696  * goto X;
17697  * ...
17698  * R2 = *(u32 *)(R1 + 0);
17699  */
17700 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17701 {
17702 	return src != prev && (!reg_type_mismatch_ok(src) ||
17703 			       !reg_type_mismatch_ok(prev));
17704 }
17705 
17706 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17707 			     bool allow_trust_mismatch)
17708 {
17709 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17710 
17711 	if (*prev_type == NOT_INIT) {
17712 		/* Saw a valid insn
17713 		 * dst_reg = *(u32 *)(src_reg + off)
17714 		 * save type to validate intersecting paths
17715 		 */
17716 		*prev_type = type;
17717 	} else if (reg_type_mismatch(type, *prev_type)) {
17718 		/* Abuser program is trying to use the same insn
17719 		 * dst_reg = *(u32*) (src_reg + off)
17720 		 * with different pointer types:
17721 		 * src_reg == ctx in one branch and
17722 		 * src_reg == stack|map in some other branch.
17723 		 * Reject it.
17724 		 */
17725 		if (allow_trust_mismatch &&
17726 		    base_type(type) == PTR_TO_BTF_ID &&
17727 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
17728 			/*
17729 			 * Have to support a use case when one path through
17730 			 * the program yields TRUSTED pointer while another
17731 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17732 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17733 			 */
17734 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17735 		} else {
17736 			verbose(env, "same insn cannot be used with different pointers\n");
17737 			return -EINVAL;
17738 		}
17739 	}
17740 
17741 	return 0;
17742 }
17743 
17744 static int do_check(struct bpf_verifier_env *env)
17745 {
17746 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17747 	struct bpf_verifier_state *state = env->cur_state;
17748 	struct bpf_insn *insns = env->prog->insnsi;
17749 	struct bpf_reg_state *regs;
17750 	int insn_cnt = env->prog->len;
17751 	bool do_print_state = false;
17752 	int prev_insn_idx = -1;
17753 
17754 	for (;;) {
17755 		bool exception_exit = false;
17756 		struct bpf_insn *insn;
17757 		u8 class;
17758 		int err;
17759 
17760 		/* reset current history entry on each new instruction */
17761 		env->cur_hist_ent = NULL;
17762 
17763 		env->prev_insn_idx = prev_insn_idx;
17764 		if (env->insn_idx >= insn_cnt) {
17765 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17766 				env->insn_idx, insn_cnt);
17767 			return -EFAULT;
17768 		}
17769 
17770 		insn = &insns[env->insn_idx];
17771 		class = BPF_CLASS(insn->code);
17772 
17773 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17774 			verbose(env,
17775 				"BPF program is too large. Processed %d insn\n",
17776 				env->insn_processed);
17777 			return -E2BIG;
17778 		}
17779 
17780 		state->last_insn_idx = env->prev_insn_idx;
17781 
17782 		if (is_prune_point(env, env->insn_idx)) {
17783 			err = is_state_visited(env, env->insn_idx);
17784 			if (err < 0)
17785 				return err;
17786 			if (err == 1) {
17787 				/* found equivalent state, can prune the search */
17788 				if (env->log.level & BPF_LOG_LEVEL) {
17789 					if (do_print_state)
17790 						verbose(env, "\nfrom %d to %d%s: safe\n",
17791 							env->prev_insn_idx, env->insn_idx,
17792 							env->cur_state->speculative ?
17793 							" (speculative execution)" : "");
17794 					else
17795 						verbose(env, "%d: safe\n", env->insn_idx);
17796 				}
17797 				goto process_bpf_exit;
17798 			}
17799 		}
17800 
17801 		if (is_jmp_point(env, env->insn_idx)) {
17802 			err = push_jmp_history(env, state, 0);
17803 			if (err)
17804 				return err;
17805 		}
17806 
17807 		if (signal_pending(current))
17808 			return -EAGAIN;
17809 
17810 		if (need_resched())
17811 			cond_resched();
17812 
17813 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17814 			verbose(env, "\nfrom %d to %d%s:",
17815 				env->prev_insn_idx, env->insn_idx,
17816 				env->cur_state->speculative ?
17817 				" (speculative execution)" : "");
17818 			print_verifier_state(env, state->frame[state->curframe], true);
17819 			do_print_state = false;
17820 		}
17821 
17822 		if (env->log.level & BPF_LOG_LEVEL) {
17823 			const struct bpf_insn_cbs cbs = {
17824 				.cb_call	= disasm_kfunc_name,
17825 				.cb_print	= verbose,
17826 				.private_data	= env,
17827 			};
17828 
17829 			if (verifier_state_scratched(env))
17830 				print_insn_state(env, state->frame[state->curframe]);
17831 
17832 			verbose_linfo(env, env->insn_idx, "; ");
17833 			env->prev_log_pos = env->log.end_pos;
17834 			verbose(env, "%d: ", env->insn_idx);
17835 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17836 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17837 			env->prev_log_pos = env->log.end_pos;
17838 		}
17839 
17840 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17841 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17842 							   env->prev_insn_idx);
17843 			if (err)
17844 				return err;
17845 		}
17846 
17847 		regs = cur_regs(env);
17848 		sanitize_mark_insn_seen(env);
17849 		prev_insn_idx = env->insn_idx;
17850 
17851 		if (class == BPF_ALU || class == BPF_ALU64) {
17852 			err = check_alu_op(env, insn);
17853 			if (err)
17854 				return err;
17855 
17856 		} else if (class == BPF_LDX) {
17857 			enum bpf_reg_type src_reg_type;
17858 
17859 			/* check for reserved fields is already done */
17860 
17861 			/* check src operand */
17862 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17863 			if (err)
17864 				return err;
17865 
17866 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17867 			if (err)
17868 				return err;
17869 
17870 			src_reg_type = regs[insn->src_reg].type;
17871 
17872 			/* check that memory (src_reg + off) is readable,
17873 			 * the state of dst_reg will be updated by this func
17874 			 */
17875 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17876 					       insn->off, BPF_SIZE(insn->code),
17877 					       BPF_READ, insn->dst_reg, false,
17878 					       BPF_MODE(insn->code) == BPF_MEMSX);
17879 			err = err ?: save_aux_ptr_type(env, src_reg_type, true);
17880 			err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], "ldx");
17881 			if (err)
17882 				return err;
17883 		} else if (class == BPF_STX) {
17884 			enum bpf_reg_type dst_reg_type;
17885 
17886 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17887 				err = check_atomic(env, env->insn_idx, insn);
17888 				if (err)
17889 					return err;
17890 				env->insn_idx++;
17891 				continue;
17892 			}
17893 
17894 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17895 				verbose(env, "BPF_STX uses reserved fields\n");
17896 				return -EINVAL;
17897 			}
17898 
17899 			/* check src1 operand */
17900 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17901 			if (err)
17902 				return err;
17903 			/* check src2 operand */
17904 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17905 			if (err)
17906 				return err;
17907 
17908 			dst_reg_type = regs[insn->dst_reg].type;
17909 
17910 			/* check that memory (dst_reg + off) is writeable */
17911 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17912 					       insn->off, BPF_SIZE(insn->code),
17913 					       BPF_WRITE, insn->src_reg, false, false);
17914 			if (err)
17915 				return err;
17916 
17917 			err = save_aux_ptr_type(env, dst_reg_type, false);
17918 			if (err)
17919 				return err;
17920 		} else if (class == BPF_ST) {
17921 			enum bpf_reg_type dst_reg_type;
17922 
17923 			if (BPF_MODE(insn->code) != BPF_MEM ||
17924 			    insn->src_reg != BPF_REG_0) {
17925 				verbose(env, "BPF_ST uses reserved fields\n");
17926 				return -EINVAL;
17927 			}
17928 			/* check src operand */
17929 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17930 			if (err)
17931 				return err;
17932 
17933 			dst_reg_type = regs[insn->dst_reg].type;
17934 
17935 			/* check that memory (dst_reg + off) is writeable */
17936 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17937 					       insn->off, BPF_SIZE(insn->code),
17938 					       BPF_WRITE, -1, false, false);
17939 			if (err)
17940 				return err;
17941 
17942 			err = save_aux_ptr_type(env, dst_reg_type, false);
17943 			if (err)
17944 				return err;
17945 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17946 			u8 opcode = BPF_OP(insn->code);
17947 
17948 			env->jmps_processed++;
17949 			if (opcode == BPF_CALL) {
17950 				if (BPF_SRC(insn->code) != BPF_K ||
17951 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17952 				     && insn->off != 0) ||
17953 				    (insn->src_reg != BPF_REG_0 &&
17954 				     insn->src_reg != BPF_PSEUDO_CALL &&
17955 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17956 				    insn->dst_reg != BPF_REG_0 ||
17957 				    class == BPF_JMP32) {
17958 					verbose(env, "BPF_CALL uses reserved fields\n");
17959 					return -EINVAL;
17960 				}
17961 
17962 				if (env->cur_state->active_lock.ptr) {
17963 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17964 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17965 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17966 						verbose(env, "function calls are not allowed while holding a lock\n");
17967 						return -EINVAL;
17968 					}
17969 				}
17970 				if (insn->src_reg == BPF_PSEUDO_CALL) {
17971 					err = check_func_call(env, insn, &env->insn_idx);
17972 				} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17973 					err = check_kfunc_call(env, insn, &env->insn_idx);
17974 					if (!err && is_bpf_throw_kfunc(insn)) {
17975 						exception_exit = true;
17976 						goto process_bpf_exit_full;
17977 					}
17978 				} else {
17979 					err = check_helper_call(env, insn, &env->insn_idx);
17980 				}
17981 				if (err)
17982 					return err;
17983 
17984 				mark_reg_scratched(env, BPF_REG_0);
17985 			} else if (opcode == BPF_JA) {
17986 				if (BPF_SRC(insn->code) != BPF_K ||
17987 				    insn->src_reg != BPF_REG_0 ||
17988 				    insn->dst_reg != BPF_REG_0 ||
17989 				    (class == BPF_JMP && insn->imm != 0) ||
17990 				    (class == BPF_JMP32 && insn->off != 0)) {
17991 					verbose(env, "BPF_JA uses reserved fields\n");
17992 					return -EINVAL;
17993 				}
17994 
17995 				if (class == BPF_JMP)
17996 					env->insn_idx += insn->off + 1;
17997 				else
17998 					env->insn_idx += insn->imm + 1;
17999 				continue;
18000 
18001 			} else if (opcode == BPF_EXIT) {
18002 				if (BPF_SRC(insn->code) != BPF_K ||
18003 				    insn->imm != 0 ||
18004 				    insn->src_reg != BPF_REG_0 ||
18005 				    insn->dst_reg != BPF_REG_0 ||
18006 				    class == BPF_JMP32) {
18007 					verbose(env, "BPF_EXIT uses reserved fields\n");
18008 					return -EINVAL;
18009 				}
18010 process_bpf_exit_full:
18011 				if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) {
18012 					verbose(env, "bpf_spin_unlock is missing\n");
18013 					return -EINVAL;
18014 				}
18015 
18016 				if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) {
18017 					verbose(env, "bpf_rcu_read_unlock is missing\n");
18018 					return -EINVAL;
18019 				}
18020 
18021 				if (env->cur_state->active_preempt_lock && !env->cur_state->curframe) {
18022 					verbose(env, "%d bpf_preempt_enable%s missing\n",
18023 						env->cur_state->active_preempt_lock,
18024 						env->cur_state->active_preempt_lock == 1 ? " is" : "(s) are");
18025 					return -EINVAL;
18026 				}
18027 
18028 				/* We must do check_reference_leak here before
18029 				 * prepare_func_exit to handle the case when
18030 				 * state->curframe > 0, it may be a callback
18031 				 * function, for which reference_state must
18032 				 * match caller reference state when it exits.
18033 				 */
18034 				err = check_reference_leak(env, exception_exit);
18035 				if (err)
18036 					return err;
18037 
18038 				/* The side effect of the prepare_func_exit
18039 				 * which is being skipped is that it frees
18040 				 * bpf_func_state. Typically, process_bpf_exit
18041 				 * will only be hit with outermost exit.
18042 				 * copy_verifier_state in pop_stack will handle
18043 				 * freeing of any extra bpf_func_state left over
18044 				 * from not processing all nested function
18045 				 * exits. We also skip return code checks as
18046 				 * they are not needed for exceptional exits.
18047 				 */
18048 				if (exception_exit)
18049 					goto process_bpf_exit;
18050 
18051 				if (state->curframe) {
18052 					/* exit from nested function */
18053 					err = prepare_func_exit(env, &env->insn_idx);
18054 					if (err)
18055 						return err;
18056 					do_print_state = true;
18057 					continue;
18058 				}
18059 
18060 				err = check_return_code(env, BPF_REG_0, "R0");
18061 				if (err)
18062 					return err;
18063 process_bpf_exit:
18064 				mark_verifier_state_scratched(env);
18065 				update_branch_counts(env, env->cur_state);
18066 				err = pop_stack(env, &prev_insn_idx,
18067 						&env->insn_idx, pop_log);
18068 				if (err < 0) {
18069 					if (err != -ENOENT)
18070 						return err;
18071 					break;
18072 				} else {
18073 					do_print_state = true;
18074 					continue;
18075 				}
18076 			} else {
18077 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
18078 				if (err)
18079 					return err;
18080 			}
18081 		} else if (class == BPF_LD) {
18082 			u8 mode = BPF_MODE(insn->code);
18083 
18084 			if (mode == BPF_ABS || mode == BPF_IND) {
18085 				err = check_ld_abs(env, insn);
18086 				if (err)
18087 					return err;
18088 
18089 			} else if (mode == BPF_IMM) {
18090 				err = check_ld_imm(env, insn);
18091 				if (err)
18092 					return err;
18093 
18094 				env->insn_idx++;
18095 				sanitize_mark_insn_seen(env);
18096 			} else {
18097 				verbose(env, "invalid BPF_LD mode\n");
18098 				return -EINVAL;
18099 			}
18100 		} else {
18101 			verbose(env, "unknown insn class %d\n", class);
18102 			return -EINVAL;
18103 		}
18104 
18105 		env->insn_idx++;
18106 	}
18107 
18108 	return 0;
18109 }
18110 
18111 static int find_btf_percpu_datasec(struct btf *btf)
18112 {
18113 	const struct btf_type *t;
18114 	const char *tname;
18115 	int i, n;
18116 
18117 	/*
18118 	 * Both vmlinux and module each have their own ".data..percpu"
18119 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
18120 	 * types to look at only module's own BTF types.
18121 	 */
18122 	n = btf_nr_types(btf);
18123 	if (btf_is_module(btf))
18124 		i = btf_nr_types(btf_vmlinux);
18125 	else
18126 		i = 1;
18127 
18128 	for(; i < n; i++) {
18129 		t = btf_type_by_id(btf, i);
18130 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
18131 			continue;
18132 
18133 		tname = btf_name_by_offset(btf, t->name_off);
18134 		if (!strcmp(tname, ".data..percpu"))
18135 			return i;
18136 	}
18137 
18138 	return -ENOENT;
18139 }
18140 
18141 /* replace pseudo btf_id with kernel symbol address */
18142 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
18143 			       struct bpf_insn *insn,
18144 			       struct bpf_insn_aux_data *aux)
18145 {
18146 	const struct btf_var_secinfo *vsi;
18147 	const struct btf_type *datasec;
18148 	struct btf_mod_pair *btf_mod;
18149 	const struct btf_type *t;
18150 	const char *sym_name;
18151 	bool percpu = false;
18152 	u32 type, id = insn->imm;
18153 	struct btf *btf;
18154 	s32 datasec_id;
18155 	u64 addr;
18156 	int i, btf_fd, err;
18157 
18158 	btf_fd = insn[1].imm;
18159 	if (btf_fd) {
18160 		btf = btf_get_by_fd(btf_fd);
18161 		if (IS_ERR(btf)) {
18162 			verbose(env, "invalid module BTF object FD specified.\n");
18163 			return -EINVAL;
18164 		}
18165 	} else {
18166 		if (!btf_vmlinux) {
18167 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
18168 			return -EINVAL;
18169 		}
18170 		btf = btf_vmlinux;
18171 		btf_get(btf);
18172 	}
18173 
18174 	t = btf_type_by_id(btf, id);
18175 	if (!t) {
18176 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
18177 		err = -ENOENT;
18178 		goto err_put;
18179 	}
18180 
18181 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
18182 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
18183 		err = -EINVAL;
18184 		goto err_put;
18185 	}
18186 
18187 	sym_name = btf_name_by_offset(btf, t->name_off);
18188 	addr = kallsyms_lookup_name(sym_name);
18189 	if (!addr) {
18190 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
18191 			sym_name);
18192 		err = -ENOENT;
18193 		goto err_put;
18194 	}
18195 	insn[0].imm = (u32)addr;
18196 	insn[1].imm = addr >> 32;
18197 
18198 	if (btf_type_is_func(t)) {
18199 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18200 		aux->btf_var.mem_size = 0;
18201 		goto check_btf;
18202 	}
18203 
18204 	datasec_id = find_btf_percpu_datasec(btf);
18205 	if (datasec_id > 0) {
18206 		datasec = btf_type_by_id(btf, datasec_id);
18207 		for_each_vsi(i, datasec, vsi) {
18208 			if (vsi->type == id) {
18209 				percpu = true;
18210 				break;
18211 			}
18212 		}
18213 	}
18214 
18215 	type = t->type;
18216 	t = btf_type_skip_modifiers(btf, type, NULL);
18217 	if (percpu) {
18218 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
18219 		aux->btf_var.btf = btf;
18220 		aux->btf_var.btf_id = type;
18221 	} else if (!btf_type_is_struct(t)) {
18222 		const struct btf_type *ret;
18223 		const char *tname;
18224 		u32 tsize;
18225 
18226 		/* resolve the type size of ksym. */
18227 		ret = btf_resolve_size(btf, t, &tsize);
18228 		if (IS_ERR(ret)) {
18229 			tname = btf_name_by_offset(btf, t->name_off);
18230 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
18231 				tname, PTR_ERR(ret));
18232 			err = -EINVAL;
18233 			goto err_put;
18234 		}
18235 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18236 		aux->btf_var.mem_size = tsize;
18237 	} else {
18238 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
18239 		aux->btf_var.btf = btf;
18240 		aux->btf_var.btf_id = type;
18241 	}
18242 check_btf:
18243 	/* check whether we recorded this BTF (and maybe module) already */
18244 	for (i = 0; i < env->used_btf_cnt; i++) {
18245 		if (env->used_btfs[i].btf == btf) {
18246 			btf_put(btf);
18247 			return 0;
18248 		}
18249 	}
18250 
18251 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
18252 		err = -E2BIG;
18253 		goto err_put;
18254 	}
18255 
18256 	btf_mod = &env->used_btfs[env->used_btf_cnt];
18257 	btf_mod->btf = btf;
18258 	btf_mod->module = NULL;
18259 
18260 	/* if we reference variables from kernel module, bump its refcount */
18261 	if (btf_is_module(btf)) {
18262 		btf_mod->module = btf_try_get_module(btf);
18263 		if (!btf_mod->module) {
18264 			err = -ENXIO;
18265 			goto err_put;
18266 		}
18267 	}
18268 
18269 	env->used_btf_cnt++;
18270 
18271 	return 0;
18272 err_put:
18273 	btf_put(btf);
18274 	return err;
18275 }
18276 
18277 static bool is_tracing_prog_type(enum bpf_prog_type type)
18278 {
18279 	switch (type) {
18280 	case BPF_PROG_TYPE_KPROBE:
18281 	case BPF_PROG_TYPE_TRACEPOINT:
18282 	case BPF_PROG_TYPE_PERF_EVENT:
18283 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
18284 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
18285 		return true;
18286 	default:
18287 		return false;
18288 	}
18289 }
18290 
18291 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
18292 					struct bpf_map *map,
18293 					struct bpf_prog *prog)
18294 
18295 {
18296 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18297 
18298 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
18299 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
18300 		if (is_tracing_prog_type(prog_type)) {
18301 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
18302 			return -EINVAL;
18303 		}
18304 	}
18305 
18306 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
18307 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
18308 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
18309 			return -EINVAL;
18310 		}
18311 
18312 		if (is_tracing_prog_type(prog_type)) {
18313 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
18314 			return -EINVAL;
18315 		}
18316 	}
18317 
18318 	if (btf_record_has_field(map->record, BPF_TIMER)) {
18319 		if (is_tracing_prog_type(prog_type)) {
18320 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
18321 			return -EINVAL;
18322 		}
18323 	}
18324 
18325 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
18326 		if (is_tracing_prog_type(prog_type)) {
18327 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
18328 			return -EINVAL;
18329 		}
18330 	}
18331 
18332 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
18333 	    !bpf_offload_prog_map_match(prog, map)) {
18334 		verbose(env, "offload device mismatch between prog and map\n");
18335 		return -EINVAL;
18336 	}
18337 
18338 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
18339 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
18340 		return -EINVAL;
18341 	}
18342 
18343 	if (prog->sleepable)
18344 		switch (map->map_type) {
18345 		case BPF_MAP_TYPE_HASH:
18346 		case BPF_MAP_TYPE_LRU_HASH:
18347 		case BPF_MAP_TYPE_ARRAY:
18348 		case BPF_MAP_TYPE_PERCPU_HASH:
18349 		case BPF_MAP_TYPE_PERCPU_ARRAY:
18350 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
18351 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
18352 		case BPF_MAP_TYPE_HASH_OF_MAPS:
18353 		case BPF_MAP_TYPE_RINGBUF:
18354 		case BPF_MAP_TYPE_USER_RINGBUF:
18355 		case BPF_MAP_TYPE_INODE_STORAGE:
18356 		case BPF_MAP_TYPE_SK_STORAGE:
18357 		case BPF_MAP_TYPE_TASK_STORAGE:
18358 		case BPF_MAP_TYPE_CGRP_STORAGE:
18359 		case BPF_MAP_TYPE_QUEUE:
18360 		case BPF_MAP_TYPE_STACK:
18361 		case BPF_MAP_TYPE_ARENA:
18362 			break;
18363 		default:
18364 			verbose(env,
18365 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
18366 			return -EINVAL;
18367 		}
18368 
18369 	return 0;
18370 }
18371 
18372 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
18373 {
18374 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
18375 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
18376 }
18377 
18378 /* find and rewrite pseudo imm in ld_imm64 instructions:
18379  *
18380  * 1. if it accesses map FD, replace it with actual map pointer.
18381  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
18382  *
18383  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
18384  */
18385 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
18386 {
18387 	struct bpf_insn *insn = env->prog->insnsi;
18388 	int insn_cnt = env->prog->len;
18389 	int i, j, err;
18390 
18391 	err = bpf_prog_calc_tag(env->prog);
18392 	if (err)
18393 		return err;
18394 
18395 	for (i = 0; i < insn_cnt; i++, insn++) {
18396 		if (BPF_CLASS(insn->code) == BPF_LDX &&
18397 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
18398 		    insn->imm != 0)) {
18399 			verbose(env, "BPF_LDX uses reserved fields\n");
18400 			return -EINVAL;
18401 		}
18402 
18403 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
18404 			struct bpf_insn_aux_data *aux;
18405 			struct bpf_map *map;
18406 			struct fd f;
18407 			u64 addr;
18408 			u32 fd;
18409 
18410 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
18411 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
18412 			    insn[1].off != 0) {
18413 				verbose(env, "invalid bpf_ld_imm64 insn\n");
18414 				return -EINVAL;
18415 			}
18416 
18417 			if (insn[0].src_reg == 0)
18418 				/* valid generic load 64-bit imm */
18419 				goto next_insn;
18420 
18421 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
18422 				aux = &env->insn_aux_data[i];
18423 				err = check_pseudo_btf_id(env, insn, aux);
18424 				if (err)
18425 					return err;
18426 				goto next_insn;
18427 			}
18428 
18429 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
18430 				aux = &env->insn_aux_data[i];
18431 				aux->ptr_type = PTR_TO_FUNC;
18432 				goto next_insn;
18433 			}
18434 
18435 			/* In final convert_pseudo_ld_imm64() step, this is
18436 			 * converted into regular 64-bit imm load insn.
18437 			 */
18438 			switch (insn[0].src_reg) {
18439 			case BPF_PSEUDO_MAP_VALUE:
18440 			case BPF_PSEUDO_MAP_IDX_VALUE:
18441 				break;
18442 			case BPF_PSEUDO_MAP_FD:
18443 			case BPF_PSEUDO_MAP_IDX:
18444 				if (insn[1].imm == 0)
18445 					break;
18446 				fallthrough;
18447 			default:
18448 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
18449 				return -EINVAL;
18450 			}
18451 
18452 			switch (insn[0].src_reg) {
18453 			case BPF_PSEUDO_MAP_IDX_VALUE:
18454 			case BPF_PSEUDO_MAP_IDX:
18455 				if (bpfptr_is_null(env->fd_array)) {
18456 					verbose(env, "fd_idx without fd_array is invalid\n");
18457 					return -EPROTO;
18458 				}
18459 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
18460 							    insn[0].imm * sizeof(fd),
18461 							    sizeof(fd)))
18462 					return -EFAULT;
18463 				break;
18464 			default:
18465 				fd = insn[0].imm;
18466 				break;
18467 			}
18468 
18469 			f = fdget(fd);
18470 			map = __bpf_map_get(f);
18471 			if (IS_ERR(map)) {
18472 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
18473 					insn[0].imm);
18474 				return PTR_ERR(map);
18475 			}
18476 
18477 			err = check_map_prog_compatibility(env, map, env->prog);
18478 			if (err) {
18479 				fdput(f);
18480 				return err;
18481 			}
18482 
18483 			aux = &env->insn_aux_data[i];
18484 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18485 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
18486 				addr = (unsigned long)map;
18487 			} else {
18488 				u32 off = insn[1].imm;
18489 
18490 				if (off >= BPF_MAX_VAR_OFF) {
18491 					verbose(env, "direct value offset of %u is not allowed\n", off);
18492 					fdput(f);
18493 					return -EINVAL;
18494 				}
18495 
18496 				if (!map->ops->map_direct_value_addr) {
18497 					verbose(env, "no direct value access support for this map type\n");
18498 					fdput(f);
18499 					return -EINVAL;
18500 				}
18501 
18502 				err = map->ops->map_direct_value_addr(map, &addr, off);
18503 				if (err) {
18504 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18505 						map->value_size, off);
18506 					fdput(f);
18507 					return err;
18508 				}
18509 
18510 				aux->map_off = off;
18511 				addr += off;
18512 			}
18513 
18514 			insn[0].imm = (u32)addr;
18515 			insn[1].imm = addr >> 32;
18516 
18517 			/* check whether we recorded this map already */
18518 			for (j = 0; j < env->used_map_cnt; j++) {
18519 				if (env->used_maps[j] == map) {
18520 					aux->map_index = j;
18521 					fdput(f);
18522 					goto next_insn;
18523 				}
18524 			}
18525 
18526 			if (env->used_map_cnt >= MAX_USED_MAPS) {
18527 				verbose(env, "The total number of maps per program has reached the limit of %u\n",
18528 					MAX_USED_MAPS);
18529 				fdput(f);
18530 				return -E2BIG;
18531 			}
18532 
18533 			if (env->prog->sleepable)
18534 				atomic64_inc(&map->sleepable_refcnt);
18535 			/* hold the map. If the program is rejected by verifier,
18536 			 * the map will be released by release_maps() or it
18537 			 * will be used by the valid program until it's unloaded
18538 			 * and all maps are released in bpf_free_used_maps()
18539 			 */
18540 			bpf_map_inc(map);
18541 
18542 			aux->map_index = env->used_map_cnt;
18543 			env->used_maps[env->used_map_cnt++] = map;
18544 
18545 			if (bpf_map_is_cgroup_storage(map) &&
18546 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
18547 				verbose(env, "only one cgroup storage of each type is allowed\n");
18548 				fdput(f);
18549 				return -EBUSY;
18550 			}
18551 			if (map->map_type == BPF_MAP_TYPE_ARENA) {
18552 				if (env->prog->aux->arena) {
18553 					verbose(env, "Only one arena per program\n");
18554 					fdput(f);
18555 					return -EBUSY;
18556 				}
18557 				if (!env->allow_ptr_leaks || !env->bpf_capable) {
18558 					verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
18559 					fdput(f);
18560 					return -EPERM;
18561 				}
18562 				if (!env->prog->jit_requested) {
18563 					verbose(env, "JIT is required to use arena\n");
18564 					fdput(f);
18565 					return -EOPNOTSUPP;
18566 				}
18567 				if (!bpf_jit_supports_arena()) {
18568 					verbose(env, "JIT doesn't support arena\n");
18569 					fdput(f);
18570 					return -EOPNOTSUPP;
18571 				}
18572 				env->prog->aux->arena = (void *)map;
18573 				if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
18574 					verbose(env, "arena's user address must be set via map_extra or mmap()\n");
18575 					fdput(f);
18576 					return -EINVAL;
18577 				}
18578 			}
18579 
18580 			fdput(f);
18581 next_insn:
18582 			insn++;
18583 			i++;
18584 			continue;
18585 		}
18586 
18587 		/* Basic sanity check before we invest more work here. */
18588 		if (!bpf_opcode_in_insntable(insn->code)) {
18589 			verbose(env, "unknown opcode %02x\n", insn->code);
18590 			return -EINVAL;
18591 		}
18592 	}
18593 
18594 	/* now all pseudo BPF_LD_IMM64 instructions load valid
18595 	 * 'struct bpf_map *' into a register instead of user map_fd.
18596 	 * These pointers will be used later by verifier to validate map access.
18597 	 */
18598 	return 0;
18599 }
18600 
18601 /* drop refcnt of maps used by the rejected program */
18602 static void release_maps(struct bpf_verifier_env *env)
18603 {
18604 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
18605 			     env->used_map_cnt);
18606 }
18607 
18608 /* drop refcnt of maps used by the rejected program */
18609 static void release_btfs(struct bpf_verifier_env *env)
18610 {
18611 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
18612 			     env->used_btf_cnt);
18613 }
18614 
18615 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18616 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18617 {
18618 	struct bpf_insn *insn = env->prog->insnsi;
18619 	int insn_cnt = env->prog->len;
18620 	int i;
18621 
18622 	for (i = 0; i < insn_cnt; i++, insn++) {
18623 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18624 			continue;
18625 		if (insn->src_reg == BPF_PSEUDO_FUNC)
18626 			continue;
18627 		insn->src_reg = 0;
18628 	}
18629 }
18630 
18631 /* single env->prog->insni[off] instruction was replaced with the range
18632  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
18633  * [0, off) and [off, end) to new locations, so the patched range stays zero
18634  */
18635 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18636 				 struct bpf_insn_aux_data *new_data,
18637 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
18638 {
18639 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
18640 	struct bpf_insn *insn = new_prog->insnsi;
18641 	u32 old_seen = old_data[off].seen;
18642 	u32 prog_len;
18643 	int i;
18644 
18645 	/* aux info at OFF always needs adjustment, no matter fast path
18646 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18647 	 * original insn at old prog.
18648 	 */
18649 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18650 
18651 	if (cnt == 1)
18652 		return;
18653 	prog_len = new_prog->len;
18654 
18655 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18656 	memcpy(new_data + off + cnt - 1, old_data + off,
18657 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
18658 	for (i = off; i < off + cnt - 1; i++) {
18659 		/* Expand insni[off]'s seen count to the patched range. */
18660 		new_data[i].seen = old_seen;
18661 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
18662 	}
18663 	env->insn_aux_data = new_data;
18664 	vfree(old_data);
18665 }
18666 
18667 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18668 {
18669 	int i;
18670 
18671 	if (len == 1)
18672 		return;
18673 	/* NOTE: fake 'exit' subprog should be updated as well. */
18674 	for (i = 0; i <= env->subprog_cnt; i++) {
18675 		if (env->subprog_info[i].start <= off)
18676 			continue;
18677 		env->subprog_info[i].start += len - 1;
18678 	}
18679 }
18680 
18681 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
18682 {
18683 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18684 	int i, sz = prog->aux->size_poke_tab;
18685 	struct bpf_jit_poke_descriptor *desc;
18686 
18687 	for (i = 0; i < sz; i++) {
18688 		desc = &tab[i];
18689 		if (desc->insn_idx <= off)
18690 			continue;
18691 		desc->insn_idx += len - 1;
18692 	}
18693 }
18694 
18695 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18696 					    const struct bpf_insn *patch, u32 len)
18697 {
18698 	struct bpf_prog *new_prog;
18699 	struct bpf_insn_aux_data *new_data = NULL;
18700 
18701 	if (len > 1) {
18702 		new_data = vzalloc(array_size(env->prog->len + len - 1,
18703 					      sizeof(struct bpf_insn_aux_data)));
18704 		if (!new_data)
18705 			return NULL;
18706 	}
18707 
18708 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18709 	if (IS_ERR(new_prog)) {
18710 		if (PTR_ERR(new_prog) == -ERANGE)
18711 			verbose(env,
18712 				"insn %d cannot be patched due to 16-bit range\n",
18713 				env->insn_aux_data[off].orig_idx);
18714 		vfree(new_data);
18715 		return NULL;
18716 	}
18717 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
18718 	adjust_subprog_starts(env, off, len);
18719 	adjust_poke_descs(new_prog, off, len);
18720 	return new_prog;
18721 }
18722 
18723 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18724 					      u32 off, u32 cnt)
18725 {
18726 	int i, j;
18727 
18728 	/* find first prog starting at or after off (first to remove) */
18729 	for (i = 0; i < env->subprog_cnt; i++)
18730 		if (env->subprog_info[i].start >= off)
18731 			break;
18732 	/* find first prog starting at or after off + cnt (first to stay) */
18733 	for (j = i; j < env->subprog_cnt; j++)
18734 		if (env->subprog_info[j].start >= off + cnt)
18735 			break;
18736 	/* if j doesn't start exactly at off + cnt, we are just removing
18737 	 * the front of previous prog
18738 	 */
18739 	if (env->subprog_info[j].start != off + cnt)
18740 		j--;
18741 
18742 	if (j > i) {
18743 		struct bpf_prog_aux *aux = env->prog->aux;
18744 		int move;
18745 
18746 		/* move fake 'exit' subprog as well */
18747 		move = env->subprog_cnt + 1 - j;
18748 
18749 		memmove(env->subprog_info + i,
18750 			env->subprog_info + j,
18751 			sizeof(*env->subprog_info) * move);
18752 		env->subprog_cnt -= j - i;
18753 
18754 		/* remove func_info */
18755 		if (aux->func_info) {
18756 			move = aux->func_info_cnt - j;
18757 
18758 			memmove(aux->func_info + i,
18759 				aux->func_info + j,
18760 				sizeof(*aux->func_info) * move);
18761 			aux->func_info_cnt -= j - i;
18762 			/* func_info->insn_off is set after all code rewrites,
18763 			 * in adjust_btf_func() - no need to adjust
18764 			 */
18765 		}
18766 	} else {
18767 		/* convert i from "first prog to remove" to "first to adjust" */
18768 		if (env->subprog_info[i].start == off)
18769 			i++;
18770 	}
18771 
18772 	/* update fake 'exit' subprog as well */
18773 	for (; i <= env->subprog_cnt; i++)
18774 		env->subprog_info[i].start -= cnt;
18775 
18776 	return 0;
18777 }
18778 
18779 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18780 				      u32 cnt)
18781 {
18782 	struct bpf_prog *prog = env->prog;
18783 	u32 i, l_off, l_cnt, nr_linfo;
18784 	struct bpf_line_info *linfo;
18785 
18786 	nr_linfo = prog->aux->nr_linfo;
18787 	if (!nr_linfo)
18788 		return 0;
18789 
18790 	linfo = prog->aux->linfo;
18791 
18792 	/* find first line info to remove, count lines to be removed */
18793 	for (i = 0; i < nr_linfo; i++)
18794 		if (linfo[i].insn_off >= off)
18795 			break;
18796 
18797 	l_off = i;
18798 	l_cnt = 0;
18799 	for (; i < nr_linfo; i++)
18800 		if (linfo[i].insn_off < off + cnt)
18801 			l_cnt++;
18802 		else
18803 			break;
18804 
18805 	/* First live insn doesn't match first live linfo, it needs to "inherit"
18806 	 * last removed linfo.  prog is already modified, so prog->len == off
18807 	 * means no live instructions after (tail of the program was removed).
18808 	 */
18809 	if (prog->len != off && l_cnt &&
18810 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18811 		l_cnt--;
18812 		linfo[--i].insn_off = off + cnt;
18813 	}
18814 
18815 	/* remove the line info which refer to the removed instructions */
18816 	if (l_cnt) {
18817 		memmove(linfo + l_off, linfo + i,
18818 			sizeof(*linfo) * (nr_linfo - i));
18819 
18820 		prog->aux->nr_linfo -= l_cnt;
18821 		nr_linfo = prog->aux->nr_linfo;
18822 	}
18823 
18824 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
18825 	for (i = l_off; i < nr_linfo; i++)
18826 		linfo[i].insn_off -= cnt;
18827 
18828 	/* fix up all subprogs (incl. 'exit') which start >= off */
18829 	for (i = 0; i <= env->subprog_cnt; i++)
18830 		if (env->subprog_info[i].linfo_idx > l_off) {
18831 			/* program may have started in the removed region but
18832 			 * may not be fully removed
18833 			 */
18834 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18835 				env->subprog_info[i].linfo_idx -= l_cnt;
18836 			else
18837 				env->subprog_info[i].linfo_idx = l_off;
18838 		}
18839 
18840 	return 0;
18841 }
18842 
18843 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18844 {
18845 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18846 	unsigned int orig_prog_len = env->prog->len;
18847 	int err;
18848 
18849 	if (bpf_prog_is_offloaded(env->prog->aux))
18850 		bpf_prog_offload_remove_insns(env, off, cnt);
18851 
18852 	err = bpf_remove_insns(env->prog, off, cnt);
18853 	if (err)
18854 		return err;
18855 
18856 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18857 	if (err)
18858 		return err;
18859 
18860 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18861 	if (err)
18862 		return err;
18863 
18864 	memmove(aux_data + off,	aux_data + off + cnt,
18865 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18866 
18867 	return 0;
18868 }
18869 
18870 /* The verifier does more data flow analysis than llvm and will not
18871  * explore branches that are dead at run time. Malicious programs can
18872  * have dead code too. Therefore replace all dead at-run-time code
18873  * with 'ja -1'.
18874  *
18875  * Just nops are not optimal, e.g. if they would sit at the end of the
18876  * program and through another bug we would manage to jump there, then
18877  * we'd execute beyond program memory otherwise. Returning exception
18878  * code also wouldn't work since we can have subprogs where the dead
18879  * code could be located.
18880  */
18881 static void sanitize_dead_code(struct bpf_verifier_env *env)
18882 {
18883 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18884 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18885 	struct bpf_insn *insn = env->prog->insnsi;
18886 	const int insn_cnt = env->prog->len;
18887 	int i;
18888 
18889 	for (i = 0; i < insn_cnt; i++) {
18890 		if (aux_data[i].seen)
18891 			continue;
18892 		memcpy(insn + i, &trap, sizeof(trap));
18893 		aux_data[i].zext_dst = false;
18894 	}
18895 }
18896 
18897 static bool insn_is_cond_jump(u8 code)
18898 {
18899 	u8 op;
18900 
18901 	op = BPF_OP(code);
18902 	if (BPF_CLASS(code) == BPF_JMP32)
18903 		return op != BPF_JA;
18904 
18905 	if (BPF_CLASS(code) != BPF_JMP)
18906 		return false;
18907 
18908 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18909 }
18910 
18911 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18912 {
18913 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18914 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18915 	struct bpf_insn *insn = env->prog->insnsi;
18916 	const int insn_cnt = env->prog->len;
18917 	int i;
18918 
18919 	for (i = 0; i < insn_cnt; i++, insn++) {
18920 		if (!insn_is_cond_jump(insn->code))
18921 			continue;
18922 
18923 		if (!aux_data[i + 1].seen)
18924 			ja.off = insn->off;
18925 		else if (!aux_data[i + 1 + insn->off].seen)
18926 			ja.off = 0;
18927 		else
18928 			continue;
18929 
18930 		if (bpf_prog_is_offloaded(env->prog->aux))
18931 			bpf_prog_offload_replace_insn(env, i, &ja);
18932 
18933 		memcpy(insn, &ja, sizeof(ja));
18934 	}
18935 }
18936 
18937 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18938 {
18939 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18940 	int insn_cnt = env->prog->len;
18941 	int i, err;
18942 
18943 	for (i = 0; i < insn_cnt; i++) {
18944 		int j;
18945 
18946 		j = 0;
18947 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18948 			j++;
18949 		if (!j)
18950 			continue;
18951 
18952 		err = verifier_remove_insns(env, i, j);
18953 		if (err)
18954 			return err;
18955 		insn_cnt = env->prog->len;
18956 	}
18957 
18958 	return 0;
18959 }
18960 
18961 static int opt_remove_nops(struct bpf_verifier_env *env)
18962 {
18963 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18964 	struct bpf_insn *insn = env->prog->insnsi;
18965 	int insn_cnt = env->prog->len;
18966 	int i, err;
18967 
18968 	for (i = 0; i < insn_cnt; i++) {
18969 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18970 			continue;
18971 
18972 		err = verifier_remove_insns(env, i, 1);
18973 		if (err)
18974 			return err;
18975 		insn_cnt--;
18976 		i--;
18977 	}
18978 
18979 	return 0;
18980 }
18981 
18982 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18983 					 const union bpf_attr *attr)
18984 {
18985 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18986 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18987 	int i, patch_len, delta = 0, len = env->prog->len;
18988 	struct bpf_insn *insns = env->prog->insnsi;
18989 	struct bpf_prog *new_prog;
18990 	bool rnd_hi32;
18991 
18992 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18993 	zext_patch[1] = BPF_ZEXT_REG(0);
18994 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18995 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18996 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18997 	for (i = 0; i < len; i++) {
18998 		int adj_idx = i + delta;
18999 		struct bpf_insn insn;
19000 		int load_reg;
19001 
19002 		insn = insns[adj_idx];
19003 		load_reg = insn_def_regno(&insn);
19004 		if (!aux[adj_idx].zext_dst) {
19005 			u8 code, class;
19006 			u32 imm_rnd;
19007 
19008 			if (!rnd_hi32)
19009 				continue;
19010 
19011 			code = insn.code;
19012 			class = BPF_CLASS(code);
19013 			if (load_reg == -1)
19014 				continue;
19015 
19016 			/* NOTE: arg "reg" (the fourth one) is only used for
19017 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
19018 			 *       here.
19019 			 */
19020 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
19021 				if (class == BPF_LD &&
19022 				    BPF_MODE(code) == BPF_IMM)
19023 					i++;
19024 				continue;
19025 			}
19026 
19027 			/* ctx load could be transformed into wider load. */
19028 			if (class == BPF_LDX &&
19029 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
19030 				continue;
19031 
19032 			imm_rnd = get_random_u32();
19033 			rnd_hi32_patch[0] = insn;
19034 			rnd_hi32_patch[1].imm = imm_rnd;
19035 			rnd_hi32_patch[3].dst_reg = load_reg;
19036 			patch = rnd_hi32_patch;
19037 			patch_len = 4;
19038 			goto apply_patch_buffer;
19039 		}
19040 
19041 		/* Add in an zero-extend instruction if a) the JIT has requested
19042 		 * it or b) it's a CMPXCHG.
19043 		 *
19044 		 * The latter is because: BPF_CMPXCHG always loads a value into
19045 		 * R0, therefore always zero-extends. However some archs'
19046 		 * equivalent instruction only does this load when the
19047 		 * comparison is successful. This detail of CMPXCHG is
19048 		 * orthogonal to the general zero-extension behaviour of the
19049 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
19050 		 */
19051 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
19052 			continue;
19053 
19054 		/* Zero-extension is done by the caller. */
19055 		if (bpf_pseudo_kfunc_call(&insn))
19056 			continue;
19057 
19058 		if (WARN_ON(load_reg == -1)) {
19059 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
19060 			return -EFAULT;
19061 		}
19062 
19063 		zext_patch[0] = insn;
19064 		zext_patch[1].dst_reg = load_reg;
19065 		zext_patch[1].src_reg = load_reg;
19066 		patch = zext_patch;
19067 		patch_len = 2;
19068 apply_patch_buffer:
19069 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
19070 		if (!new_prog)
19071 			return -ENOMEM;
19072 		env->prog = new_prog;
19073 		insns = new_prog->insnsi;
19074 		aux = env->insn_aux_data;
19075 		delta += patch_len - 1;
19076 	}
19077 
19078 	return 0;
19079 }
19080 
19081 /* convert load instructions that access fields of a context type into a
19082  * sequence of instructions that access fields of the underlying structure:
19083  *     struct __sk_buff    -> struct sk_buff
19084  *     struct bpf_sock_ops -> struct sock
19085  */
19086 static int convert_ctx_accesses(struct bpf_verifier_env *env)
19087 {
19088 	const struct bpf_verifier_ops *ops = env->ops;
19089 	int i, cnt, size, ctx_field_size, delta = 0;
19090 	const int insn_cnt = env->prog->len;
19091 	struct bpf_insn insn_buf[16], *insn;
19092 	u32 target_size, size_default, off;
19093 	struct bpf_prog *new_prog;
19094 	enum bpf_access_type type;
19095 	bool is_narrower_load;
19096 
19097 	if (ops->gen_prologue || env->seen_direct_write) {
19098 		if (!ops->gen_prologue) {
19099 			verbose(env, "bpf verifier is misconfigured\n");
19100 			return -EINVAL;
19101 		}
19102 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
19103 					env->prog);
19104 		if (cnt >= ARRAY_SIZE(insn_buf)) {
19105 			verbose(env, "bpf verifier is misconfigured\n");
19106 			return -EINVAL;
19107 		} else if (cnt) {
19108 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
19109 			if (!new_prog)
19110 				return -ENOMEM;
19111 
19112 			env->prog = new_prog;
19113 			delta += cnt - 1;
19114 		}
19115 	}
19116 
19117 	if (bpf_prog_is_offloaded(env->prog->aux))
19118 		return 0;
19119 
19120 	insn = env->prog->insnsi + delta;
19121 
19122 	for (i = 0; i < insn_cnt; i++, insn++) {
19123 		bpf_convert_ctx_access_t convert_ctx_access;
19124 		u8 mode;
19125 
19126 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
19127 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
19128 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
19129 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
19130 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
19131 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
19132 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
19133 			type = BPF_READ;
19134 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
19135 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
19136 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
19137 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
19138 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
19139 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
19140 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
19141 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
19142 			type = BPF_WRITE;
19143 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
19144 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
19145 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
19146 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
19147 			env->prog->aux->num_exentries++;
19148 			continue;
19149 		} else {
19150 			continue;
19151 		}
19152 
19153 		if (type == BPF_WRITE &&
19154 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
19155 			struct bpf_insn patch[] = {
19156 				*insn,
19157 				BPF_ST_NOSPEC(),
19158 			};
19159 
19160 			cnt = ARRAY_SIZE(patch);
19161 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
19162 			if (!new_prog)
19163 				return -ENOMEM;
19164 
19165 			delta    += cnt - 1;
19166 			env->prog = new_prog;
19167 			insn      = new_prog->insnsi + i + delta;
19168 			continue;
19169 		}
19170 
19171 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
19172 		case PTR_TO_CTX:
19173 			if (!ops->convert_ctx_access)
19174 				continue;
19175 			convert_ctx_access = ops->convert_ctx_access;
19176 			break;
19177 		case PTR_TO_SOCKET:
19178 		case PTR_TO_SOCK_COMMON:
19179 			convert_ctx_access = bpf_sock_convert_ctx_access;
19180 			break;
19181 		case PTR_TO_TCP_SOCK:
19182 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
19183 			break;
19184 		case PTR_TO_XDP_SOCK:
19185 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
19186 			break;
19187 		case PTR_TO_BTF_ID:
19188 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
19189 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
19190 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
19191 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
19192 		 * any faults for loads into such types. BPF_WRITE is disallowed
19193 		 * for this case.
19194 		 */
19195 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
19196 			if (type == BPF_READ) {
19197 				if (BPF_MODE(insn->code) == BPF_MEM)
19198 					insn->code = BPF_LDX | BPF_PROBE_MEM |
19199 						     BPF_SIZE((insn)->code);
19200 				else
19201 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
19202 						     BPF_SIZE((insn)->code);
19203 				env->prog->aux->num_exentries++;
19204 			}
19205 			continue;
19206 		case PTR_TO_ARENA:
19207 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
19208 				verbose(env, "sign extending loads from arena are not supported yet\n");
19209 				return -EOPNOTSUPP;
19210 			}
19211 			insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
19212 			env->prog->aux->num_exentries++;
19213 			continue;
19214 		default:
19215 			continue;
19216 		}
19217 
19218 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
19219 		size = BPF_LDST_BYTES(insn);
19220 		mode = BPF_MODE(insn->code);
19221 
19222 		/* If the read access is a narrower load of the field,
19223 		 * convert to a 4/8-byte load, to minimum program type specific
19224 		 * convert_ctx_access changes. If conversion is successful,
19225 		 * we will apply proper mask to the result.
19226 		 */
19227 		is_narrower_load = size < ctx_field_size;
19228 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
19229 		off = insn->off;
19230 		if (is_narrower_load) {
19231 			u8 size_code;
19232 
19233 			if (type == BPF_WRITE) {
19234 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
19235 				return -EINVAL;
19236 			}
19237 
19238 			size_code = BPF_H;
19239 			if (ctx_field_size == 4)
19240 				size_code = BPF_W;
19241 			else if (ctx_field_size == 8)
19242 				size_code = BPF_DW;
19243 
19244 			insn->off = off & ~(size_default - 1);
19245 			insn->code = BPF_LDX | BPF_MEM | size_code;
19246 		}
19247 
19248 		target_size = 0;
19249 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
19250 					 &target_size);
19251 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
19252 		    (ctx_field_size && !target_size)) {
19253 			verbose(env, "bpf verifier is misconfigured\n");
19254 			return -EINVAL;
19255 		}
19256 
19257 		if (is_narrower_load && size < target_size) {
19258 			u8 shift = bpf_ctx_narrow_access_offset(
19259 				off, size, size_default) * 8;
19260 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
19261 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
19262 				return -EINVAL;
19263 			}
19264 			if (ctx_field_size <= 4) {
19265 				if (shift)
19266 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
19267 									insn->dst_reg,
19268 									shift);
19269 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19270 								(1 << size * 8) - 1);
19271 			} else {
19272 				if (shift)
19273 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
19274 									insn->dst_reg,
19275 									shift);
19276 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19277 								(1ULL << size * 8) - 1);
19278 			}
19279 		}
19280 		if (mode == BPF_MEMSX)
19281 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
19282 						       insn->dst_reg, insn->dst_reg,
19283 						       size * 8, 0);
19284 
19285 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19286 		if (!new_prog)
19287 			return -ENOMEM;
19288 
19289 		delta += cnt - 1;
19290 
19291 		/* keep walking new program and skip insns we just inserted */
19292 		env->prog = new_prog;
19293 		insn      = new_prog->insnsi + i + delta;
19294 	}
19295 
19296 	return 0;
19297 }
19298 
19299 static int jit_subprogs(struct bpf_verifier_env *env)
19300 {
19301 	struct bpf_prog *prog = env->prog, **func, *tmp;
19302 	int i, j, subprog_start, subprog_end = 0, len, subprog;
19303 	struct bpf_map *map_ptr;
19304 	struct bpf_insn *insn;
19305 	void *old_bpf_func;
19306 	int err, num_exentries;
19307 
19308 	if (env->subprog_cnt <= 1)
19309 		return 0;
19310 
19311 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19312 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
19313 			continue;
19314 
19315 		/* Upon error here we cannot fall back to interpreter but
19316 		 * need a hard reject of the program. Thus -EFAULT is
19317 		 * propagated in any case.
19318 		 */
19319 		subprog = find_subprog(env, i + insn->imm + 1);
19320 		if (subprog < 0) {
19321 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
19322 				  i + insn->imm + 1);
19323 			return -EFAULT;
19324 		}
19325 		/* temporarily remember subprog id inside insn instead of
19326 		 * aux_data, since next loop will split up all insns into funcs
19327 		 */
19328 		insn->off = subprog;
19329 		/* remember original imm in case JIT fails and fallback
19330 		 * to interpreter will be needed
19331 		 */
19332 		env->insn_aux_data[i].call_imm = insn->imm;
19333 		/* point imm to __bpf_call_base+1 from JITs point of view */
19334 		insn->imm = 1;
19335 		if (bpf_pseudo_func(insn)) {
19336 #if defined(MODULES_VADDR)
19337 			u64 addr = MODULES_VADDR;
19338 #else
19339 			u64 addr = VMALLOC_START;
19340 #endif
19341 			/* jit (e.g. x86_64) may emit fewer instructions
19342 			 * if it learns a u32 imm is the same as a u64 imm.
19343 			 * Set close enough to possible prog address.
19344 			 */
19345 			insn[0].imm = (u32)addr;
19346 			insn[1].imm = addr >> 32;
19347 		}
19348 	}
19349 
19350 	err = bpf_prog_alloc_jited_linfo(prog);
19351 	if (err)
19352 		goto out_undo_insn;
19353 
19354 	err = -ENOMEM;
19355 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
19356 	if (!func)
19357 		goto out_undo_insn;
19358 
19359 	for (i = 0; i < env->subprog_cnt; i++) {
19360 		subprog_start = subprog_end;
19361 		subprog_end = env->subprog_info[i + 1].start;
19362 
19363 		len = subprog_end - subprog_start;
19364 		/* bpf_prog_run() doesn't call subprogs directly,
19365 		 * hence main prog stats include the runtime of subprogs.
19366 		 * subprogs don't have IDs and not reachable via prog_get_next_id
19367 		 * func[i]->stats will never be accessed and stays NULL
19368 		 */
19369 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
19370 		if (!func[i])
19371 			goto out_free;
19372 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
19373 		       len * sizeof(struct bpf_insn));
19374 		func[i]->type = prog->type;
19375 		func[i]->len = len;
19376 		if (bpf_prog_calc_tag(func[i]))
19377 			goto out_free;
19378 		func[i]->is_func = 1;
19379 		func[i]->sleepable = prog->sleepable;
19380 		func[i]->aux->func_idx = i;
19381 		/* Below members will be freed only at prog->aux */
19382 		func[i]->aux->btf = prog->aux->btf;
19383 		func[i]->aux->func_info = prog->aux->func_info;
19384 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
19385 		func[i]->aux->poke_tab = prog->aux->poke_tab;
19386 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
19387 
19388 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
19389 			struct bpf_jit_poke_descriptor *poke;
19390 
19391 			poke = &prog->aux->poke_tab[j];
19392 			if (poke->insn_idx < subprog_end &&
19393 			    poke->insn_idx >= subprog_start)
19394 				poke->aux = func[i]->aux;
19395 		}
19396 
19397 		func[i]->aux->name[0] = 'F';
19398 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
19399 		func[i]->jit_requested = 1;
19400 		func[i]->blinding_requested = prog->blinding_requested;
19401 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
19402 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
19403 		func[i]->aux->linfo = prog->aux->linfo;
19404 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
19405 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
19406 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
19407 		func[i]->aux->arena = prog->aux->arena;
19408 		num_exentries = 0;
19409 		insn = func[i]->insnsi;
19410 		for (j = 0; j < func[i]->len; j++, insn++) {
19411 			if (BPF_CLASS(insn->code) == BPF_LDX &&
19412 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
19413 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
19414 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
19415 				num_exentries++;
19416 			if ((BPF_CLASS(insn->code) == BPF_STX ||
19417 			     BPF_CLASS(insn->code) == BPF_ST) &&
19418 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
19419 				num_exentries++;
19420 			if (BPF_CLASS(insn->code) == BPF_STX &&
19421 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
19422 				num_exentries++;
19423 		}
19424 		func[i]->aux->num_exentries = num_exentries;
19425 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
19426 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
19427 		if (!i)
19428 			func[i]->aux->exception_boundary = env->seen_exception;
19429 		func[i] = bpf_int_jit_compile(func[i]);
19430 		if (!func[i]->jited) {
19431 			err = -ENOTSUPP;
19432 			goto out_free;
19433 		}
19434 		cond_resched();
19435 	}
19436 
19437 	/* at this point all bpf functions were successfully JITed
19438 	 * now populate all bpf_calls with correct addresses and
19439 	 * run last pass of JIT
19440 	 */
19441 	for (i = 0; i < env->subprog_cnt; i++) {
19442 		insn = func[i]->insnsi;
19443 		for (j = 0; j < func[i]->len; j++, insn++) {
19444 			if (bpf_pseudo_func(insn)) {
19445 				subprog = insn->off;
19446 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
19447 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
19448 				continue;
19449 			}
19450 			if (!bpf_pseudo_call(insn))
19451 				continue;
19452 			subprog = insn->off;
19453 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
19454 		}
19455 
19456 		/* we use the aux data to keep a list of the start addresses
19457 		 * of the JITed images for each function in the program
19458 		 *
19459 		 * for some architectures, such as powerpc64, the imm field
19460 		 * might not be large enough to hold the offset of the start
19461 		 * address of the callee's JITed image from __bpf_call_base
19462 		 *
19463 		 * in such cases, we can lookup the start address of a callee
19464 		 * by using its subprog id, available from the off field of
19465 		 * the call instruction, as an index for this list
19466 		 */
19467 		func[i]->aux->func = func;
19468 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19469 		func[i]->aux->real_func_cnt = env->subprog_cnt;
19470 	}
19471 	for (i = 0; i < env->subprog_cnt; i++) {
19472 		old_bpf_func = func[i]->bpf_func;
19473 		tmp = bpf_int_jit_compile(func[i]);
19474 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
19475 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
19476 			err = -ENOTSUPP;
19477 			goto out_free;
19478 		}
19479 		cond_resched();
19480 	}
19481 
19482 	/* finally lock prog and jit images for all functions and
19483 	 * populate kallsysm. Begin at the first subprogram, since
19484 	 * bpf_prog_load will add the kallsyms for the main program.
19485 	 */
19486 	for (i = 1; i < env->subprog_cnt; i++) {
19487 		err = bpf_prog_lock_ro(func[i]);
19488 		if (err)
19489 			goto out_free;
19490 	}
19491 
19492 	for (i = 1; i < env->subprog_cnt; i++)
19493 		bpf_prog_kallsyms_add(func[i]);
19494 
19495 	/* Last step: make now unused interpreter insns from main
19496 	 * prog consistent for later dump requests, so they can
19497 	 * later look the same as if they were interpreted only.
19498 	 */
19499 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19500 		if (bpf_pseudo_func(insn)) {
19501 			insn[0].imm = env->insn_aux_data[i].call_imm;
19502 			insn[1].imm = insn->off;
19503 			insn->off = 0;
19504 			continue;
19505 		}
19506 		if (!bpf_pseudo_call(insn))
19507 			continue;
19508 		insn->off = env->insn_aux_data[i].call_imm;
19509 		subprog = find_subprog(env, i + insn->off + 1);
19510 		insn->imm = subprog;
19511 	}
19512 
19513 	prog->jited = 1;
19514 	prog->bpf_func = func[0]->bpf_func;
19515 	prog->jited_len = func[0]->jited_len;
19516 	prog->aux->extable = func[0]->aux->extable;
19517 	prog->aux->num_exentries = func[0]->aux->num_exentries;
19518 	prog->aux->func = func;
19519 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19520 	prog->aux->real_func_cnt = env->subprog_cnt;
19521 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
19522 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
19523 	bpf_prog_jit_attempt_done(prog);
19524 	return 0;
19525 out_free:
19526 	/* We failed JIT'ing, so at this point we need to unregister poke
19527 	 * descriptors from subprogs, so that kernel is not attempting to
19528 	 * patch it anymore as we're freeing the subprog JIT memory.
19529 	 */
19530 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19531 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19532 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
19533 	}
19534 	/* At this point we're guaranteed that poke descriptors are not
19535 	 * live anymore. We can just unlink its descriptor table as it's
19536 	 * released with the main prog.
19537 	 */
19538 	for (i = 0; i < env->subprog_cnt; i++) {
19539 		if (!func[i])
19540 			continue;
19541 		func[i]->aux->poke_tab = NULL;
19542 		bpf_jit_free(func[i]);
19543 	}
19544 	kfree(func);
19545 out_undo_insn:
19546 	/* cleanup main prog to be interpreted */
19547 	prog->jit_requested = 0;
19548 	prog->blinding_requested = 0;
19549 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19550 		if (!bpf_pseudo_call(insn))
19551 			continue;
19552 		insn->off = 0;
19553 		insn->imm = env->insn_aux_data[i].call_imm;
19554 	}
19555 	bpf_prog_jit_attempt_done(prog);
19556 	return err;
19557 }
19558 
19559 static int fixup_call_args(struct bpf_verifier_env *env)
19560 {
19561 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19562 	struct bpf_prog *prog = env->prog;
19563 	struct bpf_insn *insn = prog->insnsi;
19564 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
19565 	int i, depth;
19566 #endif
19567 	int err = 0;
19568 
19569 	if (env->prog->jit_requested &&
19570 	    !bpf_prog_is_offloaded(env->prog->aux)) {
19571 		err = jit_subprogs(env);
19572 		if (err == 0)
19573 			return 0;
19574 		if (err == -EFAULT)
19575 			return err;
19576 	}
19577 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19578 	if (has_kfunc_call) {
19579 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
19580 		return -EINVAL;
19581 	}
19582 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
19583 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
19584 		 * have to be rejected, since interpreter doesn't support them yet.
19585 		 */
19586 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
19587 		return -EINVAL;
19588 	}
19589 	for (i = 0; i < prog->len; i++, insn++) {
19590 		if (bpf_pseudo_func(insn)) {
19591 			/* When JIT fails the progs with callback calls
19592 			 * have to be rejected, since interpreter doesn't support them yet.
19593 			 */
19594 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
19595 			return -EINVAL;
19596 		}
19597 
19598 		if (!bpf_pseudo_call(insn))
19599 			continue;
19600 		depth = get_callee_stack_depth(env, insn, i);
19601 		if (depth < 0)
19602 			return depth;
19603 		bpf_patch_call_args(insn, depth);
19604 	}
19605 	err = 0;
19606 #endif
19607 	return err;
19608 }
19609 
19610 /* replace a generic kfunc with a specialized version if necessary */
19611 static void specialize_kfunc(struct bpf_verifier_env *env,
19612 			     u32 func_id, u16 offset, unsigned long *addr)
19613 {
19614 	struct bpf_prog *prog = env->prog;
19615 	bool seen_direct_write;
19616 	void *xdp_kfunc;
19617 	bool is_rdonly;
19618 
19619 	if (bpf_dev_bound_kfunc_id(func_id)) {
19620 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19621 		if (xdp_kfunc) {
19622 			*addr = (unsigned long)xdp_kfunc;
19623 			return;
19624 		}
19625 		/* fallback to default kfunc when not supported by netdev */
19626 	}
19627 
19628 	if (offset)
19629 		return;
19630 
19631 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19632 		seen_direct_write = env->seen_direct_write;
19633 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19634 
19635 		if (is_rdonly)
19636 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19637 
19638 		/* restore env->seen_direct_write to its original value, since
19639 		 * may_access_direct_pkt_data mutates it
19640 		 */
19641 		env->seen_direct_write = seen_direct_write;
19642 	}
19643 }
19644 
19645 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19646 					    u16 struct_meta_reg,
19647 					    u16 node_offset_reg,
19648 					    struct bpf_insn *insn,
19649 					    struct bpf_insn *insn_buf,
19650 					    int *cnt)
19651 {
19652 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19653 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19654 
19655 	insn_buf[0] = addr[0];
19656 	insn_buf[1] = addr[1];
19657 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19658 	insn_buf[3] = *insn;
19659 	*cnt = 4;
19660 }
19661 
19662 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19663 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19664 {
19665 	const struct bpf_kfunc_desc *desc;
19666 
19667 	if (!insn->imm) {
19668 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19669 		return -EINVAL;
19670 	}
19671 
19672 	*cnt = 0;
19673 
19674 	/* insn->imm has the btf func_id. Replace it with an offset relative to
19675 	 * __bpf_call_base, unless the JIT needs to call functions that are
19676 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19677 	 */
19678 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19679 	if (!desc) {
19680 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19681 			insn->imm);
19682 		return -EFAULT;
19683 	}
19684 
19685 	if (!bpf_jit_supports_far_kfunc_call())
19686 		insn->imm = BPF_CALL_IMM(desc->addr);
19687 	if (insn->off)
19688 		return 0;
19689 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19690 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
19691 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19692 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19693 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19694 
19695 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19696 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19697 				insn_idx);
19698 			return -EFAULT;
19699 		}
19700 
19701 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19702 		insn_buf[1] = addr[0];
19703 		insn_buf[2] = addr[1];
19704 		insn_buf[3] = *insn;
19705 		*cnt = 4;
19706 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
19707 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
19708 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
19709 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19710 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19711 
19712 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19713 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19714 				insn_idx);
19715 			return -EFAULT;
19716 		}
19717 
19718 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19719 		    !kptr_struct_meta) {
19720 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19721 				insn_idx);
19722 			return -EFAULT;
19723 		}
19724 
19725 		insn_buf[0] = addr[0];
19726 		insn_buf[1] = addr[1];
19727 		insn_buf[2] = *insn;
19728 		*cnt = 3;
19729 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19730 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19731 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19732 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19733 		int struct_meta_reg = BPF_REG_3;
19734 		int node_offset_reg = BPF_REG_4;
19735 
19736 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19737 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19738 			struct_meta_reg = BPF_REG_4;
19739 			node_offset_reg = BPF_REG_5;
19740 		}
19741 
19742 		if (!kptr_struct_meta) {
19743 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19744 				insn_idx);
19745 			return -EFAULT;
19746 		}
19747 
19748 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19749 						node_offset_reg, insn, insn_buf, cnt);
19750 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19751 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19752 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19753 		*cnt = 1;
19754 	} else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) {
19755 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) };
19756 
19757 		insn_buf[0] = ld_addrs[0];
19758 		insn_buf[1] = ld_addrs[1];
19759 		insn_buf[2] = *insn;
19760 		*cnt = 3;
19761 	}
19762 	return 0;
19763 }
19764 
19765 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
19766 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19767 {
19768 	struct bpf_subprog_info *info = env->subprog_info;
19769 	int cnt = env->subprog_cnt;
19770 	struct bpf_prog *prog;
19771 
19772 	/* We only reserve one slot for hidden subprogs in subprog_info. */
19773 	if (env->hidden_subprog_cnt) {
19774 		verbose(env, "verifier internal error: only one hidden subprog supported\n");
19775 		return -EFAULT;
19776 	}
19777 	/* We're not patching any existing instruction, just appending the new
19778 	 * ones for the hidden subprog. Hence all of the adjustment operations
19779 	 * in bpf_patch_insn_data are no-ops.
19780 	 */
19781 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19782 	if (!prog)
19783 		return -ENOMEM;
19784 	env->prog = prog;
19785 	info[cnt + 1].start = info[cnt].start;
19786 	info[cnt].start = prog->len - len + 1;
19787 	env->subprog_cnt++;
19788 	env->hidden_subprog_cnt++;
19789 	return 0;
19790 }
19791 
19792 /* Do various post-verification rewrites in a single program pass.
19793  * These rewrites simplify JIT and interpreter implementations.
19794  */
19795 static int do_misc_fixups(struct bpf_verifier_env *env)
19796 {
19797 	struct bpf_prog *prog = env->prog;
19798 	enum bpf_attach_type eatype = prog->expected_attach_type;
19799 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
19800 	struct bpf_insn *insn = prog->insnsi;
19801 	const struct bpf_func_proto *fn;
19802 	const int insn_cnt = prog->len;
19803 	const struct bpf_map_ops *ops;
19804 	struct bpf_insn_aux_data *aux;
19805 	struct bpf_insn insn_buf[16];
19806 	struct bpf_prog *new_prog;
19807 	struct bpf_map *map_ptr;
19808 	int i, ret, cnt, delta = 0, cur_subprog = 0;
19809 	struct bpf_subprog_info *subprogs = env->subprog_info;
19810 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19811 	u16 stack_depth_extra = 0;
19812 
19813 	if (env->seen_exception && !env->exception_callback_subprog) {
19814 		struct bpf_insn patch[] = {
19815 			env->prog->insnsi[insn_cnt - 1],
19816 			BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19817 			BPF_EXIT_INSN(),
19818 		};
19819 
19820 		ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19821 		if (ret < 0)
19822 			return ret;
19823 		prog = env->prog;
19824 		insn = prog->insnsi;
19825 
19826 		env->exception_callback_subprog = env->subprog_cnt - 1;
19827 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19828 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
19829 	}
19830 
19831 	for (i = 0; i < insn_cnt;) {
19832 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
19833 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
19834 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
19835 				/* convert to 32-bit mov that clears upper 32-bit */
19836 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
19837 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
19838 				insn->off = 0;
19839 				insn->imm = 0;
19840 			} /* cast from as(0) to as(1) should be handled by JIT */
19841 			goto next_insn;
19842 		}
19843 
19844 		if (env->insn_aux_data[i + delta].needs_zext)
19845 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
19846 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
19847 
19848 		/* Make divide-by-zero exceptions impossible. */
19849 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19850 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19851 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19852 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19853 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19854 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19855 			struct bpf_insn *patchlet;
19856 			struct bpf_insn chk_and_div[] = {
19857 				/* [R,W]x div 0 -> 0 */
19858 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19859 					     BPF_JNE | BPF_K, insn->src_reg,
19860 					     0, 2, 0),
19861 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19862 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19863 				*insn,
19864 			};
19865 			struct bpf_insn chk_and_mod[] = {
19866 				/* [R,W]x mod 0 -> [R,W]x */
19867 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19868 					     BPF_JEQ | BPF_K, insn->src_reg,
19869 					     0, 1 + (is64 ? 0 : 1), 0),
19870 				*insn,
19871 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19872 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19873 			};
19874 
19875 			patchlet = isdiv ? chk_and_div : chk_and_mod;
19876 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19877 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19878 
19879 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19880 			if (!new_prog)
19881 				return -ENOMEM;
19882 
19883 			delta    += cnt - 1;
19884 			env->prog = prog = new_prog;
19885 			insn      = new_prog->insnsi + i + delta;
19886 			goto next_insn;
19887 		}
19888 
19889 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19890 		if (BPF_CLASS(insn->code) == BPF_LD &&
19891 		    (BPF_MODE(insn->code) == BPF_ABS ||
19892 		     BPF_MODE(insn->code) == BPF_IND)) {
19893 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
19894 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19895 				verbose(env, "bpf verifier is misconfigured\n");
19896 				return -EINVAL;
19897 			}
19898 
19899 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19900 			if (!new_prog)
19901 				return -ENOMEM;
19902 
19903 			delta    += cnt - 1;
19904 			env->prog = prog = new_prog;
19905 			insn      = new_prog->insnsi + i + delta;
19906 			goto next_insn;
19907 		}
19908 
19909 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
19910 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19911 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19912 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19913 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19914 			struct bpf_insn *patch = &insn_buf[0];
19915 			bool issrc, isneg, isimm;
19916 			u32 off_reg;
19917 
19918 			aux = &env->insn_aux_data[i + delta];
19919 			if (!aux->alu_state ||
19920 			    aux->alu_state == BPF_ALU_NON_POINTER)
19921 				goto next_insn;
19922 
19923 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19924 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19925 				BPF_ALU_SANITIZE_SRC;
19926 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19927 
19928 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
19929 			if (isimm) {
19930 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19931 			} else {
19932 				if (isneg)
19933 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19934 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19935 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19936 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19937 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19938 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19939 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19940 			}
19941 			if (!issrc)
19942 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19943 			insn->src_reg = BPF_REG_AX;
19944 			if (isneg)
19945 				insn->code = insn->code == code_add ?
19946 					     code_sub : code_add;
19947 			*patch++ = *insn;
19948 			if (issrc && isneg && !isimm)
19949 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19950 			cnt = patch - insn_buf;
19951 
19952 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19953 			if (!new_prog)
19954 				return -ENOMEM;
19955 
19956 			delta    += cnt - 1;
19957 			env->prog = prog = new_prog;
19958 			insn      = new_prog->insnsi + i + delta;
19959 			goto next_insn;
19960 		}
19961 
19962 		if (is_may_goto_insn(insn)) {
19963 			int stack_off = -stack_depth - 8;
19964 
19965 			stack_depth_extra = 8;
19966 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
19967 			insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
19968 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
19969 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
19970 			cnt = 4;
19971 
19972 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19973 			if (!new_prog)
19974 				return -ENOMEM;
19975 
19976 			delta += cnt - 1;
19977 			env->prog = prog = new_prog;
19978 			insn = new_prog->insnsi + i + delta;
19979 			goto next_insn;
19980 		}
19981 
19982 		if (insn->code != (BPF_JMP | BPF_CALL))
19983 			goto next_insn;
19984 		if (insn->src_reg == BPF_PSEUDO_CALL)
19985 			goto next_insn;
19986 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19987 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19988 			if (ret)
19989 				return ret;
19990 			if (cnt == 0)
19991 				goto next_insn;
19992 
19993 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19994 			if (!new_prog)
19995 				return -ENOMEM;
19996 
19997 			delta	 += cnt - 1;
19998 			env->prog = prog = new_prog;
19999 			insn	  = new_prog->insnsi + i + delta;
20000 			goto next_insn;
20001 		}
20002 
20003 		if (insn->imm == BPF_FUNC_get_route_realm)
20004 			prog->dst_needed = 1;
20005 		if (insn->imm == BPF_FUNC_get_prandom_u32)
20006 			bpf_user_rnd_init_once();
20007 		if (insn->imm == BPF_FUNC_override_return)
20008 			prog->kprobe_override = 1;
20009 		if (insn->imm == BPF_FUNC_tail_call) {
20010 			/* If we tail call into other programs, we
20011 			 * cannot make any assumptions since they can
20012 			 * be replaced dynamically during runtime in
20013 			 * the program array.
20014 			 */
20015 			prog->cb_access = 1;
20016 			if (!allow_tail_call_in_subprogs(env))
20017 				prog->aux->stack_depth = MAX_BPF_STACK;
20018 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
20019 
20020 			/* mark bpf_tail_call as different opcode to avoid
20021 			 * conditional branch in the interpreter for every normal
20022 			 * call and to prevent accidental JITing by JIT compiler
20023 			 * that doesn't support bpf_tail_call yet
20024 			 */
20025 			insn->imm = 0;
20026 			insn->code = BPF_JMP | BPF_TAIL_CALL;
20027 
20028 			aux = &env->insn_aux_data[i + delta];
20029 			if (env->bpf_capable && !prog->blinding_requested &&
20030 			    prog->jit_requested &&
20031 			    !bpf_map_key_poisoned(aux) &&
20032 			    !bpf_map_ptr_poisoned(aux) &&
20033 			    !bpf_map_ptr_unpriv(aux)) {
20034 				struct bpf_jit_poke_descriptor desc = {
20035 					.reason = BPF_POKE_REASON_TAIL_CALL,
20036 					.tail_call.map = aux->map_ptr_state.map_ptr,
20037 					.tail_call.key = bpf_map_key_immediate(aux),
20038 					.insn_idx = i + delta,
20039 				};
20040 
20041 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
20042 				if (ret < 0) {
20043 					verbose(env, "adding tail call poke descriptor failed\n");
20044 					return ret;
20045 				}
20046 
20047 				insn->imm = ret + 1;
20048 				goto next_insn;
20049 			}
20050 
20051 			if (!bpf_map_ptr_unpriv(aux))
20052 				goto next_insn;
20053 
20054 			/* instead of changing every JIT dealing with tail_call
20055 			 * emit two extra insns:
20056 			 * if (index >= max_entries) goto out;
20057 			 * index &= array->index_mask;
20058 			 * to avoid out-of-bounds cpu speculation
20059 			 */
20060 			if (bpf_map_ptr_poisoned(aux)) {
20061 				verbose(env, "tail_call abusing map_ptr\n");
20062 				return -EINVAL;
20063 			}
20064 
20065 			map_ptr = aux->map_ptr_state.map_ptr;
20066 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
20067 						  map_ptr->max_entries, 2);
20068 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
20069 						    container_of(map_ptr,
20070 								 struct bpf_array,
20071 								 map)->index_mask);
20072 			insn_buf[2] = *insn;
20073 			cnt = 3;
20074 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20075 			if (!new_prog)
20076 				return -ENOMEM;
20077 
20078 			delta    += cnt - 1;
20079 			env->prog = prog = new_prog;
20080 			insn      = new_prog->insnsi + i + delta;
20081 			goto next_insn;
20082 		}
20083 
20084 		if (insn->imm == BPF_FUNC_timer_set_callback) {
20085 			/* The verifier will process callback_fn as many times as necessary
20086 			 * with different maps and the register states prepared by
20087 			 * set_timer_callback_state will be accurate.
20088 			 *
20089 			 * The following use case is valid:
20090 			 *   map1 is shared by prog1, prog2, prog3.
20091 			 *   prog1 calls bpf_timer_init for some map1 elements
20092 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
20093 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
20094 			 *   prog3 calls bpf_timer_start for some map1 elements.
20095 			 *     Those that were not both bpf_timer_init-ed and
20096 			 *     bpf_timer_set_callback-ed will return -EINVAL.
20097 			 */
20098 			struct bpf_insn ld_addrs[2] = {
20099 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
20100 			};
20101 
20102 			insn_buf[0] = ld_addrs[0];
20103 			insn_buf[1] = ld_addrs[1];
20104 			insn_buf[2] = *insn;
20105 			cnt = 3;
20106 
20107 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20108 			if (!new_prog)
20109 				return -ENOMEM;
20110 
20111 			delta    += cnt - 1;
20112 			env->prog = prog = new_prog;
20113 			insn      = new_prog->insnsi + i + delta;
20114 			goto patch_call_imm;
20115 		}
20116 
20117 		if (is_storage_get_function(insn->imm)) {
20118 			if (!in_sleepable(env) ||
20119 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
20120 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
20121 			else
20122 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
20123 			insn_buf[1] = *insn;
20124 			cnt = 2;
20125 
20126 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20127 			if (!new_prog)
20128 				return -ENOMEM;
20129 
20130 			delta += cnt - 1;
20131 			env->prog = prog = new_prog;
20132 			insn = new_prog->insnsi + i + delta;
20133 			goto patch_call_imm;
20134 		}
20135 
20136 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
20137 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
20138 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
20139 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
20140 			 */
20141 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
20142 			insn_buf[1] = *insn;
20143 			cnt = 2;
20144 
20145 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20146 			if (!new_prog)
20147 				return -ENOMEM;
20148 
20149 			delta += cnt - 1;
20150 			env->prog = prog = new_prog;
20151 			insn = new_prog->insnsi + i + delta;
20152 			goto patch_call_imm;
20153 		}
20154 
20155 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
20156 		 * and other inlining handlers are currently limited to 64 bit
20157 		 * only.
20158 		 */
20159 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
20160 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
20161 		     insn->imm == BPF_FUNC_map_update_elem ||
20162 		     insn->imm == BPF_FUNC_map_delete_elem ||
20163 		     insn->imm == BPF_FUNC_map_push_elem   ||
20164 		     insn->imm == BPF_FUNC_map_pop_elem    ||
20165 		     insn->imm == BPF_FUNC_map_peek_elem   ||
20166 		     insn->imm == BPF_FUNC_redirect_map    ||
20167 		     insn->imm == BPF_FUNC_for_each_map_elem ||
20168 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
20169 			aux = &env->insn_aux_data[i + delta];
20170 			if (bpf_map_ptr_poisoned(aux))
20171 				goto patch_call_imm;
20172 
20173 			map_ptr = aux->map_ptr_state.map_ptr;
20174 			ops = map_ptr->ops;
20175 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
20176 			    ops->map_gen_lookup) {
20177 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
20178 				if (cnt == -EOPNOTSUPP)
20179 					goto patch_map_ops_generic;
20180 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
20181 					verbose(env, "bpf verifier is misconfigured\n");
20182 					return -EINVAL;
20183 				}
20184 
20185 				new_prog = bpf_patch_insn_data(env, i + delta,
20186 							       insn_buf, cnt);
20187 				if (!new_prog)
20188 					return -ENOMEM;
20189 
20190 				delta    += cnt - 1;
20191 				env->prog = prog = new_prog;
20192 				insn      = new_prog->insnsi + i + delta;
20193 				goto next_insn;
20194 			}
20195 
20196 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
20197 				     (void *(*)(struct bpf_map *map, void *key))NULL));
20198 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
20199 				     (long (*)(struct bpf_map *map, void *key))NULL));
20200 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
20201 				     (long (*)(struct bpf_map *map, void *key, void *value,
20202 					      u64 flags))NULL));
20203 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
20204 				     (long (*)(struct bpf_map *map, void *value,
20205 					      u64 flags))NULL));
20206 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
20207 				     (long (*)(struct bpf_map *map, void *value))NULL));
20208 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
20209 				     (long (*)(struct bpf_map *map, void *value))NULL));
20210 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
20211 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
20212 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
20213 				     (long (*)(struct bpf_map *map,
20214 					      bpf_callback_t callback_fn,
20215 					      void *callback_ctx,
20216 					      u64 flags))NULL));
20217 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
20218 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
20219 
20220 patch_map_ops_generic:
20221 			switch (insn->imm) {
20222 			case BPF_FUNC_map_lookup_elem:
20223 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
20224 				goto next_insn;
20225 			case BPF_FUNC_map_update_elem:
20226 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
20227 				goto next_insn;
20228 			case BPF_FUNC_map_delete_elem:
20229 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
20230 				goto next_insn;
20231 			case BPF_FUNC_map_push_elem:
20232 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
20233 				goto next_insn;
20234 			case BPF_FUNC_map_pop_elem:
20235 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
20236 				goto next_insn;
20237 			case BPF_FUNC_map_peek_elem:
20238 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
20239 				goto next_insn;
20240 			case BPF_FUNC_redirect_map:
20241 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
20242 				goto next_insn;
20243 			case BPF_FUNC_for_each_map_elem:
20244 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
20245 				goto next_insn;
20246 			case BPF_FUNC_map_lookup_percpu_elem:
20247 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
20248 				goto next_insn;
20249 			}
20250 
20251 			goto patch_call_imm;
20252 		}
20253 
20254 		/* Implement bpf_jiffies64 inline. */
20255 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
20256 		    insn->imm == BPF_FUNC_jiffies64) {
20257 			struct bpf_insn ld_jiffies_addr[2] = {
20258 				BPF_LD_IMM64(BPF_REG_0,
20259 					     (unsigned long)&jiffies),
20260 			};
20261 
20262 			insn_buf[0] = ld_jiffies_addr[0];
20263 			insn_buf[1] = ld_jiffies_addr[1];
20264 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
20265 						  BPF_REG_0, 0);
20266 			cnt = 3;
20267 
20268 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
20269 						       cnt);
20270 			if (!new_prog)
20271 				return -ENOMEM;
20272 
20273 			delta    += cnt - 1;
20274 			env->prog = prog = new_prog;
20275 			insn      = new_prog->insnsi + i + delta;
20276 			goto next_insn;
20277 		}
20278 
20279 #ifdef CONFIG_X86_64
20280 		/* Implement bpf_get_smp_processor_id() inline. */
20281 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
20282 		    prog->jit_requested && bpf_jit_supports_percpu_insn()) {
20283 			/* BPF_FUNC_get_smp_processor_id inlining is an
20284 			 * optimization, so if pcpu_hot.cpu_number is ever
20285 			 * changed in some incompatible and hard to support
20286 			 * way, it's fine to back out this inlining logic
20287 			 */
20288 			insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number);
20289 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
20290 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
20291 			cnt = 3;
20292 
20293 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20294 			if (!new_prog)
20295 				return -ENOMEM;
20296 
20297 			delta    += cnt - 1;
20298 			env->prog = prog = new_prog;
20299 			insn      = new_prog->insnsi + i + delta;
20300 			goto next_insn;
20301 		}
20302 #endif
20303 		/* Implement bpf_get_func_arg inline. */
20304 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20305 		    insn->imm == BPF_FUNC_get_func_arg) {
20306 			/* Load nr_args from ctx - 8 */
20307 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20308 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
20309 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
20310 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
20311 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
20312 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
20313 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
20314 			insn_buf[7] = BPF_JMP_A(1);
20315 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
20316 			cnt = 9;
20317 
20318 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20319 			if (!new_prog)
20320 				return -ENOMEM;
20321 
20322 			delta    += cnt - 1;
20323 			env->prog = prog = new_prog;
20324 			insn      = new_prog->insnsi + i + delta;
20325 			goto next_insn;
20326 		}
20327 
20328 		/* Implement bpf_get_func_ret inline. */
20329 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20330 		    insn->imm == BPF_FUNC_get_func_ret) {
20331 			if (eatype == BPF_TRACE_FEXIT ||
20332 			    eatype == BPF_MODIFY_RETURN) {
20333 				/* Load nr_args from ctx - 8 */
20334 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20335 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
20336 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
20337 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
20338 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
20339 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
20340 				cnt = 6;
20341 			} else {
20342 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
20343 				cnt = 1;
20344 			}
20345 
20346 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20347 			if (!new_prog)
20348 				return -ENOMEM;
20349 
20350 			delta    += cnt - 1;
20351 			env->prog = prog = new_prog;
20352 			insn      = new_prog->insnsi + i + delta;
20353 			goto next_insn;
20354 		}
20355 
20356 		/* Implement get_func_arg_cnt inline. */
20357 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20358 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
20359 			/* Load nr_args from ctx - 8 */
20360 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20361 
20362 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
20363 			if (!new_prog)
20364 				return -ENOMEM;
20365 
20366 			env->prog = prog = new_prog;
20367 			insn      = new_prog->insnsi + i + delta;
20368 			goto next_insn;
20369 		}
20370 
20371 		/* Implement bpf_get_func_ip inline. */
20372 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20373 		    insn->imm == BPF_FUNC_get_func_ip) {
20374 			/* Load IP address from ctx - 16 */
20375 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
20376 
20377 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
20378 			if (!new_prog)
20379 				return -ENOMEM;
20380 
20381 			env->prog = prog = new_prog;
20382 			insn      = new_prog->insnsi + i + delta;
20383 			goto next_insn;
20384 		}
20385 
20386 		/* Implement bpf_get_branch_snapshot inline. */
20387 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
20388 		    prog->jit_requested && BITS_PER_LONG == 64 &&
20389 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
20390 			/* We are dealing with the following func protos:
20391 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
20392 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
20393 			 */
20394 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
20395 
20396 			/* struct perf_branch_entry is part of UAPI and is
20397 			 * used as an array element, so extremely unlikely to
20398 			 * ever grow or shrink
20399 			 */
20400 			BUILD_BUG_ON(br_entry_size != 24);
20401 
20402 			/* if (unlikely(flags)) return -EINVAL */
20403 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
20404 
20405 			/* Transform size (bytes) into number of entries (cnt = size / 24).
20406 			 * But to avoid expensive division instruction, we implement
20407 			 * divide-by-3 through multiplication, followed by further
20408 			 * division by 8 through 3-bit right shift.
20409 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
20410 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
20411 			 *
20412 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
20413 			 */
20414 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
20415 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
20416 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
20417 
20418 			/* call perf_snapshot_branch_stack implementation */
20419 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
20420 			/* if (entry_cnt == 0) return -ENOENT */
20421 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
20422 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
20423 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
20424 			insn_buf[7] = BPF_JMP_A(3);
20425 			/* return -EINVAL; */
20426 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
20427 			insn_buf[9] = BPF_JMP_A(1);
20428 			/* return -ENOENT; */
20429 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
20430 			cnt = 11;
20431 
20432 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20433 			if (!new_prog)
20434 				return -ENOMEM;
20435 
20436 			delta    += cnt - 1;
20437 			env->prog = prog = new_prog;
20438 			insn      = new_prog->insnsi + i + delta;
20439 			continue;
20440 		}
20441 
20442 		/* Implement bpf_kptr_xchg inline */
20443 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
20444 		    insn->imm == BPF_FUNC_kptr_xchg &&
20445 		    bpf_jit_supports_ptr_xchg()) {
20446 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
20447 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
20448 			cnt = 2;
20449 
20450 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20451 			if (!new_prog)
20452 				return -ENOMEM;
20453 
20454 			delta    += cnt - 1;
20455 			env->prog = prog = new_prog;
20456 			insn      = new_prog->insnsi + i + delta;
20457 			goto next_insn;
20458 		}
20459 patch_call_imm:
20460 		fn = env->ops->get_func_proto(insn->imm, env->prog);
20461 		/* all functions that have prototype and verifier allowed
20462 		 * programs to call them, must be real in-kernel functions
20463 		 */
20464 		if (!fn->func) {
20465 			verbose(env,
20466 				"kernel subsystem misconfigured func %s#%d\n",
20467 				func_id_name(insn->imm), insn->imm);
20468 			return -EFAULT;
20469 		}
20470 		insn->imm = fn->func - __bpf_call_base;
20471 next_insn:
20472 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20473 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
20474 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
20475 			cur_subprog++;
20476 			stack_depth = subprogs[cur_subprog].stack_depth;
20477 			stack_depth_extra = 0;
20478 		}
20479 		i++;
20480 		insn++;
20481 	}
20482 
20483 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
20484 	for (i = 0; i < env->subprog_cnt; i++) {
20485 		int subprog_start = subprogs[i].start;
20486 		int stack_slots = subprogs[i].stack_extra / 8;
20487 
20488 		if (!stack_slots)
20489 			continue;
20490 		if (stack_slots > 1) {
20491 			verbose(env, "verifier bug: stack_slots supports may_goto only\n");
20492 			return -EFAULT;
20493 		}
20494 
20495 		/* Add ST insn to subprog prologue to init extra stack */
20496 		insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP,
20497 					 -subprogs[i].stack_depth, BPF_MAX_LOOPS);
20498 		/* Copy first actual insn to preserve it */
20499 		insn_buf[1] = env->prog->insnsi[subprog_start];
20500 
20501 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2);
20502 		if (!new_prog)
20503 			return -ENOMEM;
20504 		env->prog = prog = new_prog;
20505 	}
20506 
20507 	/* Since poke tab is now finalized, publish aux to tracker. */
20508 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
20509 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
20510 		if (!map_ptr->ops->map_poke_track ||
20511 		    !map_ptr->ops->map_poke_untrack ||
20512 		    !map_ptr->ops->map_poke_run) {
20513 			verbose(env, "bpf verifier is misconfigured\n");
20514 			return -EINVAL;
20515 		}
20516 
20517 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
20518 		if (ret < 0) {
20519 			verbose(env, "tracking tail call prog failed\n");
20520 			return ret;
20521 		}
20522 	}
20523 
20524 	sort_kfunc_descs_by_imm_off(env->prog);
20525 
20526 	return 0;
20527 }
20528 
20529 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
20530 					int position,
20531 					s32 stack_base,
20532 					u32 callback_subprogno,
20533 					u32 *cnt)
20534 {
20535 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
20536 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
20537 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
20538 	int reg_loop_max = BPF_REG_6;
20539 	int reg_loop_cnt = BPF_REG_7;
20540 	int reg_loop_ctx = BPF_REG_8;
20541 
20542 	struct bpf_prog *new_prog;
20543 	u32 callback_start;
20544 	u32 call_insn_offset;
20545 	s32 callback_offset;
20546 
20547 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
20548 	 * be careful to modify this code in sync.
20549 	 */
20550 	struct bpf_insn insn_buf[] = {
20551 		/* Return error and jump to the end of the patch if
20552 		 * expected number of iterations is too big.
20553 		 */
20554 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
20555 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
20556 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
20557 		/* spill R6, R7, R8 to use these as loop vars */
20558 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
20559 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
20560 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
20561 		/* initialize loop vars */
20562 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
20563 		BPF_MOV32_IMM(reg_loop_cnt, 0),
20564 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
20565 		/* loop header,
20566 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
20567 		 */
20568 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
20569 		/* callback call,
20570 		 * correct callback offset would be set after patching
20571 		 */
20572 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
20573 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
20574 		BPF_CALL_REL(0),
20575 		/* increment loop counter */
20576 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
20577 		/* jump to loop header if callback returned 0 */
20578 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
20579 		/* return value of bpf_loop,
20580 		 * set R0 to the number of iterations
20581 		 */
20582 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
20583 		/* restore original values of R6, R7, R8 */
20584 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
20585 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
20586 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
20587 	};
20588 
20589 	*cnt = ARRAY_SIZE(insn_buf);
20590 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
20591 	if (!new_prog)
20592 		return new_prog;
20593 
20594 	/* callback start is known only after patching */
20595 	callback_start = env->subprog_info[callback_subprogno].start;
20596 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
20597 	call_insn_offset = position + 12;
20598 	callback_offset = callback_start - call_insn_offset - 1;
20599 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
20600 
20601 	return new_prog;
20602 }
20603 
20604 static bool is_bpf_loop_call(struct bpf_insn *insn)
20605 {
20606 	return insn->code == (BPF_JMP | BPF_CALL) &&
20607 		insn->src_reg == 0 &&
20608 		insn->imm == BPF_FUNC_loop;
20609 }
20610 
20611 /* For all sub-programs in the program (including main) check
20612  * insn_aux_data to see if there are bpf_loop calls that require
20613  * inlining. If such calls are found the calls are replaced with a
20614  * sequence of instructions produced by `inline_bpf_loop` function and
20615  * subprog stack_depth is increased by the size of 3 registers.
20616  * This stack space is used to spill values of the R6, R7, R8.  These
20617  * registers are used to store the loop bound, counter and context
20618  * variables.
20619  */
20620 static int optimize_bpf_loop(struct bpf_verifier_env *env)
20621 {
20622 	struct bpf_subprog_info *subprogs = env->subprog_info;
20623 	int i, cur_subprog = 0, cnt, delta = 0;
20624 	struct bpf_insn *insn = env->prog->insnsi;
20625 	int insn_cnt = env->prog->len;
20626 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
20627 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20628 	u16 stack_depth_extra = 0;
20629 
20630 	for (i = 0; i < insn_cnt; i++, insn++) {
20631 		struct bpf_loop_inline_state *inline_state =
20632 			&env->insn_aux_data[i + delta].loop_inline_state;
20633 
20634 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
20635 			struct bpf_prog *new_prog;
20636 
20637 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
20638 			new_prog = inline_bpf_loop(env,
20639 						   i + delta,
20640 						   -(stack_depth + stack_depth_extra),
20641 						   inline_state->callback_subprogno,
20642 						   &cnt);
20643 			if (!new_prog)
20644 				return -ENOMEM;
20645 
20646 			delta     += cnt - 1;
20647 			env->prog  = new_prog;
20648 			insn       = new_prog->insnsi + i + delta;
20649 		}
20650 
20651 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20652 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
20653 			cur_subprog++;
20654 			stack_depth = subprogs[cur_subprog].stack_depth;
20655 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20656 			stack_depth_extra = 0;
20657 		}
20658 	}
20659 
20660 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20661 
20662 	return 0;
20663 }
20664 
20665 static void free_states(struct bpf_verifier_env *env)
20666 {
20667 	struct bpf_verifier_state_list *sl, *sln;
20668 	int i;
20669 
20670 	sl = env->free_list;
20671 	while (sl) {
20672 		sln = sl->next;
20673 		free_verifier_state(&sl->state, false);
20674 		kfree(sl);
20675 		sl = sln;
20676 	}
20677 	env->free_list = NULL;
20678 
20679 	if (!env->explored_states)
20680 		return;
20681 
20682 	for (i = 0; i < state_htab_size(env); i++) {
20683 		sl = env->explored_states[i];
20684 
20685 		while (sl) {
20686 			sln = sl->next;
20687 			free_verifier_state(&sl->state, false);
20688 			kfree(sl);
20689 			sl = sln;
20690 		}
20691 		env->explored_states[i] = NULL;
20692 	}
20693 }
20694 
20695 static int do_check_common(struct bpf_verifier_env *env, int subprog)
20696 {
20697 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20698 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
20699 	struct bpf_verifier_state *state;
20700 	struct bpf_reg_state *regs;
20701 	int ret, i;
20702 
20703 	env->prev_linfo = NULL;
20704 	env->pass_cnt++;
20705 
20706 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
20707 	if (!state)
20708 		return -ENOMEM;
20709 	state->curframe = 0;
20710 	state->speculative = false;
20711 	state->branches = 1;
20712 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
20713 	if (!state->frame[0]) {
20714 		kfree(state);
20715 		return -ENOMEM;
20716 	}
20717 	env->cur_state = state;
20718 	init_func_state(env, state->frame[0],
20719 			BPF_MAIN_FUNC /* callsite */,
20720 			0 /* frameno */,
20721 			subprog);
20722 	state->first_insn_idx = env->subprog_info[subprog].start;
20723 	state->last_insn_idx = -1;
20724 
20725 	regs = state->frame[state->curframe]->regs;
20726 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
20727 		const char *sub_name = subprog_name(env, subprog);
20728 		struct bpf_subprog_arg_info *arg;
20729 		struct bpf_reg_state *reg;
20730 
20731 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
20732 		ret = btf_prepare_func_args(env, subprog);
20733 		if (ret)
20734 			goto out;
20735 
20736 		if (subprog_is_exc_cb(env, subprog)) {
20737 			state->frame[0]->in_exception_callback_fn = true;
20738 			/* We have already ensured that the callback returns an integer, just
20739 			 * like all global subprogs. We need to determine it only has a single
20740 			 * scalar argument.
20741 			 */
20742 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
20743 				verbose(env, "exception cb only supports single integer argument\n");
20744 				ret = -EINVAL;
20745 				goto out;
20746 			}
20747 		}
20748 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
20749 			arg = &sub->args[i - BPF_REG_1];
20750 			reg = &regs[i];
20751 
20752 			if (arg->arg_type == ARG_PTR_TO_CTX) {
20753 				reg->type = PTR_TO_CTX;
20754 				mark_reg_known_zero(env, regs, i);
20755 			} else if (arg->arg_type == ARG_ANYTHING) {
20756 				reg->type = SCALAR_VALUE;
20757 				mark_reg_unknown(env, regs, i);
20758 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
20759 				/* assume unspecial LOCAL dynptr type */
20760 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
20761 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
20762 				reg->type = PTR_TO_MEM;
20763 				if (arg->arg_type & PTR_MAYBE_NULL)
20764 					reg->type |= PTR_MAYBE_NULL;
20765 				mark_reg_known_zero(env, regs, i);
20766 				reg->mem_size = arg->mem_size;
20767 				reg->id = ++env->id_gen;
20768 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
20769 				reg->type = PTR_TO_BTF_ID;
20770 				if (arg->arg_type & PTR_MAYBE_NULL)
20771 					reg->type |= PTR_MAYBE_NULL;
20772 				if (arg->arg_type & PTR_UNTRUSTED)
20773 					reg->type |= PTR_UNTRUSTED;
20774 				if (arg->arg_type & PTR_TRUSTED)
20775 					reg->type |= PTR_TRUSTED;
20776 				mark_reg_known_zero(env, regs, i);
20777 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
20778 				reg->btf_id = arg->btf_id;
20779 				reg->id = ++env->id_gen;
20780 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
20781 				/* caller can pass either PTR_TO_ARENA or SCALAR */
20782 				mark_reg_unknown(env, regs, i);
20783 			} else {
20784 				WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
20785 					  i - BPF_REG_1, arg->arg_type);
20786 				ret = -EFAULT;
20787 				goto out;
20788 			}
20789 		}
20790 	} else {
20791 		/* if main BPF program has associated BTF info, validate that
20792 		 * it's matching expected signature, and otherwise mark BTF
20793 		 * info for main program as unreliable
20794 		 */
20795 		if (env->prog->aux->func_info_aux) {
20796 			ret = btf_prepare_func_args(env, 0);
20797 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
20798 				env->prog->aux->func_info_aux[0].unreliable = true;
20799 		}
20800 
20801 		/* 1st arg to a function */
20802 		regs[BPF_REG_1].type = PTR_TO_CTX;
20803 		mark_reg_known_zero(env, regs, BPF_REG_1);
20804 	}
20805 
20806 	ret = do_check(env);
20807 out:
20808 	/* check for NULL is necessary, since cur_state can be freed inside
20809 	 * do_check() under memory pressure.
20810 	 */
20811 	if (env->cur_state) {
20812 		free_verifier_state(env->cur_state, true);
20813 		env->cur_state = NULL;
20814 	}
20815 	while (!pop_stack(env, NULL, NULL, false));
20816 	if (!ret && pop_log)
20817 		bpf_vlog_reset(&env->log, 0);
20818 	free_states(env);
20819 	return ret;
20820 }
20821 
20822 /* Lazily verify all global functions based on their BTF, if they are called
20823  * from main BPF program or any of subprograms transitively.
20824  * BPF global subprogs called from dead code are not validated.
20825  * All callable global functions must pass verification.
20826  * Otherwise the whole program is rejected.
20827  * Consider:
20828  * int bar(int);
20829  * int foo(int f)
20830  * {
20831  *    return bar(f);
20832  * }
20833  * int bar(int b)
20834  * {
20835  *    ...
20836  * }
20837  * foo() will be verified first for R1=any_scalar_value. During verification it
20838  * will be assumed that bar() already verified successfully and call to bar()
20839  * from foo() will be checked for type match only. Later bar() will be verified
20840  * independently to check that it's safe for R1=any_scalar_value.
20841  */
20842 static int do_check_subprogs(struct bpf_verifier_env *env)
20843 {
20844 	struct bpf_prog_aux *aux = env->prog->aux;
20845 	struct bpf_func_info_aux *sub_aux;
20846 	int i, ret, new_cnt;
20847 
20848 	if (!aux->func_info)
20849 		return 0;
20850 
20851 	/* exception callback is presumed to be always called */
20852 	if (env->exception_callback_subprog)
20853 		subprog_aux(env, env->exception_callback_subprog)->called = true;
20854 
20855 again:
20856 	new_cnt = 0;
20857 	for (i = 1; i < env->subprog_cnt; i++) {
20858 		if (!subprog_is_global(env, i))
20859 			continue;
20860 
20861 		sub_aux = subprog_aux(env, i);
20862 		if (!sub_aux->called || sub_aux->verified)
20863 			continue;
20864 
20865 		env->insn_idx = env->subprog_info[i].start;
20866 		WARN_ON_ONCE(env->insn_idx == 0);
20867 		ret = do_check_common(env, i);
20868 		if (ret) {
20869 			return ret;
20870 		} else if (env->log.level & BPF_LOG_LEVEL) {
20871 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
20872 				i, subprog_name(env, i));
20873 		}
20874 
20875 		/* We verified new global subprog, it might have called some
20876 		 * more global subprogs that we haven't verified yet, so we
20877 		 * need to do another pass over subprogs to verify those.
20878 		 */
20879 		sub_aux->verified = true;
20880 		new_cnt++;
20881 	}
20882 
20883 	/* We can't loop forever as we verify at least one global subprog on
20884 	 * each pass.
20885 	 */
20886 	if (new_cnt)
20887 		goto again;
20888 
20889 	return 0;
20890 }
20891 
20892 static int do_check_main(struct bpf_verifier_env *env)
20893 {
20894 	int ret;
20895 
20896 	env->insn_idx = 0;
20897 	ret = do_check_common(env, 0);
20898 	if (!ret)
20899 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20900 	return ret;
20901 }
20902 
20903 
20904 static void print_verification_stats(struct bpf_verifier_env *env)
20905 {
20906 	int i;
20907 
20908 	if (env->log.level & BPF_LOG_STATS) {
20909 		verbose(env, "verification time %lld usec\n",
20910 			div_u64(env->verification_time, 1000));
20911 		verbose(env, "stack depth ");
20912 		for (i = 0; i < env->subprog_cnt; i++) {
20913 			u32 depth = env->subprog_info[i].stack_depth;
20914 
20915 			verbose(env, "%d", depth);
20916 			if (i + 1 < env->subprog_cnt)
20917 				verbose(env, "+");
20918 		}
20919 		verbose(env, "\n");
20920 	}
20921 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
20922 		"total_states %d peak_states %d mark_read %d\n",
20923 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
20924 		env->max_states_per_insn, env->total_states,
20925 		env->peak_states, env->longest_mark_read_walk);
20926 }
20927 
20928 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
20929 {
20930 	const struct btf_type *t, *func_proto;
20931 	const struct bpf_struct_ops_desc *st_ops_desc;
20932 	const struct bpf_struct_ops *st_ops;
20933 	const struct btf_member *member;
20934 	struct bpf_prog *prog = env->prog;
20935 	u32 btf_id, member_idx;
20936 	struct btf *btf;
20937 	const char *mname;
20938 
20939 	if (!prog->gpl_compatible) {
20940 		verbose(env, "struct ops programs must have a GPL compatible license\n");
20941 		return -EINVAL;
20942 	}
20943 
20944 	if (!prog->aux->attach_btf_id)
20945 		return -ENOTSUPP;
20946 
20947 	btf = prog->aux->attach_btf;
20948 	if (btf_is_module(btf)) {
20949 		/* Make sure st_ops is valid through the lifetime of env */
20950 		env->attach_btf_mod = btf_try_get_module(btf);
20951 		if (!env->attach_btf_mod) {
20952 			verbose(env, "struct_ops module %s is not found\n",
20953 				btf_get_name(btf));
20954 			return -ENOTSUPP;
20955 		}
20956 	}
20957 
20958 	btf_id = prog->aux->attach_btf_id;
20959 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
20960 	if (!st_ops_desc) {
20961 		verbose(env, "attach_btf_id %u is not a supported struct\n",
20962 			btf_id);
20963 		return -ENOTSUPP;
20964 	}
20965 	st_ops = st_ops_desc->st_ops;
20966 
20967 	t = st_ops_desc->type;
20968 	member_idx = prog->expected_attach_type;
20969 	if (member_idx >= btf_type_vlen(t)) {
20970 		verbose(env, "attach to invalid member idx %u of struct %s\n",
20971 			member_idx, st_ops->name);
20972 		return -EINVAL;
20973 	}
20974 
20975 	member = &btf_type_member(t)[member_idx];
20976 	mname = btf_name_by_offset(btf, member->name_off);
20977 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
20978 					       NULL);
20979 	if (!func_proto) {
20980 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
20981 			mname, member_idx, st_ops->name);
20982 		return -EINVAL;
20983 	}
20984 
20985 	if (st_ops->check_member) {
20986 		int err = st_ops->check_member(t, member, prog);
20987 
20988 		if (err) {
20989 			verbose(env, "attach to unsupported member %s of struct %s\n",
20990 				mname, st_ops->name);
20991 			return err;
20992 		}
20993 	}
20994 
20995 	/* btf_ctx_access() used this to provide argument type info */
20996 	prog->aux->ctx_arg_info =
20997 		st_ops_desc->arg_info[member_idx].info;
20998 	prog->aux->ctx_arg_info_size =
20999 		st_ops_desc->arg_info[member_idx].cnt;
21000 
21001 	prog->aux->attach_func_proto = func_proto;
21002 	prog->aux->attach_func_name = mname;
21003 	env->ops = st_ops->verifier_ops;
21004 
21005 	return 0;
21006 }
21007 #define SECURITY_PREFIX "security_"
21008 
21009 static int check_attach_modify_return(unsigned long addr, const char *func_name)
21010 {
21011 	if (within_error_injection_list(addr) ||
21012 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
21013 		return 0;
21014 
21015 	return -EINVAL;
21016 }
21017 
21018 /* list of non-sleepable functions that are otherwise on
21019  * ALLOW_ERROR_INJECTION list
21020  */
21021 BTF_SET_START(btf_non_sleepable_error_inject)
21022 /* Three functions below can be called from sleepable and non-sleepable context.
21023  * Assume non-sleepable from bpf safety point of view.
21024  */
21025 BTF_ID(func, __filemap_add_folio)
21026 BTF_ID(func, should_fail_alloc_page)
21027 BTF_ID(func, should_failslab)
21028 BTF_SET_END(btf_non_sleepable_error_inject)
21029 
21030 static int check_non_sleepable_error_inject(u32 btf_id)
21031 {
21032 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
21033 }
21034 
21035 int bpf_check_attach_target(struct bpf_verifier_log *log,
21036 			    const struct bpf_prog *prog,
21037 			    const struct bpf_prog *tgt_prog,
21038 			    u32 btf_id,
21039 			    struct bpf_attach_target_info *tgt_info)
21040 {
21041 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
21042 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
21043 	const char prefix[] = "btf_trace_";
21044 	int ret = 0, subprog = -1, i;
21045 	const struct btf_type *t;
21046 	bool conservative = true;
21047 	const char *tname;
21048 	struct btf *btf;
21049 	long addr = 0;
21050 	struct module *mod = NULL;
21051 
21052 	if (!btf_id) {
21053 		bpf_log(log, "Tracing programs must provide btf_id\n");
21054 		return -EINVAL;
21055 	}
21056 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
21057 	if (!btf) {
21058 		bpf_log(log,
21059 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
21060 		return -EINVAL;
21061 	}
21062 	t = btf_type_by_id(btf, btf_id);
21063 	if (!t) {
21064 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
21065 		return -EINVAL;
21066 	}
21067 	tname = btf_name_by_offset(btf, t->name_off);
21068 	if (!tname) {
21069 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
21070 		return -EINVAL;
21071 	}
21072 	if (tgt_prog) {
21073 		struct bpf_prog_aux *aux = tgt_prog->aux;
21074 
21075 		if (bpf_prog_is_dev_bound(prog->aux) &&
21076 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
21077 			bpf_log(log, "Target program bound device mismatch");
21078 			return -EINVAL;
21079 		}
21080 
21081 		for (i = 0; i < aux->func_info_cnt; i++)
21082 			if (aux->func_info[i].type_id == btf_id) {
21083 				subprog = i;
21084 				break;
21085 			}
21086 		if (subprog == -1) {
21087 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
21088 			return -EINVAL;
21089 		}
21090 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
21091 			bpf_log(log,
21092 				"%s programs cannot attach to exception callback\n",
21093 				prog_extension ? "Extension" : "FENTRY/FEXIT");
21094 			return -EINVAL;
21095 		}
21096 		conservative = aux->func_info_aux[subprog].unreliable;
21097 		if (prog_extension) {
21098 			if (conservative) {
21099 				bpf_log(log,
21100 					"Cannot replace static functions\n");
21101 				return -EINVAL;
21102 			}
21103 			if (!prog->jit_requested) {
21104 				bpf_log(log,
21105 					"Extension programs should be JITed\n");
21106 				return -EINVAL;
21107 			}
21108 		}
21109 		if (!tgt_prog->jited) {
21110 			bpf_log(log, "Can attach to only JITed progs\n");
21111 			return -EINVAL;
21112 		}
21113 		if (prog_tracing) {
21114 			if (aux->attach_tracing_prog) {
21115 				/*
21116 				 * Target program is an fentry/fexit which is already attached
21117 				 * to another tracing program. More levels of nesting
21118 				 * attachment are not allowed.
21119 				 */
21120 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
21121 				return -EINVAL;
21122 			}
21123 		} else if (tgt_prog->type == prog->type) {
21124 			/*
21125 			 * To avoid potential call chain cycles, prevent attaching of a
21126 			 * program extension to another extension. It's ok to attach
21127 			 * fentry/fexit to extension program.
21128 			 */
21129 			bpf_log(log, "Cannot recursively attach\n");
21130 			return -EINVAL;
21131 		}
21132 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
21133 		    prog_extension &&
21134 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
21135 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
21136 			/* Program extensions can extend all program types
21137 			 * except fentry/fexit. The reason is the following.
21138 			 * The fentry/fexit programs are used for performance
21139 			 * analysis, stats and can be attached to any program
21140 			 * type. When extension program is replacing XDP function
21141 			 * it is necessary to allow performance analysis of all
21142 			 * functions. Both original XDP program and its program
21143 			 * extension. Hence attaching fentry/fexit to
21144 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
21145 			 * fentry/fexit was allowed it would be possible to create
21146 			 * long call chain fentry->extension->fentry->extension
21147 			 * beyond reasonable stack size. Hence extending fentry
21148 			 * is not allowed.
21149 			 */
21150 			bpf_log(log, "Cannot extend fentry/fexit\n");
21151 			return -EINVAL;
21152 		}
21153 	} else {
21154 		if (prog_extension) {
21155 			bpf_log(log, "Cannot replace kernel functions\n");
21156 			return -EINVAL;
21157 		}
21158 	}
21159 
21160 	switch (prog->expected_attach_type) {
21161 	case BPF_TRACE_RAW_TP:
21162 		if (tgt_prog) {
21163 			bpf_log(log,
21164 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
21165 			return -EINVAL;
21166 		}
21167 		if (!btf_type_is_typedef(t)) {
21168 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
21169 				btf_id);
21170 			return -EINVAL;
21171 		}
21172 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
21173 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
21174 				btf_id, tname);
21175 			return -EINVAL;
21176 		}
21177 		tname += sizeof(prefix) - 1;
21178 		t = btf_type_by_id(btf, t->type);
21179 		if (!btf_type_is_ptr(t))
21180 			/* should never happen in valid vmlinux build */
21181 			return -EINVAL;
21182 		t = btf_type_by_id(btf, t->type);
21183 		if (!btf_type_is_func_proto(t))
21184 			/* should never happen in valid vmlinux build */
21185 			return -EINVAL;
21186 
21187 		break;
21188 	case BPF_TRACE_ITER:
21189 		if (!btf_type_is_func(t)) {
21190 			bpf_log(log, "attach_btf_id %u is not a function\n",
21191 				btf_id);
21192 			return -EINVAL;
21193 		}
21194 		t = btf_type_by_id(btf, t->type);
21195 		if (!btf_type_is_func_proto(t))
21196 			return -EINVAL;
21197 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
21198 		if (ret)
21199 			return ret;
21200 		break;
21201 	default:
21202 		if (!prog_extension)
21203 			return -EINVAL;
21204 		fallthrough;
21205 	case BPF_MODIFY_RETURN:
21206 	case BPF_LSM_MAC:
21207 	case BPF_LSM_CGROUP:
21208 	case BPF_TRACE_FENTRY:
21209 	case BPF_TRACE_FEXIT:
21210 		if (!btf_type_is_func(t)) {
21211 			bpf_log(log, "attach_btf_id %u is not a function\n",
21212 				btf_id);
21213 			return -EINVAL;
21214 		}
21215 		if (prog_extension &&
21216 		    btf_check_type_match(log, prog, btf, t))
21217 			return -EINVAL;
21218 		t = btf_type_by_id(btf, t->type);
21219 		if (!btf_type_is_func_proto(t))
21220 			return -EINVAL;
21221 
21222 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
21223 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
21224 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
21225 			return -EINVAL;
21226 
21227 		if (tgt_prog && conservative)
21228 			t = NULL;
21229 
21230 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
21231 		if (ret < 0)
21232 			return ret;
21233 
21234 		if (tgt_prog) {
21235 			if (subprog == 0)
21236 				addr = (long) tgt_prog->bpf_func;
21237 			else
21238 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
21239 		} else {
21240 			if (btf_is_module(btf)) {
21241 				mod = btf_try_get_module(btf);
21242 				if (mod)
21243 					addr = find_kallsyms_symbol_value(mod, tname);
21244 				else
21245 					addr = 0;
21246 			} else {
21247 				addr = kallsyms_lookup_name(tname);
21248 			}
21249 			if (!addr) {
21250 				module_put(mod);
21251 				bpf_log(log,
21252 					"The address of function %s cannot be found\n",
21253 					tname);
21254 				return -ENOENT;
21255 			}
21256 		}
21257 
21258 		if (prog->sleepable) {
21259 			ret = -EINVAL;
21260 			switch (prog->type) {
21261 			case BPF_PROG_TYPE_TRACING:
21262 
21263 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
21264 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
21265 				 */
21266 				if (!check_non_sleepable_error_inject(btf_id) &&
21267 				    within_error_injection_list(addr))
21268 					ret = 0;
21269 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
21270 				 * in the fmodret id set with the KF_SLEEPABLE flag.
21271 				 */
21272 				else {
21273 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
21274 										prog);
21275 
21276 					if (flags && (*flags & KF_SLEEPABLE))
21277 						ret = 0;
21278 				}
21279 				break;
21280 			case BPF_PROG_TYPE_LSM:
21281 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
21282 				 * Only some of them are sleepable.
21283 				 */
21284 				if (bpf_lsm_is_sleepable_hook(btf_id))
21285 					ret = 0;
21286 				break;
21287 			default:
21288 				break;
21289 			}
21290 			if (ret) {
21291 				module_put(mod);
21292 				bpf_log(log, "%s is not sleepable\n", tname);
21293 				return ret;
21294 			}
21295 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
21296 			if (tgt_prog) {
21297 				module_put(mod);
21298 				bpf_log(log, "can't modify return codes of BPF programs\n");
21299 				return -EINVAL;
21300 			}
21301 			ret = -EINVAL;
21302 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
21303 			    !check_attach_modify_return(addr, tname))
21304 				ret = 0;
21305 			if (ret) {
21306 				module_put(mod);
21307 				bpf_log(log, "%s() is not modifiable\n", tname);
21308 				return ret;
21309 			}
21310 		}
21311 
21312 		break;
21313 	}
21314 	tgt_info->tgt_addr = addr;
21315 	tgt_info->tgt_name = tname;
21316 	tgt_info->tgt_type = t;
21317 	tgt_info->tgt_mod = mod;
21318 	return 0;
21319 }
21320 
21321 BTF_SET_START(btf_id_deny)
21322 BTF_ID_UNUSED
21323 #ifdef CONFIG_SMP
21324 BTF_ID(func, migrate_disable)
21325 BTF_ID(func, migrate_enable)
21326 #endif
21327 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
21328 BTF_ID(func, rcu_read_unlock_strict)
21329 #endif
21330 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
21331 BTF_ID(func, preempt_count_add)
21332 BTF_ID(func, preempt_count_sub)
21333 #endif
21334 #ifdef CONFIG_PREEMPT_RCU
21335 BTF_ID(func, __rcu_read_lock)
21336 BTF_ID(func, __rcu_read_unlock)
21337 #endif
21338 BTF_SET_END(btf_id_deny)
21339 
21340 static bool can_be_sleepable(struct bpf_prog *prog)
21341 {
21342 	if (prog->type == BPF_PROG_TYPE_TRACING) {
21343 		switch (prog->expected_attach_type) {
21344 		case BPF_TRACE_FENTRY:
21345 		case BPF_TRACE_FEXIT:
21346 		case BPF_MODIFY_RETURN:
21347 		case BPF_TRACE_ITER:
21348 			return true;
21349 		default:
21350 			return false;
21351 		}
21352 	}
21353 	return prog->type == BPF_PROG_TYPE_LSM ||
21354 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
21355 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
21356 }
21357 
21358 static int check_attach_btf_id(struct bpf_verifier_env *env)
21359 {
21360 	struct bpf_prog *prog = env->prog;
21361 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
21362 	struct bpf_attach_target_info tgt_info = {};
21363 	u32 btf_id = prog->aux->attach_btf_id;
21364 	struct bpf_trampoline *tr;
21365 	int ret;
21366 	u64 key;
21367 
21368 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
21369 		if (prog->sleepable)
21370 			/* attach_btf_id checked to be zero already */
21371 			return 0;
21372 		verbose(env, "Syscall programs can only be sleepable\n");
21373 		return -EINVAL;
21374 	}
21375 
21376 	if (prog->sleepable && !can_be_sleepable(prog)) {
21377 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
21378 		return -EINVAL;
21379 	}
21380 
21381 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
21382 		return check_struct_ops_btf_id(env);
21383 
21384 	if (prog->type != BPF_PROG_TYPE_TRACING &&
21385 	    prog->type != BPF_PROG_TYPE_LSM &&
21386 	    prog->type != BPF_PROG_TYPE_EXT)
21387 		return 0;
21388 
21389 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
21390 	if (ret)
21391 		return ret;
21392 
21393 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
21394 		/* to make freplace equivalent to their targets, they need to
21395 		 * inherit env->ops and expected_attach_type for the rest of the
21396 		 * verification
21397 		 */
21398 		env->ops = bpf_verifier_ops[tgt_prog->type];
21399 		prog->expected_attach_type = tgt_prog->expected_attach_type;
21400 	}
21401 
21402 	/* store info about the attachment target that will be used later */
21403 	prog->aux->attach_func_proto = tgt_info.tgt_type;
21404 	prog->aux->attach_func_name = tgt_info.tgt_name;
21405 	prog->aux->mod = tgt_info.tgt_mod;
21406 
21407 	if (tgt_prog) {
21408 		prog->aux->saved_dst_prog_type = tgt_prog->type;
21409 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
21410 	}
21411 
21412 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
21413 		prog->aux->attach_btf_trace = true;
21414 		return 0;
21415 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
21416 		if (!bpf_iter_prog_supported(prog))
21417 			return -EINVAL;
21418 		return 0;
21419 	}
21420 
21421 	if (prog->type == BPF_PROG_TYPE_LSM) {
21422 		ret = bpf_lsm_verify_prog(&env->log, prog);
21423 		if (ret < 0)
21424 			return ret;
21425 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
21426 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
21427 		return -EINVAL;
21428 	}
21429 
21430 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
21431 	tr = bpf_trampoline_get(key, &tgt_info);
21432 	if (!tr)
21433 		return -ENOMEM;
21434 
21435 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
21436 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
21437 
21438 	prog->aux->dst_trampoline = tr;
21439 	return 0;
21440 }
21441 
21442 struct btf *bpf_get_btf_vmlinux(void)
21443 {
21444 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
21445 		mutex_lock(&bpf_verifier_lock);
21446 		if (!btf_vmlinux)
21447 			btf_vmlinux = btf_parse_vmlinux();
21448 		mutex_unlock(&bpf_verifier_lock);
21449 	}
21450 	return btf_vmlinux;
21451 }
21452 
21453 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
21454 {
21455 	u64 start_time = ktime_get_ns();
21456 	struct bpf_verifier_env *env;
21457 	int i, len, ret = -EINVAL, err;
21458 	u32 log_true_size;
21459 	bool is_priv;
21460 
21461 	/* no program is valid */
21462 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
21463 		return -EINVAL;
21464 
21465 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
21466 	 * allocate/free it every time bpf_check() is called
21467 	 */
21468 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
21469 	if (!env)
21470 		return -ENOMEM;
21471 
21472 	env->bt.env = env;
21473 
21474 	len = (*prog)->len;
21475 	env->insn_aux_data =
21476 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
21477 	ret = -ENOMEM;
21478 	if (!env->insn_aux_data)
21479 		goto err_free_env;
21480 	for (i = 0; i < len; i++)
21481 		env->insn_aux_data[i].orig_idx = i;
21482 	env->prog = *prog;
21483 	env->ops = bpf_verifier_ops[env->prog->type];
21484 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
21485 
21486 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
21487 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
21488 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
21489 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
21490 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
21491 
21492 	bpf_get_btf_vmlinux();
21493 
21494 	/* grab the mutex to protect few globals used by verifier */
21495 	if (!is_priv)
21496 		mutex_lock(&bpf_verifier_lock);
21497 
21498 	/* user could have requested verbose verifier output
21499 	 * and supplied buffer to store the verification trace
21500 	 */
21501 	ret = bpf_vlog_init(&env->log, attr->log_level,
21502 			    (char __user *) (unsigned long) attr->log_buf,
21503 			    attr->log_size);
21504 	if (ret)
21505 		goto err_unlock;
21506 
21507 	mark_verifier_state_clean(env);
21508 
21509 	if (IS_ERR(btf_vmlinux)) {
21510 		/* Either gcc or pahole or kernel are broken. */
21511 		verbose(env, "in-kernel BTF is malformed\n");
21512 		ret = PTR_ERR(btf_vmlinux);
21513 		goto skip_full_check;
21514 	}
21515 
21516 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
21517 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
21518 		env->strict_alignment = true;
21519 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
21520 		env->strict_alignment = false;
21521 
21522 	if (is_priv)
21523 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
21524 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
21525 
21526 	env->explored_states = kvcalloc(state_htab_size(env),
21527 				       sizeof(struct bpf_verifier_state_list *),
21528 				       GFP_USER);
21529 	ret = -ENOMEM;
21530 	if (!env->explored_states)
21531 		goto skip_full_check;
21532 
21533 	ret = check_btf_info_early(env, attr, uattr);
21534 	if (ret < 0)
21535 		goto skip_full_check;
21536 
21537 	ret = add_subprog_and_kfunc(env);
21538 	if (ret < 0)
21539 		goto skip_full_check;
21540 
21541 	ret = check_subprogs(env);
21542 	if (ret < 0)
21543 		goto skip_full_check;
21544 
21545 	ret = check_btf_info(env, attr, uattr);
21546 	if (ret < 0)
21547 		goto skip_full_check;
21548 
21549 	ret = check_attach_btf_id(env);
21550 	if (ret)
21551 		goto skip_full_check;
21552 
21553 	ret = resolve_pseudo_ldimm64(env);
21554 	if (ret < 0)
21555 		goto skip_full_check;
21556 
21557 	if (bpf_prog_is_offloaded(env->prog->aux)) {
21558 		ret = bpf_prog_offload_verifier_prep(env->prog);
21559 		if (ret)
21560 			goto skip_full_check;
21561 	}
21562 
21563 	ret = check_cfg(env);
21564 	if (ret < 0)
21565 		goto skip_full_check;
21566 
21567 	ret = do_check_main(env);
21568 	ret = ret ?: do_check_subprogs(env);
21569 
21570 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
21571 		ret = bpf_prog_offload_finalize(env);
21572 
21573 skip_full_check:
21574 	kvfree(env->explored_states);
21575 
21576 	if (ret == 0)
21577 		ret = check_max_stack_depth(env);
21578 
21579 	/* instruction rewrites happen after this point */
21580 	if (ret == 0)
21581 		ret = optimize_bpf_loop(env);
21582 
21583 	if (is_priv) {
21584 		if (ret == 0)
21585 			opt_hard_wire_dead_code_branches(env);
21586 		if (ret == 0)
21587 			ret = opt_remove_dead_code(env);
21588 		if (ret == 0)
21589 			ret = opt_remove_nops(env);
21590 	} else {
21591 		if (ret == 0)
21592 			sanitize_dead_code(env);
21593 	}
21594 
21595 	if (ret == 0)
21596 		/* program is valid, convert *(u32*)(ctx + off) accesses */
21597 		ret = convert_ctx_accesses(env);
21598 
21599 	if (ret == 0)
21600 		ret = do_misc_fixups(env);
21601 
21602 	/* do 32-bit optimization after insn patching has done so those patched
21603 	 * insns could be handled correctly.
21604 	 */
21605 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
21606 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
21607 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
21608 								     : false;
21609 	}
21610 
21611 	if (ret == 0)
21612 		ret = fixup_call_args(env);
21613 
21614 	env->verification_time = ktime_get_ns() - start_time;
21615 	print_verification_stats(env);
21616 	env->prog->aux->verified_insns = env->insn_processed;
21617 
21618 	/* preserve original error even if log finalization is successful */
21619 	err = bpf_vlog_finalize(&env->log, &log_true_size);
21620 	if (err)
21621 		ret = err;
21622 
21623 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
21624 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
21625 				  &log_true_size, sizeof(log_true_size))) {
21626 		ret = -EFAULT;
21627 		goto err_release_maps;
21628 	}
21629 
21630 	if (ret)
21631 		goto err_release_maps;
21632 
21633 	if (env->used_map_cnt) {
21634 		/* if program passed verifier, update used_maps in bpf_prog_info */
21635 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
21636 							  sizeof(env->used_maps[0]),
21637 							  GFP_KERNEL);
21638 
21639 		if (!env->prog->aux->used_maps) {
21640 			ret = -ENOMEM;
21641 			goto err_release_maps;
21642 		}
21643 
21644 		memcpy(env->prog->aux->used_maps, env->used_maps,
21645 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
21646 		env->prog->aux->used_map_cnt = env->used_map_cnt;
21647 	}
21648 	if (env->used_btf_cnt) {
21649 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
21650 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
21651 							  sizeof(env->used_btfs[0]),
21652 							  GFP_KERNEL);
21653 		if (!env->prog->aux->used_btfs) {
21654 			ret = -ENOMEM;
21655 			goto err_release_maps;
21656 		}
21657 
21658 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
21659 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
21660 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
21661 	}
21662 	if (env->used_map_cnt || env->used_btf_cnt) {
21663 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
21664 		 * bpf_ld_imm64 instructions
21665 		 */
21666 		convert_pseudo_ld_imm64(env);
21667 	}
21668 
21669 	adjust_btf_func(env);
21670 
21671 err_release_maps:
21672 	if (!env->prog->aux->used_maps)
21673 		/* if we didn't copy map pointers into bpf_prog_info, release
21674 		 * them now. Otherwise free_used_maps() will release them.
21675 		 */
21676 		release_maps(env);
21677 	if (!env->prog->aux->used_btfs)
21678 		release_btfs(env);
21679 
21680 	/* extension progs temporarily inherit the attach_type of their targets
21681 	   for verification purposes, so set it back to zero before returning
21682 	 */
21683 	if (env->prog->type == BPF_PROG_TYPE_EXT)
21684 		env->prog->expected_attach_type = 0;
21685 
21686 	*prog = env->prog;
21687 
21688 	module_put(env->attach_btf_mod);
21689 err_unlock:
21690 	if (!is_priv)
21691 		mutex_unlock(&bpf_verifier_lock);
21692 	vfree(env->insn_aux_data);
21693 err_free_env:
21694 	kfree(env);
21695 	return ret;
21696 }
21697