xref: /linux-6.15/kernel/bpf/verifier.c (revision 37cce22d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <linux/bpf_mem_alloc.h>
30 #include <net/xdp.h>
31 #include <linux/trace_events.h>
32 #include <linux/kallsyms.h>
33 
34 #include "disasm.h"
35 
36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
38 	[_id] = & _name ## _verifier_ops,
39 #define BPF_MAP_TYPE(_id, _ops)
40 #define BPF_LINK_TYPE(_id, _name)
41 #include <linux/bpf_types.h>
42 #undef BPF_PROG_TYPE
43 #undef BPF_MAP_TYPE
44 #undef BPF_LINK_TYPE
45 };
46 
47 struct bpf_mem_alloc bpf_global_percpu_ma;
48 static bool bpf_global_percpu_ma_set;
49 
50 /* bpf_check() is a static code analyzer that walks eBPF program
51  * instruction by instruction and updates register/stack state.
52  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
53  *
54  * The first pass is depth-first-search to check that the program is a DAG.
55  * It rejects the following programs:
56  * - larger than BPF_MAXINSNS insns
57  * - if loop is present (detected via back-edge)
58  * - unreachable insns exist (shouldn't be a forest. program = one function)
59  * - out of bounds or malformed jumps
60  * The second pass is all possible path descent from the 1st insn.
61  * Since it's analyzing all paths through the program, the length of the
62  * analysis is limited to 64k insn, which may be hit even if total number of
63  * insn is less then 4K, but there are too many branches that change stack/regs.
64  * Number of 'branches to be analyzed' is limited to 1k
65  *
66  * On entry to each instruction, each register has a type, and the instruction
67  * changes the types of the registers depending on instruction semantics.
68  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
69  * copied to R1.
70  *
71  * All registers are 64-bit.
72  * R0 - return register
73  * R1-R5 argument passing registers
74  * R6-R9 callee saved registers
75  * R10 - frame pointer read-only
76  *
77  * At the start of BPF program the register R1 contains a pointer to bpf_context
78  * and has type PTR_TO_CTX.
79  *
80  * Verifier tracks arithmetic operations on pointers in case:
81  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
82  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
83  * 1st insn copies R10 (which has FRAME_PTR) type into R1
84  * and 2nd arithmetic instruction is pattern matched to recognize
85  * that it wants to construct a pointer to some element within stack.
86  * So after 2nd insn, the register R1 has type PTR_TO_STACK
87  * (and -20 constant is saved for further stack bounds checking).
88  * Meaning that this reg is a pointer to stack plus known immediate constant.
89  *
90  * Most of the time the registers have SCALAR_VALUE type, which
91  * means the register has some value, but it's not a valid pointer.
92  * (like pointer plus pointer becomes SCALAR_VALUE type)
93  *
94  * When verifier sees load or store instructions the type of base register
95  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
96  * four pointer types recognized by check_mem_access() function.
97  *
98  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
99  * and the range of [ptr, ptr + map's value_size) is accessible.
100  *
101  * registers used to pass values to function calls are checked against
102  * function argument constraints.
103  *
104  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
105  * It means that the register type passed to this function must be
106  * PTR_TO_STACK and it will be used inside the function as
107  * 'pointer to map element key'
108  *
109  * For example the argument constraints for bpf_map_lookup_elem():
110  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
111  *   .arg1_type = ARG_CONST_MAP_PTR,
112  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
113  *
114  * ret_type says that this function returns 'pointer to map elem value or null'
115  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
116  * 2nd argument should be a pointer to stack, which will be used inside
117  * the helper function as a pointer to map element key.
118  *
119  * On the kernel side the helper function looks like:
120  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
121  * {
122  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
123  *    void *key = (void *) (unsigned long) r2;
124  *    void *value;
125  *
126  *    here kernel can access 'key' and 'map' pointers safely, knowing that
127  *    [key, key + map->key_size) bytes are valid and were initialized on
128  *    the stack of eBPF program.
129  * }
130  *
131  * Corresponding eBPF program may look like:
132  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
133  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
134  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
135  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
136  * here verifier looks at prototype of map_lookup_elem() and sees:
137  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
138  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
139  *
140  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
141  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
142  * and were initialized prior to this call.
143  * If it's ok, then verifier allows this BPF_CALL insn and looks at
144  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
145  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
146  * returns either pointer to map value or NULL.
147  *
148  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
149  * insn, the register holding that pointer in the true branch changes state to
150  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
151  * branch. See check_cond_jmp_op().
152  *
153  * After the call R0 is set to return type of the function and registers R1-R5
154  * are set to NOT_INIT to indicate that they are no longer readable.
155  *
156  * The following reference types represent a potential reference to a kernel
157  * resource which, after first being allocated, must be checked and freed by
158  * the BPF program:
159  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
160  *
161  * When the verifier sees a helper call return a reference type, it allocates a
162  * pointer id for the reference and stores it in the current function state.
163  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
164  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
165  * passes through a NULL-check conditional. For the branch wherein the state is
166  * changed to CONST_IMM, the verifier releases the reference.
167  *
168  * For each helper function that allocates a reference, such as
169  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
170  * bpf_sk_release(). When a reference type passes into the release function,
171  * the verifier also releases the reference. If any unchecked or unreleased
172  * reference remains at the end of the program, the verifier rejects it.
173  */
174 
175 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
176 struct bpf_verifier_stack_elem {
177 	/* verifier state is 'st'
178 	 * before processing instruction 'insn_idx'
179 	 * and after processing instruction 'prev_insn_idx'
180 	 */
181 	struct bpf_verifier_state st;
182 	int insn_idx;
183 	int prev_insn_idx;
184 	struct bpf_verifier_stack_elem *next;
185 	/* length of verifier log at the time this state was pushed on stack */
186 	u32 log_pos;
187 };
188 
189 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
190 #define BPF_COMPLEXITY_LIMIT_STATES	64
191 
192 #define BPF_MAP_KEY_POISON	(1ULL << 63)
193 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
194 
195 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
196 
197 #define BPF_PRIV_STACK_MIN_SIZE		64
198 
199 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx);
200 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id);
201 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
202 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
203 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
204 static int ref_set_non_owning(struct bpf_verifier_env *env,
205 			      struct bpf_reg_state *reg);
206 static void specialize_kfunc(struct bpf_verifier_env *env,
207 			     u32 func_id, u16 offset, unsigned long *addr);
208 static bool is_trusted_reg(const struct bpf_reg_state *reg);
209 
210 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
211 {
212 	return aux->map_ptr_state.poison;
213 }
214 
215 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
216 {
217 	return aux->map_ptr_state.unpriv;
218 }
219 
220 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
221 			      struct bpf_map *map,
222 			      bool unpriv, bool poison)
223 {
224 	unpriv |= bpf_map_ptr_unpriv(aux);
225 	aux->map_ptr_state.unpriv = unpriv;
226 	aux->map_ptr_state.poison = poison;
227 	aux->map_ptr_state.map_ptr = map;
228 }
229 
230 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
231 {
232 	return aux->map_key_state & BPF_MAP_KEY_POISON;
233 }
234 
235 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
236 {
237 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
238 }
239 
240 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
241 {
242 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
243 }
244 
245 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
246 {
247 	bool poisoned = bpf_map_key_poisoned(aux);
248 
249 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
250 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
251 }
252 
253 static bool bpf_helper_call(const struct bpf_insn *insn)
254 {
255 	return insn->code == (BPF_JMP | BPF_CALL) &&
256 	       insn->src_reg == 0;
257 }
258 
259 static bool bpf_pseudo_call(const struct bpf_insn *insn)
260 {
261 	return insn->code == (BPF_JMP | BPF_CALL) &&
262 	       insn->src_reg == BPF_PSEUDO_CALL;
263 }
264 
265 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
266 {
267 	return insn->code == (BPF_JMP | BPF_CALL) &&
268 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
269 }
270 
271 struct bpf_call_arg_meta {
272 	struct bpf_map *map_ptr;
273 	bool raw_mode;
274 	bool pkt_access;
275 	u8 release_regno;
276 	int regno;
277 	int access_size;
278 	int mem_size;
279 	u64 msize_max_value;
280 	int ref_obj_id;
281 	int dynptr_id;
282 	int map_uid;
283 	int func_id;
284 	struct btf *btf;
285 	u32 btf_id;
286 	struct btf *ret_btf;
287 	u32 ret_btf_id;
288 	u32 subprogno;
289 	struct btf_field *kptr_field;
290 };
291 
292 struct bpf_kfunc_call_arg_meta {
293 	/* In parameters */
294 	struct btf *btf;
295 	u32 func_id;
296 	u32 kfunc_flags;
297 	const struct btf_type *func_proto;
298 	const char *func_name;
299 	/* Out parameters */
300 	u32 ref_obj_id;
301 	u8 release_regno;
302 	bool r0_rdonly;
303 	u32 ret_btf_id;
304 	u64 r0_size;
305 	u32 subprogno;
306 	struct {
307 		u64 value;
308 		bool found;
309 	} arg_constant;
310 
311 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
312 	 * generally to pass info about user-defined local kptr types to later
313 	 * verification logic
314 	 *   bpf_obj_drop/bpf_percpu_obj_drop
315 	 *     Record the local kptr type to be drop'd
316 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
317 	 *     Record the local kptr type to be refcount_incr'd and use
318 	 *     arg_owning_ref to determine whether refcount_acquire should be
319 	 *     fallible
320 	 */
321 	struct btf *arg_btf;
322 	u32 arg_btf_id;
323 	bool arg_owning_ref;
324 
325 	struct {
326 		struct btf_field *field;
327 	} arg_list_head;
328 	struct {
329 		struct btf_field *field;
330 	} arg_rbtree_root;
331 	struct {
332 		enum bpf_dynptr_type type;
333 		u32 id;
334 		u32 ref_obj_id;
335 	} initialized_dynptr;
336 	struct {
337 		u8 spi;
338 		u8 frameno;
339 	} iter;
340 	struct {
341 		struct bpf_map *ptr;
342 		int uid;
343 	} map;
344 	u64 mem_size;
345 };
346 
347 struct btf *btf_vmlinux;
348 
349 static const char *btf_type_name(const struct btf *btf, u32 id)
350 {
351 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
352 }
353 
354 static DEFINE_MUTEX(bpf_verifier_lock);
355 static DEFINE_MUTEX(bpf_percpu_ma_lock);
356 
357 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
358 {
359 	struct bpf_verifier_env *env = private_data;
360 	va_list args;
361 
362 	if (!bpf_verifier_log_needed(&env->log))
363 		return;
364 
365 	va_start(args, fmt);
366 	bpf_verifier_vlog(&env->log, fmt, args);
367 	va_end(args);
368 }
369 
370 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
371 				   struct bpf_reg_state *reg,
372 				   struct bpf_retval_range range, const char *ctx,
373 				   const char *reg_name)
374 {
375 	bool unknown = true;
376 
377 	verbose(env, "%s the register %s has", ctx, reg_name);
378 	if (reg->smin_value > S64_MIN) {
379 		verbose(env, " smin=%lld", reg->smin_value);
380 		unknown = false;
381 	}
382 	if (reg->smax_value < S64_MAX) {
383 		verbose(env, " smax=%lld", reg->smax_value);
384 		unknown = false;
385 	}
386 	if (unknown)
387 		verbose(env, " unknown scalar value");
388 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
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 int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
646 {
647 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
648 }
649 
650 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
651 {
652 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
653 	case DYNPTR_TYPE_LOCAL:
654 		return BPF_DYNPTR_TYPE_LOCAL;
655 	case DYNPTR_TYPE_RINGBUF:
656 		return BPF_DYNPTR_TYPE_RINGBUF;
657 	case DYNPTR_TYPE_SKB:
658 		return BPF_DYNPTR_TYPE_SKB;
659 	case DYNPTR_TYPE_XDP:
660 		return BPF_DYNPTR_TYPE_XDP;
661 	default:
662 		return BPF_DYNPTR_TYPE_INVALID;
663 	}
664 }
665 
666 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
667 {
668 	switch (type) {
669 	case BPF_DYNPTR_TYPE_LOCAL:
670 		return DYNPTR_TYPE_LOCAL;
671 	case BPF_DYNPTR_TYPE_RINGBUF:
672 		return DYNPTR_TYPE_RINGBUF;
673 	case BPF_DYNPTR_TYPE_SKB:
674 		return DYNPTR_TYPE_SKB;
675 	case BPF_DYNPTR_TYPE_XDP:
676 		return DYNPTR_TYPE_XDP;
677 	default:
678 		return 0;
679 	}
680 }
681 
682 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
683 {
684 	return type == BPF_DYNPTR_TYPE_RINGBUF;
685 }
686 
687 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
688 			      enum bpf_dynptr_type type,
689 			      bool first_slot, int dynptr_id);
690 
691 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
692 				struct bpf_reg_state *reg);
693 
694 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
695 				   struct bpf_reg_state *sreg1,
696 				   struct bpf_reg_state *sreg2,
697 				   enum bpf_dynptr_type type)
698 {
699 	int id = ++env->id_gen;
700 
701 	__mark_dynptr_reg(sreg1, type, true, id);
702 	__mark_dynptr_reg(sreg2, type, false, id);
703 }
704 
705 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
706 			       struct bpf_reg_state *reg,
707 			       enum bpf_dynptr_type type)
708 {
709 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
710 }
711 
712 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
713 				        struct bpf_func_state *state, int spi);
714 
715 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
716 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
717 {
718 	struct bpf_func_state *state = func(env, reg);
719 	enum bpf_dynptr_type type;
720 	int spi, i, err;
721 
722 	spi = dynptr_get_spi(env, reg);
723 	if (spi < 0)
724 		return spi;
725 
726 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
727 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
728 	 * to ensure that for the following example:
729 	 *	[d1][d1][d2][d2]
730 	 * spi    3   2   1   0
731 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
732 	 * case they do belong to same dynptr, second call won't see slot_type
733 	 * as STACK_DYNPTR and will simply skip destruction.
734 	 */
735 	err = destroy_if_dynptr_stack_slot(env, state, spi);
736 	if (err)
737 		return err;
738 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
739 	if (err)
740 		return err;
741 
742 	for (i = 0; i < BPF_REG_SIZE; i++) {
743 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
744 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
745 	}
746 
747 	type = arg_to_dynptr_type(arg_type);
748 	if (type == BPF_DYNPTR_TYPE_INVALID)
749 		return -EINVAL;
750 
751 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
752 			       &state->stack[spi - 1].spilled_ptr, type);
753 
754 	if (dynptr_type_refcounted(type)) {
755 		/* The id is used to track proper releasing */
756 		int id;
757 
758 		if (clone_ref_obj_id)
759 			id = clone_ref_obj_id;
760 		else
761 			id = acquire_reference(env, insn_idx);
762 
763 		if (id < 0)
764 			return id;
765 
766 		state->stack[spi].spilled_ptr.ref_obj_id = id;
767 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
768 	}
769 
770 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
771 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
772 
773 	return 0;
774 }
775 
776 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
777 {
778 	int i;
779 
780 	for (i = 0; i < BPF_REG_SIZE; i++) {
781 		state->stack[spi].slot_type[i] = STACK_INVALID;
782 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
783 	}
784 
785 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
786 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
787 
788 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
789 	 *
790 	 * While we don't allow reading STACK_INVALID, it is still possible to
791 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
792 	 * helpers or insns can do partial read of that part without failing,
793 	 * but check_stack_range_initialized, check_stack_read_var_off, and
794 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
795 	 * the slot conservatively. Hence we need to prevent those liveness
796 	 * marking walks.
797 	 *
798 	 * This was not a problem before because STACK_INVALID is only set by
799 	 * default (where the default reg state has its reg->parent as NULL), or
800 	 * in clean_live_states after REG_LIVE_DONE (at which point
801 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
802 	 * verifier state exploration (like we did above). Hence, for our case
803 	 * parentage chain will still be live (i.e. reg->parent may be
804 	 * non-NULL), while earlier reg->parent was NULL, so we need
805 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
806 	 * done later on reads or by mark_dynptr_read as well to unnecessary
807 	 * mark registers in verifier state.
808 	 */
809 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
810 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
811 }
812 
813 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
814 {
815 	struct bpf_func_state *state = func(env, reg);
816 	int spi, ref_obj_id, i;
817 
818 	spi = dynptr_get_spi(env, reg);
819 	if (spi < 0)
820 		return spi;
821 
822 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
823 		invalidate_dynptr(env, state, spi);
824 		return 0;
825 	}
826 
827 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
828 
829 	/* If the dynptr has a ref_obj_id, then we need to invalidate
830 	 * two things:
831 	 *
832 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
833 	 * 2) Any slices derived from this dynptr.
834 	 */
835 
836 	/* Invalidate any slices associated with this dynptr */
837 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
838 
839 	/* Invalidate any dynptr clones */
840 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
841 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
842 			continue;
843 
844 		/* it should always be the case that if the ref obj id
845 		 * matches then the stack slot also belongs to a
846 		 * dynptr
847 		 */
848 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
849 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
850 			return -EFAULT;
851 		}
852 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
853 			invalidate_dynptr(env, state, i);
854 	}
855 
856 	return 0;
857 }
858 
859 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
860 			       struct bpf_reg_state *reg);
861 
862 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
863 {
864 	if (!env->allow_ptr_leaks)
865 		__mark_reg_not_init(env, reg);
866 	else
867 		__mark_reg_unknown(env, reg);
868 }
869 
870 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
871 				        struct bpf_func_state *state, int spi)
872 {
873 	struct bpf_func_state *fstate;
874 	struct bpf_reg_state *dreg;
875 	int i, dynptr_id;
876 
877 	/* We always ensure that STACK_DYNPTR is never set partially,
878 	 * hence just checking for slot_type[0] is enough. This is
879 	 * different for STACK_SPILL, where it may be only set for
880 	 * 1 byte, so code has to use is_spilled_reg.
881 	 */
882 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
883 		return 0;
884 
885 	/* Reposition spi to first slot */
886 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
887 		spi = spi + 1;
888 
889 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
890 		verbose(env, "cannot overwrite referenced dynptr\n");
891 		return -EINVAL;
892 	}
893 
894 	mark_stack_slot_scratched(env, spi);
895 	mark_stack_slot_scratched(env, spi - 1);
896 
897 	/* Writing partially to one dynptr stack slot destroys both. */
898 	for (i = 0; i < BPF_REG_SIZE; i++) {
899 		state->stack[spi].slot_type[i] = STACK_INVALID;
900 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
901 	}
902 
903 	dynptr_id = state->stack[spi].spilled_ptr.id;
904 	/* Invalidate any slices associated with this dynptr */
905 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
906 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
907 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
908 			continue;
909 		if (dreg->dynptr_id == dynptr_id)
910 			mark_reg_invalid(env, dreg);
911 	}));
912 
913 	/* Do not release reference state, we are destroying dynptr on stack,
914 	 * not using some helper to release it. Just reset register.
915 	 */
916 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
917 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
918 
919 	/* Same reason as unmark_stack_slots_dynptr above */
920 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
921 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
922 
923 	return 0;
924 }
925 
926 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
927 {
928 	int spi;
929 
930 	if (reg->type == CONST_PTR_TO_DYNPTR)
931 		return false;
932 
933 	spi = dynptr_get_spi(env, reg);
934 
935 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
936 	 * error because this just means the stack state hasn't been updated yet.
937 	 * We will do check_mem_access to check and update stack bounds later.
938 	 */
939 	if (spi < 0 && spi != -ERANGE)
940 		return false;
941 
942 	/* We don't need to check if the stack slots are marked by previous
943 	 * dynptr initializations because we allow overwriting existing unreferenced
944 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
945 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
946 	 * touching are completely destructed before we reinitialize them for a new
947 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
948 	 * instead of delaying it until the end where the user will get "Unreleased
949 	 * reference" error.
950 	 */
951 	return true;
952 }
953 
954 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
955 {
956 	struct bpf_func_state *state = func(env, reg);
957 	int i, spi;
958 
959 	/* This already represents first slot of initialized bpf_dynptr.
960 	 *
961 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
962 	 * check_func_arg_reg_off's logic, so we don't need to check its
963 	 * offset and alignment.
964 	 */
965 	if (reg->type == CONST_PTR_TO_DYNPTR)
966 		return true;
967 
968 	spi = dynptr_get_spi(env, reg);
969 	if (spi < 0)
970 		return false;
971 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
972 		return false;
973 
974 	for (i = 0; i < BPF_REG_SIZE; i++) {
975 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
976 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
977 			return false;
978 	}
979 
980 	return true;
981 }
982 
983 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
984 				    enum bpf_arg_type arg_type)
985 {
986 	struct bpf_func_state *state = func(env, reg);
987 	enum bpf_dynptr_type dynptr_type;
988 	int spi;
989 
990 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
991 	if (arg_type == ARG_PTR_TO_DYNPTR)
992 		return true;
993 
994 	dynptr_type = arg_to_dynptr_type(arg_type);
995 	if (reg->type == CONST_PTR_TO_DYNPTR) {
996 		return reg->dynptr.type == dynptr_type;
997 	} else {
998 		spi = dynptr_get_spi(env, reg);
999 		if (spi < 0)
1000 			return false;
1001 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1002 	}
1003 }
1004 
1005 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1006 
1007 static bool in_rcu_cs(struct bpf_verifier_env *env);
1008 
1009 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1010 
1011 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1012 				 struct bpf_kfunc_call_arg_meta *meta,
1013 				 struct bpf_reg_state *reg, int insn_idx,
1014 				 struct btf *btf, u32 btf_id, int nr_slots)
1015 {
1016 	struct bpf_func_state *state = func(env, reg);
1017 	int spi, i, j, id;
1018 
1019 	spi = iter_get_spi(env, reg, nr_slots);
1020 	if (spi < 0)
1021 		return spi;
1022 
1023 	id = acquire_reference(env, insn_idx);
1024 	if (id < 0)
1025 		return id;
1026 
1027 	for (i = 0; i < nr_slots; i++) {
1028 		struct bpf_stack_state *slot = &state->stack[spi - i];
1029 		struct bpf_reg_state *st = &slot->spilled_ptr;
1030 
1031 		__mark_reg_known_zero(st);
1032 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1033 		if (is_kfunc_rcu_protected(meta)) {
1034 			if (in_rcu_cs(env))
1035 				st->type |= MEM_RCU;
1036 			else
1037 				st->type |= PTR_UNTRUSTED;
1038 		}
1039 		st->live |= REG_LIVE_WRITTEN;
1040 		st->ref_obj_id = i == 0 ? id : 0;
1041 		st->iter.btf = btf;
1042 		st->iter.btf_id = btf_id;
1043 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1044 		st->iter.depth = 0;
1045 
1046 		for (j = 0; j < BPF_REG_SIZE; j++)
1047 			slot->slot_type[j] = STACK_ITER;
1048 
1049 		mark_stack_slot_scratched(env, spi - i);
1050 	}
1051 
1052 	return 0;
1053 }
1054 
1055 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1056 				   struct bpf_reg_state *reg, int nr_slots)
1057 {
1058 	struct bpf_func_state *state = func(env, reg);
1059 	int spi, i, j;
1060 
1061 	spi = iter_get_spi(env, reg, nr_slots);
1062 	if (spi < 0)
1063 		return spi;
1064 
1065 	for (i = 0; i < nr_slots; i++) {
1066 		struct bpf_stack_state *slot = &state->stack[spi - i];
1067 		struct bpf_reg_state *st = &slot->spilled_ptr;
1068 
1069 		if (i == 0)
1070 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1071 
1072 		__mark_reg_not_init(env, st);
1073 
1074 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1075 		st->live |= REG_LIVE_WRITTEN;
1076 
1077 		for (j = 0; j < BPF_REG_SIZE; j++)
1078 			slot->slot_type[j] = STACK_INVALID;
1079 
1080 		mark_stack_slot_scratched(env, spi - i);
1081 	}
1082 
1083 	return 0;
1084 }
1085 
1086 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1087 				     struct bpf_reg_state *reg, int nr_slots)
1088 {
1089 	struct bpf_func_state *state = func(env, reg);
1090 	int spi, i, j;
1091 
1092 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1093 	 * will do check_mem_access to check and update stack bounds later, so
1094 	 * return true for that case.
1095 	 */
1096 	spi = iter_get_spi(env, reg, nr_slots);
1097 	if (spi == -ERANGE)
1098 		return true;
1099 	if (spi < 0)
1100 		return false;
1101 
1102 	for (i = 0; i < nr_slots; i++) {
1103 		struct bpf_stack_state *slot = &state->stack[spi - i];
1104 
1105 		for (j = 0; j < BPF_REG_SIZE; j++)
1106 			if (slot->slot_type[j] == STACK_ITER)
1107 				return false;
1108 	}
1109 
1110 	return true;
1111 }
1112 
1113 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1114 				   struct btf *btf, u32 btf_id, int nr_slots)
1115 {
1116 	struct bpf_func_state *state = func(env, reg);
1117 	int spi, i, j;
1118 
1119 	spi = iter_get_spi(env, reg, nr_slots);
1120 	if (spi < 0)
1121 		return -EINVAL;
1122 
1123 	for (i = 0; i < nr_slots; i++) {
1124 		struct bpf_stack_state *slot = &state->stack[spi - i];
1125 		struct bpf_reg_state *st = &slot->spilled_ptr;
1126 
1127 		if (st->type & PTR_UNTRUSTED)
1128 			return -EPROTO;
1129 		/* only main (first) slot has ref_obj_id set */
1130 		if (i == 0 && !st->ref_obj_id)
1131 			return -EINVAL;
1132 		if (i != 0 && st->ref_obj_id)
1133 			return -EINVAL;
1134 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1135 			return -EINVAL;
1136 
1137 		for (j = 0; j < BPF_REG_SIZE; j++)
1138 			if (slot->slot_type[j] != STACK_ITER)
1139 				return -EINVAL;
1140 	}
1141 
1142 	return 0;
1143 }
1144 
1145 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1146 static int release_irq_state(struct bpf_verifier_state *state, int id);
1147 
1148 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1149 				     struct bpf_kfunc_call_arg_meta *meta,
1150 				     struct bpf_reg_state *reg, int insn_idx)
1151 {
1152 	struct bpf_func_state *state = func(env, reg);
1153 	struct bpf_stack_state *slot;
1154 	struct bpf_reg_state *st;
1155 	int spi, i, id;
1156 
1157 	spi = irq_flag_get_spi(env, reg);
1158 	if (spi < 0)
1159 		return spi;
1160 
1161 	id = acquire_irq_state(env, insn_idx);
1162 	if (id < 0)
1163 		return id;
1164 
1165 	slot = &state->stack[spi];
1166 	st = &slot->spilled_ptr;
1167 
1168 	__mark_reg_known_zero(st);
1169 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1170 	st->live |= REG_LIVE_WRITTEN;
1171 	st->ref_obj_id = id;
1172 
1173 	for (i = 0; i < BPF_REG_SIZE; i++)
1174 		slot->slot_type[i] = STACK_IRQ_FLAG;
1175 
1176 	mark_stack_slot_scratched(env, spi);
1177 	return 0;
1178 }
1179 
1180 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1181 {
1182 	struct bpf_func_state *state = func(env, reg);
1183 	struct bpf_stack_state *slot;
1184 	struct bpf_reg_state *st;
1185 	int spi, i, err;
1186 
1187 	spi = irq_flag_get_spi(env, reg);
1188 	if (spi < 0)
1189 		return spi;
1190 
1191 	slot = &state->stack[spi];
1192 	st = &slot->spilled_ptr;
1193 
1194 	err = release_irq_state(env->cur_state, st->ref_obj_id);
1195 	WARN_ON_ONCE(err && err != -EACCES);
1196 	if (err) {
1197 		int insn_idx = 0;
1198 
1199 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1200 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1201 				insn_idx = env->cur_state->refs[i].insn_idx;
1202 				break;
1203 			}
1204 		}
1205 
1206 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1207 			env->cur_state->active_irq_id, insn_idx);
1208 		return err;
1209 	}
1210 
1211 	__mark_reg_not_init(env, st);
1212 
1213 	/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1214 	st->live |= REG_LIVE_WRITTEN;
1215 
1216 	for (i = 0; i < BPF_REG_SIZE; i++)
1217 		slot->slot_type[i] = STACK_INVALID;
1218 
1219 	mark_stack_slot_scratched(env, spi);
1220 	return 0;
1221 }
1222 
1223 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1224 {
1225 	struct bpf_func_state *state = func(env, reg);
1226 	struct bpf_stack_state *slot;
1227 	int spi, i;
1228 
1229 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1230 	 * will do check_mem_access to check and update stack bounds later, so
1231 	 * return true for that case.
1232 	 */
1233 	spi = irq_flag_get_spi(env, reg);
1234 	if (spi == -ERANGE)
1235 		return true;
1236 	if (spi < 0)
1237 		return false;
1238 
1239 	slot = &state->stack[spi];
1240 
1241 	for (i = 0; i < BPF_REG_SIZE; i++)
1242 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1243 			return false;
1244 	return true;
1245 }
1246 
1247 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1248 {
1249 	struct bpf_func_state *state = func(env, reg);
1250 	struct bpf_stack_state *slot;
1251 	struct bpf_reg_state *st;
1252 	int spi, i;
1253 
1254 	spi = irq_flag_get_spi(env, reg);
1255 	if (spi < 0)
1256 		return -EINVAL;
1257 
1258 	slot = &state->stack[spi];
1259 	st = &slot->spilled_ptr;
1260 
1261 	if (!st->ref_obj_id)
1262 		return -EINVAL;
1263 
1264 	for (i = 0; i < BPF_REG_SIZE; i++)
1265 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1266 			return -EINVAL;
1267 	return 0;
1268 }
1269 
1270 /* Check if given stack slot is "special":
1271  *   - spilled register state (STACK_SPILL);
1272  *   - dynptr state (STACK_DYNPTR);
1273  *   - iter state (STACK_ITER).
1274  *   - irq flag state (STACK_IRQ_FLAG)
1275  */
1276 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1277 {
1278 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1279 
1280 	switch (type) {
1281 	case STACK_SPILL:
1282 	case STACK_DYNPTR:
1283 	case STACK_ITER:
1284 	case STACK_IRQ_FLAG:
1285 		return true;
1286 	case STACK_INVALID:
1287 	case STACK_MISC:
1288 	case STACK_ZERO:
1289 		return false;
1290 	default:
1291 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1292 		return true;
1293 	}
1294 }
1295 
1296 /* The reg state of a pointer or a bounded scalar was saved when
1297  * it was spilled to the stack.
1298  */
1299 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1300 {
1301 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1302 }
1303 
1304 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1305 {
1306 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1307 	       stack->spilled_ptr.type == SCALAR_VALUE;
1308 }
1309 
1310 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1311 {
1312 	return stack->slot_type[0] == STACK_SPILL &&
1313 	       stack->spilled_ptr.type == SCALAR_VALUE;
1314 }
1315 
1316 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1317  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1318  * more precise STACK_ZERO.
1319  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1320  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1321  * unnecessary as both are considered equivalent when loading data and pruning,
1322  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1323  * slots.
1324  */
1325 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1326 {
1327 	if (*stype == STACK_ZERO)
1328 		return;
1329 	if (*stype == STACK_INVALID)
1330 		return;
1331 	*stype = STACK_MISC;
1332 }
1333 
1334 static void scrub_spilled_slot(u8 *stype)
1335 {
1336 	if (*stype != STACK_INVALID)
1337 		*stype = STACK_MISC;
1338 }
1339 
1340 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1341  * small to hold src. This is different from krealloc since we don't want to preserve
1342  * the contents of dst.
1343  *
1344  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1345  * not be allocated.
1346  */
1347 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1348 {
1349 	size_t alloc_bytes;
1350 	void *orig = dst;
1351 	size_t bytes;
1352 
1353 	if (ZERO_OR_NULL_PTR(src))
1354 		goto out;
1355 
1356 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1357 		return NULL;
1358 
1359 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1360 	dst = krealloc(orig, alloc_bytes, flags);
1361 	if (!dst) {
1362 		kfree(orig);
1363 		return NULL;
1364 	}
1365 
1366 	memcpy(dst, src, bytes);
1367 out:
1368 	return dst ? dst : ZERO_SIZE_PTR;
1369 }
1370 
1371 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1372  * small to hold new_n items. new items are zeroed out if the array grows.
1373  *
1374  * Contrary to krealloc_array, does not free arr if new_n is zero.
1375  */
1376 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1377 {
1378 	size_t alloc_size;
1379 	void *new_arr;
1380 
1381 	if (!new_n || old_n == new_n)
1382 		goto out;
1383 
1384 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1385 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1386 	if (!new_arr) {
1387 		kfree(arr);
1388 		return NULL;
1389 	}
1390 	arr = new_arr;
1391 
1392 	if (new_n > old_n)
1393 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1394 
1395 out:
1396 	return arr ? arr : ZERO_SIZE_PTR;
1397 }
1398 
1399 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1400 {
1401 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1402 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1403 	if (!dst->refs)
1404 		return -ENOMEM;
1405 
1406 	dst->acquired_refs = src->acquired_refs;
1407 	dst->active_locks = src->active_locks;
1408 	dst->active_preempt_locks = src->active_preempt_locks;
1409 	dst->active_rcu_lock = src->active_rcu_lock;
1410 	dst->active_irq_id = src->active_irq_id;
1411 	return 0;
1412 }
1413 
1414 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1415 {
1416 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1417 
1418 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1419 				GFP_KERNEL);
1420 	if (!dst->stack)
1421 		return -ENOMEM;
1422 
1423 	dst->allocated_stack = src->allocated_stack;
1424 	return 0;
1425 }
1426 
1427 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1428 {
1429 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1430 				    sizeof(struct bpf_reference_state));
1431 	if (!state->refs)
1432 		return -ENOMEM;
1433 
1434 	state->acquired_refs = n;
1435 	return 0;
1436 }
1437 
1438 /* Possibly update state->allocated_stack to be at least size bytes. Also
1439  * possibly update the function's high-water mark in its bpf_subprog_info.
1440  */
1441 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1442 {
1443 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1444 
1445 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1446 	size = round_up(size, BPF_REG_SIZE);
1447 	n = size / BPF_REG_SIZE;
1448 
1449 	if (old_n >= n)
1450 		return 0;
1451 
1452 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1453 	if (!state->stack)
1454 		return -ENOMEM;
1455 
1456 	state->allocated_stack = size;
1457 
1458 	/* update known max for given subprogram */
1459 	if (env->subprog_info[state->subprogno].stack_depth < size)
1460 		env->subprog_info[state->subprogno].stack_depth = size;
1461 
1462 	return 0;
1463 }
1464 
1465 /* Acquire a pointer id from the env and update the state->refs to include
1466  * this new pointer reference.
1467  * On success, returns a valid pointer id to associate with the register
1468  * On failure, returns a negative errno.
1469  */
1470 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1471 {
1472 	struct bpf_verifier_state *state = env->cur_state;
1473 	int new_ofs = state->acquired_refs;
1474 	int err;
1475 
1476 	err = resize_reference_state(state, state->acquired_refs + 1);
1477 	if (err)
1478 		return NULL;
1479 	state->refs[new_ofs].insn_idx = insn_idx;
1480 
1481 	return &state->refs[new_ofs];
1482 }
1483 
1484 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx)
1485 {
1486 	struct bpf_reference_state *s;
1487 
1488 	s = acquire_reference_state(env, insn_idx);
1489 	if (!s)
1490 		return -ENOMEM;
1491 	s->type = REF_TYPE_PTR;
1492 	s->id = ++env->id_gen;
1493 	return s->id;
1494 }
1495 
1496 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1497 			      int id, void *ptr)
1498 {
1499 	struct bpf_verifier_state *state = env->cur_state;
1500 	struct bpf_reference_state *s;
1501 
1502 	s = acquire_reference_state(env, insn_idx);
1503 	s->type = type;
1504 	s->id = id;
1505 	s->ptr = ptr;
1506 
1507 	state->active_locks++;
1508 	return 0;
1509 }
1510 
1511 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1512 {
1513 	struct bpf_verifier_state *state = env->cur_state;
1514 	struct bpf_reference_state *s;
1515 
1516 	s = acquire_reference_state(env, insn_idx);
1517 	if (!s)
1518 		return -ENOMEM;
1519 	s->type = REF_TYPE_IRQ;
1520 	s->id = ++env->id_gen;
1521 
1522 	state->active_irq_id = s->id;
1523 	return s->id;
1524 }
1525 
1526 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1527 {
1528 	int last_idx;
1529 	size_t rem;
1530 
1531 	/* IRQ state requires the relative ordering of elements remaining the
1532 	 * same, since it relies on the refs array to behave as a stack, so that
1533 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1534 	 * the array instead of swapping the final element into the deleted idx.
1535 	 */
1536 	last_idx = state->acquired_refs - 1;
1537 	rem = state->acquired_refs - idx - 1;
1538 	if (last_idx && idx != last_idx)
1539 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1540 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1541 	state->acquired_refs--;
1542 	return;
1543 }
1544 
1545 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
1546 {
1547 	int i;
1548 
1549 	for (i = 0; i < state->acquired_refs; i++) {
1550 		if (state->refs[i].type != type)
1551 			continue;
1552 		if (state->refs[i].id == id && state->refs[i].ptr == ptr) {
1553 			release_reference_state(state, i);
1554 			state->active_locks--;
1555 			return 0;
1556 		}
1557 	}
1558 	return -EINVAL;
1559 }
1560 
1561 static int release_irq_state(struct bpf_verifier_state *state, int id)
1562 {
1563 	u32 prev_id = 0;
1564 	int i;
1565 
1566 	if (id != state->active_irq_id)
1567 		return -EACCES;
1568 
1569 	for (i = 0; i < state->acquired_refs; i++) {
1570 		if (state->refs[i].type != REF_TYPE_IRQ)
1571 			continue;
1572 		if (state->refs[i].id == id) {
1573 			release_reference_state(state, i);
1574 			state->active_irq_id = prev_id;
1575 			return 0;
1576 		} else {
1577 			prev_id = state->refs[i].id;
1578 		}
1579 	}
1580 	return -EINVAL;
1581 }
1582 
1583 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1584 						   int id, void *ptr)
1585 {
1586 	int i;
1587 
1588 	for (i = 0; i < state->acquired_refs; i++) {
1589 		struct bpf_reference_state *s = &state->refs[i];
1590 
1591 		if (s->type != type)
1592 			continue;
1593 
1594 		if (s->id == id && s->ptr == ptr)
1595 			return s;
1596 	}
1597 	return NULL;
1598 }
1599 
1600 static void free_func_state(struct bpf_func_state *state)
1601 {
1602 	if (!state)
1603 		return;
1604 	kfree(state->stack);
1605 	kfree(state);
1606 }
1607 
1608 static void free_verifier_state(struct bpf_verifier_state *state,
1609 				bool free_self)
1610 {
1611 	int i;
1612 
1613 	for (i = 0; i <= state->curframe; i++) {
1614 		free_func_state(state->frame[i]);
1615 		state->frame[i] = NULL;
1616 	}
1617 	kfree(state->refs);
1618 	if (free_self)
1619 		kfree(state);
1620 }
1621 
1622 /* copy verifier state from src to dst growing dst stack space
1623  * when necessary to accommodate larger src stack
1624  */
1625 static int copy_func_state(struct bpf_func_state *dst,
1626 			   const struct bpf_func_state *src)
1627 {
1628 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1629 	return copy_stack_state(dst, src);
1630 }
1631 
1632 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1633 			       const struct bpf_verifier_state *src)
1634 {
1635 	struct bpf_func_state *dst;
1636 	int i, err;
1637 
1638 	/* if dst has more stack frames then src frame, free them, this is also
1639 	 * necessary in case of exceptional exits using bpf_throw.
1640 	 */
1641 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1642 		free_func_state(dst_state->frame[i]);
1643 		dst_state->frame[i] = NULL;
1644 	}
1645 	err = copy_reference_state(dst_state, src);
1646 	if (err)
1647 		return err;
1648 	dst_state->speculative = src->speculative;
1649 	dst_state->in_sleepable = src->in_sleepable;
1650 	dst_state->curframe = src->curframe;
1651 	dst_state->branches = src->branches;
1652 	dst_state->parent = src->parent;
1653 	dst_state->first_insn_idx = src->first_insn_idx;
1654 	dst_state->last_insn_idx = src->last_insn_idx;
1655 	dst_state->insn_hist_start = src->insn_hist_start;
1656 	dst_state->insn_hist_end = src->insn_hist_end;
1657 	dst_state->dfs_depth = src->dfs_depth;
1658 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1659 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1660 	dst_state->may_goto_depth = src->may_goto_depth;
1661 	for (i = 0; i <= src->curframe; i++) {
1662 		dst = dst_state->frame[i];
1663 		if (!dst) {
1664 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1665 			if (!dst)
1666 				return -ENOMEM;
1667 			dst_state->frame[i] = dst;
1668 		}
1669 		err = copy_func_state(dst, src->frame[i]);
1670 		if (err)
1671 			return err;
1672 	}
1673 	return 0;
1674 }
1675 
1676 static u32 state_htab_size(struct bpf_verifier_env *env)
1677 {
1678 	return env->prog->len;
1679 }
1680 
1681 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1682 {
1683 	struct bpf_verifier_state *cur = env->cur_state;
1684 	struct bpf_func_state *state = cur->frame[cur->curframe];
1685 
1686 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1687 }
1688 
1689 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1690 {
1691 	int fr;
1692 
1693 	if (a->curframe != b->curframe)
1694 		return false;
1695 
1696 	for (fr = a->curframe; fr >= 0; fr--)
1697 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1698 			return false;
1699 
1700 	return true;
1701 }
1702 
1703 /* Open coded iterators allow back-edges in the state graph in order to
1704  * check unbounded loops that iterators.
1705  *
1706  * In is_state_visited() it is necessary to know if explored states are
1707  * part of some loops in order to decide whether non-exact states
1708  * comparison could be used:
1709  * - non-exact states comparison establishes sub-state relation and uses
1710  *   read and precision marks to do so, these marks are propagated from
1711  *   children states and thus are not guaranteed to be final in a loop;
1712  * - exact states comparison just checks if current and explored states
1713  *   are identical (and thus form a back-edge).
1714  *
1715  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1716  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1717  * algorithm for loop structure detection and gives an overview of
1718  * relevant terminology. It also has helpful illustrations.
1719  *
1720  * [1] https://api.semanticscholar.org/CorpusID:15784067
1721  *
1722  * We use a similar algorithm but because loop nested structure is
1723  * irrelevant for verifier ours is significantly simpler and resembles
1724  * strongly connected components algorithm from Sedgewick's textbook.
1725  *
1726  * Define topmost loop entry as a first node of the loop traversed in a
1727  * depth first search starting from initial state. The goal of the loop
1728  * tracking algorithm is to associate topmost loop entries with states
1729  * derived from these entries.
1730  *
1731  * For each step in the DFS states traversal algorithm needs to identify
1732  * the following situations:
1733  *
1734  *          initial                     initial                   initial
1735  *            |                           |                         |
1736  *            V                           V                         V
1737  *           ...                         ...           .---------> hdr
1738  *            |                           |            |            |
1739  *            V                           V            |            V
1740  *           cur                     .-> succ          |    .------...
1741  *            |                      |    |            |    |       |
1742  *            V                      |    V            |    V       V
1743  *           succ                    '-- cur           |   ...     ...
1744  *                                                     |    |       |
1745  *                                                     |    V       V
1746  *                                                     |   succ <- cur
1747  *                                                     |    |
1748  *                                                     |    V
1749  *                                                     |   ...
1750  *                                                     |    |
1751  *                                                     '----'
1752  *
1753  *  (A) successor state of cur   (B) successor state of cur or it's entry
1754  *      not yet traversed            are in current DFS path, thus cur and succ
1755  *                                   are members of the same outermost loop
1756  *
1757  *                      initial                  initial
1758  *                        |                        |
1759  *                        V                        V
1760  *                       ...                      ...
1761  *                        |                        |
1762  *                        V                        V
1763  *                .------...               .------...
1764  *                |       |                |       |
1765  *                V       V                V       V
1766  *           .-> hdr     ...              ...     ...
1767  *           |    |       |                |       |
1768  *           |    V       V                V       V
1769  *           |   succ <- cur              succ <- cur
1770  *           |    |                        |
1771  *           |    V                        V
1772  *           |   ...                      ...
1773  *           |    |                        |
1774  *           '----'                       exit
1775  *
1776  * (C) successor state of cur is a part of some loop but this loop
1777  *     does not include cur or successor state is not in a loop at all.
1778  *
1779  * Algorithm could be described as the following python code:
1780  *
1781  *     traversed = set()   # Set of traversed nodes
1782  *     entries = {}        # Mapping from node to loop entry
1783  *     depths = {}         # Depth level assigned to graph node
1784  *     path = set()        # Current DFS path
1785  *
1786  *     # Find outermost loop entry known for n
1787  *     def get_loop_entry(n):
1788  *         h = entries.get(n, None)
1789  *         while h in entries and entries[h] != h:
1790  *             h = entries[h]
1791  *         return h
1792  *
1793  *     # Update n's loop entry if h's outermost entry comes
1794  *     # before n's outermost entry in current DFS path.
1795  *     def update_loop_entry(n, h):
1796  *         n1 = get_loop_entry(n) or n
1797  *         h1 = get_loop_entry(h) or h
1798  *         if h1 in path and depths[h1] <= depths[n1]:
1799  *             entries[n] = h1
1800  *
1801  *     def dfs(n, depth):
1802  *         traversed.add(n)
1803  *         path.add(n)
1804  *         depths[n] = depth
1805  *         for succ in G.successors(n):
1806  *             if succ not in traversed:
1807  *                 # Case A: explore succ and update cur's loop entry
1808  *                 #         only if succ's entry is in current DFS path.
1809  *                 dfs(succ, depth + 1)
1810  *                 h = get_loop_entry(succ)
1811  *                 update_loop_entry(n, h)
1812  *             else:
1813  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1814  *                 update_loop_entry(n, succ)
1815  *         path.remove(n)
1816  *
1817  * To adapt this algorithm for use with verifier:
1818  * - use st->branch == 0 as a signal that DFS of succ had been finished
1819  *   and cur's loop entry has to be updated (case A), handle this in
1820  *   update_branch_counts();
1821  * - use st->branch > 0 as a signal that st is in the current DFS path;
1822  * - handle cases B and C in is_state_visited();
1823  * - update topmost loop entry for intermediate states in get_loop_entry().
1824  */
1825 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1826 {
1827 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1828 
1829 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1830 		topmost = topmost->loop_entry;
1831 	/* Update loop entries for intermediate states to avoid this
1832 	 * traversal in future get_loop_entry() calls.
1833 	 */
1834 	while (st && st->loop_entry != topmost) {
1835 		old = st->loop_entry;
1836 		st->loop_entry = topmost;
1837 		st = old;
1838 	}
1839 	return topmost;
1840 }
1841 
1842 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1843 {
1844 	struct bpf_verifier_state *cur1, *hdr1;
1845 
1846 	cur1 = get_loop_entry(cur) ?: cur;
1847 	hdr1 = get_loop_entry(hdr) ?: hdr;
1848 	/* The head1->branches check decides between cases B and C in
1849 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1850 	 * head's topmost loop entry is not in current DFS path,
1851 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1852 	 * no need to update cur->loop_entry.
1853 	 */
1854 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1855 		cur->loop_entry = hdr;
1856 		hdr->used_as_loop_entry = true;
1857 	}
1858 }
1859 
1860 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1861 {
1862 	while (st) {
1863 		u32 br = --st->branches;
1864 
1865 		/* br == 0 signals that DFS exploration for 'st' is finished,
1866 		 * thus it is necessary to update parent's loop entry if it
1867 		 * turned out that st is a part of some loop.
1868 		 * This is a part of 'case A' in get_loop_entry() comment.
1869 		 */
1870 		if (br == 0 && st->parent && st->loop_entry)
1871 			update_loop_entry(st->parent, st->loop_entry);
1872 
1873 		/* WARN_ON(br > 1) technically makes sense here,
1874 		 * but see comment in push_stack(), hence:
1875 		 */
1876 		WARN_ONCE((int)br < 0,
1877 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1878 			  br);
1879 		if (br)
1880 			break;
1881 		st = st->parent;
1882 	}
1883 }
1884 
1885 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1886 		     int *insn_idx, bool pop_log)
1887 {
1888 	struct bpf_verifier_state *cur = env->cur_state;
1889 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1890 	int err;
1891 
1892 	if (env->head == NULL)
1893 		return -ENOENT;
1894 
1895 	if (cur) {
1896 		err = copy_verifier_state(cur, &head->st);
1897 		if (err)
1898 			return err;
1899 	}
1900 	if (pop_log)
1901 		bpf_vlog_reset(&env->log, head->log_pos);
1902 	if (insn_idx)
1903 		*insn_idx = head->insn_idx;
1904 	if (prev_insn_idx)
1905 		*prev_insn_idx = head->prev_insn_idx;
1906 	elem = head->next;
1907 	free_verifier_state(&head->st, false);
1908 	kfree(head);
1909 	env->head = elem;
1910 	env->stack_size--;
1911 	return 0;
1912 }
1913 
1914 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1915 					     int insn_idx, int prev_insn_idx,
1916 					     bool speculative)
1917 {
1918 	struct bpf_verifier_state *cur = env->cur_state;
1919 	struct bpf_verifier_stack_elem *elem;
1920 	int err;
1921 
1922 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1923 	if (!elem)
1924 		goto err;
1925 
1926 	elem->insn_idx = insn_idx;
1927 	elem->prev_insn_idx = prev_insn_idx;
1928 	elem->next = env->head;
1929 	elem->log_pos = env->log.end_pos;
1930 	env->head = elem;
1931 	env->stack_size++;
1932 	err = copy_verifier_state(&elem->st, cur);
1933 	if (err)
1934 		goto err;
1935 	elem->st.speculative |= speculative;
1936 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1937 		verbose(env, "The sequence of %d jumps is too complex.\n",
1938 			env->stack_size);
1939 		goto err;
1940 	}
1941 	if (elem->st.parent) {
1942 		++elem->st.parent->branches;
1943 		/* WARN_ON(branches > 2) technically makes sense here,
1944 		 * but
1945 		 * 1. speculative states will bump 'branches' for non-branch
1946 		 * instructions
1947 		 * 2. is_state_visited() heuristics may decide not to create
1948 		 * a new state for a sequence of branches and all such current
1949 		 * and cloned states will be pointing to a single parent state
1950 		 * which might have large 'branches' count.
1951 		 */
1952 	}
1953 	return &elem->st;
1954 err:
1955 	free_verifier_state(env->cur_state, true);
1956 	env->cur_state = NULL;
1957 	/* pop all elements and return */
1958 	while (!pop_stack(env, NULL, NULL, false));
1959 	return NULL;
1960 }
1961 
1962 #define CALLER_SAVED_REGS 6
1963 static const int caller_saved[CALLER_SAVED_REGS] = {
1964 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1965 };
1966 
1967 /* This helper doesn't clear reg->id */
1968 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1969 {
1970 	reg->var_off = tnum_const(imm);
1971 	reg->smin_value = (s64)imm;
1972 	reg->smax_value = (s64)imm;
1973 	reg->umin_value = imm;
1974 	reg->umax_value = imm;
1975 
1976 	reg->s32_min_value = (s32)imm;
1977 	reg->s32_max_value = (s32)imm;
1978 	reg->u32_min_value = (u32)imm;
1979 	reg->u32_max_value = (u32)imm;
1980 }
1981 
1982 /* Mark the unknown part of a register (variable offset or scalar value) as
1983  * known to have the value @imm.
1984  */
1985 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1986 {
1987 	/* Clear off and union(map_ptr, range) */
1988 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1989 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1990 	reg->id = 0;
1991 	reg->ref_obj_id = 0;
1992 	___mark_reg_known(reg, imm);
1993 }
1994 
1995 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1996 {
1997 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1998 	reg->s32_min_value = (s32)imm;
1999 	reg->s32_max_value = (s32)imm;
2000 	reg->u32_min_value = (u32)imm;
2001 	reg->u32_max_value = (u32)imm;
2002 }
2003 
2004 /* Mark the 'variable offset' part of a register as zero.  This should be
2005  * used only on registers holding a pointer type.
2006  */
2007 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2008 {
2009 	__mark_reg_known(reg, 0);
2010 }
2011 
2012 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2013 {
2014 	__mark_reg_known(reg, 0);
2015 	reg->type = SCALAR_VALUE;
2016 	/* all scalars are assumed imprecise initially (unless unprivileged,
2017 	 * in which case everything is forced to be precise)
2018 	 */
2019 	reg->precise = !env->bpf_capable;
2020 }
2021 
2022 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2023 				struct bpf_reg_state *regs, u32 regno)
2024 {
2025 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2026 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2027 		/* Something bad happened, let's kill all regs */
2028 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2029 			__mark_reg_not_init(env, regs + regno);
2030 		return;
2031 	}
2032 	__mark_reg_known_zero(regs + regno);
2033 }
2034 
2035 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2036 			      bool first_slot, int dynptr_id)
2037 {
2038 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2039 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2040 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2041 	 */
2042 	__mark_reg_known_zero(reg);
2043 	reg->type = CONST_PTR_TO_DYNPTR;
2044 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2045 	reg->id = dynptr_id;
2046 	reg->dynptr.type = type;
2047 	reg->dynptr.first_slot = first_slot;
2048 }
2049 
2050 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2051 {
2052 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2053 		const struct bpf_map *map = reg->map_ptr;
2054 
2055 		if (map->inner_map_meta) {
2056 			reg->type = CONST_PTR_TO_MAP;
2057 			reg->map_ptr = map->inner_map_meta;
2058 			/* transfer reg's id which is unique for every map_lookup_elem
2059 			 * as UID of the inner map.
2060 			 */
2061 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2062 				reg->map_uid = reg->id;
2063 			if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE))
2064 				reg->map_uid = reg->id;
2065 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2066 			reg->type = PTR_TO_XDP_SOCK;
2067 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2068 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2069 			reg->type = PTR_TO_SOCKET;
2070 		} else {
2071 			reg->type = PTR_TO_MAP_VALUE;
2072 		}
2073 		return;
2074 	}
2075 
2076 	reg->type &= ~PTR_MAYBE_NULL;
2077 }
2078 
2079 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2080 				struct btf_field_graph_root *ds_head)
2081 {
2082 	__mark_reg_known_zero(&regs[regno]);
2083 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2084 	regs[regno].btf = ds_head->btf;
2085 	regs[regno].btf_id = ds_head->value_btf_id;
2086 	regs[regno].off = ds_head->node_offset;
2087 }
2088 
2089 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2090 {
2091 	return type_is_pkt_pointer(reg->type);
2092 }
2093 
2094 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2095 {
2096 	return reg_is_pkt_pointer(reg) ||
2097 	       reg->type == PTR_TO_PACKET_END;
2098 }
2099 
2100 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2101 {
2102 	return base_type(reg->type) == PTR_TO_MEM &&
2103 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2104 }
2105 
2106 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2107 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2108 				    enum bpf_reg_type which)
2109 {
2110 	/* The register can already have a range from prior markings.
2111 	 * This is fine as long as it hasn't been advanced from its
2112 	 * origin.
2113 	 */
2114 	return reg->type == which &&
2115 	       reg->id == 0 &&
2116 	       reg->off == 0 &&
2117 	       tnum_equals_const(reg->var_off, 0);
2118 }
2119 
2120 /* Reset the min/max bounds of a register */
2121 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2122 {
2123 	reg->smin_value = S64_MIN;
2124 	reg->smax_value = S64_MAX;
2125 	reg->umin_value = 0;
2126 	reg->umax_value = U64_MAX;
2127 
2128 	reg->s32_min_value = S32_MIN;
2129 	reg->s32_max_value = S32_MAX;
2130 	reg->u32_min_value = 0;
2131 	reg->u32_max_value = U32_MAX;
2132 }
2133 
2134 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2135 {
2136 	reg->smin_value = S64_MIN;
2137 	reg->smax_value = S64_MAX;
2138 	reg->umin_value = 0;
2139 	reg->umax_value = U64_MAX;
2140 }
2141 
2142 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2143 {
2144 	reg->s32_min_value = S32_MIN;
2145 	reg->s32_max_value = S32_MAX;
2146 	reg->u32_min_value = 0;
2147 	reg->u32_max_value = U32_MAX;
2148 }
2149 
2150 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2151 {
2152 	struct tnum var32_off = tnum_subreg(reg->var_off);
2153 
2154 	/* min signed is max(sign bit) | min(other bits) */
2155 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2156 			var32_off.value | (var32_off.mask & S32_MIN));
2157 	/* max signed is min(sign bit) | max(other bits) */
2158 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2159 			var32_off.value | (var32_off.mask & S32_MAX));
2160 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2161 	reg->u32_max_value = min(reg->u32_max_value,
2162 				 (u32)(var32_off.value | var32_off.mask));
2163 }
2164 
2165 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2166 {
2167 	/* min signed is max(sign bit) | min(other bits) */
2168 	reg->smin_value = max_t(s64, reg->smin_value,
2169 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2170 	/* max signed is min(sign bit) | max(other bits) */
2171 	reg->smax_value = min_t(s64, reg->smax_value,
2172 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2173 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2174 	reg->umax_value = min(reg->umax_value,
2175 			      reg->var_off.value | reg->var_off.mask);
2176 }
2177 
2178 static void __update_reg_bounds(struct bpf_reg_state *reg)
2179 {
2180 	__update_reg32_bounds(reg);
2181 	__update_reg64_bounds(reg);
2182 }
2183 
2184 /* Uses signed min/max values to inform unsigned, and vice-versa */
2185 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2186 {
2187 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
2188 	 * bits to improve our u32/s32 boundaries.
2189 	 *
2190 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
2191 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
2192 	 * [10, 20] range. But this property holds for any 64-bit range as
2193 	 * long as upper 32 bits in that entire range of values stay the same.
2194 	 *
2195 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
2196 	 * in decimal) has the same upper 32 bits throughout all the values in
2197 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
2198 	 * range.
2199 	 *
2200 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
2201 	 * following the rules outlined below about u64/s64 correspondence
2202 	 * (which equally applies to u32 vs s32 correspondence). In general it
2203 	 * depends on actual hexadecimal values of 32-bit range. They can form
2204 	 * only valid u32, or only valid s32 ranges in some cases.
2205 	 *
2206 	 * So we use all these insights to derive bounds for subregisters here.
2207 	 */
2208 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
2209 		/* u64 to u32 casting preserves validity of low 32 bits as
2210 		 * a range, if upper 32 bits are the same
2211 		 */
2212 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2213 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2214 
2215 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2216 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2217 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2218 		}
2219 	}
2220 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2221 		/* low 32 bits should form a proper u32 range */
2222 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2223 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2224 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2225 		}
2226 		/* low 32 bits should form a proper s32 range */
2227 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2228 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2229 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2230 		}
2231 	}
2232 	/* Special case where upper bits form a small sequence of two
2233 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2234 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2235 	 * going from negative numbers to positive numbers. E.g., let's say we
2236 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2237 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2238 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2239 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2240 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2241 	 * upper 32 bits. As a random example, s64 range
2242 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2243 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2244 	 */
2245 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2246 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2247 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2248 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2249 	}
2250 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2251 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2252 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2253 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2254 	}
2255 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2256 	 * try to learn from that
2257 	 */
2258 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2259 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2260 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2261 	}
2262 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2263 	 * are the same, so combine.  This works even in the negative case, e.g.
2264 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2265 	 */
2266 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2267 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2268 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2269 	}
2270 }
2271 
2272 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2273 {
2274 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2275 	 * try to learn from that. Let's do a bit of ASCII art to see when
2276 	 * this is happening. Let's take u64 range first:
2277 	 *
2278 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2279 	 * |-------------------------------|--------------------------------|
2280 	 *
2281 	 * Valid u64 range is formed when umin and umax are anywhere in the
2282 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2283 	 * straightforward. Let's see how s64 range maps onto the same range
2284 	 * of values, annotated below the line for comparison:
2285 	 *
2286 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2287 	 * |-------------------------------|--------------------------------|
2288 	 * 0                        S64_MAX S64_MIN                        -1
2289 	 *
2290 	 * So s64 values basically start in the middle and they are logically
2291 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2292 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2293 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2294 	 * more visually as mapped to sign-agnostic range of hex values.
2295 	 *
2296 	 *  u64 start                                               u64 end
2297 	 *  _______________________________________________________________
2298 	 * /                                                               \
2299 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2300 	 * |-------------------------------|--------------------------------|
2301 	 * 0                        S64_MAX S64_MIN                        -1
2302 	 *                                / \
2303 	 * >------------------------------   ------------------------------->
2304 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2305 	 *
2306 	 * What this means is that, in general, we can't always derive
2307 	 * something new about u64 from any random s64 range, and vice versa.
2308 	 *
2309 	 * But we can do that in two particular cases. One is when entire
2310 	 * u64/s64 range is *entirely* contained within left half of the above
2311 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2312 	 *
2313 	 * |-------------------------------|--------------------------------|
2314 	 *     ^                   ^            ^                 ^
2315 	 *     A                   B            C                 D
2316 	 *
2317 	 * [A, B] and [C, D] are contained entirely in their respective halves
2318 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2319 	 * will be non-negative both as u64 and s64 (and in fact it will be
2320 	 * identical ranges no matter the signedness). [C, D] treated as s64
2321 	 * will be a range of negative values, while in u64 it will be
2322 	 * non-negative range of values larger than 0x8000000000000000.
2323 	 *
2324 	 * Now, any other range here can't be represented in both u64 and s64
2325 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2326 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2327 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2328 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2329 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2330 	 * ranges as u64. Currently reg_state can't represent two segments per
2331 	 * numeric domain, so in such situations we can only derive maximal
2332 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2333 	 *
2334 	 * So we use these facts to derive umin/umax from smin/smax and vice
2335 	 * versa only if they stay within the same "half". This is equivalent
2336 	 * to checking sign bit: lower half will have sign bit as zero, upper
2337 	 * half have sign bit 1. Below in code we simplify this by just
2338 	 * casting umin/umax as smin/smax and checking if they form valid
2339 	 * range, and vice versa. Those are equivalent checks.
2340 	 */
2341 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2342 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2343 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2344 	}
2345 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2346 	 * are the same, so combine.  This works even in the negative case, e.g.
2347 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2348 	 */
2349 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2350 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2351 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2352 	}
2353 }
2354 
2355 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2356 {
2357 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2358 	 * values on both sides of 64-bit range in hope to have tighter range.
2359 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2360 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2361 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2362 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2363 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2364 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2365 	 * We just need to make sure that derived bounds we are intersecting
2366 	 * with are well-formed ranges in respective s64 or u64 domain, just
2367 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2368 	 */
2369 	__u64 new_umin, new_umax;
2370 	__s64 new_smin, new_smax;
2371 
2372 	/* u32 -> u64 tightening, it's always well-formed */
2373 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2374 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2375 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2376 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2377 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2378 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2379 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2380 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2381 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2382 
2383 	/* if s32 can be treated as valid u32 range, we can use it as well */
2384 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2385 		/* s32 -> u64 tightening */
2386 		new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2387 		new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2388 		reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2389 		reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2390 		/* s32 -> s64 tightening */
2391 		new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2392 		new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2393 		reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2394 		reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2395 	}
2396 
2397 	/* Here we would like to handle a special case after sign extending load,
2398 	 * when upper bits for a 64-bit range are all 1s or all 0s.
2399 	 *
2400 	 * Upper bits are all 1s when register is in a range:
2401 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2402 	 * Upper bits are all 0s when register is in a range:
2403 	 *   [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2404 	 * Together this forms are continuous range:
2405 	 *   [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2406 	 *
2407 	 * Now, suppose that register range is in fact tighter:
2408 	 *   [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2409 	 * Also suppose that it's 32-bit range is positive,
2410 	 * meaning that lower 32-bits of the full 64-bit register
2411 	 * are in the range:
2412 	 *   [0x0000_0000, 0x7fff_ffff] (W)
2413 	 *
2414 	 * If this happens, then any value in a range:
2415 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2416 	 * is smaller than a lowest bound of the range (R):
2417 	 *   0xffff_ffff_8000_0000
2418 	 * which means that upper bits of the full 64-bit register
2419 	 * can't be all 1s, when lower bits are in range (W).
2420 	 *
2421 	 * Note that:
2422 	 *  - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2423 	 *  - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2424 	 * These relations are used in the conditions below.
2425 	 */
2426 	if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2427 		reg->smin_value = reg->s32_min_value;
2428 		reg->smax_value = reg->s32_max_value;
2429 		reg->umin_value = reg->s32_min_value;
2430 		reg->umax_value = reg->s32_max_value;
2431 		reg->var_off = tnum_intersect(reg->var_off,
2432 					      tnum_range(reg->smin_value, reg->smax_value));
2433 	}
2434 }
2435 
2436 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2437 {
2438 	__reg32_deduce_bounds(reg);
2439 	__reg64_deduce_bounds(reg);
2440 	__reg_deduce_mixed_bounds(reg);
2441 }
2442 
2443 /* Attempts to improve var_off based on unsigned min/max information */
2444 static void __reg_bound_offset(struct bpf_reg_state *reg)
2445 {
2446 	struct tnum var64_off = tnum_intersect(reg->var_off,
2447 					       tnum_range(reg->umin_value,
2448 							  reg->umax_value));
2449 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2450 					       tnum_range(reg->u32_min_value,
2451 							  reg->u32_max_value));
2452 
2453 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2454 }
2455 
2456 static void reg_bounds_sync(struct bpf_reg_state *reg)
2457 {
2458 	/* We might have learned new bounds from the var_off. */
2459 	__update_reg_bounds(reg);
2460 	/* We might have learned something about the sign bit. */
2461 	__reg_deduce_bounds(reg);
2462 	__reg_deduce_bounds(reg);
2463 	/* We might have learned some bits from the bounds. */
2464 	__reg_bound_offset(reg);
2465 	/* Intersecting with the old var_off might have improved our bounds
2466 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2467 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2468 	 */
2469 	__update_reg_bounds(reg);
2470 }
2471 
2472 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2473 				   struct bpf_reg_state *reg, const char *ctx)
2474 {
2475 	const char *msg;
2476 
2477 	if (reg->umin_value > reg->umax_value ||
2478 	    reg->smin_value > reg->smax_value ||
2479 	    reg->u32_min_value > reg->u32_max_value ||
2480 	    reg->s32_min_value > reg->s32_max_value) {
2481 		    msg = "range bounds violation";
2482 		    goto out;
2483 	}
2484 
2485 	if (tnum_is_const(reg->var_off)) {
2486 		u64 uval = reg->var_off.value;
2487 		s64 sval = (s64)uval;
2488 
2489 		if (reg->umin_value != uval || reg->umax_value != uval ||
2490 		    reg->smin_value != sval || reg->smax_value != sval) {
2491 			msg = "const tnum out of sync with range bounds";
2492 			goto out;
2493 		}
2494 	}
2495 
2496 	if (tnum_subreg_is_const(reg->var_off)) {
2497 		u32 uval32 = tnum_subreg(reg->var_off).value;
2498 		s32 sval32 = (s32)uval32;
2499 
2500 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2501 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2502 			msg = "const subreg tnum out of sync with range bounds";
2503 			goto out;
2504 		}
2505 	}
2506 
2507 	return 0;
2508 out:
2509 	verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2510 		"s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2511 		ctx, msg, reg->umin_value, reg->umax_value,
2512 		reg->smin_value, reg->smax_value,
2513 		reg->u32_min_value, reg->u32_max_value,
2514 		reg->s32_min_value, reg->s32_max_value,
2515 		reg->var_off.value, reg->var_off.mask);
2516 	if (env->test_reg_invariants)
2517 		return -EFAULT;
2518 	__mark_reg_unbounded(reg);
2519 	return 0;
2520 }
2521 
2522 static bool __reg32_bound_s64(s32 a)
2523 {
2524 	return a >= 0 && a <= S32_MAX;
2525 }
2526 
2527 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2528 {
2529 	reg->umin_value = reg->u32_min_value;
2530 	reg->umax_value = reg->u32_max_value;
2531 
2532 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2533 	 * be positive otherwise set to worse case bounds and refine later
2534 	 * from tnum.
2535 	 */
2536 	if (__reg32_bound_s64(reg->s32_min_value) &&
2537 	    __reg32_bound_s64(reg->s32_max_value)) {
2538 		reg->smin_value = reg->s32_min_value;
2539 		reg->smax_value = reg->s32_max_value;
2540 	} else {
2541 		reg->smin_value = 0;
2542 		reg->smax_value = U32_MAX;
2543 	}
2544 }
2545 
2546 /* Mark a register as having a completely unknown (scalar) value. */
2547 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2548 {
2549 	/*
2550 	 * Clear type, off, and union(map_ptr, range) and
2551 	 * padding between 'type' and union
2552 	 */
2553 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2554 	reg->type = SCALAR_VALUE;
2555 	reg->id = 0;
2556 	reg->ref_obj_id = 0;
2557 	reg->var_off = tnum_unknown;
2558 	reg->frameno = 0;
2559 	reg->precise = false;
2560 	__mark_reg_unbounded(reg);
2561 }
2562 
2563 /* Mark a register as having a completely unknown (scalar) value,
2564  * initialize .precise as true when not bpf capable.
2565  */
2566 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2567 			       struct bpf_reg_state *reg)
2568 {
2569 	__mark_reg_unknown_imprecise(reg);
2570 	reg->precise = !env->bpf_capable;
2571 }
2572 
2573 static void mark_reg_unknown(struct bpf_verifier_env *env,
2574 			     struct bpf_reg_state *regs, u32 regno)
2575 {
2576 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2577 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2578 		/* Something bad happened, let's kill all regs except FP */
2579 		for (regno = 0; regno < BPF_REG_FP; regno++)
2580 			__mark_reg_not_init(env, regs + regno);
2581 		return;
2582 	}
2583 	__mark_reg_unknown(env, regs + regno);
2584 }
2585 
2586 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2587 				struct bpf_reg_state *regs,
2588 				u32 regno,
2589 				s32 s32_min,
2590 				s32 s32_max)
2591 {
2592 	struct bpf_reg_state *reg = regs + regno;
2593 
2594 	reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2595 	reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2596 
2597 	reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2598 	reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2599 
2600 	reg_bounds_sync(reg);
2601 
2602 	return reg_bounds_sanity_check(env, reg, "s32_range");
2603 }
2604 
2605 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2606 				struct bpf_reg_state *reg)
2607 {
2608 	__mark_reg_unknown(env, reg);
2609 	reg->type = NOT_INIT;
2610 }
2611 
2612 static void mark_reg_not_init(struct bpf_verifier_env *env,
2613 			      struct bpf_reg_state *regs, u32 regno)
2614 {
2615 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2616 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2617 		/* Something bad happened, let's kill all regs except FP */
2618 		for (regno = 0; regno < BPF_REG_FP; regno++)
2619 			__mark_reg_not_init(env, regs + regno);
2620 		return;
2621 	}
2622 	__mark_reg_not_init(env, regs + regno);
2623 }
2624 
2625 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2626 			    struct bpf_reg_state *regs, u32 regno,
2627 			    enum bpf_reg_type reg_type,
2628 			    struct btf *btf, u32 btf_id,
2629 			    enum bpf_type_flag flag)
2630 {
2631 	if (reg_type == SCALAR_VALUE) {
2632 		mark_reg_unknown(env, regs, regno);
2633 		return;
2634 	}
2635 	mark_reg_known_zero(env, regs, regno);
2636 	regs[regno].type = PTR_TO_BTF_ID | flag;
2637 	regs[regno].btf = btf;
2638 	regs[regno].btf_id = btf_id;
2639 	if (type_may_be_null(flag))
2640 		regs[regno].id = ++env->id_gen;
2641 }
2642 
2643 #define DEF_NOT_SUBREG	(0)
2644 static void init_reg_state(struct bpf_verifier_env *env,
2645 			   struct bpf_func_state *state)
2646 {
2647 	struct bpf_reg_state *regs = state->regs;
2648 	int i;
2649 
2650 	for (i = 0; i < MAX_BPF_REG; i++) {
2651 		mark_reg_not_init(env, regs, i);
2652 		regs[i].live = REG_LIVE_NONE;
2653 		regs[i].parent = NULL;
2654 		regs[i].subreg_def = DEF_NOT_SUBREG;
2655 	}
2656 
2657 	/* frame pointer */
2658 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2659 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2660 	regs[BPF_REG_FP].frameno = state->frameno;
2661 }
2662 
2663 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2664 {
2665 	return (struct bpf_retval_range){ minval, maxval };
2666 }
2667 
2668 #define BPF_MAIN_FUNC (-1)
2669 static void init_func_state(struct bpf_verifier_env *env,
2670 			    struct bpf_func_state *state,
2671 			    int callsite, int frameno, int subprogno)
2672 {
2673 	state->callsite = callsite;
2674 	state->frameno = frameno;
2675 	state->subprogno = subprogno;
2676 	state->callback_ret_range = retval_range(0, 0);
2677 	init_reg_state(env, state);
2678 	mark_verifier_state_scratched(env);
2679 }
2680 
2681 /* Similar to push_stack(), but for async callbacks */
2682 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2683 						int insn_idx, int prev_insn_idx,
2684 						int subprog, bool is_sleepable)
2685 {
2686 	struct bpf_verifier_stack_elem *elem;
2687 	struct bpf_func_state *frame;
2688 
2689 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2690 	if (!elem)
2691 		goto err;
2692 
2693 	elem->insn_idx = insn_idx;
2694 	elem->prev_insn_idx = prev_insn_idx;
2695 	elem->next = env->head;
2696 	elem->log_pos = env->log.end_pos;
2697 	env->head = elem;
2698 	env->stack_size++;
2699 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2700 		verbose(env,
2701 			"The sequence of %d jumps is too complex for async cb.\n",
2702 			env->stack_size);
2703 		goto err;
2704 	}
2705 	/* Unlike push_stack() do not copy_verifier_state().
2706 	 * The caller state doesn't matter.
2707 	 * This is async callback. It starts in a fresh stack.
2708 	 * Initialize it similar to do_check_common().
2709 	 * But we do need to make sure to not clobber insn_hist, so we keep
2710 	 * chaining insn_hist_start/insn_hist_end indices as for a normal
2711 	 * child state.
2712 	 */
2713 	elem->st.branches = 1;
2714 	elem->st.in_sleepable = is_sleepable;
2715 	elem->st.insn_hist_start = env->cur_state->insn_hist_end;
2716 	elem->st.insn_hist_end = elem->st.insn_hist_start;
2717 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2718 	if (!frame)
2719 		goto err;
2720 	init_func_state(env, frame,
2721 			BPF_MAIN_FUNC /* callsite */,
2722 			0 /* frameno within this callchain */,
2723 			subprog /* subprog number within this prog */);
2724 	elem->st.frame[0] = frame;
2725 	return &elem->st;
2726 err:
2727 	free_verifier_state(env->cur_state, true);
2728 	env->cur_state = NULL;
2729 	/* pop all elements and return */
2730 	while (!pop_stack(env, NULL, NULL, false));
2731 	return NULL;
2732 }
2733 
2734 
2735 enum reg_arg_type {
2736 	SRC_OP,		/* register is used as source operand */
2737 	DST_OP,		/* register is used as destination operand */
2738 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2739 };
2740 
2741 static int cmp_subprogs(const void *a, const void *b)
2742 {
2743 	return ((struct bpf_subprog_info *)a)->start -
2744 	       ((struct bpf_subprog_info *)b)->start;
2745 }
2746 
2747 /* Find subprogram that contains instruction at 'off' */
2748 static struct bpf_subprog_info *find_containing_subprog(struct bpf_verifier_env *env, int off)
2749 {
2750 	struct bpf_subprog_info *vals = env->subprog_info;
2751 	int l, r, m;
2752 
2753 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2754 		return NULL;
2755 
2756 	l = 0;
2757 	r = env->subprog_cnt - 1;
2758 	while (l < r) {
2759 		m = l + (r - l + 1) / 2;
2760 		if (vals[m].start <= off)
2761 			l = m;
2762 		else
2763 			r = m - 1;
2764 	}
2765 	return &vals[l];
2766 }
2767 
2768 /* Find subprogram that starts exactly at 'off' */
2769 static int find_subprog(struct bpf_verifier_env *env, int off)
2770 {
2771 	struct bpf_subprog_info *p;
2772 
2773 	p = find_containing_subprog(env, off);
2774 	if (!p || p->start != off)
2775 		return -ENOENT;
2776 	return p - env->subprog_info;
2777 }
2778 
2779 static int add_subprog(struct bpf_verifier_env *env, int off)
2780 {
2781 	int insn_cnt = env->prog->len;
2782 	int ret;
2783 
2784 	if (off >= insn_cnt || off < 0) {
2785 		verbose(env, "call to invalid destination\n");
2786 		return -EINVAL;
2787 	}
2788 	ret = find_subprog(env, off);
2789 	if (ret >= 0)
2790 		return ret;
2791 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2792 		verbose(env, "too many subprograms\n");
2793 		return -E2BIG;
2794 	}
2795 	/* determine subprog starts. The end is one before the next starts */
2796 	env->subprog_info[env->subprog_cnt++].start = off;
2797 	sort(env->subprog_info, env->subprog_cnt,
2798 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2799 	return env->subprog_cnt - 1;
2800 }
2801 
2802 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2803 {
2804 	struct bpf_prog_aux *aux = env->prog->aux;
2805 	struct btf *btf = aux->btf;
2806 	const struct btf_type *t;
2807 	u32 main_btf_id, id;
2808 	const char *name;
2809 	int ret, i;
2810 
2811 	/* Non-zero func_info_cnt implies valid btf */
2812 	if (!aux->func_info_cnt)
2813 		return 0;
2814 	main_btf_id = aux->func_info[0].type_id;
2815 
2816 	t = btf_type_by_id(btf, main_btf_id);
2817 	if (!t) {
2818 		verbose(env, "invalid btf id for main subprog in func_info\n");
2819 		return -EINVAL;
2820 	}
2821 
2822 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2823 	if (IS_ERR(name)) {
2824 		ret = PTR_ERR(name);
2825 		/* If there is no tag present, there is no exception callback */
2826 		if (ret == -ENOENT)
2827 			ret = 0;
2828 		else if (ret == -EEXIST)
2829 			verbose(env, "multiple exception callback tags for main subprog\n");
2830 		return ret;
2831 	}
2832 
2833 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2834 	if (ret < 0) {
2835 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2836 		return ret;
2837 	}
2838 	id = ret;
2839 	t = btf_type_by_id(btf, id);
2840 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2841 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2842 		return -EINVAL;
2843 	}
2844 	ret = 0;
2845 	for (i = 0; i < aux->func_info_cnt; i++) {
2846 		if (aux->func_info[i].type_id != id)
2847 			continue;
2848 		ret = aux->func_info[i].insn_off;
2849 		/* Further func_info and subprog checks will also happen
2850 		 * later, so assume this is the right insn_off for now.
2851 		 */
2852 		if (!ret) {
2853 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2854 			ret = -EINVAL;
2855 		}
2856 	}
2857 	if (!ret) {
2858 		verbose(env, "exception callback type id not found in func_info\n");
2859 		ret = -EINVAL;
2860 	}
2861 	return ret;
2862 }
2863 
2864 #define MAX_KFUNC_DESCS 256
2865 #define MAX_KFUNC_BTFS	256
2866 
2867 struct bpf_kfunc_desc {
2868 	struct btf_func_model func_model;
2869 	u32 func_id;
2870 	s32 imm;
2871 	u16 offset;
2872 	unsigned long addr;
2873 };
2874 
2875 struct bpf_kfunc_btf {
2876 	struct btf *btf;
2877 	struct module *module;
2878 	u16 offset;
2879 };
2880 
2881 struct bpf_kfunc_desc_tab {
2882 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2883 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2884 	 * available, therefore at the end of verification do_misc_fixups()
2885 	 * sorts this by imm and offset.
2886 	 */
2887 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2888 	u32 nr_descs;
2889 };
2890 
2891 struct bpf_kfunc_btf_tab {
2892 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2893 	u32 nr_descs;
2894 };
2895 
2896 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2897 {
2898 	const struct bpf_kfunc_desc *d0 = a;
2899 	const struct bpf_kfunc_desc *d1 = b;
2900 
2901 	/* func_id is not greater than BTF_MAX_TYPE */
2902 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2903 }
2904 
2905 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2906 {
2907 	const struct bpf_kfunc_btf *d0 = a;
2908 	const struct bpf_kfunc_btf *d1 = b;
2909 
2910 	return d0->offset - d1->offset;
2911 }
2912 
2913 static const struct bpf_kfunc_desc *
2914 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2915 {
2916 	struct bpf_kfunc_desc desc = {
2917 		.func_id = func_id,
2918 		.offset = offset,
2919 	};
2920 	struct bpf_kfunc_desc_tab *tab;
2921 
2922 	tab = prog->aux->kfunc_tab;
2923 	return bsearch(&desc, tab->descs, tab->nr_descs,
2924 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2925 }
2926 
2927 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2928 		       u16 btf_fd_idx, u8 **func_addr)
2929 {
2930 	const struct bpf_kfunc_desc *desc;
2931 
2932 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2933 	if (!desc)
2934 		return -EFAULT;
2935 
2936 	*func_addr = (u8 *)desc->addr;
2937 	return 0;
2938 }
2939 
2940 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2941 					 s16 offset)
2942 {
2943 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2944 	struct bpf_kfunc_btf_tab *tab;
2945 	struct bpf_kfunc_btf *b;
2946 	struct module *mod;
2947 	struct btf *btf;
2948 	int btf_fd;
2949 
2950 	tab = env->prog->aux->kfunc_btf_tab;
2951 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2952 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2953 	if (!b) {
2954 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2955 			verbose(env, "too many different module BTFs\n");
2956 			return ERR_PTR(-E2BIG);
2957 		}
2958 
2959 		if (bpfptr_is_null(env->fd_array)) {
2960 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2961 			return ERR_PTR(-EPROTO);
2962 		}
2963 
2964 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2965 					    offset * sizeof(btf_fd),
2966 					    sizeof(btf_fd)))
2967 			return ERR_PTR(-EFAULT);
2968 
2969 		btf = btf_get_by_fd(btf_fd);
2970 		if (IS_ERR(btf)) {
2971 			verbose(env, "invalid module BTF fd specified\n");
2972 			return btf;
2973 		}
2974 
2975 		if (!btf_is_module(btf)) {
2976 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2977 			btf_put(btf);
2978 			return ERR_PTR(-EINVAL);
2979 		}
2980 
2981 		mod = btf_try_get_module(btf);
2982 		if (!mod) {
2983 			btf_put(btf);
2984 			return ERR_PTR(-ENXIO);
2985 		}
2986 
2987 		b = &tab->descs[tab->nr_descs++];
2988 		b->btf = btf;
2989 		b->module = mod;
2990 		b->offset = offset;
2991 
2992 		/* sort() reorders entries by value, so b may no longer point
2993 		 * to the right entry after this
2994 		 */
2995 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2996 		     kfunc_btf_cmp_by_off, NULL);
2997 	} else {
2998 		btf = b->btf;
2999 	}
3000 
3001 	return btf;
3002 }
3003 
3004 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
3005 {
3006 	if (!tab)
3007 		return;
3008 
3009 	while (tab->nr_descs--) {
3010 		module_put(tab->descs[tab->nr_descs].module);
3011 		btf_put(tab->descs[tab->nr_descs].btf);
3012 	}
3013 	kfree(tab);
3014 }
3015 
3016 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
3017 {
3018 	if (offset) {
3019 		if (offset < 0) {
3020 			/* In the future, this can be allowed to increase limit
3021 			 * of fd index into fd_array, interpreted as u16.
3022 			 */
3023 			verbose(env, "negative offset disallowed for kernel module function call\n");
3024 			return ERR_PTR(-EINVAL);
3025 		}
3026 
3027 		return __find_kfunc_desc_btf(env, offset);
3028 	}
3029 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
3030 }
3031 
3032 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
3033 {
3034 	const struct btf_type *func, *func_proto;
3035 	struct bpf_kfunc_btf_tab *btf_tab;
3036 	struct bpf_kfunc_desc_tab *tab;
3037 	struct bpf_prog_aux *prog_aux;
3038 	struct bpf_kfunc_desc *desc;
3039 	const char *func_name;
3040 	struct btf *desc_btf;
3041 	unsigned long call_imm;
3042 	unsigned long addr;
3043 	int err;
3044 
3045 	prog_aux = env->prog->aux;
3046 	tab = prog_aux->kfunc_tab;
3047 	btf_tab = prog_aux->kfunc_btf_tab;
3048 	if (!tab) {
3049 		if (!btf_vmlinux) {
3050 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3051 			return -ENOTSUPP;
3052 		}
3053 
3054 		if (!env->prog->jit_requested) {
3055 			verbose(env, "JIT is required for calling kernel function\n");
3056 			return -ENOTSUPP;
3057 		}
3058 
3059 		if (!bpf_jit_supports_kfunc_call()) {
3060 			verbose(env, "JIT does not support calling kernel function\n");
3061 			return -ENOTSUPP;
3062 		}
3063 
3064 		if (!env->prog->gpl_compatible) {
3065 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3066 			return -EINVAL;
3067 		}
3068 
3069 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
3070 		if (!tab)
3071 			return -ENOMEM;
3072 		prog_aux->kfunc_tab = tab;
3073 	}
3074 
3075 	/* func_id == 0 is always invalid, but instead of returning an error, be
3076 	 * conservative and wait until the code elimination pass before returning
3077 	 * error, so that invalid calls that get pruned out can be in BPF programs
3078 	 * loaded from userspace.  It is also required that offset be untouched
3079 	 * for such calls.
3080 	 */
3081 	if (!func_id && !offset)
3082 		return 0;
3083 
3084 	if (!btf_tab && offset) {
3085 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
3086 		if (!btf_tab)
3087 			return -ENOMEM;
3088 		prog_aux->kfunc_btf_tab = btf_tab;
3089 	}
3090 
3091 	desc_btf = find_kfunc_desc_btf(env, offset);
3092 	if (IS_ERR(desc_btf)) {
3093 		verbose(env, "failed to find BTF for kernel function\n");
3094 		return PTR_ERR(desc_btf);
3095 	}
3096 
3097 	if (find_kfunc_desc(env->prog, func_id, offset))
3098 		return 0;
3099 
3100 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
3101 		verbose(env, "too many different kernel function calls\n");
3102 		return -E2BIG;
3103 	}
3104 
3105 	func = btf_type_by_id(desc_btf, func_id);
3106 	if (!func || !btf_type_is_func(func)) {
3107 		verbose(env, "kernel btf_id %u is not a function\n",
3108 			func_id);
3109 		return -EINVAL;
3110 	}
3111 	func_proto = btf_type_by_id(desc_btf, func->type);
3112 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3113 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
3114 			func_id);
3115 		return -EINVAL;
3116 	}
3117 
3118 	func_name = btf_name_by_offset(desc_btf, func->name_off);
3119 	addr = kallsyms_lookup_name(func_name);
3120 	if (!addr) {
3121 		verbose(env, "cannot find address for kernel function %s\n",
3122 			func_name);
3123 		return -EINVAL;
3124 	}
3125 	specialize_kfunc(env, func_id, offset, &addr);
3126 
3127 	if (bpf_jit_supports_far_kfunc_call()) {
3128 		call_imm = func_id;
3129 	} else {
3130 		call_imm = BPF_CALL_IMM(addr);
3131 		/* Check whether the relative offset overflows desc->imm */
3132 		if ((unsigned long)(s32)call_imm != call_imm) {
3133 			verbose(env, "address of kernel function %s is out of range\n",
3134 				func_name);
3135 			return -EINVAL;
3136 		}
3137 	}
3138 
3139 	if (bpf_dev_bound_kfunc_id(func_id)) {
3140 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3141 		if (err)
3142 			return err;
3143 	}
3144 
3145 	desc = &tab->descs[tab->nr_descs++];
3146 	desc->func_id = func_id;
3147 	desc->imm = call_imm;
3148 	desc->offset = offset;
3149 	desc->addr = addr;
3150 	err = btf_distill_func_proto(&env->log, desc_btf,
3151 				     func_proto, func_name,
3152 				     &desc->func_model);
3153 	if (!err)
3154 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3155 		     kfunc_desc_cmp_by_id_off, NULL);
3156 	return err;
3157 }
3158 
3159 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3160 {
3161 	const struct bpf_kfunc_desc *d0 = a;
3162 	const struct bpf_kfunc_desc *d1 = b;
3163 
3164 	if (d0->imm != d1->imm)
3165 		return d0->imm < d1->imm ? -1 : 1;
3166 	if (d0->offset != d1->offset)
3167 		return d0->offset < d1->offset ? -1 : 1;
3168 	return 0;
3169 }
3170 
3171 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
3172 {
3173 	struct bpf_kfunc_desc_tab *tab;
3174 
3175 	tab = prog->aux->kfunc_tab;
3176 	if (!tab)
3177 		return;
3178 
3179 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3180 	     kfunc_desc_cmp_by_imm_off, NULL);
3181 }
3182 
3183 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3184 {
3185 	return !!prog->aux->kfunc_tab;
3186 }
3187 
3188 const struct btf_func_model *
3189 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3190 			 const struct bpf_insn *insn)
3191 {
3192 	const struct bpf_kfunc_desc desc = {
3193 		.imm = insn->imm,
3194 		.offset = insn->off,
3195 	};
3196 	const struct bpf_kfunc_desc *res;
3197 	struct bpf_kfunc_desc_tab *tab;
3198 
3199 	tab = prog->aux->kfunc_tab;
3200 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3201 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3202 
3203 	return res ? &res->func_model : NULL;
3204 }
3205 
3206 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3207 {
3208 	struct bpf_subprog_info *subprog = env->subprog_info;
3209 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3210 	struct bpf_insn *insn = env->prog->insnsi;
3211 
3212 	/* Add entry function. */
3213 	ret = add_subprog(env, 0);
3214 	if (ret)
3215 		return ret;
3216 
3217 	for (i = 0; i < insn_cnt; i++, insn++) {
3218 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3219 		    !bpf_pseudo_kfunc_call(insn))
3220 			continue;
3221 
3222 		if (!env->bpf_capable) {
3223 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3224 			return -EPERM;
3225 		}
3226 
3227 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3228 			ret = add_subprog(env, i + insn->imm + 1);
3229 		else
3230 			ret = add_kfunc_call(env, insn->imm, insn->off);
3231 
3232 		if (ret < 0)
3233 			return ret;
3234 	}
3235 
3236 	ret = bpf_find_exception_callback_insn_off(env);
3237 	if (ret < 0)
3238 		return ret;
3239 	ex_cb_insn = ret;
3240 
3241 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3242 	 * marked using BTF decl tag to serve as the exception callback.
3243 	 */
3244 	if (ex_cb_insn) {
3245 		ret = add_subprog(env, ex_cb_insn);
3246 		if (ret < 0)
3247 			return ret;
3248 		for (i = 1; i < env->subprog_cnt; i++) {
3249 			if (env->subprog_info[i].start != ex_cb_insn)
3250 				continue;
3251 			env->exception_callback_subprog = i;
3252 			mark_subprog_exc_cb(env, i);
3253 			break;
3254 		}
3255 	}
3256 
3257 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3258 	 * logic. 'subprog_cnt' should not be increased.
3259 	 */
3260 	subprog[env->subprog_cnt].start = insn_cnt;
3261 
3262 	if (env->log.level & BPF_LOG_LEVEL2)
3263 		for (i = 0; i < env->subprog_cnt; i++)
3264 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3265 
3266 	return 0;
3267 }
3268 
3269 static int check_subprogs(struct bpf_verifier_env *env)
3270 {
3271 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3272 	struct bpf_subprog_info *subprog = env->subprog_info;
3273 	struct bpf_insn *insn = env->prog->insnsi;
3274 	int insn_cnt = env->prog->len;
3275 
3276 	/* now check that all jumps are within the same subprog */
3277 	subprog_start = subprog[cur_subprog].start;
3278 	subprog_end = subprog[cur_subprog + 1].start;
3279 	for (i = 0; i < insn_cnt; i++) {
3280 		u8 code = insn[i].code;
3281 
3282 		if (code == (BPF_JMP | BPF_CALL) &&
3283 		    insn[i].src_reg == 0 &&
3284 		    insn[i].imm == BPF_FUNC_tail_call) {
3285 			subprog[cur_subprog].has_tail_call = true;
3286 			subprog[cur_subprog].tail_call_reachable = true;
3287 		}
3288 		if (BPF_CLASS(code) == BPF_LD &&
3289 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3290 			subprog[cur_subprog].has_ld_abs = true;
3291 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3292 			goto next;
3293 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3294 			goto next;
3295 		if (code == (BPF_JMP32 | BPF_JA))
3296 			off = i + insn[i].imm + 1;
3297 		else
3298 			off = i + insn[i].off + 1;
3299 		if (off < subprog_start || off >= subprog_end) {
3300 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3301 			return -EINVAL;
3302 		}
3303 next:
3304 		if (i == subprog_end - 1) {
3305 			/* to avoid fall-through from one subprog into another
3306 			 * the last insn of the subprog should be either exit
3307 			 * or unconditional jump back or bpf_throw call
3308 			 */
3309 			if (code != (BPF_JMP | BPF_EXIT) &&
3310 			    code != (BPF_JMP32 | BPF_JA) &&
3311 			    code != (BPF_JMP | BPF_JA)) {
3312 				verbose(env, "last insn is not an exit or jmp\n");
3313 				return -EINVAL;
3314 			}
3315 			subprog_start = subprog_end;
3316 			cur_subprog++;
3317 			if (cur_subprog < env->subprog_cnt)
3318 				subprog_end = subprog[cur_subprog + 1].start;
3319 		}
3320 	}
3321 	return 0;
3322 }
3323 
3324 /* Parentage chain of this register (or stack slot) should take care of all
3325  * issues like callee-saved registers, stack slot allocation time, etc.
3326  */
3327 static int mark_reg_read(struct bpf_verifier_env *env,
3328 			 const struct bpf_reg_state *state,
3329 			 struct bpf_reg_state *parent, u8 flag)
3330 {
3331 	bool writes = parent == state->parent; /* Observe write marks */
3332 	int cnt = 0;
3333 
3334 	while (parent) {
3335 		/* if read wasn't screened by an earlier write ... */
3336 		if (writes && state->live & REG_LIVE_WRITTEN)
3337 			break;
3338 		if (parent->live & REG_LIVE_DONE) {
3339 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3340 				reg_type_str(env, parent->type),
3341 				parent->var_off.value, parent->off);
3342 			return -EFAULT;
3343 		}
3344 		/* The first condition is more likely to be true than the
3345 		 * second, checked it first.
3346 		 */
3347 		if ((parent->live & REG_LIVE_READ) == flag ||
3348 		    parent->live & REG_LIVE_READ64)
3349 			/* The parentage chain never changes and
3350 			 * this parent was already marked as LIVE_READ.
3351 			 * There is no need to keep walking the chain again and
3352 			 * keep re-marking all parents as LIVE_READ.
3353 			 * This case happens when the same register is read
3354 			 * multiple times without writes into it in-between.
3355 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3356 			 * then no need to set the weak REG_LIVE_READ32.
3357 			 */
3358 			break;
3359 		/* ... then we depend on parent's value */
3360 		parent->live |= flag;
3361 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3362 		if (flag == REG_LIVE_READ64)
3363 			parent->live &= ~REG_LIVE_READ32;
3364 		state = parent;
3365 		parent = state->parent;
3366 		writes = true;
3367 		cnt++;
3368 	}
3369 
3370 	if (env->longest_mark_read_walk < cnt)
3371 		env->longest_mark_read_walk = cnt;
3372 	return 0;
3373 }
3374 
3375 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3376 				    int spi, int nr_slots)
3377 {
3378 	struct bpf_func_state *state = func(env, reg);
3379 	int err, i;
3380 
3381 	for (i = 0; i < nr_slots; i++) {
3382 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3383 
3384 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3385 		if (err)
3386 			return err;
3387 
3388 		mark_stack_slot_scratched(env, spi - i);
3389 	}
3390 	return 0;
3391 }
3392 
3393 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3394 {
3395 	int spi;
3396 
3397 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3398 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3399 	 * check_kfunc_call.
3400 	 */
3401 	if (reg->type == CONST_PTR_TO_DYNPTR)
3402 		return 0;
3403 	spi = dynptr_get_spi(env, reg);
3404 	if (spi < 0)
3405 		return spi;
3406 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3407 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3408 	 * read.
3409 	 */
3410 	return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS);
3411 }
3412 
3413 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3414 			  int spi, int nr_slots)
3415 {
3416 	return mark_stack_slot_obj_read(env, reg, spi, nr_slots);
3417 }
3418 
3419 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3420 {
3421 	int spi;
3422 
3423 	spi = irq_flag_get_spi(env, reg);
3424 	if (spi < 0)
3425 		return spi;
3426 	return mark_stack_slot_obj_read(env, reg, spi, 1);
3427 }
3428 
3429 /* This function is supposed to be used by the following 32-bit optimization
3430  * code only. It returns TRUE if the source or destination register operates
3431  * on 64-bit, otherwise return FALSE.
3432  */
3433 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3434 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3435 {
3436 	u8 code, class, op;
3437 
3438 	code = insn->code;
3439 	class = BPF_CLASS(code);
3440 	op = BPF_OP(code);
3441 	if (class == BPF_JMP) {
3442 		/* BPF_EXIT for "main" will reach here. Return TRUE
3443 		 * conservatively.
3444 		 */
3445 		if (op == BPF_EXIT)
3446 			return true;
3447 		if (op == BPF_CALL) {
3448 			/* BPF to BPF call will reach here because of marking
3449 			 * caller saved clobber with DST_OP_NO_MARK for which we
3450 			 * don't care the register def because they are anyway
3451 			 * marked as NOT_INIT already.
3452 			 */
3453 			if (insn->src_reg == BPF_PSEUDO_CALL)
3454 				return false;
3455 			/* Helper call will reach here because of arg type
3456 			 * check, conservatively return TRUE.
3457 			 */
3458 			if (t == SRC_OP)
3459 				return true;
3460 
3461 			return false;
3462 		}
3463 	}
3464 
3465 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3466 		return false;
3467 
3468 	if (class == BPF_ALU64 || class == BPF_JMP ||
3469 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3470 		return true;
3471 
3472 	if (class == BPF_ALU || class == BPF_JMP32)
3473 		return false;
3474 
3475 	if (class == BPF_LDX) {
3476 		if (t != SRC_OP)
3477 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3478 		/* LDX source must be ptr. */
3479 		return true;
3480 	}
3481 
3482 	if (class == BPF_STX) {
3483 		/* BPF_STX (including atomic variants) has multiple source
3484 		 * operands, one of which is a ptr. Check whether the caller is
3485 		 * asking about it.
3486 		 */
3487 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3488 			return true;
3489 		return BPF_SIZE(code) == BPF_DW;
3490 	}
3491 
3492 	if (class == BPF_LD) {
3493 		u8 mode = BPF_MODE(code);
3494 
3495 		/* LD_IMM64 */
3496 		if (mode == BPF_IMM)
3497 			return true;
3498 
3499 		/* Both LD_IND and LD_ABS return 32-bit data. */
3500 		if (t != SRC_OP)
3501 			return  false;
3502 
3503 		/* Implicit ctx ptr. */
3504 		if (regno == BPF_REG_6)
3505 			return true;
3506 
3507 		/* Explicit source could be any width. */
3508 		return true;
3509 	}
3510 
3511 	if (class == BPF_ST)
3512 		/* The only source register for BPF_ST is a ptr. */
3513 		return true;
3514 
3515 	/* Conservatively return true at default. */
3516 	return true;
3517 }
3518 
3519 /* Return the regno defined by the insn, or -1. */
3520 static int insn_def_regno(const struct bpf_insn *insn)
3521 {
3522 	switch (BPF_CLASS(insn->code)) {
3523 	case BPF_JMP:
3524 	case BPF_JMP32:
3525 	case BPF_ST:
3526 		return -1;
3527 	case BPF_STX:
3528 		if ((BPF_MODE(insn->code) == BPF_ATOMIC ||
3529 		     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) &&
3530 		    (insn->imm & BPF_FETCH)) {
3531 			if (insn->imm == BPF_CMPXCHG)
3532 				return BPF_REG_0;
3533 			else
3534 				return insn->src_reg;
3535 		} else {
3536 			return -1;
3537 		}
3538 	default:
3539 		return insn->dst_reg;
3540 	}
3541 }
3542 
3543 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3544 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3545 {
3546 	int dst_reg = insn_def_regno(insn);
3547 
3548 	if (dst_reg == -1)
3549 		return false;
3550 
3551 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3552 }
3553 
3554 static void mark_insn_zext(struct bpf_verifier_env *env,
3555 			   struct bpf_reg_state *reg)
3556 {
3557 	s32 def_idx = reg->subreg_def;
3558 
3559 	if (def_idx == DEF_NOT_SUBREG)
3560 		return;
3561 
3562 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3563 	/* The dst will be zero extended, so won't be sub-register anymore. */
3564 	reg->subreg_def = DEF_NOT_SUBREG;
3565 }
3566 
3567 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3568 			   enum reg_arg_type t)
3569 {
3570 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3571 	struct bpf_reg_state *reg;
3572 	bool rw64;
3573 
3574 	if (regno >= MAX_BPF_REG) {
3575 		verbose(env, "R%d is invalid\n", regno);
3576 		return -EINVAL;
3577 	}
3578 
3579 	mark_reg_scratched(env, regno);
3580 
3581 	reg = &regs[regno];
3582 	rw64 = is_reg64(env, insn, regno, reg, t);
3583 	if (t == SRC_OP) {
3584 		/* check whether register used as source operand can be read */
3585 		if (reg->type == NOT_INIT) {
3586 			verbose(env, "R%d !read_ok\n", regno);
3587 			return -EACCES;
3588 		}
3589 		/* We don't need to worry about FP liveness because it's read-only */
3590 		if (regno == BPF_REG_FP)
3591 			return 0;
3592 
3593 		if (rw64)
3594 			mark_insn_zext(env, reg);
3595 
3596 		return mark_reg_read(env, reg, reg->parent,
3597 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3598 	} else {
3599 		/* check whether register used as dest operand can be written to */
3600 		if (regno == BPF_REG_FP) {
3601 			verbose(env, "frame pointer is read only\n");
3602 			return -EACCES;
3603 		}
3604 		reg->live |= REG_LIVE_WRITTEN;
3605 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3606 		if (t == DST_OP)
3607 			mark_reg_unknown(env, regs, regno);
3608 	}
3609 	return 0;
3610 }
3611 
3612 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3613 			 enum reg_arg_type t)
3614 {
3615 	struct bpf_verifier_state *vstate = env->cur_state;
3616 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3617 
3618 	return __check_reg_arg(env, state->regs, regno, t);
3619 }
3620 
3621 static int insn_stack_access_flags(int frameno, int spi)
3622 {
3623 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3624 }
3625 
3626 static int insn_stack_access_spi(int insn_flags)
3627 {
3628 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3629 }
3630 
3631 static int insn_stack_access_frameno(int insn_flags)
3632 {
3633 	return insn_flags & INSN_F_FRAMENO_MASK;
3634 }
3635 
3636 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3637 {
3638 	env->insn_aux_data[idx].jmp_point = true;
3639 }
3640 
3641 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3642 {
3643 	return env->insn_aux_data[insn_idx].jmp_point;
3644 }
3645 
3646 #define LR_FRAMENO_BITS	3
3647 #define LR_SPI_BITS	6
3648 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3649 #define LR_SIZE_BITS	4
3650 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3651 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3652 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3653 #define LR_SPI_OFF	LR_FRAMENO_BITS
3654 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3655 #define LINKED_REGS_MAX	6
3656 
3657 struct linked_reg {
3658 	u8 frameno;
3659 	union {
3660 		u8 spi;
3661 		u8 regno;
3662 	};
3663 	bool is_reg;
3664 };
3665 
3666 struct linked_regs {
3667 	int cnt;
3668 	struct linked_reg entries[LINKED_REGS_MAX];
3669 };
3670 
3671 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3672 {
3673 	if (s->cnt < LINKED_REGS_MAX)
3674 		return &s->entries[s->cnt++];
3675 
3676 	return NULL;
3677 }
3678 
3679 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3680  * number of elements currently in stack.
3681  * Pack one history entry for linked registers as 10 bits in the following format:
3682  * - 3-bits frameno
3683  * - 6-bits spi_or_reg
3684  * - 1-bit  is_reg
3685  */
3686 static u64 linked_regs_pack(struct linked_regs *s)
3687 {
3688 	u64 val = 0;
3689 	int i;
3690 
3691 	for (i = 0; i < s->cnt; ++i) {
3692 		struct linked_reg *e = &s->entries[i];
3693 		u64 tmp = 0;
3694 
3695 		tmp |= e->frameno;
3696 		tmp |= e->spi << LR_SPI_OFF;
3697 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3698 
3699 		val <<= LR_ENTRY_BITS;
3700 		val |= tmp;
3701 	}
3702 	val <<= LR_SIZE_BITS;
3703 	val |= s->cnt;
3704 	return val;
3705 }
3706 
3707 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3708 {
3709 	int i;
3710 
3711 	s->cnt = val & LR_SIZE_MASK;
3712 	val >>= LR_SIZE_BITS;
3713 
3714 	for (i = 0; i < s->cnt; ++i) {
3715 		struct linked_reg *e = &s->entries[i];
3716 
3717 		e->frameno =  val & LR_FRAMENO_MASK;
3718 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3719 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3720 		val >>= LR_ENTRY_BITS;
3721 	}
3722 }
3723 
3724 /* for any branch, call, exit record the history of jmps in the given state */
3725 static int push_insn_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3726 			     int insn_flags, u64 linked_regs)
3727 {
3728 	struct bpf_insn_hist_entry *p;
3729 	size_t alloc_size;
3730 
3731 	/* combine instruction flags if we already recorded this instruction */
3732 	if (env->cur_hist_ent) {
3733 		/* atomic instructions push insn_flags twice, for READ and
3734 		 * WRITE sides, but they should agree on stack slot
3735 		 */
3736 		WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3737 			  (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3738 			  "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3739 			  env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3740 		env->cur_hist_ent->flags |= insn_flags;
3741 		WARN_ONCE(env->cur_hist_ent->linked_regs != 0,
3742 			  "verifier insn history bug: insn_idx %d linked_regs != 0: %#llx\n",
3743 			  env->insn_idx, env->cur_hist_ent->linked_regs);
3744 		env->cur_hist_ent->linked_regs = linked_regs;
3745 		return 0;
3746 	}
3747 
3748 	if (cur->insn_hist_end + 1 > env->insn_hist_cap) {
3749 		alloc_size = size_mul(cur->insn_hist_end + 1, sizeof(*p));
3750 		p = kvrealloc(env->insn_hist, alloc_size, GFP_USER);
3751 		if (!p)
3752 			return -ENOMEM;
3753 		env->insn_hist = p;
3754 		env->insn_hist_cap = alloc_size / sizeof(*p);
3755 	}
3756 
3757 	p = &env->insn_hist[cur->insn_hist_end];
3758 	p->idx = env->insn_idx;
3759 	p->prev_idx = env->prev_insn_idx;
3760 	p->flags = insn_flags;
3761 	p->linked_regs = linked_regs;
3762 
3763 	cur->insn_hist_end++;
3764 	env->cur_hist_ent = p;
3765 
3766 	return 0;
3767 }
3768 
3769 static struct bpf_insn_hist_entry *get_insn_hist_entry(struct bpf_verifier_env *env,
3770 						       u32 hist_start, u32 hist_end, int insn_idx)
3771 {
3772 	if (hist_end > hist_start && env->insn_hist[hist_end - 1].idx == insn_idx)
3773 		return &env->insn_hist[hist_end - 1];
3774 	return NULL;
3775 }
3776 
3777 /* Backtrack one insn at a time. If idx is not at the top of recorded
3778  * history then previous instruction came from straight line execution.
3779  * Return -ENOENT if we exhausted all instructions within given state.
3780  *
3781  * It's legal to have a bit of a looping with the same starting and ending
3782  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3783  * instruction index is the same as state's first_idx doesn't mean we are
3784  * done. If there is still some jump history left, we should keep going. We
3785  * need to take into account that we might have a jump history between given
3786  * state's parent and itself, due to checkpointing. In this case, we'll have
3787  * history entry recording a jump from last instruction of parent state and
3788  * first instruction of given state.
3789  */
3790 static int get_prev_insn_idx(const struct bpf_verifier_env *env,
3791 			     struct bpf_verifier_state *st,
3792 			     int insn_idx, u32 hist_start, u32 *hist_endp)
3793 {
3794 	u32 hist_end = *hist_endp;
3795 	u32 cnt = hist_end - hist_start;
3796 
3797 	if (insn_idx == st->first_insn_idx) {
3798 		if (cnt == 0)
3799 			return -ENOENT;
3800 		if (cnt == 1 && env->insn_hist[hist_start].idx == insn_idx)
3801 			return -ENOENT;
3802 	}
3803 
3804 	if (cnt && env->insn_hist[hist_end - 1].idx == insn_idx) {
3805 		(*hist_endp)--;
3806 		return env->insn_hist[hist_end - 1].prev_idx;
3807 	} else {
3808 		return insn_idx - 1;
3809 	}
3810 }
3811 
3812 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3813 {
3814 	const struct btf_type *func;
3815 	struct btf *desc_btf;
3816 
3817 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3818 		return NULL;
3819 
3820 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3821 	if (IS_ERR(desc_btf))
3822 		return "<error>";
3823 
3824 	func = btf_type_by_id(desc_btf, insn->imm);
3825 	return btf_name_by_offset(desc_btf, func->name_off);
3826 }
3827 
3828 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3829 {
3830 	bt->frame = frame;
3831 }
3832 
3833 static inline void bt_reset(struct backtrack_state *bt)
3834 {
3835 	struct bpf_verifier_env *env = bt->env;
3836 
3837 	memset(bt, 0, sizeof(*bt));
3838 	bt->env = env;
3839 }
3840 
3841 static inline u32 bt_empty(struct backtrack_state *bt)
3842 {
3843 	u64 mask = 0;
3844 	int i;
3845 
3846 	for (i = 0; i <= bt->frame; i++)
3847 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3848 
3849 	return mask == 0;
3850 }
3851 
3852 static inline int bt_subprog_enter(struct backtrack_state *bt)
3853 {
3854 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3855 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3856 		WARN_ONCE(1, "verifier backtracking bug");
3857 		return -EFAULT;
3858 	}
3859 	bt->frame++;
3860 	return 0;
3861 }
3862 
3863 static inline int bt_subprog_exit(struct backtrack_state *bt)
3864 {
3865 	if (bt->frame == 0) {
3866 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3867 		WARN_ONCE(1, "verifier backtracking bug");
3868 		return -EFAULT;
3869 	}
3870 	bt->frame--;
3871 	return 0;
3872 }
3873 
3874 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3875 {
3876 	bt->reg_masks[frame] |= 1 << reg;
3877 }
3878 
3879 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3880 {
3881 	bt->reg_masks[frame] &= ~(1 << reg);
3882 }
3883 
3884 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3885 {
3886 	bt_set_frame_reg(bt, bt->frame, reg);
3887 }
3888 
3889 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3890 {
3891 	bt_clear_frame_reg(bt, bt->frame, reg);
3892 }
3893 
3894 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3895 {
3896 	bt->stack_masks[frame] |= 1ull << slot;
3897 }
3898 
3899 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3900 {
3901 	bt->stack_masks[frame] &= ~(1ull << slot);
3902 }
3903 
3904 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3905 {
3906 	return bt->reg_masks[frame];
3907 }
3908 
3909 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3910 {
3911 	return bt->reg_masks[bt->frame];
3912 }
3913 
3914 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3915 {
3916 	return bt->stack_masks[frame];
3917 }
3918 
3919 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3920 {
3921 	return bt->stack_masks[bt->frame];
3922 }
3923 
3924 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3925 {
3926 	return bt->reg_masks[bt->frame] & (1 << reg);
3927 }
3928 
3929 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
3930 {
3931 	return bt->reg_masks[frame] & (1 << reg);
3932 }
3933 
3934 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3935 {
3936 	return bt->stack_masks[frame] & (1ull << slot);
3937 }
3938 
3939 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3940 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3941 {
3942 	DECLARE_BITMAP(mask, 64);
3943 	bool first = true;
3944 	int i, n;
3945 
3946 	buf[0] = '\0';
3947 
3948 	bitmap_from_u64(mask, reg_mask);
3949 	for_each_set_bit(i, mask, 32) {
3950 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3951 		first = false;
3952 		buf += n;
3953 		buf_sz -= n;
3954 		if (buf_sz < 0)
3955 			break;
3956 	}
3957 }
3958 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3959 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3960 {
3961 	DECLARE_BITMAP(mask, 64);
3962 	bool first = true;
3963 	int i, n;
3964 
3965 	buf[0] = '\0';
3966 
3967 	bitmap_from_u64(mask, stack_mask);
3968 	for_each_set_bit(i, mask, 64) {
3969 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3970 		first = false;
3971 		buf += n;
3972 		buf_sz -= n;
3973 		if (buf_sz < 0)
3974 			break;
3975 	}
3976 }
3977 
3978 /* If any register R in hist->linked_regs is marked as precise in bt,
3979  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
3980  */
3981 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_insn_hist_entry *hist)
3982 {
3983 	struct linked_regs linked_regs;
3984 	bool some_precise = false;
3985 	int i;
3986 
3987 	if (!hist || hist->linked_regs == 0)
3988 		return;
3989 
3990 	linked_regs_unpack(hist->linked_regs, &linked_regs);
3991 	for (i = 0; i < linked_regs.cnt; ++i) {
3992 		struct linked_reg *e = &linked_regs.entries[i];
3993 
3994 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
3995 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
3996 			some_precise = true;
3997 			break;
3998 		}
3999 	}
4000 
4001 	if (!some_precise)
4002 		return;
4003 
4004 	for (i = 0; i < linked_regs.cnt; ++i) {
4005 		struct linked_reg *e = &linked_regs.entries[i];
4006 
4007 		if (e->is_reg)
4008 			bt_set_frame_reg(bt, e->frameno, e->regno);
4009 		else
4010 			bt_set_frame_slot(bt, e->frameno, e->spi);
4011 	}
4012 }
4013 
4014 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
4015 
4016 /* For given verifier state backtrack_insn() is called from the last insn to
4017  * the first insn. Its purpose is to compute a bitmask of registers and
4018  * stack slots that needs precision in the parent verifier state.
4019  *
4020  * @idx is an index of the instruction we are currently processing;
4021  * @subseq_idx is an index of the subsequent instruction that:
4022  *   - *would be* executed next, if jump history is viewed in forward order;
4023  *   - *was* processed previously during backtracking.
4024  */
4025 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
4026 			  struct bpf_insn_hist_entry *hist, struct backtrack_state *bt)
4027 {
4028 	const struct bpf_insn_cbs cbs = {
4029 		.cb_call	= disasm_kfunc_name,
4030 		.cb_print	= verbose,
4031 		.private_data	= env,
4032 	};
4033 	struct bpf_insn *insn = env->prog->insnsi + idx;
4034 	u8 class = BPF_CLASS(insn->code);
4035 	u8 opcode = BPF_OP(insn->code);
4036 	u8 mode = BPF_MODE(insn->code);
4037 	u32 dreg = insn->dst_reg;
4038 	u32 sreg = insn->src_reg;
4039 	u32 spi, i, fr;
4040 
4041 	if (insn->code == 0)
4042 		return 0;
4043 	if (env->log.level & BPF_LOG_LEVEL2) {
4044 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
4045 		verbose(env, "mark_precise: frame%d: regs=%s ",
4046 			bt->frame, env->tmp_str_buf);
4047 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
4048 		verbose(env, "stack=%s before ", env->tmp_str_buf);
4049 		verbose(env, "%d: ", idx);
4050 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
4051 	}
4052 
4053 	/* If there is a history record that some registers gained range at this insn,
4054 	 * propagate precision marks to those registers, so that bt_is_reg_set()
4055 	 * accounts for these registers.
4056 	 */
4057 	bt_sync_linked_regs(bt, hist);
4058 
4059 	if (class == BPF_ALU || class == BPF_ALU64) {
4060 		if (!bt_is_reg_set(bt, dreg))
4061 			return 0;
4062 		if (opcode == BPF_END || opcode == BPF_NEG) {
4063 			/* sreg is reserved and unused
4064 			 * dreg still need precision before this insn
4065 			 */
4066 			return 0;
4067 		} else if (opcode == BPF_MOV) {
4068 			if (BPF_SRC(insn->code) == BPF_X) {
4069 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
4070 				 * dreg needs precision after this insn
4071 				 * sreg needs precision before this insn
4072 				 */
4073 				bt_clear_reg(bt, dreg);
4074 				if (sreg != BPF_REG_FP)
4075 					bt_set_reg(bt, sreg);
4076 			} else {
4077 				/* dreg = K
4078 				 * dreg needs precision after this insn.
4079 				 * Corresponding register is already marked
4080 				 * as precise=true in this verifier state.
4081 				 * No further markings in parent are necessary
4082 				 */
4083 				bt_clear_reg(bt, dreg);
4084 			}
4085 		} else {
4086 			if (BPF_SRC(insn->code) == BPF_X) {
4087 				/* dreg += sreg
4088 				 * both dreg and sreg need precision
4089 				 * before this insn
4090 				 */
4091 				if (sreg != BPF_REG_FP)
4092 					bt_set_reg(bt, sreg);
4093 			} /* else dreg += K
4094 			   * dreg still needs precision before this insn
4095 			   */
4096 		}
4097 	} else if (class == BPF_LDX) {
4098 		if (!bt_is_reg_set(bt, dreg))
4099 			return 0;
4100 		bt_clear_reg(bt, dreg);
4101 
4102 		/* scalars can only be spilled into stack w/o losing precision.
4103 		 * Load from any other memory can be zero extended.
4104 		 * The desire to keep that precision is already indicated
4105 		 * by 'precise' mark in corresponding register of this state.
4106 		 * No further tracking necessary.
4107 		 */
4108 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4109 			return 0;
4110 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
4111 		 * that [fp - off] slot contains scalar that needs to be
4112 		 * tracked with precision
4113 		 */
4114 		spi = insn_stack_access_spi(hist->flags);
4115 		fr = insn_stack_access_frameno(hist->flags);
4116 		bt_set_frame_slot(bt, fr, spi);
4117 	} else if (class == BPF_STX || class == BPF_ST) {
4118 		if (bt_is_reg_set(bt, dreg))
4119 			/* stx & st shouldn't be using _scalar_ dst_reg
4120 			 * to access memory. It means backtracking
4121 			 * encountered a case of pointer subtraction.
4122 			 */
4123 			return -ENOTSUPP;
4124 		/* scalars can only be spilled into stack */
4125 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4126 			return 0;
4127 		spi = insn_stack_access_spi(hist->flags);
4128 		fr = insn_stack_access_frameno(hist->flags);
4129 		if (!bt_is_frame_slot_set(bt, fr, spi))
4130 			return 0;
4131 		bt_clear_frame_slot(bt, fr, spi);
4132 		if (class == BPF_STX)
4133 			bt_set_reg(bt, sreg);
4134 	} else if (class == BPF_JMP || class == BPF_JMP32) {
4135 		if (bpf_pseudo_call(insn)) {
4136 			int subprog_insn_idx, subprog;
4137 
4138 			subprog_insn_idx = idx + insn->imm + 1;
4139 			subprog = find_subprog(env, subprog_insn_idx);
4140 			if (subprog < 0)
4141 				return -EFAULT;
4142 
4143 			if (subprog_is_global(env, subprog)) {
4144 				/* check that jump history doesn't have any
4145 				 * extra instructions from subprog; the next
4146 				 * instruction after call to global subprog
4147 				 * should be literally next instruction in
4148 				 * caller program
4149 				 */
4150 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
4151 				/* r1-r5 are invalidated after subprog call,
4152 				 * so for global func call it shouldn't be set
4153 				 * anymore
4154 				 */
4155 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4156 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
4157 					WARN_ONCE(1, "verifier backtracking bug");
4158 					return -EFAULT;
4159 				}
4160 				/* global subprog always sets R0 */
4161 				bt_clear_reg(bt, BPF_REG_0);
4162 				return 0;
4163 			} else {
4164 				/* static subprog call instruction, which
4165 				 * means that we are exiting current subprog,
4166 				 * so only r1-r5 could be still requested as
4167 				 * precise, r0 and r6-r10 or any stack slot in
4168 				 * the current frame should be zero by now
4169 				 */
4170 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4171 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
4172 					WARN_ONCE(1, "verifier backtracking bug");
4173 					return -EFAULT;
4174 				}
4175 				/* we are now tracking register spills correctly,
4176 				 * so any instance of leftover slots is a bug
4177 				 */
4178 				if (bt_stack_mask(bt) != 0) {
4179 					verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
4180 					WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
4181 					return -EFAULT;
4182 				}
4183 				/* propagate r1-r5 to the caller */
4184 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
4185 					if (bt_is_reg_set(bt, i)) {
4186 						bt_clear_reg(bt, i);
4187 						bt_set_frame_reg(bt, bt->frame - 1, i);
4188 					}
4189 				}
4190 				if (bt_subprog_exit(bt))
4191 					return -EFAULT;
4192 				return 0;
4193 			}
4194 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
4195 			/* exit from callback subprog to callback-calling helper or
4196 			 * kfunc call. Use idx/subseq_idx check to discern it from
4197 			 * straight line code backtracking.
4198 			 * Unlike the subprog call handling above, we shouldn't
4199 			 * propagate precision of r1-r5 (if any requested), as they are
4200 			 * not actually arguments passed directly to callback subprogs
4201 			 */
4202 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4203 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
4204 				WARN_ONCE(1, "verifier backtracking bug");
4205 				return -EFAULT;
4206 			}
4207 			if (bt_stack_mask(bt) != 0) {
4208 				verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
4209 				WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
4210 				return -EFAULT;
4211 			}
4212 			/* clear r1-r5 in callback subprog's mask */
4213 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4214 				bt_clear_reg(bt, i);
4215 			if (bt_subprog_exit(bt))
4216 				return -EFAULT;
4217 			return 0;
4218 		} else if (opcode == BPF_CALL) {
4219 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
4220 			 * catch this error later. Make backtracking conservative
4221 			 * with ENOTSUPP.
4222 			 */
4223 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
4224 				return -ENOTSUPP;
4225 			/* regular helper call sets R0 */
4226 			bt_clear_reg(bt, BPF_REG_0);
4227 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4228 				/* if backtracing was looking for registers R1-R5
4229 				 * they should have been found already.
4230 				 */
4231 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
4232 				WARN_ONCE(1, "verifier backtracking bug");
4233 				return -EFAULT;
4234 			}
4235 		} else if (opcode == BPF_EXIT) {
4236 			bool r0_precise;
4237 
4238 			/* Backtracking to a nested function call, 'idx' is a part of
4239 			 * the inner frame 'subseq_idx' is a part of the outer frame.
4240 			 * In case of a regular function call, instructions giving
4241 			 * precision to registers R1-R5 should have been found already.
4242 			 * In case of a callback, it is ok to have R1-R5 marked for
4243 			 * backtracking, as these registers are set by the function
4244 			 * invoking callback.
4245 			 */
4246 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
4247 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4248 					bt_clear_reg(bt, i);
4249 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4250 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
4251 				WARN_ONCE(1, "verifier backtracking bug");
4252 				return -EFAULT;
4253 			}
4254 
4255 			/* BPF_EXIT in subprog or callback always returns
4256 			 * right after the call instruction, so by checking
4257 			 * whether the instruction at subseq_idx-1 is subprog
4258 			 * call or not we can distinguish actual exit from
4259 			 * *subprog* from exit from *callback*. In the former
4260 			 * case, we need to propagate r0 precision, if
4261 			 * necessary. In the former we never do that.
4262 			 */
4263 			r0_precise = subseq_idx - 1 >= 0 &&
4264 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4265 				     bt_is_reg_set(bt, BPF_REG_0);
4266 
4267 			bt_clear_reg(bt, BPF_REG_0);
4268 			if (bt_subprog_enter(bt))
4269 				return -EFAULT;
4270 
4271 			if (r0_precise)
4272 				bt_set_reg(bt, BPF_REG_0);
4273 			/* r6-r9 and stack slots will stay set in caller frame
4274 			 * bitmasks until we return back from callee(s)
4275 			 */
4276 			return 0;
4277 		} else if (BPF_SRC(insn->code) == BPF_X) {
4278 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4279 				return 0;
4280 			/* dreg <cond> sreg
4281 			 * Both dreg and sreg need precision before
4282 			 * this insn. If only sreg was marked precise
4283 			 * before it would be equally necessary to
4284 			 * propagate it to dreg.
4285 			 */
4286 			bt_set_reg(bt, dreg);
4287 			bt_set_reg(bt, sreg);
4288 		} else if (BPF_SRC(insn->code) == BPF_K) {
4289 			 /* dreg <cond> K
4290 			  * Only dreg still needs precision before
4291 			  * this insn, so for the K-based conditional
4292 			  * there is nothing new to be marked.
4293 			  */
4294 		}
4295 	} else if (class == BPF_LD) {
4296 		if (!bt_is_reg_set(bt, dreg))
4297 			return 0;
4298 		bt_clear_reg(bt, dreg);
4299 		/* It's ld_imm64 or ld_abs or ld_ind.
4300 		 * For ld_imm64 no further tracking of precision
4301 		 * into parent is necessary
4302 		 */
4303 		if (mode == BPF_IND || mode == BPF_ABS)
4304 			/* to be analyzed */
4305 			return -ENOTSUPP;
4306 	}
4307 	/* Propagate precision marks to linked registers, to account for
4308 	 * registers marked as precise in this function.
4309 	 */
4310 	bt_sync_linked_regs(bt, hist);
4311 	return 0;
4312 }
4313 
4314 /* the scalar precision tracking algorithm:
4315  * . at the start all registers have precise=false.
4316  * . scalar ranges are tracked as normal through alu and jmp insns.
4317  * . once precise value of the scalar register is used in:
4318  *   .  ptr + scalar alu
4319  *   . if (scalar cond K|scalar)
4320  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
4321  *   backtrack through the verifier states and mark all registers and
4322  *   stack slots with spilled constants that these scalar regisers
4323  *   should be precise.
4324  * . during state pruning two registers (or spilled stack slots)
4325  *   are equivalent if both are not precise.
4326  *
4327  * Note the verifier cannot simply walk register parentage chain,
4328  * since many different registers and stack slots could have been
4329  * used to compute single precise scalar.
4330  *
4331  * The approach of starting with precise=true for all registers and then
4332  * backtrack to mark a register as not precise when the verifier detects
4333  * that program doesn't care about specific value (e.g., when helper
4334  * takes register as ARG_ANYTHING parameter) is not safe.
4335  *
4336  * It's ok to walk single parentage chain of the verifier states.
4337  * It's possible that this backtracking will go all the way till 1st insn.
4338  * All other branches will be explored for needing precision later.
4339  *
4340  * The backtracking needs to deal with cases like:
4341  *   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)
4342  * r9 -= r8
4343  * r5 = r9
4344  * if r5 > 0x79f goto pc+7
4345  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4346  * r5 += 1
4347  * ...
4348  * call bpf_perf_event_output#25
4349  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4350  *
4351  * and this case:
4352  * r6 = 1
4353  * call foo // uses callee's r6 inside to compute r0
4354  * r0 += r6
4355  * if r0 == 0 goto
4356  *
4357  * to track above reg_mask/stack_mask needs to be independent for each frame.
4358  *
4359  * Also if parent's curframe > frame where backtracking started,
4360  * the verifier need to mark registers in both frames, otherwise callees
4361  * may incorrectly prune callers. This is similar to
4362  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4363  *
4364  * For now backtracking falls back into conservative marking.
4365  */
4366 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4367 				     struct bpf_verifier_state *st)
4368 {
4369 	struct bpf_func_state *func;
4370 	struct bpf_reg_state *reg;
4371 	int i, j;
4372 
4373 	if (env->log.level & BPF_LOG_LEVEL2) {
4374 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4375 			st->curframe);
4376 	}
4377 
4378 	/* big hammer: mark all scalars precise in this path.
4379 	 * pop_stack may still get !precise scalars.
4380 	 * We also skip current state and go straight to first parent state,
4381 	 * because precision markings in current non-checkpointed state are
4382 	 * not needed. See why in the comment in __mark_chain_precision below.
4383 	 */
4384 	for (st = st->parent; st; st = st->parent) {
4385 		for (i = 0; i <= st->curframe; i++) {
4386 			func = st->frame[i];
4387 			for (j = 0; j < BPF_REG_FP; j++) {
4388 				reg = &func->regs[j];
4389 				if (reg->type != SCALAR_VALUE || reg->precise)
4390 					continue;
4391 				reg->precise = true;
4392 				if (env->log.level & BPF_LOG_LEVEL2) {
4393 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4394 						i, j);
4395 				}
4396 			}
4397 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4398 				if (!is_spilled_reg(&func->stack[j]))
4399 					continue;
4400 				reg = &func->stack[j].spilled_ptr;
4401 				if (reg->type != SCALAR_VALUE || reg->precise)
4402 					continue;
4403 				reg->precise = true;
4404 				if (env->log.level & BPF_LOG_LEVEL2) {
4405 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4406 						i, -(j + 1) * 8);
4407 				}
4408 			}
4409 		}
4410 	}
4411 }
4412 
4413 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4414 {
4415 	struct bpf_func_state *func;
4416 	struct bpf_reg_state *reg;
4417 	int i, j;
4418 
4419 	for (i = 0; i <= st->curframe; i++) {
4420 		func = st->frame[i];
4421 		for (j = 0; j < BPF_REG_FP; j++) {
4422 			reg = &func->regs[j];
4423 			if (reg->type != SCALAR_VALUE)
4424 				continue;
4425 			reg->precise = false;
4426 		}
4427 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4428 			if (!is_spilled_reg(&func->stack[j]))
4429 				continue;
4430 			reg = &func->stack[j].spilled_ptr;
4431 			if (reg->type != SCALAR_VALUE)
4432 				continue;
4433 			reg->precise = false;
4434 		}
4435 	}
4436 }
4437 
4438 /*
4439  * __mark_chain_precision() backtracks BPF program instruction sequence and
4440  * chain of verifier states making sure that register *regno* (if regno >= 0)
4441  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4442  * SCALARS, as well as any other registers and slots that contribute to
4443  * a tracked state of given registers/stack slots, depending on specific BPF
4444  * assembly instructions (see backtrack_insns() for exact instruction handling
4445  * logic). This backtracking relies on recorded insn_hist and is able to
4446  * traverse entire chain of parent states. This process ends only when all the
4447  * necessary registers/slots and their transitive dependencies are marked as
4448  * precise.
4449  *
4450  * One important and subtle aspect is that precise marks *do not matter* in
4451  * the currently verified state (current state). It is important to understand
4452  * why this is the case.
4453  *
4454  * First, note that current state is the state that is not yet "checkpointed",
4455  * i.e., it is not yet put into env->explored_states, and it has no children
4456  * states as well. It's ephemeral, and can end up either a) being discarded if
4457  * compatible explored state is found at some point or BPF_EXIT instruction is
4458  * reached or b) checkpointed and put into env->explored_states, branching out
4459  * into one or more children states.
4460  *
4461  * In the former case, precise markings in current state are completely
4462  * ignored by state comparison code (see regsafe() for details). Only
4463  * checkpointed ("old") state precise markings are important, and if old
4464  * state's register/slot is precise, regsafe() assumes current state's
4465  * register/slot as precise and checks value ranges exactly and precisely. If
4466  * states turn out to be compatible, current state's necessary precise
4467  * markings and any required parent states' precise markings are enforced
4468  * after the fact with propagate_precision() logic, after the fact. But it's
4469  * important to realize that in this case, even after marking current state
4470  * registers/slots as precise, we immediately discard current state. So what
4471  * actually matters is any of the precise markings propagated into current
4472  * state's parent states, which are always checkpointed (due to b) case above).
4473  * As such, for scenario a) it doesn't matter if current state has precise
4474  * markings set or not.
4475  *
4476  * Now, for the scenario b), checkpointing and forking into child(ren)
4477  * state(s). Note that before current state gets to checkpointing step, any
4478  * processed instruction always assumes precise SCALAR register/slot
4479  * knowledge: if precise value or range is useful to prune jump branch, BPF
4480  * verifier takes this opportunity enthusiastically. Similarly, when
4481  * register's value is used to calculate offset or memory address, exact
4482  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4483  * what we mentioned above about state comparison ignoring precise markings
4484  * during state comparison, BPF verifier ignores and also assumes precise
4485  * markings *at will* during instruction verification process. But as verifier
4486  * assumes precision, it also propagates any precision dependencies across
4487  * parent states, which are not yet finalized, so can be further restricted
4488  * based on new knowledge gained from restrictions enforced by their children
4489  * states. This is so that once those parent states are finalized, i.e., when
4490  * they have no more active children state, state comparison logic in
4491  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4492  * required for correctness.
4493  *
4494  * To build a bit more intuition, note also that once a state is checkpointed,
4495  * the path we took to get to that state is not important. This is crucial
4496  * property for state pruning. When state is checkpointed and finalized at
4497  * some instruction index, it can be correctly and safely used to "short
4498  * circuit" any *compatible* state that reaches exactly the same instruction
4499  * index. I.e., if we jumped to that instruction from a completely different
4500  * code path than original finalized state was derived from, it doesn't
4501  * matter, current state can be discarded because from that instruction
4502  * forward having a compatible state will ensure we will safely reach the
4503  * exit. States describe preconditions for further exploration, but completely
4504  * forget the history of how we got here.
4505  *
4506  * This also means that even if we needed precise SCALAR range to get to
4507  * finalized state, but from that point forward *that same* SCALAR register is
4508  * never used in a precise context (i.e., it's precise value is not needed for
4509  * correctness), it's correct and safe to mark such register as "imprecise"
4510  * (i.e., precise marking set to false). This is what we rely on when we do
4511  * not set precise marking in current state. If no child state requires
4512  * precision for any given SCALAR register, it's safe to dictate that it can
4513  * be imprecise. If any child state does require this register to be precise,
4514  * we'll mark it precise later retroactively during precise markings
4515  * propagation from child state to parent states.
4516  *
4517  * Skipping precise marking setting in current state is a mild version of
4518  * relying on the above observation. But we can utilize this property even
4519  * more aggressively by proactively forgetting any precise marking in the
4520  * current state (which we inherited from the parent state), right before we
4521  * checkpoint it and branch off into new child state. This is done by
4522  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4523  * finalized states which help in short circuiting more future states.
4524  */
4525 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4526 {
4527 	struct backtrack_state *bt = &env->bt;
4528 	struct bpf_verifier_state *st = env->cur_state;
4529 	int first_idx = st->first_insn_idx;
4530 	int last_idx = env->insn_idx;
4531 	int subseq_idx = -1;
4532 	struct bpf_func_state *func;
4533 	struct bpf_reg_state *reg;
4534 	bool skip_first = true;
4535 	int i, fr, err;
4536 
4537 	if (!env->bpf_capable)
4538 		return 0;
4539 
4540 	/* set frame number from which we are starting to backtrack */
4541 	bt_init(bt, env->cur_state->curframe);
4542 
4543 	/* Do sanity checks against current state of register and/or stack
4544 	 * slot, but don't set precise flag in current state, as precision
4545 	 * tracking in the current state is unnecessary.
4546 	 */
4547 	func = st->frame[bt->frame];
4548 	if (regno >= 0) {
4549 		reg = &func->regs[regno];
4550 		if (reg->type != SCALAR_VALUE) {
4551 			WARN_ONCE(1, "backtracing misuse");
4552 			return -EFAULT;
4553 		}
4554 		bt_set_reg(bt, regno);
4555 	}
4556 
4557 	if (bt_empty(bt))
4558 		return 0;
4559 
4560 	for (;;) {
4561 		DECLARE_BITMAP(mask, 64);
4562 		u32 hist_start = st->insn_hist_start;
4563 		u32 hist_end = st->insn_hist_end;
4564 		struct bpf_insn_hist_entry *hist;
4565 
4566 		if (env->log.level & BPF_LOG_LEVEL2) {
4567 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4568 				bt->frame, last_idx, first_idx, subseq_idx);
4569 		}
4570 
4571 		if (last_idx < 0) {
4572 			/* we are at the entry into subprog, which
4573 			 * is expected for global funcs, but only if
4574 			 * requested precise registers are R1-R5
4575 			 * (which are global func's input arguments)
4576 			 */
4577 			if (st->curframe == 0 &&
4578 			    st->frame[0]->subprogno > 0 &&
4579 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4580 			    bt_stack_mask(bt) == 0 &&
4581 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4582 				bitmap_from_u64(mask, bt_reg_mask(bt));
4583 				for_each_set_bit(i, mask, 32) {
4584 					reg = &st->frame[0]->regs[i];
4585 					bt_clear_reg(bt, i);
4586 					if (reg->type == SCALAR_VALUE)
4587 						reg->precise = true;
4588 				}
4589 				return 0;
4590 			}
4591 
4592 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4593 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4594 			WARN_ONCE(1, "verifier backtracking bug");
4595 			return -EFAULT;
4596 		}
4597 
4598 		for (i = last_idx;;) {
4599 			if (skip_first) {
4600 				err = 0;
4601 				skip_first = false;
4602 			} else {
4603 				hist = get_insn_hist_entry(env, hist_start, hist_end, i);
4604 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4605 			}
4606 			if (err == -ENOTSUPP) {
4607 				mark_all_scalars_precise(env, env->cur_state);
4608 				bt_reset(bt);
4609 				return 0;
4610 			} else if (err) {
4611 				return err;
4612 			}
4613 			if (bt_empty(bt))
4614 				/* Found assignment(s) into tracked register in this state.
4615 				 * Since this state is already marked, just return.
4616 				 * Nothing to be tracked further in the parent state.
4617 				 */
4618 				return 0;
4619 			subseq_idx = i;
4620 			i = get_prev_insn_idx(env, st, i, hist_start, &hist_end);
4621 			if (i == -ENOENT)
4622 				break;
4623 			if (i >= env->prog->len) {
4624 				/* This can happen if backtracking reached insn 0
4625 				 * and there are still reg_mask or stack_mask
4626 				 * to backtrack.
4627 				 * It means the backtracking missed the spot where
4628 				 * particular register was initialized with a constant.
4629 				 */
4630 				verbose(env, "BUG backtracking idx %d\n", i);
4631 				WARN_ONCE(1, "verifier backtracking bug");
4632 				return -EFAULT;
4633 			}
4634 		}
4635 		st = st->parent;
4636 		if (!st)
4637 			break;
4638 
4639 		for (fr = bt->frame; fr >= 0; fr--) {
4640 			func = st->frame[fr];
4641 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4642 			for_each_set_bit(i, mask, 32) {
4643 				reg = &func->regs[i];
4644 				if (reg->type != SCALAR_VALUE) {
4645 					bt_clear_frame_reg(bt, fr, i);
4646 					continue;
4647 				}
4648 				if (reg->precise)
4649 					bt_clear_frame_reg(bt, fr, i);
4650 				else
4651 					reg->precise = true;
4652 			}
4653 
4654 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4655 			for_each_set_bit(i, mask, 64) {
4656 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4657 					verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4658 						i, func->allocated_stack / BPF_REG_SIZE);
4659 					WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4660 					return -EFAULT;
4661 				}
4662 
4663 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4664 					bt_clear_frame_slot(bt, fr, i);
4665 					continue;
4666 				}
4667 				reg = &func->stack[i].spilled_ptr;
4668 				if (reg->precise)
4669 					bt_clear_frame_slot(bt, fr, i);
4670 				else
4671 					reg->precise = true;
4672 			}
4673 			if (env->log.level & BPF_LOG_LEVEL2) {
4674 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4675 					     bt_frame_reg_mask(bt, fr));
4676 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4677 					fr, env->tmp_str_buf);
4678 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4679 					       bt_frame_stack_mask(bt, fr));
4680 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4681 				print_verifier_state(env, st, fr, true);
4682 			}
4683 		}
4684 
4685 		if (bt_empty(bt))
4686 			return 0;
4687 
4688 		subseq_idx = first_idx;
4689 		last_idx = st->last_insn_idx;
4690 		first_idx = st->first_insn_idx;
4691 	}
4692 
4693 	/* if we still have requested precise regs or slots, we missed
4694 	 * something (e.g., stack access through non-r10 register), so
4695 	 * fallback to marking all precise
4696 	 */
4697 	if (!bt_empty(bt)) {
4698 		mark_all_scalars_precise(env, env->cur_state);
4699 		bt_reset(bt);
4700 	}
4701 
4702 	return 0;
4703 }
4704 
4705 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4706 {
4707 	return __mark_chain_precision(env, regno);
4708 }
4709 
4710 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4711  * desired reg and stack masks across all relevant frames
4712  */
4713 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4714 {
4715 	return __mark_chain_precision(env, -1);
4716 }
4717 
4718 static bool is_spillable_regtype(enum bpf_reg_type type)
4719 {
4720 	switch (base_type(type)) {
4721 	case PTR_TO_MAP_VALUE:
4722 	case PTR_TO_STACK:
4723 	case PTR_TO_CTX:
4724 	case PTR_TO_PACKET:
4725 	case PTR_TO_PACKET_META:
4726 	case PTR_TO_PACKET_END:
4727 	case PTR_TO_FLOW_KEYS:
4728 	case CONST_PTR_TO_MAP:
4729 	case PTR_TO_SOCKET:
4730 	case PTR_TO_SOCK_COMMON:
4731 	case PTR_TO_TCP_SOCK:
4732 	case PTR_TO_XDP_SOCK:
4733 	case PTR_TO_BTF_ID:
4734 	case PTR_TO_BUF:
4735 	case PTR_TO_MEM:
4736 	case PTR_TO_FUNC:
4737 	case PTR_TO_MAP_KEY:
4738 	case PTR_TO_ARENA:
4739 		return true;
4740 	default:
4741 		return false;
4742 	}
4743 }
4744 
4745 /* Does this register contain a constant zero? */
4746 static bool register_is_null(struct bpf_reg_state *reg)
4747 {
4748 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4749 }
4750 
4751 /* check if register is a constant scalar value */
4752 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4753 {
4754 	return reg->type == SCALAR_VALUE &&
4755 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4756 }
4757 
4758 /* assuming is_reg_const() is true, return constant value of a register */
4759 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4760 {
4761 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4762 }
4763 
4764 static bool __is_pointer_value(bool allow_ptr_leaks,
4765 			       const struct bpf_reg_state *reg)
4766 {
4767 	if (allow_ptr_leaks)
4768 		return false;
4769 
4770 	return reg->type != SCALAR_VALUE;
4771 }
4772 
4773 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4774 					struct bpf_reg_state *src_reg)
4775 {
4776 	if (src_reg->type != SCALAR_VALUE)
4777 		return;
4778 
4779 	if (src_reg->id & BPF_ADD_CONST) {
4780 		/*
4781 		 * The verifier is processing rX = rY insn and
4782 		 * rY->id has special linked register already.
4783 		 * Cleared it, since multiple rX += const are not supported.
4784 		 */
4785 		src_reg->id = 0;
4786 		src_reg->off = 0;
4787 	}
4788 
4789 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
4790 		/* Ensure that src_reg has a valid ID that will be copied to
4791 		 * dst_reg and then will be used by sync_linked_regs() to
4792 		 * propagate min/max range.
4793 		 */
4794 		src_reg->id = ++env->id_gen;
4795 }
4796 
4797 /* Copy src state preserving dst->parent and dst->live fields */
4798 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4799 {
4800 	struct bpf_reg_state *parent = dst->parent;
4801 	enum bpf_reg_liveness live = dst->live;
4802 
4803 	*dst = *src;
4804 	dst->parent = parent;
4805 	dst->live = live;
4806 }
4807 
4808 static void save_register_state(struct bpf_verifier_env *env,
4809 				struct bpf_func_state *state,
4810 				int spi, struct bpf_reg_state *reg,
4811 				int size)
4812 {
4813 	int i;
4814 
4815 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4816 	if (size == BPF_REG_SIZE)
4817 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4818 
4819 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4820 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4821 
4822 	/* size < 8 bytes spill */
4823 	for (; i; i--)
4824 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4825 }
4826 
4827 static bool is_bpf_st_mem(struct bpf_insn *insn)
4828 {
4829 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4830 }
4831 
4832 static int get_reg_width(struct bpf_reg_state *reg)
4833 {
4834 	return fls64(reg->umax_value);
4835 }
4836 
4837 /* See comment for mark_fastcall_pattern_for_call() */
4838 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
4839 					  struct bpf_func_state *state, int insn_idx, int off)
4840 {
4841 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4842 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
4843 	int i;
4844 
4845 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
4846 		return;
4847 	/* access to the region [max_stack_depth .. fastcall_stack_off)
4848 	 * from something that is not a part of the fastcall pattern,
4849 	 * disable fastcall rewrites for current subprogram by setting
4850 	 * fastcall_stack_off to a value smaller than any possible offset.
4851 	 */
4852 	subprog->fastcall_stack_off = S16_MIN;
4853 	/* reset fastcall aux flags within subprogram,
4854 	 * happens at most once per subprogram
4855 	 */
4856 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
4857 		aux[i].fastcall_spills_num = 0;
4858 		aux[i].fastcall_pattern = 0;
4859 	}
4860 }
4861 
4862 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4863  * stack boundary and alignment are checked in check_mem_access()
4864  */
4865 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4866 				       /* stack frame we're writing to */
4867 				       struct bpf_func_state *state,
4868 				       int off, int size, int value_regno,
4869 				       int insn_idx)
4870 {
4871 	struct bpf_func_state *cur; /* state of the current function */
4872 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4873 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4874 	struct bpf_reg_state *reg = NULL;
4875 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
4876 
4877 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4878 	 * so it's aligned access and [off, off + size) are within stack limits
4879 	 */
4880 	if (!env->allow_ptr_leaks &&
4881 	    is_spilled_reg(&state->stack[spi]) &&
4882 	    !is_spilled_scalar_reg(&state->stack[spi]) &&
4883 	    size != BPF_REG_SIZE) {
4884 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4885 		return -EACCES;
4886 	}
4887 
4888 	cur = env->cur_state->frame[env->cur_state->curframe];
4889 	if (value_regno >= 0)
4890 		reg = &cur->regs[value_regno];
4891 	if (!env->bypass_spec_v4) {
4892 		bool sanitize = reg && is_spillable_regtype(reg->type);
4893 
4894 		for (i = 0; i < size; i++) {
4895 			u8 type = state->stack[spi].slot_type[i];
4896 
4897 			if (type != STACK_MISC && type != STACK_ZERO) {
4898 				sanitize = true;
4899 				break;
4900 			}
4901 		}
4902 
4903 		if (sanitize)
4904 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4905 	}
4906 
4907 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4908 	if (err)
4909 		return err;
4910 
4911 	check_fastcall_stack_contract(env, state, insn_idx, off);
4912 	mark_stack_slot_scratched(env, spi);
4913 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
4914 		bool reg_value_fits;
4915 
4916 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
4917 		/* Make sure that reg had an ID to build a relation on spill. */
4918 		if (reg_value_fits)
4919 			assign_scalar_id_before_mov(env, reg);
4920 		save_register_state(env, state, spi, reg, size);
4921 		/* Break the relation on a narrowing spill. */
4922 		if (!reg_value_fits)
4923 			state->stack[spi].spilled_ptr.id = 0;
4924 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4925 		   env->bpf_capable) {
4926 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
4927 
4928 		memset(tmp_reg, 0, sizeof(*tmp_reg));
4929 		__mark_reg_known(tmp_reg, insn->imm);
4930 		tmp_reg->type = SCALAR_VALUE;
4931 		save_register_state(env, state, spi, tmp_reg, size);
4932 	} else if (reg && is_spillable_regtype(reg->type)) {
4933 		/* register containing pointer is being spilled into stack */
4934 		if (size != BPF_REG_SIZE) {
4935 			verbose_linfo(env, insn_idx, "; ");
4936 			verbose(env, "invalid size of register spill\n");
4937 			return -EACCES;
4938 		}
4939 		if (state != cur && reg->type == PTR_TO_STACK) {
4940 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4941 			return -EINVAL;
4942 		}
4943 		save_register_state(env, state, spi, reg, size);
4944 	} else {
4945 		u8 type = STACK_MISC;
4946 
4947 		/* regular write of data into stack destroys any spilled ptr */
4948 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4949 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4950 		if (is_stack_slot_special(&state->stack[spi]))
4951 			for (i = 0; i < BPF_REG_SIZE; i++)
4952 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4953 
4954 		/* only mark the slot as written if all 8 bytes were written
4955 		 * otherwise read propagation may incorrectly stop too soon
4956 		 * when stack slots are partially written.
4957 		 * This heuristic means that read propagation will be
4958 		 * conservative, since it will add reg_live_read marks
4959 		 * to stack slots all the way to first state when programs
4960 		 * writes+reads less than 8 bytes
4961 		 */
4962 		if (size == BPF_REG_SIZE)
4963 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4964 
4965 		/* when we zero initialize stack slots mark them as such */
4966 		if ((reg && register_is_null(reg)) ||
4967 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4968 			/* STACK_ZERO case happened because register spill
4969 			 * wasn't properly aligned at the stack slot boundary,
4970 			 * so it's not a register spill anymore; force
4971 			 * originating register to be precise to make
4972 			 * STACK_ZERO correct for subsequent states
4973 			 */
4974 			err = mark_chain_precision(env, value_regno);
4975 			if (err)
4976 				return err;
4977 			type = STACK_ZERO;
4978 		}
4979 
4980 		/* Mark slots affected by this stack write. */
4981 		for (i = 0; i < size; i++)
4982 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4983 		insn_flags = 0; /* not a register spill */
4984 	}
4985 
4986 	if (insn_flags)
4987 		return push_insn_history(env, env->cur_state, insn_flags, 0);
4988 	return 0;
4989 }
4990 
4991 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4992  * known to contain a variable offset.
4993  * This function checks whether the write is permitted and conservatively
4994  * tracks the effects of the write, considering that each stack slot in the
4995  * dynamic range is potentially written to.
4996  *
4997  * 'off' includes 'regno->off'.
4998  * 'value_regno' can be -1, meaning that an unknown value is being written to
4999  * the stack.
5000  *
5001  * Spilled pointers in range are not marked as written because we don't know
5002  * what's going to be actually written. This means that read propagation for
5003  * future reads cannot be terminated by this write.
5004  *
5005  * For privileged programs, uninitialized stack slots are considered
5006  * initialized by this write (even though we don't know exactly what offsets
5007  * are going to be written to). The idea is that we don't want the verifier to
5008  * reject future reads that access slots written to through variable offsets.
5009  */
5010 static int check_stack_write_var_off(struct bpf_verifier_env *env,
5011 				     /* func where register points to */
5012 				     struct bpf_func_state *state,
5013 				     int ptr_regno, int off, int size,
5014 				     int value_regno, int insn_idx)
5015 {
5016 	struct bpf_func_state *cur; /* state of the current function */
5017 	int min_off, max_off;
5018 	int i, err;
5019 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
5020 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5021 	bool writing_zero = false;
5022 	/* set if the fact that we're writing a zero is used to let any
5023 	 * stack slots remain STACK_ZERO
5024 	 */
5025 	bool zero_used = false;
5026 
5027 	cur = env->cur_state->frame[env->cur_state->curframe];
5028 	ptr_reg = &cur->regs[ptr_regno];
5029 	min_off = ptr_reg->smin_value + off;
5030 	max_off = ptr_reg->smax_value + off + size;
5031 	if (value_regno >= 0)
5032 		value_reg = &cur->regs[value_regno];
5033 	if ((value_reg && register_is_null(value_reg)) ||
5034 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
5035 		writing_zero = true;
5036 
5037 	for (i = min_off; i < max_off; i++) {
5038 		int spi;
5039 
5040 		spi = __get_spi(i);
5041 		err = destroy_if_dynptr_stack_slot(env, state, spi);
5042 		if (err)
5043 			return err;
5044 	}
5045 
5046 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
5047 	/* Variable offset writes destroy any spilled pointers in range. */
5048 	for (i = min_off; i < max_off; i++) {
5049 		u8 new_type, *stype;
5050 		int slot, spi;
5051 
5052 		slot = -i - 1;
5053 		spi = slot / BPF_REG_SIZE;
5054 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5055 		mark_stack_slot_scratched(env, spi);
5056 
5057 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
5058 			/* Reject the write if range we may write to has not
5059 			 * been initialized beforehand. If we didn't reject
5060 			 * here, the ptr status would be erased below (even
5061 			 * though not all slots are actually overwritten),
5062 			 * possibly opening the door to leaks.
5063 			 *
5064 			 * We do however catch STACK_INVALID case below, and
5065 			 * only allow reading possibly uninitialized memory
5066 			 * later for CAP_PERFMON, as the write may not happen to
5067 			 * that slot.
5068 			 */
5069 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
5070 				insn_idx, i);
5071 			return -EINVAL;
5072 		}
5073 
5074 		/* If writing_zero and the spi slot contains a spill of value 0,
5075 		 * maintain the spill type.
5076 		 */
5077 		if (writing_zero && *stype == STACK_SPILL &&
5078 		    is_spilled_scalar_reg(&state->stack[spi])) {
5079 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
5080 
5081 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
5082 				zero_used = true;
5083 				continue;
5084 			}
5085 		}
5086 
5087 		/* Erase all other spilled pointers. */
5088 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5089 
5090 		/* Update the slot type. */
5091 		new_type = STACK_MISC;
5092 		if (writing_zero && *stype == STACK_ZERO) {
5093 			new_type = STACK_ZERO;
5094 			zero_used = true;
5095 		}
5096 		/* If the slot is STACK_INVALID, we check whether it's OK to
5097 		 * pretend that it will be initialized by this write. The slot
5098 		 * might not actually be written to, and so if we mark it as
5099 		 * initialized future reads might leak uninitialized memory.
5100 		 * For privileged programs, we will accept such reads to slots
5101 		 * that may or may not be written because, if we're reject
5102 		 * them, the error would be too confusing.
5103 		 */
5104 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
5105 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
5106 					insn_idx, i);
5107 			return -EINVAL;
5108 		}
5109 		*stype = new_type;
5110 	}
5111 	if (zero_used) {
5112 		/* backtracking doesn't work for STACK_ZERO yet. */
5113 		err = mark_chain_precision(env, value_regno);
5114 		if (err)
5115 			return err;
5116 	}
5117 	return 0;
5118 }
5119 
5120 /* When register 'dst_regno' is assigned some values from stack[min_off,
5121  * max_off), we set the register's type according to the types of the
5122  * respective stack slots. If all the stack values are known to be zeros, then
5123  * so is the destination reg. Otherwise, the register is considered to be
5124  * SCALAR. This function does not deal with register filling; the caller must
5125  * ensure that all spilled registers in the stack range have been marked as
5126  * read.
5127  */
5128 static void mark_reg_stack_read(struct bpf_verifier_env *env,
5129 				/* func where src register points to */
5130 				struct bpf_func_state *ptr_state,
5131 				int min_off, int max_off, int dst_regno)
5132 {
5133 	struct bpf_verifier_state *vstate = env->cur_state;
5134 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5135 	int i, slot, spi;
5136 	u8 *stype;
5137 	int zeros = 0;
5138 
5139 	for (i = min_off; i < max_off; i++) {
5140 		slot = -i - 1;
5141 		spi = slot / BPF_REG_SIZE;
5142 		mark_stack_slot_scratched(env, spi);
5143 		stype = ptr_state->stack[spi].slot_type;
5144 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
5145 			break;
5146 		zeros++;
5147 	}
5148 	if (zeros == max_off - min_off) {
5149 		/* Any access_size read into register is zero extended,
5150 		 * so the whole register == const_zero.
5151 		 */
5152 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
5153 	} else {
5154 		/* have read misc data from the stack */
5155 		mark_reg_unknown(env, state->regs, dst_regno);
5156 	}
5157 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5158 }
5159 
5160 /* Read the stack at 'off' and put the results into the register indicated by
5161  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
5162  * spilled reg.
5163  *
5164  * 'dst_regno' can be -1, meaning that the read value is not going to a
5165  * register.
5166  *
5167  * The access is assumed to be within the current stack bounds.
5168  */
5169 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
5170 				      /* func where src register points to */
5171 				      struct bpf_func_state *reg_state,
5172 				      int off, int size, int dst_regno)
5173 {
5174 	struct bpf_verifier_state *vstate = env->cur_state;
5175 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5176 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
5177 	struct bpf_reg_state *reg;
5178 	u8 *stype, type;
5179 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
5180 
5181 	stype = reg_state->stack[spi].slot_type;
5182 	reg = &reg_state->stack[spi].spilled_ptr;
5183 
5184 	mark_stack_slot_scratched(env, spi);
5185 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
5186 
5187 	if (is_spilled_reg(&reg_state->stack[spi])) {
5188 		u8 spill_size = 1;
5189 
5190 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
5191 			spill_size++;
5192 
5193 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
5194 			if (reg->type != SCALAR_VALUE) {
5195 				verbose_linfo(env, env->insn_idx, "; ");
5196 				verbose(env, "invalid size of register fill\n");
5197 				return -EACCES;
5198 			}
5199 
5200 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5201 			if (dst_regno < 0)
5202 				return 0;
5203 
5204 			if (size <= spill_size &&
5205 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
5206 				/* The earlier check_reg_arg() has decided the
5207 				 * subreg_def for this insn.  Save it first.
5208 				 */
5209 				s32 subreg_def = state->regs[dst_regno].subreg_def;
5210 
5211 				copy_register_state(&state->regs[dst_regno], reg);
5212 				state->regs[dst_regno].subreg_def = subreg_def;
5213 
5214 				/* Break the relation on a narrowing fill.
5215 				 * coerce_reg_to_size will adjust the boundaries.
5216 				 */
5217 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
5218 					state->regs[dst_regno].id = 0;
5219 			} else {
5220 				int spill_cnt = 0, zero_cnt = 0;
5221 
5222 				for (i = 0; i < size; i++) {
5223 					type = stype[(slot - i) % BPF_REG_SIZE];
5224 					if (type == STACK_SPILL) {
5225 						spill_cnt++;
5226 						continue;
5227 					}
5228 					if (type == STACK_MISC)
5229 						continue;
5230 					if (type == STACK_ZERO) {
5231 						zero_cnt++;
5232 						continue;
5233 					}
5234 					if (type == STACK_INVALID && env->allow_uninit_stack)
5235 						continue;
5236 					verbose(env, "invalid read from stack off %d+%d size %d\n",
5237 						off, i, size);
5238 					return -EACCES;
5239 				}
5240 
5241 				if (spill_cnt == size &&
5242 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
5243 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5244 					/* this IS register fill, so keep insn_flags */
5245 				} else if (zero_cnt == size) {
5246 					/* similarly to mark_reg_stack_read(), preserve zeroes */
5247 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5248 					insn_flags = 0; /* not restoring original register state */
5249 				} else {
5250 					mark_reg_unknown(env, state->regs, dst_regno);
5251 					insn_flags = 0; /* not restoring original register state */
5252 				}
5253 			}
5254 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5255 		} else if (dst_regno >= 0) {
5256 			/* restore register state from stack */
5257 			copy_register_state(&state->regs[dst_regno], reg);
5258 			/* mark reg as written since spilled pointer state likely
5259 			 * has its liveness marks cleared by is_state_visited()
5260 			 * which resets stack/reg liveness for state transitions
5261 			 */
5262 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5263 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5264 			/* If dst_regno==-1, the caller is asking us whether
5265 			 * it is acceptable to use this value as a SCALAR_VALUE
5266 			 * (e.g. for XADD).
5267 			 * We must not allow unprivileged callers to do that
5268 			 * with spilled pointers.
5269 			 */
5270 			verbose(env, "leaking pointer from stack off %d\n",
5271 				off);
5272 			return -EACCES;
5273 		}
5274 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5275 	} else {
5276 		for (i = 0; i < size; i++) {
5277 			type = stype[(slot - i) % BPF_REG_SIZE];
5278 			if (type == STACK_MISC)
5279 				continue;
5280 			if (type == STACK_ZERO)
5281 				continue;
5282 			if (type == STACK_INVALID && env->allow_uninit_stack)
5283 				continue;
5284 			verbose(env, "invalid read from stack off %d+%d size %d\n",
5285 				off, i, size);
5286 			return -EACCES;
5287 		}
5288 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5289 		if (dst_regno >= 0)
5290 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5291 		insn_flags = 0; /* we are not restoring spilled register */
5292 	}
5293 	if (insn_flags)
5294 		return push_insn_history(env, env->cur_state, insn_flags, 0);
5295 	return 0;
5296 }
5297 
5298 enum bpf_access_src {
5299 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5300 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
5301 };
5302 
5303 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5304 					 int regno, int off, int access_size,
5305 					 bool zero_size_allowed,
5306 					 enum bpf_access_type type,
5307 					 struct bpf_call_arg_meta *meta);
5308 
5309 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5310 {
5311 	return cur_regs(env) + regno;
5312 }
5313 
5314 /* Read the stack at 'ptr_regno + off' and put the result into the register
5315  * 'dst_regno'.
5316  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5317  * but not its variable offset.
5318  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5319  *
5320  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5321  * filling registers (i.e. reads of spilled register cannot be detected when
5322  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5323  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5324  * offset; for a fixed offset check_stack_read_fixed_off should be used
5325  * instead.
5326  */
5327 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5328 				    int ptr_regno, int off, int size, int dst_regno)
5329 {
5330 	/* The state of the source register. */
5331 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5332 	struct bpf_func_state *ptr_state = func(env, reg);
5333 	int err;
5334 	int min_off, max_off;
5335 
5336 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5337 	 */
5338 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5339 					    false, BPF_READ, NULL);
5340 	if (err)
5341 		return err;
5342 
5343 	min_off = reg->smin_value + off;
5344 	max_off = reg->smax_value + off;
5345 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5346 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5347 	return 0;
5348 }
5349 
5350 /* check_stack_read dispatches to check_stack_read_fixed_off or
5351  * check_stack_read_var_off.
5352  *
5353  * The caller must ensure that the offset falls within the allocated stack
5354  * bounds.
5355  *
5356  * 'dst_regno' is a register which will receive the value from the stack. It
5357  * can be -1, meaning that the read value is not going to a register.
5358  */
5359 static int check_stack_read(struct bpf_verifier_env *env,
5360 			    int ptr_regno, int off, int size,
5361 			    int dst_regno)
5362 {
5363 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5364 	struct bpf_func_state *state = func(env, reg);
5365 	int err;
5366 	/* Some accesses are only permitted with a static offset. */
5367 	bool var_off = !tnum_is_const(reg->var_off);
5368 
5369 	/* The offset is required to be static when reads don't go to a
5370 	 * register, in order to not leak pointers (see
5371 	 * check_stack_read_fixed_off).
5372 	 */
5373 	if (dst_regno < 0 && var_off) {
5374 		char tn_buf[48];
5375 
5376 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5377 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5378 			tn_buf, off, size);
5379 		return -EACCES;
5380 	}
5381 	/* Variable offset is prohibited for unprivileged mode for simplicity
5382 	 * since it requires corresponding support in Spectre masking for stack
5383 	 * ALU. See also retrieve_ptr_limit(). The check in
5384 	 * check_stack_access_for_ptr_arithmetic() called by
5385 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5386 	 * with variable offsets, therefore no check is required here. Further,
5387 	 * just checking it here would be insufficient as speculative stack
5388 	 * writes could still lead to unsafe speculative behaviour.
5389 	 */
5390 	if (!var_off) {
5391 		off += reg->var_off.value;
5392 		err = check_stack_read_fixed_off(env, state, off, size,
5393 						 dst_regno);
5394 	} else {
5395 		/* Variable offset stack reads need more conservative handling
5396 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5397 		 * branch.
5398 		 */
5399 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5400 					       dst_regno);
5401 	}
5402 	return err;
5403 }
5404 
5405 
5406 /* check_stack_write dispatches to check_stack_write_fixed_off or
5407  * check_stack_write_var_off.
5408  *
5409  * 'ptr_regno' is the register used as a pointer into the stack.
5410  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5411  * 'value_regno' is the register whose value we're writing to the stack. It can
5412  * be -1, meaning that we're not writing from a register.
5413  *
5414  * The caller must ensure that the offset falls within the maximum stack size.
5415  */
5416 static int check_stack_write(struct bpf_verifier_env *env,
5417 			     int ptr_regno, int off, int size,
5418 			     int value_regno, int insn_idx)
5419 {
5420 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5421 	struct bpf_func_state *state = func(env, reg);
5422 	int err;
5423 
5424 	if (tnum_is_const(reg->var_off)) {
5425 		off += reg->var_off.value;
5426 		err = check_stack_write_fixed_off(env, state, off, size,
5427 						  value_regno, insn_idx);
5428 	} else {
5429 		/* Variable offset stack reads need more conservative handling
5430 		 * than fixed offset ones.
5431 		 */
5432 		err = check_stack_write_var_off(env, state,
5433 						ptr_regno, off, size,
5434 						value_regno, insn_idx);
5435 	}
5436 	return err;
5437 }
5438 
5439 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5440 				 int off, int size, enum bpf_access_type type)
5441 {
5442 	struct bpf_reg_state *regs = cur_regs(env);
5443 	struct bpf_map *map = regs[regno].map_ptr;
5444 	u32 cap = bpf_map_flags_to_cap(map);
5445 
5446 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5447 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5448 			map->value_size, off, size);
5449 		return -EACCES;
5450 	}
5451 
5452 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5453 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5454 			map->value_size, off, size);
5455 		return -EACCES;
5456 	}
5457 
5458 	return 0;
5459 }
5460 
5461 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5462 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5463 			      int off, int size, u32 mem_size,
5464 			      bool zero_size_allowed)
5465 {
5466 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5467 	struct bpf_reg_state *reg;
5468 
5469 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5470 		return 0;
5471 
5472 	reg = &cur_regs(env)[regno];
5473 	switch (reg->type) {
5474 	case PTR_TO_MAP_KEY:
5475 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5476 			mem_size, off, size);
5477 		break;
5478 	case PTR_TO_MAP_VALUE:
5479 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5480 			mem_size, off, size);
5481 		break;
5482 	case PTR_TO_PACKET:
5483 	case PTR_TO_PACKET_META:
5484 	case PTR_TO_PACKET_END:
5485 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5486 			off, size, regno, reg->id, off, mem_size);
5487 		break;
5488 	case PTR_TO_MEM:
5489 	default:
5490 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5491 			mem_size, off, size);
5492 	}
5493 
5494 	return -EACCES;
5495 }
5496 
5497 /* check read/write into a memory region with possible variable offset */
5498 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5499 				   int off, int size, u32 mem_size,
5500 				   bool zero_size_allowed)
5501 {
5502 	struct bpf_verifier_state *vstate = env->cur_state;
5503 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5504 	struct bpf_reg_state *reg = &state->regs[regno];
5505 	int err;
5506 
5507 	/* We may have adjusted the register pointing to memory region, so we
5508 	 * need to try adding each of min_value and max_value to off
5509 	 * to make sure our theoretical access will be safe.
5510 	 *
5511 	 * The minimum value is only important with signed
5512 	 * comparisons where we can't assume the floor of a
5513 	 * value is 0.  If we are using signed variables for our
5514 	 * index'es we need to make sure that whatever we use
5515 	 * will have a set floor within our range.
5516 	 */
5517 	if (reg->smin_value < 0 &&
5518 	    (reg->smin_value == S64_MIN ||
5519 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5520 	      reg->smin_value + off < 0)) {
5521 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5522 			regno);
5523 		return -EACCES;
5524 	}
5525 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5526 				 mem_size, zero_size_allowed);
5527 	if (err) {
5528 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5529 			regno);
5530 		return err;
5531 	}
5532 
5533 	/* If we haven't set a max value then we need to bail since we can't be
5534 	 * sure we won't do bad things.
5535 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5536 	 */
5537 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5538 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5539 			regno);
5540 		return -EACCES;
5541 	}
5542 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5543 				 mem_size, zero_size_allowed);
5544 	if (err) {
5545 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5546 			regno);
5547 		return err;
5548 	}
5549 
5550 	return 0;
5551 }
5552 
5553 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5554 			       const struct bpf_reg_state *reg, int regno,
5555 			       bool fixed_off_ok)
5556 {
5557 	/* Access to this pointer-typed register or passing it to a helper
5558 	 * is only allowed in its original, unmodified form.
5559 	 */
5560 
5561 	if (reg->off < 0) {
5562 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5563 			reg_type_str(env, reg->type), regno, reg->off);
5564 		return -EACCES;
5565 	}
5566 
5567 	if (!fixed_off_ok && reg->off) {
5568 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5569 			reg_type_str(env, reg->type), regno, reg->off);
5570 		return -EACCES;
5571 	}
5572 
5573 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5574 		char tn_buf[48];
5575 
5576 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5577 		verbose(env, "variable %s access var_off=%s disallowed\n",
5578 			reg_type_str(env, reg->type), tn_buf);
5579 		return -EACCES;
5580 	}
5581 
5582 	return 0;
5583 }
5584 
5585 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5586 		             const struct bpf_reg_state *reg, int regno)
5587 {
5588 	return __check_ptr_off_reg(env, reg, regno, false);
5589 }
5590 
5591 static int map_kptr_match_type(struct bpf_verifier_env *env,
5592 			       struct btf_field *kptr_field,
5593 			       struct bpf_reg_state *reg, u32 regno)
5594 {
5595 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5596 	int perm_flags;
5597 	const char *reg_name = "";
5598 
5599 	if (btf_is_kernel(reg->btf)) {
5600 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5601 
5602 		/* Only unreferenced case accepts untrusted pointers */
5603 		if (kptr_field->type == BPF_KPTR_UNREF)
5604 			perm_flags |= PTR_UNTRUSTED;
5605 	} else {
5606 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5607 		if (kptr_field->type == BPF_KPTR_PERCPU)
5608 			perm_flags |= MEM_PERCPU;
5609 	}
5610 
5611 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5612 		goto bad_type;
5613 
5614 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5615 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5616 
5617 	/* For ref_ptr case, release function check should ensure we get one
5618 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5619 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5620 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5621 	 * reg->off and reg->ref_obj_id are not needed here.
5622 	 */
5623 	if (__check_ptr_off_reg(env, reg, regno, true))
5624 		return -EACCES;
5625 
5626 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5627 	 * we also need to take into account the reg->off.
5628 	 *
5629 	 * We want to support cases like:
5630 	 *
5631 	 * struct foo {
5632 	 *         struct bar br;
5633 	 *         struct baz bz;
5634 	 * };
5635 	 *
5636 	 * struct foo *v;
5637 	 * v = func();	      // PTR_TO_BTF_ID
5638 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5639 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5640 	 *                    // first member type of struct after comparison fails
5641 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5642 	 *                    // to match type
5643 	 *
5644 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5645 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5646 	 * the struct to match type against first member of struct, i.e. reject
5647 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5648 	 * strict mode to true for type match.
5649 	 */
5650 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5651 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5652 				  kptr_field->type != BPF_KPTR_UNREF))
5653 		goto bad_type;
5654 	return 0;
5655 bad_type:
5656 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5657 		reg_type_str(env, reg->type), reg_name);
5658 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5659 	if (kptr_field->type == BPF_KPTR_UNREF)
5660 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5661 			targ_name);
5662 	else
5663 		verbose(env, "\n");
5664 	return -EINVAL;
5665 }
5666 
5667 static bool in_sleepable(struct bpf_verifier_env *env)
5668 {
5669 	return env->prog->sleepable ||
5670 	       (env->cur_state && env->cur_state->in_sleepable);
5671 }
5672 
5673 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5674  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5675  */
5676 static bool in_rcu_cs(struct bpf_verifier_env *env)
5677 {
5678 	return env->cur_state->active_rcu_lock ||
5679 	       env->cur_state->active_locks ||
5680 	       !in_sleepable(env);
5681 }
5682 
5683 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5684 BTF_SET_START(rcu_protected_types)
5685 #ifdef CONFIG_NET
5686 BTF_ID(struct, prog_test_ref_kfunc)
5687 #endif
5688 #ifdef CONFIG_CGROUPS
5689 BTF_ID(struct, cgroup)
5690 #endif
5691 #ifdef CONFIG_BPF_JIT
5692 BTF_ID(struct, bpf_cpumask)
5693 #endif
5694 BTF_ID(struct, task_struct)
5695 #ifdef CONFIG_CRYPTO
5696 BTF_ID(struct, bpf_crypto_ctx)
5697 #endif
5698 BTF_SET_END(rcu_protected_types)
5699 
5700 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5701 {
5702 	if (!btf_is_kernel(btf))
5703 		return true;
5704 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5705 }
5706 
5707 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5708 {
5709 	struct btf_struct_meta *meta;
5710 
5711 	if (btf_is_kernel(kptr_field->kptr.btf))
5712 		return NULL;
5713 
5714 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5715 				    kptr_field->kptr.btf_id);
5716 
5717 	return meta ? meta->record : NULL;
5718 }
5719 
5720 static bool rcu_safe_kptr(const struct btf_field *field)
5721 {
5722 	const struct btf_field_kptr *kptr = &field->kptr;
5723 
5724 	return field->type == BPF_KPTR_PERCPU ||
5725 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5726 }
5727 
5728 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5729 {
5730 	struct btf_record *rec;
5731 	u32 ret;
5732 
5733 	ret = PTR_MAYBE_NULL;
5734 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5735 		ret |= MEM_RCU;
5736 		if (kptr_field->type == BPF_KPTR_PERCPU)
5737 			ret |= MEM_PERCPU;
5738 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5739 			ret |= MEM_ALLOC;
5740 
5741 		rec = kptr_pointee_btf_record(kptr_field);
5742 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5743 			ret |= NON_OWN_REF;
5744 	} else {
5745 		ret |= PTR_UNTRUSTED;
5746 	}
5747 
5748 	return ret;
5749 }
5750 
5751 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
5752 			    struct btf_field *field)
5753 {
5754 	struct bpf_reg_state *reg;
5755 	const struct btf_type *t;
5756 
5757 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
5758 	mark_reg_known_zero(env, cur_regs(env), regno);
5759 	reg = reg_state(env, regno);
5760 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5761 	reg->mem_size = t->size;
5762 	reg->id = ++env->id_gen;
5763 
5764 	return 0;
5765 }
5766 
5767 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5768 				 int value_regno, int insn_idx,
5769 				 struct btf_field *kptr_field)
5770 {
5771 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5772 	int class = BPF_CLASS(insn->code);
5773 	struct bpf_reg_state *val_reg;
5774 
5775 	/* Things we already checked for in check_map_access and caller:
5776 	 *  - Reject cases where variable offset may touch kptr
5777 	 *  - size of access (must be BPF_DW)
5778 	 *  - tnum_is_const(reg->var_off)
5779 	 *  - kptr_field->offset == off + reg->var_off.value
5780 	 */
5781 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5782 	if (BPF_MODE(insn->code) != BPF_MEM) {
5783 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5784 		return -EACCES;
5785 	}
5786 
5787 	/* We only allow loading referenced kptr, since it will be marked as
5788 	 * untrusted, similar to unreferenced kptr.
5789 	 */
5790 	if (class != BPF_LDX &&
5791 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5792 		verbose(env, "store to referenced kptr disallowed\n");
5793 		return -EACCES;
5794 	}
5795 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
5796 		verbose(env, "store to uptr disallowed\n");
5797 		return -EACCES;
5798 	}
5799 
5800 	if (class == BPF_LDX) {
5801 		if (kptr_field->type == BPF_UPTR)
5802 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
5803 
5804 		/* We can simply mark the value_regno receiving the pointer
5805 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5806 		 */
5807 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5808 				kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5809 	} else if (class == BPF_STX) {
5810 		val_reg = reg_state(env, value_regno);
5811 		if (!register_is_null(val_reg) &&
5812 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5813 			return -EACCES;
5814 	} else if (class == BPF_ST) {
5815 		if (insn->imm) {
5816 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5817 				kptr_field->offset);
5818 			return -EACCES;
5819 		}
5820 	} else {
5821 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5822 		return -EACCES;
5823 	}
5824 	return 0;
5825 }
5826 
5827 /* check read/write into a map element with possible variable offset */
5828 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5829 			    int off, int size, bool zero_size_allowed,
5830 			    enum bpf_access_src src)
5831 {
5832 	struct bpf_verifier_state *vstate = env->cur_state;
5833 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5834 	struct bpf_reg_state *reg = &state->regs[regno];
5835 	struct bpf_map *map = reg->map_ptr;
5836 	struct btf_record *rec;
5837 	int err, i;
5838 
5839 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5840 				      zero_size_allowed);
5841 	if (err)
5842 		return err;
5843 
5844 	if (IS_ERR_OR_NULL(map->record))
5845 		return 0;
5846 	rec = map->record;
5847 	for (i = 0; i < rec->cnt; i++) {
5848 		struct btf_field *field = &rec->fields[i];
5849 		u32 p = field->offset;
5850 
5851 		/* If any part of a field  can be touched by load/store, reject
5852 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5853 		 * it is sufficient to check x1 < y2 && y1 < x2.
5854 		 */
5855 		if (reg->smin_value + off < p + field->size &&
5856 		    p < reg->umax_value + off + size) {
5857 			switch (field->type) {
5858 			case BPF_KPTR_UNREF:
5859 			case BPF_KPTR_REF:
5860 			case BPF_KPTR_PERCPU:
5861 			case BPF_UPTR:
5862 				if (src != ACCESS_DIRECT) {
5863 					verbose(env, "%s cannot be accessed indirectly by helper\n",
5864 						btf_field_type_name(field->type));
5865 					return -EACCES;
5866 				}
5867 				if (!tnum_is_const(reg->var_off)) {
5868 					verbose(env, "%s access cannot have variable offset\n",
5869 						btf_field_type_name(field->type));
5870 					return -EACCES;
5871 				}
5872 				if (p != off + reg->var_off.value) {
5873 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
5874 						btf_field_type_name(field->type),
5875 						p, off + reg->var_off.value);
5876 					return -EACCES;
5877 				}
5878 				if (size != bpf_size_to_bytes(BPF_DW)) {
5879 					verbose(env, "%s access size must be BPF_DW\n",
5880 						btf_field_type_name(field->type));
5881 					return -EACCES;
5882 				}
5883 				break;
5884 			default:
5885 				verbose(env, "%s cannot be accessed directly by load/store\n",
5886 					btf_field_type_name(field->type));
5887 				return -EACCES;
5888 			}
5889 		}
5890 	}
5891 	return 0;
5892 }
5893 
5894 #define MAX_PACKET_OFF 0xffff
5895 
5896 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5897 				       const struct bpf_call_arg_meta *meta,
5898 				       enum bpf_access_type t)
5899 {
5900 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5901 
5902 	switch (prog_type) {
5903 	/* Program types only with direct read access go here! */
5904 	case BPF_PROG_TYPE_LWT_IN:
5905 	case BPF_PROG_TYPE_LWT_OUT:
5906 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5907 	case BPF_PROG_TYPE_SK_REUSEPORT:
5908 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5909 	case BPF_PROG_TYPE_CGROUP_SKB:
5910 		if (t == BPF_WRITE)
5911 			return false;
5912 		fallthrough;
5913 
5914 	/* Program types with direct read + write access go here! */
5915 	case BPF_PROG_TYPE_SCHED_CLS:
5916 	case BPF_PROG_TYPE_SCHED_ACT:
5917 	case BPF_PROG_TYPE_XDP:
5918 	case BPF_PROG_TYPE_LWT_XMIT:
5919 	case BPF_PROG_TYPE_SK_SKB:
5920 	case BPF_PROG_TYPE_SK_MSG:
5921 		if (meta)
5922 			return meta->pkt_access;
5923 
5924 		env->seen_direct_write = true;
5925 		return true;
5926 
5927 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5928 		if (t == BPF_WRITE)
5929 			env->seen_direct_write = true;
5930 
5931 		return true;
5932 
5933 	default:
5934 		return false;
5935 	}
5936 }
5937 
5938 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5939 			       int size, bool zero_size_allowed)
5940 {
5941 	struct bpf_reg_state *regs = cur_regs(env);
5942 	struct bpf_reg_state *reg = &regs[regno];
5943 	int err;
5944 
5945 	/* We may have added a variable offset to the packet pointer; but any
5946 	 * reg->range we have comes after that.  We are only checking the fixed
5947 	 * offset.
5948 	 */
5949 
5950 	/* We don't allow negative numbers, because we aren't tracking enough
5951 	 * detail to prove they're safe.
5952 	 */
5953 	if (reg->smin_value < 0) {
5954 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5955 			regno);
5956 		return -EACCES;
5957 	}
5958 
5959 	err = reg->range < 0 ? -EINVAL :
5960 	      __check_mem_access(env, regno, off, size, reg->range,
5961 				 zero_size_allowed);
5962 	if (err) {
5963 		verbose(env, "R%d offset is outside of the packet\n", regno);
5964 		return err;
5965 	}
5966 
5967 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5968 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5969 	 * otherwise find_good_pkt_pointers would have refused to set range info
5970 	 * that __check_mem_access would have rejected this pkt access.
5971 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5972 	 */
5973 	env->prog->aux->max_pkt_offset =
5974 		max_t(u32, env->prog->aux->max_pkt_offset,
5975 		      off + reg->umax_value + size - 1);
5976 
5977 	return err;
5978 }
5979 
5980 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5981 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5982 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5983 			    struct btf **btf, u32 *btf_id, bool *is_retval, bool is_ldsx)
5984 {
5985 	struct bpf_insn_access_aux info = {
5986 		.reg_type = *reg_type,
5987 		.log = &env->log,
5988 		.is_retval = false,
5989 		.is_ldsx = is_ldsx,
5990 	};
5991 
5992 	if (env->ops->is_valid_access &&
5993 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5994 		/* A non zero info.ctx_field_size indicates that this field is a
5995 		 * candidate for later verifier transformation to load the whole
5996 		 * field and then apply a mask when accessed with a narrower
5997 		 * access than actual ctx access size. A zero info.ctx_field_size
5998 		 * will only allow for whole field access and rejects any other
5999 		 * type of narrower access.
6000 		 */
6001 		*reg_type = info.reg_type;
6002 		*is_retval = info.is_retval;
6003 
6004 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
6005 			*btf = info.btf;
6006 			*btf_id = info.btf_id;
6007 		} else {
6008 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
6009 		}
6010 		/* remember the offset of last byte accessed in ctx */
6011 		if (env->prog->aux->max_ctx_offset < off + size)
6012 			env->prog->aux->max_ctx_offset = off + size;
6013 		return 0;
6014 	}
6015 
6016 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
6017 	return -EACCES;
6018 }
6019 
6020 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
6021 				  int size)
6022 {
6023 	if (size < 0 || off < 0 ||
6024 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
6025 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
6026 			off, size);
6027 		return -EACCES;
6028 	}
6029 	return 0;
6030 }
6031 
6032 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
6033 			     u32 regno, int off, int size,
6034 			     enum bpf_access_type t)
6035 {
6036 	struct bpf_reg_state *regs = cur_regs(env);
6037 	struct bpf_reg_state *reg = &regs[regno];
6038 	struct bpf_insn_access_aux info = {};
6039 	bool valid;
6040 
6041 	if (reg->smin_value < 0) {
6042 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6043 			regno);
6044 		return -EACCES;
6045 	}
6046 
6047 	switch (reg->type) {
6048 	case PTR_TO_SOCK_COMMON:
6049 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
6050 		break;
6051 	case PTR_TO_SOCKET:
6052 		valid = bpf_sock_is_valid_access(off, size, t, &info);
6053 		break;
6054 	case PTR_TO_TCP_SOCK:
6055 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
6056 		break;
6057 	case PTR_TO_XDP_SOCK:
6058 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
6059 		break;
6060 	default:
6061 		valid = false;
6062 	}
6063 
6064 
6065 	if (valid) {
6066 		env->insn_aux_data[insn_idx].ctx_field_size =
6067 			info.ctx_field_size;
6068 		return 0;
6069 	}
6070 
6071 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
6072 		regno, reg_type_str(env, reg->type), off, size);
6073 
6074 	return -EACCES;
6075 }
6076 
6077 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
6078 {
6079 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
6080 }
6081 
6082 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
6083 {
6084 	const struct bpf_reg_state *reg = reg_state(env, regno);
6085 
6086 	return reg->type == PTR_TO_CTX;
6087 }
6088 
6089 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
6090 {
6091 	const struct bpf_reg_state *reg = reg_state(env, regno);
6092 
6093 	return type_is_sk_pointer(reg->type);
6094 }
6095 
6096 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
6097 {
6098 	const struct bpf_reg_state *reg = reg_state(env, regno);
6099 
6100 	return type_is_pkt_pointer(reg->type);
6101 }
6102 
6103 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
6104 {
6105 	const struct bpf_reg_state *reg = reg_state(env, regno);
6106 
6107 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
6108 	return reg->type == PTR_TO_FLOW_KEYS;
6109 }
6110 
6111 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
6112 {
6113 	const struct bpf_reg_state *reg = reg_state(env, regno);
6114 
6115 	return reg->type == PTR_TO_ARENA;
6116 }
6117 
6118 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
6119 #ifdef CONFIG_NET
6120 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
6121 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6122 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
6123 #endif
6124 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
6125 };
6126 
6127 static bool is_trusted_reg(const struct bpf_reg_state *reg)
6128 {
6129 	/* A referenced register is always trusted. */
6130 	if (reg->ref_obj_id)
6131 		return true;
6132 
6133 	/* Types listed in the reg2btf_ids are always trusted */
6134 	if (reg2btf_ids[base_type(reg->type)] &&
6135 	    !bpf_type_has_unsafe_modifiers(reg->type))
6136 		return true;
6137 
6138 	/* If a register is not referenced, it is trusted if it has the
6139 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
6140 	 * other type modifiers may be safe, but we elect to take an opt-in
6141 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
6142 	 * not.
6143 	 *
6144 	 * Eventually, we should make PTR_TRUSTED the single source of truth
6145 	 * for whether a register is trusted.
6146 	 */
6147 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
6148 	       !bpf_type_has_unsafe_modifiers(reg->type);
6149 }
6150 
6151 static bool is_rcu_reg(const struct bpf_reg_state *reg)
6152 {
6153 	return reg->type & MEM_RCU;
6154 }
6155 
6156 static void clear_trusted_flags(enum bpf_type_flag *flag)
6157 {
6158 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
6159 }
6160 
6161 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
6162 				   const struct bpf_reg_state *reg,
6163 				   int off, int size, bool strict)
6164 {
6165 	struct tnum reg_off;
6166 	int ip_align;
6167 
6168 	/* Byte size accesses are always allowed. */
6169 	if (!strict || size == 1)
6170 		return 0;
6171 
6172 	/* For platforms that do not have a Kconfig enabling
6173 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
6174 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
6175 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
6176 	 * to this code only in strict mode where we want to emulate
6177 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
6178 	 * unconditional IP align value of '2'.
6179 	 */
6180 	ip_align = 2;
6181 
6182 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
6183 	if (!tnum_is_aligned(reg_off, size)) {
6184 		char tn_buf[48];
6185 
6186 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6187 		verbose(env,
6188 			"misaligned packet access off %d+%s+%d+%d size %d\n",
6189 			ip_align, tn_buf, reg->off, off, size);
6190 		return -EACCES;
6191 	}
6192 
6193 	return 0;
6194 }
6195 
6196 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
6197 				       const struct bpf_reg_state *reg,
6198 				       const char *pointer_desc,
6199 				       int off, int size, bool strict)
6200 {
6201 	struct tnum reg_off;
6202 
6203 	/* Byte size accesses are always allowed. */
6204 	if (!strict || size == 1)
6205 		return 0;
6206 
6207 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
6208 	if (!tnum_is_aligned(reg_off, size)) {
6209 		char tn_buf[48];
6210 
6211 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6212 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
6213 			pointer_desc, tn_buf, reg->off, off, size);
6214 		return -EACCES;
6215 	}
6216 
6217 	return 0;
6218 }
6219 
6220 static int check_ptr_alignment(struct bpf_verifier_env *env,
6221 			       const struct bpf_reg_state *reg, int off,
6222 			       int size, bool strict_alignment_once)
6223 {
6224 	bool strict = env->strict_alignment || strict_alignment_once;
6225 	const char *pointer_desc = "";
6226 
6227 	switch (reg->type) {
6228 	case PTR_TO_PACKET:
6229 	case PTR_TO_PACKET_META:
6230 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
6231 		 * right in front, treat it the very same way.
6232 		 */
6233 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
6234 	case PTR_TO_FLOW_KEYS:
6235 		pointer_desc = "flow keys ";
6236 		break;
6237 	case PTR_TO_MAP_KEY:
6238 		pointer_desc = "key ";
6239 		break;
6240 	case PTR_TO_MAP_VALUE:
6241 		pointer_desc = "value ";
6242 		break;
6243 	case PTR_TO_CTX:
6244 		pointer_desc = "context ";
6245 		break;
6246 	case PTR_TO_STACK:
6247 		pointer_desc = "stack ";
6248 		/* The stack spill tracking logic in check_stack_write_fixed_off()
6249 		 * and check_stack_read_fixed_off() relies on stack accesses being
6250 		 * aligned.
6251 		 */
6252 		strict = true;
6253 		break;
6254 	case PTR_TO_SOCKET:
6255 		pointer_desc = "sock ";
6256 		break;
6257 	case PTR_TO_SOCK_COMMON:
6258 		pointer_desc = "sock_common ";
6259 		break;
6260 	case PTR_TO_TCP_SOCK:
6261 		pointer_desc = "tcp_sock ";
6262 		break;
6263 	case PTR_TO_XDP_SOCK:
6264 		pointer_desc = "xdp_sock ";
6265 		break;
6266 	case PTR_TO_ARENA:
6267 		return 0;
6268 	default:
6269 		break;
6270 	}
6271 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
6272 					   strict);
6273 }
6274 
6275 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
6276 {
6277 	if (!bpf_jit_supports_private_stack())
6278 		return NO_PRIV_STACK;
6279 
6280 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
6281 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
6282 	 * explicitly.
6283 	 */
6284 	switch (prog->type) {
6285 	case BPF_PROG_TYPE_KPROBE:
6286 	case BPF_PROG_TYPE_TRACEPOINT:
6287 	case BPF_PROG_TYPE_PERF_EVENT:
6288 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6289 		return PRIV_STACK_ADAPTIVE;
6290 	case BPF_PROG_TYPE_TRACING:
6291 	case BPF_PROG_TYPE_LSM:
6292 	case BPF_PROG_TYPE_STRUCT_OPS:
6293 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
6294 			return PRIV_STACK_ADAPTIVE;
6295 		fallthrough;
6296 	default:
6297 		break;
6298 	}
6299 
6300 	return NO_PRIV_STACK;
6301 }
6302 
6303 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
6304 {
6305 	if (env->prog->jit_requested)
6306 		return round_up(stack_depth, 16);
6307 
6308 	/* round up to 32-bytes, since this is granularity
6309 	 * of interpreter stack size
6310 	 */
6311 	return round_up(max_t(u32, stack_depth, 1), 32);
6312 }
6313 
6314 /* starting from main bpf function walk all instructions of the function
6315  * and recursively walk all callees that given function can call.
6316  * Ignore jump and exit insns.
6317  * Since recursion is prevented by check_cfg() this algorithm
6318  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6319  */
6320 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
6321 					 bool priv_stack_supported)
6322 {
6323 	struct bpf_subprog_info *subprog = env->subprog_info;
6324 	struct bpf_insn *insn = env->prog->insnsi;
6325 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
6326 	bool tail_call_reachable = false;
6327 	int ret_insn[MAX_CALL_FRAMES];
6328 	int ret_prog[MAX_CALL_FRAMES];
6329 	int j;
6330 
6331 	i = subprog[idx].start;
6332 	if (!priv_stack_supported)
6333 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6334 process_func:
6335 	/* protect against potential stack overflow that might happen when
6336 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6337 	 * depth for such case down to 256 so that the worst case scenario
6338 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
6339 	 * 8k).
6340 	 *
6341 	 * To get the idea what might happen, see an example:
6342 	 * func1 -> sub rsp, 128
6343 	 *  subfunc1 -> sub rsp, 256
6344 	 *  tailcall1 -> add rsp, 256
6345 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6346 	 *   subfunc2 -> sub rsp, 64
6347 	 *   subfunc22 -> sub rsp, 128
6348 	 *   tailcall2 -> add rsp, 128
6349 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6350 	 *
6351 	 * tailcall will unwind the current stack frame but it will not get rid
6352 	 * of caller's stack as shown on the example above.
6353 	 */
6354 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
6355 		verbose(env,
6356 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6357 			depth);
6358 		return -EACCES;
6359 	}
6360 
6361 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
6362 	if (priv_stack_supported) {
6363 		/* Request private stack support only if the subprog stack
6364 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
6365 		 * avoid jit penalty if the stack usage is small.
6366 		 */
6367 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
6368 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
6369 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
6370 	}
6371 
6372 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6373 		if (subprog_depth > MAX_BPF_STACK) {
6374 			verbose(env, "stack size of subprog %d is %d. Too large\n",
6375 				idx, subprog_depth);
6376 			return -EACCES;
6377 		}
6378 	} else {
6379 		depth += subprog_depth;
6380 		if (depth > MAX_BPF_STACK) {
6381 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
6382 				frame + 1, depth);
6383 			return -EACCES;
6384 		}
6385 	}
6386 continue_func:
6387 	subprog_end = subprog[idx + 1].start;
6388 	for (; i < subprog_end; i++) {
6389 		int next_insn, sidx;
6390 
6391 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6392 			bool err = false;
6393 
6394 			if (!is_bpf_throw_kfunc(insn + i))
6395 				continue;
6396 			if (subprog[idx].is_cb)
6397 				err = true;
6398 			for (int c = 0; c < frame && !err; c++) {
6399 				if (subprog[ret_prog[c]].is_cb) {
6400 					err = true;
6401 					break;
6402 				}
6403 			}
6404 			if (!err)
6405 				continue;
6406 			verbose(env,
6407 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6408 				i, idx);
6409 			return -EINVAL;
6410 		}
6411 
6412 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6413 			continue;
6414 		/* remember insn and function to return to */
6415 		ret_insn[frame] = i + 1;
6416 		ret_prog[frame] = idx;
6417 
6418 		/* find the callee */
6419 		next_insn = i + insn[i].imm + 1;
6420 		sidx = find_subprog(env, next_insn);
6421 		if (sidx < 0) {
6422 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6423 				  next_insn);
6424 			return -EFAULT;
6425 		}
6426 		if (subprog[sidx].is_async_cb) {
6427 			if (subprog[sidx].has_tail_call) {
6428 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
6429 				return -EFAULT;
6430 			}
6431 			/* async callbacks don't increase bpf prog stack size unless called directly */
6432 			if (!bpf_pseudo_call(insn + i))
6433 				continue;
6434 			if (subprog[sidx].is_exception_cb) {
6435 				verbose(env, "insn %d cannot call exception cb directly\n", i);
6436 				return -EINVAL;
6437 			}
6438 		}
6439 		i = next_insn;
6440 		idx = sidx;
6441 		if (!priv_stack_supported)
6442 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6443 
6444 		if (subprog[idx].has_tail_call)
6445 			tail_call_reachable = true;
6446 
6447 		frame++;
6448 		if (frame >= MAX_CALL_FRAMES) {
6449 			verbose(env, "the call stack of %d frames is too deep !\n",
6450 				frame);
6451 			return -E2BIG;
6452 		}
6453 		goto process_func;
6454 	}
6455 	/* if tail call got detected across bpf2bpf calls then mark each of the
6456 	 * currently present subprog frames as tail call reachable subprogs;
6457 	 * this info will be utilized by JIT so that we will be preserving the
6458 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6459 	 */
6460 	if (tail_call_reachable)
6461 		for (j = 0; j < frame; j++) {
6462 			if (subprog[ret_prog[j]].is_exception_cb) {
6463 				verbose(env, "cannot tail call within exception cb\n");
6464 				return -EINVAL;
6465 			}
6466 			subprog[ret_prog[j]].tail_call_reachable = true;
6467 		}
6468 	if (subprog[0].tail_call_reachable)
6469 		env->prog->aux->tail_call_reachable = true;
6470 
6471 	/* end of for() loop means the last insn of the 'subprog'
6472 	 * was reached. Doesn't matter whether it was JA or EXIT
6473 	 */
6474 	if (frame == 0)
6475 		return 0;
6476 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6477 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6478 	frame--;
6479 	i = ret_insn[frame];
6480 	idx = ret_prog[frame];
6481 	goto continue_func;
6482 }
6483 
6484 static int check_max_stack_depth(struct bpf_verifier_env *env)
6485 {
6486 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6487 	struct bpf_subprog_info *si = env->subprog_info;
6488 	bool priv_stack_supported;
6489 	int ret;
6490 
6491 	for (int i = 0; i < env->subprog_cnt; i++) {
6492 		if (si[i].has_tail_call) {
6493 			priv_stack_mode = NO_PRIV_STACK;
6494 			break;
6495 		}
6496 	}
6497 
6498 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6499 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6500 
6501 	/* All async_cb subprogs use normal kernel stack. If a particular
6502 	 * subprog appears in both main prog and async_cb subtree, that
6503 	 * subprog will use normal kernel stack to avoid potential nesting.
6504 	 * The reverse subprog traversal ensures when main prog subtree is
6505 	 * checked, the subprogs appearing in async_cb subtrees are already
6506 	 * marked as using normal kernel stack, so stack size checking can
6507 	 * be done properly.
6508 	 */
6509 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6510 		if (!i || si[i].is_async_cb) {
6511 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6512 			ret = check_max_stack_depth_subprog(env, i, priv_stack_supported);
6513 			if (ret < 0)
6514 				return ret;
6515 		}
6516 	}
6517 
6518 	for (int i = 0; i < env->subprog_cnt; i++) {
6519 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6520 			env->prog->aux->jits_use_priv_stack = true;
6521 			break;
6522 		}
6523 	}
6524 
6525 	return 0;
6526 }
6527 
6528 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6529 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6530 				  const struct bpf_insn *insn, int idx)
6531 {
6532 	int start = idx + insn->imm + 1, subprog;
6533 
6534 	subprog = find_subprog(env, start);
6535 	if (subprog < 0) {
6536 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6537 			  start);
6538 		return -EFAULT;
6539 	}
6540 	return env->subprog_info[subprog].stack_depth;
6541 }
6542 #endif
6543 
6544 static int __check_buffer_access(struct bpf_verifier_env *env,
6545 				 const char *buf_info,
6546 				 const struct bpf_reg_state *reg,
6547 				 int regno, int off, int size)
6548 {
6549 	if (off < 0) {
6550 		verbose(env,
6551 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6552 			regno, buf_info, off, size);
6553 		return -EACCES;
6554 	}
6555 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6556 		char tn_buf[48];
6557 
6558 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6559 		verbose(env,
6560 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6561 			regno, off, tn_buf);
6562 		return -EACCES;
6563 	}
6564 
6565 	return 0;
6566 }
6567 
6568 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6569 				  const struct bpf_reg_state *reg,
6570 				  int regno, int off, int size)
6571 {
6572 	int err;
6573 
6574 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6575 	if (err)
6576 		return err;
6577 
6578 	if (off + size > env->prog->aux->max_tp_access)
6579 		env->prog->aux->max_tp_access = off + size;
6580 
6581 	return 0;
6582 }
6583 
6584 static int check_buffer_access(struct bpf_verifier_env *env,
6585 			       const struct bpf_reg_state *reg,
6586 			       int regno, int off, int size,
6587 			       bool zero_size_allowed,
6588 			       u32 *max_access)
6589 {
6590 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6591 	int err;
6592 
6593 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6594 	if (err)
6595 		return err;
6596 
6597 	if (off + size > *max_access)
6598 		*max_access = off + size;
6599 
6600 	return 0;
6601 }
6602 
6603 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6604 static void zext_32_to_64(struct bpf_reg_state *reg)
6605 {
6606 	reg->var_off = tnum_subreg(reg->var_off);
6607 	__reg_assign_32_into_64(reg);
6608 }
6609 
6610 /* truncate register to smaller size (in bytes)
6611  * must be called with size < BPF_REG_SIZE
6612  */
6613 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6614 {
6615 	u64 mask;
6616 
6617 	/* clear high bits in bit representation */
6618 	reg->var_off = tnum_cast(reg->var_off, size);
6619 
6620 	/* fix arithmetic bounds */
6621 	mask = ((u64)1 << (size * 8)) - 1;
6622 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6623 		reg->umin_value &= mask;
6624 		reg->umax_value &= mask;
6625 	} else {
6626 		reg->umin_value = 0;
6627 		reg->umax_value = mask;
6628 	}
6629 	reg->smin_value = reg->umin_value;
6630 	reg->smax_value = reg->umax_value;
6631 
6632 	/* If size is smaller than 32bit register the 32bit register
6633 	 * values are also truncated so we push 64-bit bounds into
6634 	 * 32-bit bounds. Above were truncated < 32-bits already.
6635 	 */
6636 	if (size < 4)
6637 		__mark_reg32_unbounded(reg);
6638 
6639 	reg_bounds_sync(reg);
6640 }
6641 
6642 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6643 {
6644 	if (size == 1) {
6645 		reg->smin_value = reg->s32_min_value = S8_MIN;
6646 		reg->smax_value = reg->s32_max_value = S8_MAX;
6647 	} else if (size == 2) {
6648 		reg->smin_value = reg->s32_min_value = S16_MIN;
6649 		reg->smax_value = reg->s32_max_value = S16_MAX;
6650 	} else {
6651 		/* size == 4 */
6652 		reg->smin_value = reg->s32_min_value = S32_MIN;
6653 		reg->smax_value = reg->s32_max_value = S32_MAX;
6654 	}
6655 	reg->umin_value = reg->u32_min_value = 0;
6656 	reg->umax_value = U64_MAX;
6657 	reg->u32_max_value = U32_MAX;
6658 	reg->var_off = tnum_unknown;
6659 }
6660 
6661 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6662 {
6663 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6664 	u64 top_smax_value, top_smin_value;
6665 	u64 num_bits = size * 8;
6666 
6667 	if (tnum_is_const(reg->var_off)) {
6668 		u64_cval = reg->var_off.value;
6669 		if (size == 1)
6670 			reg->var_off = tnum_const((s8)u64_cval);
6671 		else if (size == 2)
6672 			reg->var_off = tnum_const((s16)u64_cval);
6673 		else
6674 			/* size == 4 */
6675 			reg->var_off = tnum_const((s32)u64_cval);
6676 
6677 		u64_cval = reg->var_off.value;
6678 		reg->smax_value = reg->smin_value = u64_cval;
6679 		reg->umax_value = reg->umin_value = u64_cval;
6680 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6681 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6682 		return;
6683 	}
6684 
6685 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6686 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6687 
6688 	if (top_smax_value != top_smin_value)
6689 		goto out;
6690 
6691 	/* find the s64_min and s64_min after sign extension */
6692 	if (size == 1) {
6693 		init_s64_max = (s8)reg->smax_value;
6694 		init_s64_min = (s8)reg->smin_value;
6695 	} else if (size == 2) {
6696 		init_s64_max = (s16)reg->smax_value;
6697 		init_s64_min = (s16)reg->smin_value;
6698 	} else {
6699 		init_s64_max = (s32)reg->smax_value;
6700 		init_s64_min = (s32)reg->smin_value;
6701 	}
6702 
6703 	s64_max = max(init_s64_max, init_s64_min);
6704 	s64_min = min(init_s64_max, init_s64_min);
6705 
6706 	/* both of s64_max/s64_min positive or negative */
6707 	if ((s64_max >= 0) == (s64_min >= 0)) {
6708 		reg->s32_min_value = reg->smin_value = s64_min;
6709 		reg->s32_max_value = reg->smax_value = s64_max;
6710 		reg->u32_min_value = reg->umin_value = s64_min;
6711 		reg->u32_max_value = reg->umax_value = s64_max;
6712 		reg->var_off = tnum_range(s64_min, s64_max);
6713 		return;
6714 	}
6715 
6716 out:
6717 	set_sext64_default_val(reg, size);
6718 }
6719 
6720 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6721 {
6722 	if (size == 1) {
6723 		reg->s32_min_value = S8_MIN;
6724 		reg->s32_max_value = S8_MAX;
6725 	} else {
6726 		/* size == 2 */
6727 		reg->s32_min_value = S16_MIN;
6728 		reg->s32_max_value = S16_MAX;
6729 	}
6730 	reg->u32_min_value = 0;
6731 	reg->u32_max_value = U32_MAX;
6732 	reg->var_off = tnum_subreg(tnum_unknown);
6733 }
6734 
6735 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6736 {
6737 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6738 	u32 top_smax_value, top_smin_value;
6739 	u32 num_bits = size * 8;
6740 
6741 	if (tnum_is_const(reg->var_off)) {
6742 		u32_val = reg->var_off.value;
6743 		if (size == 1)
6744 			reg->var_off = tnum_const((s8)u32_val);
6745 		else
6746 			reg->var_off = tnum_const((s16)u32_val);
6747 
6748 		u32_val = reg->var_off.value;
6749 		reg->s32_min_value = reg->s32_max_value = u32_val;
6750 		reg->u32_min_value = reg->u32_max_value = u32_val;
6751 		return;
6752 	}
6753 
6754 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6755 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6756 
6757 	if (top_smax_value != top_smin_value)
6758 		goto out;
6759 
6760 	/* find the s32_min and s32_min after sign extension */
6761 	if (size == 1) {
6762 		init_s32_max = (s8)reg->s32_max_value;
6763 		init_s32_min = (s8)reg->s32_min_value;
6764 	} else {
6765 		/* size == 2 */
6766 		init_s32_max = (s16)reg->s32_max_value;
6767 		init_s32_min = (s16)reg->s32_min_value;
6768 	}
6769 	s32_max = max(init_s32_max, init_s32_min);
6770 	s32_min = min(init_s32_max, init_s32_min);
6771 
6772 	if ((s32_min >= 0) == (s32_max >= 0)) {
6773 		reg->s32_min_value = s32_min;
6774 		reg->s32_max_value = s32_max;
6775 		reg->u32_min_value = (u32)s32_min;
6776 		reg->u32_max_value = (u32)s32_max;
6777 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6778 		return;
6779 	}
6780 
6781 out:
6782 	set_sext32_default_val(reg, size);
6783 }
6784 
6785 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6786 {
6787 	/* A map is considered read-only if the following condition are true:
6788 	 *
6789 	 * 1) BPF program side cannot change any of the map content. The
6790 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6791 	 *    and was set at map creation time.
6792 	 * 2) The map value(s) have been initialized from user space by a
6793 	 *    loader and then "frozen", such that no new map update/delete
6794 	 *    operations from syscall side are possible for the rest of
6795 	 *    the map's lifetime from that point onwards.
6796 	 * 3) Any parallel/pending map update/delete operations from syscall
6797 	 *    side have been completed. Only after that point, it's safe to
6798 	 *    assume that map value(s) are immutable.
6799 	 */
6800 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6801 	       READ_ONCE(map->frozen) &&
6802 	       !bpf_map_write_active(map);
6803 }
6804 
6805 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6806 			       bool is_ldsx)
6807 {
6808 	void *ptr;
6809 	u64 addr;
6810 	int err;
6811 
6812 	err = map->ops->map_direct_value_addr(map, &addr, off);
6813 	if (err)
6814 		return err;
6815 	ptr = (void *)(long)addr + off;
6816 
6817 	switch (size) {
6818 	case sizeof(u8):
6819 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6820 		break;
6821 	case sizeof(u16):
6822 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6823 		break;
6824 	case sizeof(u32):
6825 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6826 		break;
6827 	case sizeof(u64):
6828 		*val = *(u64 *)ptr;
6829 		break;
6830 	default:
6831 		return -EINVAL;
6832 	}
6833 	return 0;
6834 }
6835 
6836 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6837 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6838 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6839 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6840 
6841 /*
6842  * Allow list few fields as RCU trusted or full trusted.
6843  * This logic doesn't allow mix tagging and will be removed once GCC supports
6844  * btf_type_tag.
6845  */
6846 
6847 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6848 BTF_TYPE_SAFE_RCU(struct task_struct) {
6849 	const cpumask_t *cpus_ptr;
6850 	struct css_set __rcu *cgroups;
6851 	struct task_struct __rcu *real_parent;
6852 	struct task_struct *group_leader;
6853 };
6854 
6855 BTF_TYPE_SAFE_RCU(struct cgroup) {
6856 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6857 	struct kernfs_node *kn;
6858 };
6859 
6860 BTF_TYPE_SAFE_RCU(struct css_set) {
6861 	struct cgroup *dfl_cgrp;
6862 };
6863 
6864 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6865 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6866 	struct file __rcu *exe_file;
6867 };
6868 
6869 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6870  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6871  */
6872 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6873 	struct sock *sk;
6874 };
6875 
6876 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6877 	struct sock *sk;
6878 };
6879 
6880 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6881 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6882 	struct seq_file *seq;
6883 };
6884 
6885 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6886 	struct bpf_iter_meta *meta;
6887 	struct task_struct *task;
6888 };
6889 
6890 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6891 	struct file *file;
6892 };
6893 
6894 BTF_TYPE_SAFE_TRUSTED(struct file) {
6895 	struct inode *f_inode;
6896 };
6897 
6898 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6899 	/* no negative dentry-s in places where bpf can see it */
6900 	struct inode *d_inode;
6901 };
6902 
6903 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6904 	struct sock *sk;
6905 };
6906 
6907 static bool type_is_rcu(struct bpf_verifier_env *env,
6908 			struct bpf_reg_state *reg,
6909 			const char *field_name, u32 btf_id)
6910 {
6911 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6912 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6913 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6914 
6915 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6916 }
6917 
6918 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6919 				struct bpf_reg_state *reg,
6920 				const char *field_name, u32 btf_id)
6921 {
6922 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6923 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6924 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6925 
6926 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6927 }
6928 
6929 static bool type_is_trusted(struct bpf_verifier_env *env,
6930 			    struct bpf_reg_state *reg,
6931 			    const char *field_name, u32 btf_id)
6932 {
6933 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6934 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6935 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6936 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6937 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6938 
6939 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6940 }
6941 
6942 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6943 				    struct bpf_reg_state *reg,
6944 				    const char *field_name, u32 btf_id)
6945 {
6946 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6947 
6948 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6949 					  "__safe_trusted_or_null");
6950 }
6951 
6952 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6953 				   struct bpf_reg_state *regs,
6954 				   int regno, int off, int size,
6955 				   enum bpf_access_type atype,
6956 				   int value_regno)
6957 {
6958 	struct bpf_reg_state *reg = regs + regno;
6959 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6960 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6961 	const char *field_name = NULL;
6962 	enum bpf_type_flag flag = 0;
6963 	u32 btf_id = 0;
6964 	int ret;
6965 
6966 	if (!env->allow_ptr_leaks) {
6967 		verbose(env,
6968 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6969 			tname);
6970 		return -EPERM;
6971 	}
6972 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6973 		verbose(env,
6974 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6975 			tname);
6976 		return -EINVAL;
6977 	}
6978 	if (off < 0) {
6979 		verbose(env,
6980 			"R%d is ptr_%s invalid negative access: off=%d\n",
6981 			regno, tname, off);
6982 		return -EACCES;
6983 	}
6984 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6985 		char tn_buf[48];
6986 
6987 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6988 		verbose(env,
6989 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6990 			regno, tname, off, tn_buf);
6991 		return -EACCES;
6992 	}
6993 
6994 	if (reg->type & MEM_USER) {
6995 		verbose(env,
6996 			"R%d is ptr_%s access user memory: off=%d\n",
6997 			regno, tname, off);
6998 		return -EACCES;
6999 	}
7000 
7001 	if (reg->type & MEM_PERCPU) {
7002 		verbose(env,
7003 			"R%d is ptr_%s access percpu memory: off=%d\n",
7004 			regno, tname, off);
7005 		return -EACCES;
7006 	}
7007 
7008 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
7009 		if (!btf_is_kernel(reg->btf)) {
7010 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
7011 			return -EFAULT;
7012 		}
7013 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
7014 	} else {
7015 		/* Writes are permitted with default btf_struct_access for
7016 		 * program allocated objects (which always have ref_obj_id > 0),
7017 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
7018 		 */
7019 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
7020 			verbose(env, "only read is supported\n");
7021 			return -EACCES;
7022 		}
7023 
7024 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
7025 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
7026 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
7027 			return -EFAULT;
7028 		}
7029 
7030 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
7031 	}
7032 
7033 	if (ret < 0)
7034 		return ret;
7035 
7036 	if (ret != PTR_TO_BTF_ID) {
7037 		/* just mark; */
7038 
7039 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
7040 		/* If this is an untrusted pointer, all pointers formed by walking it
7041 		 * also inherit the untrusted flag.
7042 		 */
7043 		flag = PTR_UNTRUSTED;
7044 
7045 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
7046 		/* By default any pointer obtained from walking a trusted pointer is no
7047 		 * longer trusted, unless the field being accessed has explicitly been
7048 		 * marked as inheriting its parent's state of trust (either full or RCU).
7049 		 * For example:
7050 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
7051 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
7052 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
7053 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
7054 		 *
7055 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
7056 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
7057 		 */
7058 		if (type_is_trusted(env, reg, field_name, btf_id)) {
7059 			flag |= PTR_TRUSTED;
7060 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
7061 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
7062 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
7063 			if (type_is_rcu(env, reg, field_name, btf_id)) {
7064 				/* ignore __rcu tag and mark it MEM_RCU */
7065 				flag |= MEM_RCU;
7066 			} else if (flag & MEM_RCU ||
7067 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
7068 				/* __rcu tagged pointers can be NULL */
7069 				flag |= MEM_RCU | PTR_MAYBE_NULL;
7070 
7071 				/* We always trust them */
7072 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
7073 				    flag & PTR_UNTRUSTED)
7074 					flag &= ~PTR_UNTRUSTED;
7075 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
7076 				/* keep as-is */
7077 			} else {
7078 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
7079 				clear_trusted_flags(&flag);
7080 			}
7081 		} else {
7082 			/*
7083 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
7084 			 * aggressively mark as untrusted otherwise such
7085 			 * pointers will be plain PTR_TO_BTF_ID without flags
7086 			 * and will be allowed to be passed into helpers for
7087 			 * compat reasons.
7088 			 */
7089 			flag = PTR_UNTRUSTED;
7090 		}
7091 	} else {
7092 		/* Old compat. Deprecated */
7093 		clear_trusted_flags(&flag);
7094 	}
7095 
7096 	if (atype == BPF_READ && value_regno >= 0)
7097 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
7098 
7099 	return 0;
7100 }
7101 
7102 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
7103 				   struct bpf_reg_state *regs,
7104 				   int regno, int off, int size,
7105 				   enum bpf_access_type atype,
7106 				   int value_regno)
7107 {
7108 	struct bpf_reg_state *reg = regs + regno;
7109 	struct bpf_map *map = reg->map_ptr;
7110 	struct bpf_reg_state map_reg;
7111 	enum bpf_type_flag flag = 0;
7112 	const struct btf_type *t;
7113 	const char *tname;
7114 	u32 btf_id;
7115 	int ret;
7116 
7117 	if (!btf_vmlinux) {
7118 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
7119 		return -ENOTSUPP;
7120 	}
7121 
7122 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
7123 		verbose(env, "map_ptr access not supported for map type %d\n",
7124 			map->map_type);
7125 		return -ENOTSUPP;
7126 	}
7127 
7128 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
7129 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
7130 
7131 	if (!env->allow_ptr_leaks) {
7132 		verbose(env,
7133 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7134 			tname);
7135 		return -EPERM;
7136 	}
7137 
7138 	if (off < 0) {
7139 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
7140 			regno, tname, off);
7141 		return -EACCES;
7142 	}
7143 
7144 	if (atype != BPF_READ) {
7145 		verbose(env, "only read from %s is supported\n", tname);
7146 		return -EACCES;
7147 	}
7148 
7149 	/* Simulate access to a PTR_TO_BTF_ID */
7150 	memset(&map_reg, 0, sizeof(map_reg));
7151 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
7152 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
7153 	if (ret < 0)
7154 		return ret;
7155 
7156 	if (value_regno >= 0)
7157 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
7158 
7159 	return 0;
7160 }
7161 
7162 /* Check that the stack access at the given offset is within bounds. The
7163  * maximum valid offset is -1.
7164  *
7165  * The minimum valid offset is -MAX_BPF_STACK for writes, and
7166  * -state->allocated_stack for reads.
7167  */
7168 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
7169                                           s64 off,
7170                                           struct bpf_func_state *state,
7171                                           enum bpf_access_type t)
7172 {
7173 	int min_valid_off;
7174 
7175 	if (t == BPF_WRITE || env->allow_uninit_stack)
7176 		min_valid_off = -MAX_BPF_STACK;
7177 	else
7178 		min_valid_off = -state->allocated_stack;
7179 
7180 	if (off < min_valid_off || off > -1)
7181 		return -EACCES;
7182 	return 0;
7183 }
7184 
7185 /* Check that the stack access at 'regno + off' falls within the maximum stack
7186  * bounds.
7187  *
7188  * 'off' includes `regno->offset`, but not its dynamic part (if any).
7189  */
7190 static int check_stack_access_within_bounds(
7191 		struct bpf_verifier_env *env,
7192 		int regno, int off, int access_size,
7193 		enum bpf_access_type type)
7194 {
7195 	struct bpf_reg_state *regs = cur_regs(env);
7196 	struct bpf_reg_state *reg = regs + regno;
7197 	struct bpf_func_state *state = func(env, reg);
7198 	s64 min_off, max_off;
7199 	int err;
7200 	char *err_extra;
7201 
7202 	if (type == BPF_READ)
7203 		err_extra = " read from";
7204 	else
7205 		err_extra = " write to";
7206 
7207 	if (tnum_is_const(reg->var_off)) {
7208 		min_off = (s64)reg->var_off.value + off;
7209 		max_off = min_off + access_size;
7210 	} else {
7211 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
7212 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
7213 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
7214 				err_extra, regno);
7215 			return -EACCES;
7216 		}
7217 		min_off = reg->smin_value + off;
7218 		max_off = reg->smax_value + off + access_size;
7219 	}
7220 
7221 	err = check_stack_slot_within_bounds(env, min_off, state, type);
7222 	if (!err && max_off > 0)
7223 		err = -EINVAL; /* out of stack access into non-negative offsets */
7224 	if (!err && access_size < 0)
7225 		/* access_size should not be negative (or overflow an int); others checks
7226 		 * along the way should have prevented such an access.
7227 		 */
7228 		err = -EFAULT; /* invalid negative access size; integer overflow? */
7229 
7230 	if (err) {
7231 		if (tnum_is_const(reg->var_off)) {
7232 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
7233 				err_extra, regno, off, access_size);
7234 		} else {
7235 			char tn_buf[48];
7236 
7237 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7238 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
7239 				err_extra, regno, tn_buf, off, access_size);
7240 		}
7241 		return err;
7242 	}
7243 
7244 	/* Note that there is no stack access with offset zero, so the needed stack
7245 	 * size is -min_off, not -min_off+1.
7246 	 */
7247 	return grow_stack_state(env, state, -min_off /* size */);
7248 }
7249 
7250 static bool get_func_retval_range(struct bpf_prog *prog,
7251 				  struct bpf_retval_range *range)
7252 {
7253 	if (prog->type == BPF_PROG_TYPE_LSM &&
7254 		prog->expected_attach_type == BPF_LSM_MAC &&
7255 		!bpf_lsm_get_retval_range(prog, range)) {
7256 		return true;
7257 	}
7258 	return false;
7259 }
7260 
7261 /* check whether memory at (regno + off) is accessible for t = (read | write)
7262  * if t==write, value_regno is a register which value is stored into memory
7263  * if t==read, value_regno is a register which will receive the value from memory
7264  * if t==write && value_regno==-1, some unknown value is stored into memory
7265  * if t==read && value_regno==-1, don't care what we read from memory
7266  */
7267 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
7268 			    int off, int bpf_size, enum bpf_access_type t,
7269 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7270 {
7271 	struct bpf_reg_state *regs = cur_regs(env);
7272 	struct bpf_reg_state *reg = regs + regno;
7273 	int size, err = 0;
7274 
7275 	size = bpf_size_to_bytes(bpf_size);
7276 	if (size < 0)
7277 		return size;
7278 
7279 	/* alignment checks will add in reg->off themselves */
7280 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7281 	if (err)
7282 		return err;
7283 
7284 	/* for access checks, reg->off is just part of off */
7285 	off += reg->off;
7286 
7287 	if (reg->type == PTR_TO_MAP_KEY) {
7288 		if (t == BPF_WRITE) {
7289 			verbose(env, "write to change key R%d not allowed\n", regno);
7290 			return -EACCES;
7291 		}
7292 
7293 		err = check_mem_region_access(env, regno, off, size,
7294 					      reg->map_ptr->key_size, false);
7295 		if (err)
7296 			return err;
7297 		if (value_regno >= 0)
7298 			mark_reg_unknown(env, regs, value_regno);
7299 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7300 		struct btf_field *kptr_field = NULL;
7301 
7302 		if (t == BPF_WRITE && value_regno >= 0 &&
7303 		    is_pointer_value(env, value_regno)) {
7304 			verbose(env, "R%d leaks addr into map\n", value_regno);
7305 			return -EACCES;
7306 		}
7307 		err = check_map_access_type(env, regno, off, size, t);
7308 		if (err)
7309 			return err;
7310 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
7311 		if (err)
7312 			return err;
7313 		if (tnum_is_const(reg->var_off))
7314 			kptr_field = btf_record_find(reg->map_ptr->record,
7315 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7316 		if (kptr_field) {
7317 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
7318 		} else if (t == BPF_READ && value_regno >= 0) {
7319 			struct bpf_map *map = reg->map_ptr;
7320 
7321 			/* if map is read-only, track its contents as scalars */
7322 			if (tnum_is_const(reg->var_off) &&
7323 			    bpf_map_is_rdonly(map) &&
7324 			    map->ops->map_direct_value_addr) {
7325 				int map_off = off + reg->var_off.value;
7326 				u64 val = 0;
7327 
7328 				err = bpf_map_direct_read(map, map_off, size,
7329 							  &val, is_ldsx);
7330 				if (err)
7331 					return err;
7332 
7333 				regs[value_regno].type = SCALAR_VALUE;
7334 				__mark_reg_known(&regs[value_regno], val);
7335 			} else {
7336 				mark_reg_unknown(env, regs, value_regno);
7337 			}
7338 		}
7339 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7340 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7341 
7342 		if (type_may_be_null(reg->type)) {
7343 			verbose(env, "R%d invalid mem access '%s'\n", regno,
7344 				reg_type_str(env, reg->type));
7345 			return -EACCES;
7346 		}
7347 
7348 		if (t == BPF_WRITE && rdonly_mem) {
7349 			verbose(env, "R%d cannot write into %s\n",
7350 				regno, reg_type_str(env, reg->type));
7351 			return -EACCES;
7352 		}
7353 
7354 		if (t == BPF_WRITE && value_regno >= 0 &&
7355 		    is_pointer_value(env, value_regno)) {
7356 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7357 			return -EACCES;
7358 		}
7359 
7360 		err = check_mem_region_access(env, regno, off, size,
7361 					      reg->mem_size, false);
7362 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7363 			mark_reg_unknown(env, regs, value_regno);
7364 	} else if (reg->type == PTR_TO_CTX) {
7365 		bool is_retval = false;
7366 		struct bpf_retval_range range;
7367 		enum bpf_reg_type reg_type = SCALAR_VALUE;
7368 		struct btf *btf = NULL;
7369 		u32 btf_id = 0;
7370 
7371 		if (t == BPF_WRITE && value_regno >= 0 &&
7372 		    is_pointer_value(env, value_regno)) {
7373 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7374 			return -EACCES;
7375 		}
7376 
7377 		err = check_ptr_off_reg(env, reg, regno);
7378 		if (err < 0)
7379 			return err;
7380 
7381 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
7382 				       &btf_id, &is_retval, is_ldsx);
7383 		if (err)
7384 			verbose_linfo(env, insn_idx, "; ");
7385 		if (!err && t == BPF_READ && value_regno >= 0) {
7386 			/* ctx access returns either a scalar, or a
7387 			 * PTR_TO_PACKET[_META,_END]. In the latter
7388 			 * case, we know the offset is zero.
7389 			 */
7390 			if (reg_type == SCALAR_VALUE) {
7391 				if (is_retval && get_func_retval_range(env->prog, &range)) {
7392 					err = __mark_reg_s32_range(env, regs, value_regno,
7393 								   range.minval, range.maxval);
7394 					if (err)
7395 						return err;
7396 				} else {
7397 					mark_reg_unknown(env, regs, value_regno);
7398 				}
7399 			} else {
7400 				mark_reg_known_zero(env, regs,
7401 						    value_regno);
7402 				if (type_may_be_null(reg_type))
7403 					regs[value_regno].id = ++env->id_gen;
7404 				/* A load of ctx field could have different
7405 				 * actual load size with the one encoded in the
7406 				 * insn. When the dst is PTR, it is for sure not
7407 				 * a sub-register.
7408 				 */
7409 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7410 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
7411 					regs[value_regno].btf = btf;
7412 					regs[value_regno].btf_id = btf_id;
7413 				}
7414 			}
7415 			regs[value_regno].type = reg_type;
7416 		}
7417 
7418 	} else if (reg->type == PTR_TO_STACK) {
7419 		/* Basic bounds checks. */
7420 		err = check_stack_access_within_bounds(env, regno, off, size, t);
7421 		if (err)
7422 			return err;
7423 
7424 		if (t == BPF_READ)
7425 			err = check_stack_read(env, regno, off, size,
7426 					       value_regno);
7427 		else
7428 			err = check_stack_write(env, regno, off, size,
7429 						value_regno, insn_idx);
7430 	} else if (reg_is_pkt_pointer(reg)) {
7431 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7432 			verbose(env, "cannot write into packet\n");
7433 			return -EACCES;
7434 		}
7435 		if (t == BPF_WRITE && value_regno >= 0 &&
7436 		    is_pointer_value(env, value_regno)) {
7437 			verbose(env, "R%d leaks addr into packet\n",
7438 				value_regno);
7439 			return -EACCES;
7440 		}
7441 		err = check_packet_access(env, regno, off, size, false);
7442 		if (!err && t == BPF_READ && value_regno >= 0)
7443 			mark_reg_unknown(env, regs, value_regno);
7444 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7445 		if (t == BPF_WRITE && value_regno >= 0 &&
7446 		    is_pointer_value(env, value_regno)) {
7447 			verbose(env, "R%d leaks addr into flow keys\n",
7448 				value_regno);
7449 			return -EACCES;
7450 		}
7451 
7452 		err = check_flow_keys_access(env, off, size);
7453 		if (!err && t == BPF_READ && value_regno >= 0)
7454 			mark_reg_unknown(env, regs, value_regno);
7455 	} else if (type_is_sk_pointer(reg->type)) {
7456 		if (t == BPF_WRITE) {
7457 			verbose(env, "R%d cannot write into %s\n",
7458 				regno, reg_type_str(env, reg->type));
7459 			return -EACCES;
7460 		}
7461 		err = check_sock_access(env, insn_idx, regno, off, size, t);
7462 		if (!err && value_regno >= 0)
7463 			mark_reg_unknown(env, regs, value_regno);
7464 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7465 		err = check_tp_buffer_access(env, reg, regno, off, size);
7466 		if (!err && t == BPF_READ && value_regno >= 0)
7467 			mark_reg_unknown(env, regs, value_regno);
7468 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7469 		   !type_may_be_null(reg->type)) {
7470 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7471 					      value_regno);
7472 	} else if (reg->type == CONST_PTR_TO_MAP) {
7473 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7474 					      value_regno);
7475 	} else if (base_type(reg->type) == PTR_TO_BUF) {
7476 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7477 		u32 *max_access;
7478 
7479 		if (rdonly_mem) {
7480 			if (t == BPF_WRITE) {
7481 				verbose(env, "R%d cannot write into %s\n",
7482 					regno, reg_type_str(env, reg->type));
7483 				return -EACCES;
7484 			}
7485 			max_access = &env->prog->aux->max_rdonly_access;
7486 		} else {
7487 			max_access = &env->prog->aux->max_rdwr_access;
7488 		}
7489 
7490 		err = check_buffer_access(env, reg, regno, off, size, false,
7491 					  max_access);
7492 
7493 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7494 			mark_reg_unknown(env, regs, value_regno);
7495 	} else if (reg->type == PTR_TO_ARENA) {
7496 		if (t == BPF_READ && value_regno >= 0)
7497 			mark_reg_unknown(env, regs, value_regno);
7498 	} else {
7499 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7500 			reg_type_str(env, reg->type));
7501 		return -EACCES;
7502 	}
7503 
7504 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7505 	    regs[value_regno].type == SCALAR_VALUE) {
7506 		if (!is_ldsx)
7507 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7508 			coerce_reg_to_size(&regs[value_regno], size);
7509 		else
7510 			coerce_reg_to_size_sx(&regs[value_regno], size);
7511 	}
7512 	return err;
7513 }
7514 
7515 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7516 			     bool allow_trust_mismatch);
7517 
7518 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
7519 {
7520 	int load_reg;
7521 	int err;
7522 
7523 	switch (insn->imm) {
7524 	case BPF_ADD:
7525 	case BPF_ADD | BPF_FETCH:
7526 	case BPF_AND:
7527 	case BPF_AND | BPF_FETCH:
7528 	case BPF_OR:
7529 	case BPF_OR | BPF_FETCH:
7530 	case BPF_XOR:
7531 	case BPF_XOR | BPF_FETCH:
7532 	case BPF_XCHG:
7533 	case BPF_CMPXCHG:
7534 		break;
7535 	default:
7536 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
7537 		return -EINVAL;
7538 	}
7539 
7540 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7541 		verbose(env, "invalid atomic operand size\n");
7542 		return -EINVAL;
7543 	}
7544 
7545 	/* check src1 operand */
7546 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7547 	if (err)
7548 		return err;
7549 
7550 	/* check src2 operand */
7551 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7552 	if (err)
7553 		return err;
7554 
7555 	if (insn->imm == BPF_CMPXCHG) {
7556 		/* Check comparison of R0 with memory location */
7557 		const u32 aux_reg = BPF_REG_0;
7558 
7559 		err = check_reg_arg(env, aux_reg, SRC_OP);
7560 		if (err)
7561 			return err;
7562 
7563 		if (is_pointer_value(env, aux_reg)) {
7564 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7565 			return -EACCES;
7566 		}
7567 	}
7568 
7569 	if (is_pointer_value(env, insn->src_reg)) {
7570 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7571 		return -EACCES;
7572 	}
7573 
7574 	if (is_ctx_reg(env, insn->dst_reg) ||
7575 	    is_pkt_reg(env, insn->dst_reg) ||
7576 	    is_flow_key_reg(env, insn->dst_reg) ||
7577 	    is_sk_reg(env, insn->dst_reg) ||
7578 	    (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) {
7579 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7580 			insn->dst_reg,
7581 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7582 		return -EACCES;
7583 	}
7584 
7585 	if (insn->imm & BPF_FETCH) {
7586 		if (insn->imm == BPF_CMPXCHG)
7587 			load_reg = BPF_REG_0;
7588 		else
7589 			load_reg = insn->src_reg;
7590 
7591 		/* check and record load of old value */
7592 		err = check_reg_arg(env, load_reg, DST_OP);
7593 		if (err)
7594 			return err;
7595 	} else {
7596 		/* This instruction accesses a memory location but doesn't
7597 		 * actually load it into a register.
7598 		 */
7599 		load_reg = -1;
7600 	}
7601 
7602 	/* Check whether we can read the memory, with second call for fetch
7603 	 * case to simulate the register fill.
7604 	 */
7605 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7606 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7607 	if (!err && load_reg >= 0)
7608 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7609 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7610 				       true, false);
7611 	if (err)
7612 		return err;
7613 
7614 	if (is_arena_reg(env, insn->dst_reg)) {
7615 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7616 		if (err)
7617 			return err;
7618 	}
7619 	/* Check whether we can write into the same memory. */
7620 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7621 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7622 	if (err)
7623 		return err;
7624 	return 0;
7625 }
7626 
7627 /* When register 'regno' is used to read the stack (either directly or through
7628  * a helper function) make sure that it's within stack boundary and, depending
7629  * on the access type and privileges, that all elements of the stack are
7630  * initialized.
7631  *
7632  * 'off' includes 'regno->off', but not its dynamic part (if any).
7633  *
7634  * All registers that have been spilled on the stack in the slots within the
7635  * read offsets are marked as read.
7636  */
7637 static int check_stack_range_initialized(
7638 		struct bpf_verifier_env *env, int regno, int off,
7639 		int access_size, bool zero_size_allowed,
7640 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
7641 {
7642 	struct bpf_reg_state *reg = reg_state(env, regno);
7643 	struct bpf_func_state *state = func(env, reg);
7644 	int err, min_off, max_off, i, j, slot, spi;
7645 	/* Some accesses can write anything into the stack, others are
7646 	 * read-only.
7647 	 */
7648 	bool clobber = false;
7649 
7650 	if (access_size == 0 && !zero_size_allowed) {
7651 		verbose(env, "invalid zero-sized read\n");
7652 		return -EACCES;
7653 	}
7654 
7655 	if (type == BPF_WRITE)
7656 		clobber = true;
7657 
7658 	err = check_stack_access_within_bounds(env, regno, off, access_size, type);
7659 	if (err)
7660 		return err;
7661 
7662 
7663 	if (tnum_is_const(reg->var_off)) {
7664 		min_off = max_off = reg->var_off.value + off;
7665 	} else {
7666 		/* Variable offset is prohibited for unprivileged mode for
7667 		 * simplicity since it requires corresponding support in
7668 		 * Spectre masking for stack ALU.
7669 		 * See also retrieve_ptr_limit().
7670 		 */
7671 		if (!env->bypass_spec_v1) {
7672 			char tn_buf[48];
7673 
7674 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7675 			verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
7676 				regno, tn_buf);
7677 			return -EACCES;
7678 		}
7679 		/* Only initialized buffer on stack is allowed to be accessed
7680 		 * with variable offset. With uninitialized buffer it's hard to
7681 		 * guarantee that whole memory is marked as initialized on
7682 		 * helper return since specific bounds are unknown what may
7683 		 * cause uninitialized stack leaking.
7684 		 */
7685 		if (meta && meta->raw_mode)
7686 			meta = NULL;
7687 
7688 		min_off = reg->smin_value + off;
7689 		max_off = reg->smax_value + off;
7690 	}
7691 
7692 	if (meta && meta->raw_mode) {
7693 		/* Ensure we won't be overwriting dynptrs when simulating byte
7694 		 * by byte access in check_helper_call using meta.access_size.
7695 		 * This would be a problem if we have a helper in the future
7696 		 * which takes:
7697 		 *
7698 		 *	helper(uninit_mem, len, dynptr)
7699 		 *
7700 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7701 		 * may end up writing to dynptr itself when touching memory from
7702 		 * arg 1. This can be relaxed on a case by case basis for known
7703 		 * safe cases, but reject due to the possibilitiy of aliasing by
7704 		 * default.
7705 		 */
7706 		for (i = min_off; i < max_off + access_size; i++) {
7707 			int stack_off = -i - 1;
7708 
7709 			spi = __get_spi(i);
7710 			/* raw_mode may write past allocated_stack */
7711 			if (state->allocated_stack <= stack_off)
7712 				continue;
7713 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7714 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7715 				return -EACCES;
7716 			}
7717 		}
7718 		meta->access_size = access_size;
7719 		meta->regno = regno;
7720 		return 0;
7721 	}
7722 
7723 	for (i = min_off; i < max_off + access_size; i++) {
7724 		u8 *stype;
7725 
7726 		slot = -i - 1;
7727 		spi = slot / BPF_REG_SIZE;
7728 		if (state->allocated_stack <= slot) {
7729 			verbose(env, "verifier bug: allocated_stack too small\n");
7730 			return -EFAULT;
7731 		}
7732 
7733 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7734 		if (*stype == STACK_MISC)
7735 			goto mark;
7736 		if ((*stype == STACK_ZERO) ||
7737 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7738 			if (clobber) {
7739 				/* helper can write anything into the stack */
7740 				*stype = STACK_MISC;
7741 			}
7742 			goto mark;
7743 		}
7744 
7745 		if (is_spilled_reg(&state->stack[spi]) &&
7746 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7747 		     env->allow_ptr_leaks)) {
7748 			if (clobber) {
7749 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7750 				for (j = 0; j < BPF_REG_SIZE; j++)
7751 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7752 			}
7753 			goto mark;
7754 		}
7755 
7756 		if (tnum_is_const(reg->var_off)) {
7757 			verbose(env, "invalid read from stack R%d off %d+%d size %d\n",
7758 				regno, min_off, i - min_off, access_size);
7759 		} else {
7760 			char tn_buf[48];
7761 
7762 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7763 			verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n",
7764 				regno, tn_buf, i - min_off, access_size);
7765 		}
7766 		return -EACCES;
7767 mark:
7768 		/* reading any byte out of 8-byte 'spill_slot' will cause
7769 		 * the whole slot to be marked as 'read'
7770 		 */
7771 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7772 			      state->stack[spi].spilled_ptr.parent,
7773 			      REG_LIVE_READ64);
7774 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7775 		 * be sure that whether stack slot is written to or not. Hence,
7776 		 * we must still conservatively propagate reads upwards even if
7777 		 * helper may write to the entire memory range.
7778 		 */
7779 	}
7780 	return 0;
7781 }
7782 
7783 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7784 				   int access_size, enum bpf_access_type access_type,
7785 				   bool zero_size_allowed,
7786 				   struct bpf_call_arg_meta *meta)
7787 {
7788 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7789 	u32 *max_access;
7790 
7791 	switch (base_type(reg->type)) {
7792 	case PTR_TO_PACKET:
7793 	case PTR_TO_PACKET_META:
7794 		return check_packet_access(env, regno, reg->off, access_size,
7795 					   zero_size_allowed);
7796 	case PTR_TO_MAP_KEY:
7797 		if (access_type == BPF_WRITE) {
7798 			verbose(env, "R%d cannot write into %s\n", regno,
7799 				reg_type_str(env, reg->type));
7800 			return -EACCES;
7801 		}
7802 		return check_mem_region_access(env, regno, reg->off, access_size,
7803 					       reg->map_ptr->key_size, false);
7804 	case PTR_TO_MAP_VALUE:
7805 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
7806 			return -EACCES;
7807 		return check_map_access(env, regno, reg->off, access_size,
7808 					zero_size_allowed, ACCESS_HELPER);
7809 	case PTR_TO_MEM:
7810 		if (type_is_rdonly_mem(reg->type)) {
7811 			if (access_type == BPF_WRITE) {
7812 				verbose(env, "R%d cannot write into %s\n", regno,
7813 					reg_type_str(env, reg->type));
7814 				return -EACCES;
7815 			}
7816 		}
7817 		return check_mem_region_access(env, regno, reg->off,
7818 					       access_size, reg->mem_size,
7819 					       zero_size_allowed);
7820 	case PTR_TO_BUF:
7821 		if (type_is_rdonly_mem(reg->type)) {
7822 			if (access_type == BPF_WRITE) {
7823 				verbose(env, "R%d cannot write into %s\n", regno,
7824 					reg_type_str(env, reg->type));
7825 				return -EACCES;
7826 			}
7827 
7828 			max_access = &env->prog->aux->max_rdonly_access;
7829 		} else {
7830 			max_access = &env->prog->aux->max_rdwr_access;
7831 		}
7832 		return check_buffer_access(env, reg, regno, reg->off,
7833 					   access_size, zero_size_allowed,
7834 					   max_access);
7835 	case PTR_TO_STACK:
7836 		return check_stack_range_initialized(
7837 				env,
7838 				regno, reg->off, access_size,
7839 				zero_size_allowed, access_type, meta);
7840 	case PTR_TO_BTF_ID:
7841 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7842 					       access_size, BPF_READ, -1);
7843 	case PTR_TO_CTX:
7844 		/* in case the function doesn't know how to access the context,
7845 		 * (because we are in a program of type SYSCALL for example), we
7846 		 * can not statically check its size.
7847 		 * Dynamically check it now.
7848 		 */
7849 		if (!env->ops->convert_ctx_access) {
7850 			int offset = access_size - 1;
7851 
7852 			/* Allow zero-byte read from PTR_TO_CTX */
7853 			if (access_size == 0)
7854 				return zero_size_allowed ? 0 : -EACCES;
7855 
7856 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7857 						access_type, -1, false, false);
7858 		}
7859 
7860 		fallthrough;
7861 	default: /* scalar_value or invalid ptr */
7862 		/* Allow zero-byte read from NULL, regardless of pointer type */
7863 		if (zero_size_allowed && access_size == 0 &&
7864 		    register_is_null(reg))
7865 			return 0;
7866 
7867 		verbose(env, "R%d type=%s ", regno,
7868 			reg_type_str(env, reg->type));
7869 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7870 		return -EACCES;
7871 	}
7872 }
7873 
7874 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7875  * size.
7876  *
7877  * @regno is the register containing the access size. regno-1 is the register
7878  * containing the pointer.
7879  */
7880 static int check_mem_size_reg(struct bpf_verifier_env *env,
7881 			      struct bpf_reg_state *reg, u32 regno,
7882 			      enum bpf_access_type access_type,
7883 			      bool zero_size_allowed,
7884 			      struct bpf_call_arg_meta *meta)
7885 {
7886 	int err;
7887 
7888 	/* This is used to refine r0 return value bounds for helpers
7889 	 * that enforce this value as an upper bound on return values.
7890 	 * See do_refine_retval_range() for helpers that can refine
7891 	 * the return value. C type of helper is u32 so we pull register
7892 	 * bound from umax_value however, if negative verifier errors
7893 	 * out. Only upper bounds can be learned because retval is an
7894 	 * int type and negative retvals are allowed.
7895 	 */
7896 	meta->msize_max_value = reg->umax_value;
7897 
7898 	/* The register is SCALAR_VALUE; the access check happens using
7899 	 * its boundaries. For unprivileged variable accesses, disable
7900 	 * raw mode so that the program is required to initialize all
7901 	 * the memory that the helper could just partially fill up.
7902 	 */
7903 	if (!tnum_is_const(reg->var_off))
7904 		meta = NULL;
7905 
7906 	if (reg->smin_value < 0) {
7907 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7908 			regno);
7909 		return -EACCES;
7910 	}
7911 
7912 	if (reg->umin_value == 0 && !zero_size_allowed) {
7913 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7914 			regno, reg->umin_value, reg->umax_value);
7915 		return -EACCES;
7916 	}
7917 
7918 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7919 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7920 			regno);
7921 		return -EACCES;
7922 	}
7923 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
7924 				      access_type, zero_size_allowed, meta);
7925 	if (!err)
7926 		err = mark_chain_precision(env, regno);
7927 	return err;
7928 }
7929 
7930 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7931 			 u32 regno, u32 mem_size)
7932 {
7933 	bool may_be_null = type_may_be_null(reg->type);
7934 	struct bpf_reg_state saved_reg;
7935 	int err;
7936 
7937 	if (register_is_null(reg))
7938 		return 0;
7939 
7940 	/* Assuming that the register contains a value check if the memory
7941 	 * access is safe. Temporarily save and restore the register's state as
7942 	 * the conversion shouldn't be visible to a caller.
7943 	 */
7944 	if (may_be_null) {
7945 		saved_reg = *reg;
7946 		mark_ptr_not_null_reg(reg);
7947 	}
7948 
7949 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
7950 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
7951 
7952 	if (may_be_null)
7953 		*reg = saved_reg;
7954 
7955 	return err;
7956 }
7957 
7958 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7959 				    u32 regno)
7960 {
7961 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7962 	bool may_be_null = type_may_be_null(mem_reg->type);
7963 	struct bpf_reg_state saved_reg;
7964 	struct bpf_call_arg_meta meta;
7965 	int err;
7966 
7967 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7968 
7969 	memset(&meta, 0, sizeof(meta));
7970 
7971 	if (may_be_null) {
7972 		saved_reg = *mem_reg;
7973 		mark_ptr_not_null_reg(mem_reg);
7974 	}
7975 
7976 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
7977 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
7978 
7979 	if (may_be_null)
7980 		*mem_reg = saved_reg;
7981 
7982 	return err;
7983 }
7984 
7985 /* Implementation details:
7986  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7987  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7988  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7989  * Two separate bpf_obj_new will also have different reg->id.
7990  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7991  * clears reg->id after value_or_null->value transition, since the verifier only
7992  * cares about the range of access to valid map value pointer and doesn't care
7993  * about actual address of the map element.
7994  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7995  * reg->id > 0 after value_or_null->value transition. By doing so
7996  * two bpf_map_lookups will be considered two different pointers that
7997  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7998  * returned from bpf_obj_new.
7999  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8000  * dead-locks.
8001  * Since only one bpf_spin_lock is allowed the checks are simpler than
8002  * reg_is_refcounted() logic. The verifier needs to remember only
8003  * one spin_lock instead of array of acquired_refs.
8004  * env->cur_state->active_locks remembers which map value element or allocated
8005  * object got locked and clears it after bpf_spin_unlock.
8006  */
8007 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
8008 			     bool is_lock)
8009 {
8010 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8011 	struct bpf_verifier_state *cur = env->cur_state;
8012 	bool is_const = tnum_is_const(reg->var_off);
8013 	u64 val = reg->var_off.value;
8014 	struct bpf_map *map = NULL;
8015 	struct btf *btf = NULL;
8016 	struct btf_record *rec;
8017 	int err;
8018 
8019 	if (!is_const) {
8020 		verbose(env,
8021 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
8022 			regno);
8023 		return -EINVAL;
8024 	}
8025 	if (reg->type == PTR_TO_MAP_VALUE) {
8026 		map = reg->map_ptr;
8027 		if (!map->btf) {
8028 			verbose(env,
8029 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
8030 				map->name);
8031 			return -EINVAL;
8032 		}
8033 	} else {
8034 		btf = reg->btf;
8035 	}
8036 
8037 	rec = reg_btf_record(reg);
8038 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
8039 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
8040 			map ? map->name : "kptr");
8041 		return -EINVAL;
8042 	}
8043 	if (rec->spin_lock_off != val + reg->off) {
8044 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
8045 			val + reg->off, rec->spin_lock_off);
8046 		return -EINVAL;
8047 	}
8048 	if (is_lock) {
8049 		void *ptr;
8050 
8051 		if (map)
8052 			ptr = map;
8053 		else
8054 			ptr = btf;
8055 
8056 		if (cur->active_locks) {
8057 			verbose(env,
8058 				"Locking two bpf_spin_locks are not allowed\n");
8059 			return -EINVAL;
8060 		}
8061 		err = acquire_lock_state(env, env->insn_idx, REF_TYPE_LOCK, reg->id, ptr);
8062 		if (err < 0) {
8063 			verbose(env, "Failed to acquire lock state\n");
8064 			return err;
8065 		}
8066 	} else {
8067 		void *ptr;
8068 
8069 		if (map)
8070 			ptr = map;
8071 		else
8072 			ptr = btf;
8073 
8074 		if (!cur->active_locks) {
8075 			verbose(env, "bpf_spin_unlock without taking a lock\n");
8076 			return -EINVAL;
8077 		}
8078 
8079 		if (release_lock_state(env->cur_state, REF_TYPE_LOCK, reg->id, ptr)) {
8080 			verbose(env, "bpf_spin_unlock of different lock\n");
8081 			return -EINVAL;
8082 		}
8083 
8084 		invalidate_non_owning_refs(env);
8085 	}
8086 	return 0;
8087 }
8088 
8089 static int process_timer_func(struct bpf_verifier_env *env, int regno,
8090 			      struct bpf_call_arg_meta *meta)
8091 {
8092 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8093 	bool is_const = tnum_is_const(reg->var_off);
8094 	struct bpf_map *map = reg->map_ptr;
8095 	u64 val = reg->var_off.value;
8096 
8097 	if (!is_const) {
8098 		verbose(env,
8099 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
8100 			regno);
8101 		return -EINVAL;
8102 	}
8103 	if (!map->btf) {
8104 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
8105 			map->name);
8106 		return -EINVAL;
8107 	}
8108 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
8109 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
8110 		return -EINVAL;
8111 	}
8112 	if (map->record->timer_off != val + reg->off) {
8113 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
8114 			val + reg->off, map->record->timer_off);
8115 		return -EINVAL;
8116 	}
8117 	if (meta->map_ptr) {
8118 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
8119 		return -EFAULT;
8120 	}
8121 	meta->map_uid = reg->map_uid;
8122 	meta->map_ptr = map;
8123 	return 0;
8124 }
8125 
8126 static int process_wq_func(struct bpf_verifier_env *env, int regno,
8127 			   struct bpf_kfunc_call_arg_meta *meta)
8128 {
8129 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8130 	struct bpf_map *map = reg->map_ptr;
8131 	u64 val = reg->var_off.value;
8132 
8133 	if (map->record->wq_off != val + reg->off) {
8134 		verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
8135 			val + reg->off, map->record->wq_off);
8136 		return -EINVAL;
8137 	}
8138 	meta->map.uid = reg->map_uid;
8139 	meta->map.ptr = map;
8140 	return 0;
8141 }
8142 
8143 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8144 			     struct bpf_call_arg_meta *meta)
8145 {
8146 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8147 	struct btf_field *kptr_field;
8148 	struct bpf_map *map_ptr;
8149 	struct btf_record *rec;
8150 	u32 kptr_off;
8151 
8152 	if (type_is_ptr_alloc_obj(reg->type)) {
8153 		rec = reg_btf_record(reg);
8154 	} else { /* PTR_TO_MAP_VALUE */
8155 		map_ptr = reg->map_ptr;
8156 		if (!map_ptr->btf) {
8157 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8158 				map_ptr->name);
8159 			return -EINVAL;
8160 		}
8161 		rec = map_ptr->record;
8162 		meta->map_ptr = map_ptr;
8163 	}
8164 
8165 	if (!tnum_is_const(reg->var_off)) {
8166 		verbose(env,
8167 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8168 			regno);
8169 		return -EINVAL;
8170 	}
8171 
8172 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8173 		verbose(env, "R%d has no valid kptr\n", regno);
8174 		return -EINVAL;
8175 	}
8176 
8177 	kptr_off = reg->off + reg->var_off.value;
8178 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8179 	if (!kptr_field) {
8180 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8181 		return -EACCES;
8182 	}
8183 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8184 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8185 		return -EACCES;
8186 	}
8187 	meta->kptr_field = kptr_field;
8188 	return 0;
8189 }
8190 
8191 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8192  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8193  *
8194  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8195  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8196  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8197  *
8198  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
8199  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
8200  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
8201  * mutate the view of the dynptr and also possibly destroy it. In the latter
8202  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
8203  * memory that dynptr points to.
8204  *
8205  * The verifier will keep track both levels of mutation (bpf_dynptr's in
8206  * reg->type and the memory's in reg->dynptr.type), but there is no support for
8207  * readonly dynptr view yet, hence only the first case is tracked and checked.
8208  *
8209  * This is consistent with how C applies the const modifier to a struct object,
8210  * where the pointer itself inside bpf_dynptr becomes const but not what it
8211  * points to.
8212  *
8213  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
8214  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
8215  */
8216 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
8217 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
8218 {
8219 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8220 	int err;
8221 
8222 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
8223 		verbose(env,
8224 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
8225 			regno - 1);
8226 		return -EINVAL;
8227 	}
8228 
8229 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
8230 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
8231 	 */
8232 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
8233 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
8234 		return -EFAULT;
8235 	}
8236 
8237 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8238 	 *		 constructing a mutable bpf_dynptr object.
8239 	 *
8240 	 *		 Currently, this is only possible with PTR_TO_STACK
8241 	 *		 pointing to a region of at least 16 bytes which doesn't
8242 	 *		 contain an existing bpf_dynptr.
8243 	 *
8244 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
8245 	 *		 mutated or destroyed. However, the memory it points to
8246 	 *		 may be mutated.
8247 	 *
8248 	 *  None       - Points to a initialized dynptr that can be mutated and
8249 	 *		 destroyed, including mutation of the memory it points
8250 	 *		 to.
8251 	 */
8252 	if (arg_type & MEM_UNINIT) {
8253 		int i;
8254 
8255 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8256 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8257 			return -EINVAL;
8258 		}
8259 
8260 		/* we write BPF_DW bits (8 bytes) at a time */
8261 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8262 			err = check_mem_access(env, insn_idx, regno,
8263 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8264 			if (err)
8265 				return err;
8266 		}
8267 
8268 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
8269 	} else /* MEM_RDONLY and None case from above */ {
8270 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8271 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
8272 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
8273 			return -EINVAL;
8274 		}
8275 
8276 		if (!is_dynptr_reg_valid_init(env, reg)) {
8277 			verbose(env,
8278 				"Expected an initialized dynptr as arg #%d\n",
8279 				regno - 1);
8280 			return -EINVAL;
8281 		}
8282 
8283 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
8284 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
8285 			verbose(env,
8286 				"Expected a dynptr of type %s as arg #%d\n",
8287 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
8288 			return -EINVAL;
8289 		}
8290 
8291 		err = mark_dynptr_read(env, reg);
8292 	}
8293 	return err;
8294 }
8295 
8296 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
8297 {
8298 	struct bpf_func_state *state = func(env, reg);
8299 
8300 	return state->stack[spi].spilled_ptr.ref_obj_id;
8301 }
8302 
8303 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8304 {
8305 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8306 }
8307 
8308 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8309 {
8310 	return meta->kfunc_flags & KF_ITER_NEW;
8311 }
8312 
8313 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8314 {
8315 	return meta->kfunc_flags & KF_ITER_NEXT;
8316 }
8317 
8318 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8319 {
8320 	return meta->kfunc_flags & KF_ITER_DESTROY;
8321 }
8322 
8323 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
8324 			      const struct btf_param *arg)
8325 {
8326 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8327 	 * kfunc is iter state pointer
8328 	 */
8329 	if (is_iter_kfunc(meta))
8330 		return arg_idx == 0;
8331 
8332 	/* iter passed as an argument to a generic kfunc */
8333 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8334 }
8335 
8336 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
8337 			    struct bpf_kfunc_call_arg_meta *meta)
8338 {
8339 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8340 	const struct btf_type *t;
8341 	int spi, err, i, nr_slots, btf_id;
8342 
8343 	if (reg->type != PTR_TO_STACK) {
8344 		verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
8345 		return -EINVAL;
8346 	}
8347 
8348 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8349 	 * ensures struct convention, so we wouldn't need to do any BTF
8350 	 * validation here. But given iter state can be passed as a parameter
8351 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8352 	 * conservative here.
8353 	 */
8354 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8355 	if (btf_id < 0) {
8356 		verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
8357 		return -EINVAL;
8358 	}
8359 	t = btf_type_by_id(meta->btf, btf_id);
8360 	nr_slots = t->size / BPF_REG_SIZE;
8361 
8362 	if (is_iter_new_kfunc(meta)) {
8363 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8364 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8365 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8366 				iter_type_str(meta->btf, btf_id), regno - 1);
8367 			return -EINVAL;
8368 		}
8369 
8370 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8371 			err = check_mem_access(env, insn_idx, regno,
8372 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8373 			if (err)
8374 				return err;
8375 		}
8376 
8377 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8378 		if (err)
8379 			return err;
8380 	} else {
8381 		/* iter_next() or iter_destroy(), as well as any kfunc
8382 		 * accepting iter argument, expect initialized iter state
8383 		 */
8384 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8385 		switch (err) {
8386 		case 0:
8387 			break;
8388 		case -EINVAL:
8389 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
8390 				iter_type_str(meta->btf, btf_id), regno - 1);
8391 			return err;
8392 		case -EPROTO:
8393 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8394 			return err;
8395 		default:
8396 			return err;
8397 		}
8398 
8399 		spi = iter_get_spi(env, reg, nr_slots);
8400 		if (spi < 0)
8401 			return spi;
8402 
8403 		err = mark_iter_read(env, reg, spi, nr_slots);
8404 		if (err)
8405 			return err;
8406 
8407 		/* remember meta->iter info for process_iter_next_call() */
8408 		meta->iter.spi = spi;
8409 		meta->iter.frameno = reg->frameno;
8410 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8411 
8412 		if (is_iter_destroy_kfunc(meta)) {
8413 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8414 			if (err)
8415 				return err;
8416 		}
8417 	}
8418 
8419 	return 0;
8420 }
8421 
8422 /* Look for a previous loop entry at insn_idx: nearest parent state
8423  * stopped at insn_idx with callsites matching those in cur->frame.
8424  */
8425 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8426 						  struct bpf_verifier_state *cur,
8427 						  int insn_idx)
8428 {
8429 	struct bpf_verifier_state_list *sl;
8430 	struct bpf_verifier_state *st;
8431 
8432 	/* Explored states are pushed in stack order, most recent states come first */
8433 	sl = *explored_state(env, insn_idx);
8434 	for (; sl; sl = sl->next) {
8435 		/* If st->branches != 0 state is a part of current DFS verification path,
8436 		 * hence cur & st for a loop.
8437 		 */
8438 		st = &sl->state;
8439 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8440 		    st->dfs_depth < cur->dfs_depth)
8441 			return st;
8442 	}
8443 
8444 	return NULL;
8445 }
8446 
8447 static void reset_idmap_scratch(struct bpf_verifier_env *env);
8448 static bool regs_exact(const struct bpf_reg_state *rold,
8449 		       const struct bpf_reg_state *rcur,
8450 		       struct bpf_idmap *idmap);
8451 
8452 static void maybe_widen_reg(struct bpf_verifier_env *env,
8453 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8454 			    struct bpf_idmap *idmap)
8455 {
8456 	if (rold->type != SCALAR_VALUE)
8457 		return;
8458 	if (rold->type != rcur->type)
8459 		return;
8460 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
8461 		return;
8462 	__mark_reg_unknown(env, rcur);
8463 }
8464 
8465 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8466 				   struct bpf_verifier_state *old,
8467 				   struct bpf_verifier_state *cur)
8468 {
8469 	struct bpf_func_state *fold, *fcur;
8470 	int i, fr;
8471 
8472 	reset_idmap_scratch(env);
8473 	for (fr = old->curframe; fr >= 0; fr--) {
8474 		fold = old->frame[fr];
8475 		fcur = cur->frame[fr];
8476 
8477 		for (i = 0; i < MAX_BPF_REG; i++)
8478 			maybe_widen_reg(env,
8479 					&fold->regs[i],
8480 					&fcur->regs[i],
8481 					&env->idmap_scratch);
8482 
8483 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
8484 			if (!is_spilled_reg(&fold->stack[i]) ||
8485 			    !is_spilled_reg(&fcur->stack[i]))
8486 				continue;
8487 
8488 			maybe_widen_reg(env,
8489 					&fold->stack[i].spilled_ptr,
8490 					&fcur->stack[i].spilled_ptr,
8491 					&env->idmap_scratch);
8492 		}
8493 	}
8494 	return 0;
8495 }
8496 
8497 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8498 						 struct bpf_kfunc_call_arg_meta *meta)
8499 {
8500 	int iter_frameno = meta->iter.frameno;
8501 	int iter_spi = meta->iter.spi;
8502 
8503 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8504 }
8505 
8506 /* process_iter_next_call() is called when verifier gets to iterator's next
8507  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8508  * to it as just "iter_next()" in comments below.
8509  *
8510  * BPF verifier relies on a crucial contract for any iter_next()
8511  * implementation: it should *eventually* return NULL, and once that happens
8512  * it should keep returning NULL. That is, once iterator exhausts elements to
8513  * iterate, it should never reset or spuriously return new elements.
8514  *
8515  * With the assumption of such contract, process_iter_next_call() simulates
8516  * a fork in the verifier state to validate loop logic correctness and safety
8517  * without having to simulate infinite amount of iterations.
8518  *
8519  * In current state, we first assume that iter_next() returned NULL and
8520  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8521  * conditions we should not form an infinite loop and should eventually reach
8522  * exit.
8523  *
8524  * Besides that, we also fork current state and enqueue it for later
8525  * verification. In a forked state we keep iterator state as ACTIVE
8526  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8527  * also bump iteration depth to prevent erroneous infinite loop detection
8528  * later on (see iter_active_depths_differ() comment for details). In this
8529  * state we assume that we'll eventually loop back to another iter_next()
8530  * calls (it could be in exactly same location or in some other instruction,
8531  * it doesn't matter, we don't make any unnecessary assumptions about this,
8532  * everything revolves around iterator state in a stack slot, not which
8533  * instruction is calling iter_next()). When that happens, we either will come
8534  * to iter_next() with equivalent state and can conclude that next iteration
8535  * will proceed in exactly the same way as we just verified, so it's safe to
8536  * assume that loop converges. If not, we'll go on another iteration
8537  * simulation with a different input state, until all possible starting states
8538  * are validated or we reach maximum number of instructions limit.
8539  *
8540  * This way, we will either exhaustively discover all possible input states
8541  * that iterator loop can start with and eventually will converge, or we'll
8542  * effectively regress into bounded loop simulation logic and either reach
8543  * maximum number of instructions if loop is not provably convergent, or there
8544  * is some statically known limit on number of iterations (e.g., if there is
8545  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8546  *
8547  * Iteration convergence logic in is_state_visited() relies on exact
8548  * states comparison, which ignores read and precision marks.
8549  * This is necessary because read and precision marks are not finalized
8550  * while in the loop. Exact comparison might preclude convergence for
8551  * simple programs like below:
8552  *
8553  *     i = 0;
8554  *     while(iter_next(&it))
8555  *       i++;
8556  *
8557  * At each iteration step i++ would produce a new distinct state and
8558  * eventually instruction processing limit would be reached.
8559  *
8560  * To avoid such behavior speculatively forget (widen) range for
8561  * imprecise scalar registers, if those registers were not precise at the
8562  * end of the previous iteration and do not match exactly.
8563  *
8564  * This is a conservative heuristic that allows to verify wide range of programs,
8565  * however it precludes verification of programs that conjure an
8566  * imprecise value on the first loop iteration and use it as precise on a second.
8567  * For example, the following safe program would fail to verify:
8568  *
8569  *     struct bpf_num_iter it;
8570  *     int arr[10];
8571  *     int i = 0, a = 0;
8572  *     bpf_iter_num_new(&it, 0, 10);
8573  *     while (bpf_iter_num_next(&it)) {
8574  *       if (a == 0) {
8575  *         a = 1;
8576  *         i = 7; // Because i changed verifier would forget
8577  *                // it's range on second loop entry.
8578  *       } else {
8579  *         arr[i] = 42; // This would fail to verify.
8580  *       }
8581  *     }
8582  *     bpf_iter_num_destroy(&it);
8583  */
8584 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8585 				  struct bpf_kfunc_call_arg_meta *meta)
8586 {
8587 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8588 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8589 	struct bpf_reg_state *cur_iter, *queued_iter;
8590 
8591 	BTF_TYPE_EMIT(struct bpf_iter);
8592 
8593 	cur_iter = get_iter_from_state(cur_st, meta);
8594 
8595 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8596 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8597 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
8598 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8599 		return -EFAULT;
8600 	}
8601 
8602 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8603 		/* Because iter_next() call is a checkpoint is_state_visitied()
8604 		 * should guarantee parent state with same call sites and insn_idx.
8605 		 */
8606 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8607 		    !same_callsites(cur_st->parent, cur_st)) {
8608 			verbose(env, "bug: bad parent state for iter next call");
8609 			return -EFAULT;
8610 		}
8611 		/* Note cur_st->parent in the call below, it is necessary to skip
8612 		 * checkpoint created for cur_st by is_state_visited()
8613 		 * right at this instruction.
8614 		 */
8615 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8616 		/* branch out active iter state */
8617 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8618 		if (!queued_st)
8619 			return -ENOMEM;
8620 
8621 		queued_iter = get_iter_from_state(queued_st, meta);
8622 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8623 		queued_iter->iter.depth++;
8624 		if (prev_st)
8625 			widen_imprecise_scalars(env, prev_st, queued_st);
8626 
8627 		queued_fr = queued_st->frame[queued_st->curframe];
8628 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8629 	}
8630 
8631 	/* switch to DRAINED state, but keep the depth unchanged */
8632 	/* mark current iter state as drained and assume returned NULL */
8633 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8634 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8635 
8636 	return 0;
8637 }
8638 
8639 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8640 {
8641 	return type == ARG_CONST_SIZE ||
8642 	       type == ARG_CONST_SIZE_OR_ZERO;
8643 }
8644 
8645 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
8646 {
8647 	return base_type(type) == ARG_PTR_TO_MEM &&
8648 	       type & MEM_UNINIT;
8649 }
8650 
8651 static bool arg_type_is_release(enum bpf_arg_type type)
8652 {
8653 	return type & OBJ_RELEASE;
8654 }
8655 
8656 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8657 {
8658 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8659 }
8660 
8661 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8662 				 const struct bpf_call_arg_meta *meta,
8663 				 enum bpf_arg_type *arg_type)
8664 {
8665 	if (!meta->map_ptr) {
8666 		/* kernel subsystem misconfigured verifier */
8667 		verbose(env, "invalid map_ptr to access map->type\n");
8668 		return -EACCES;
8669 	}
8670 
8671 	switch (meta->map_ptr->map_type) {
8672 	case BPF_MAP_TYPE_SOCKMAP:
8673 	case BPF_MAP_TYPE_SOCKHASH:
8674 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8675 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8676 		} else {
8677 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8678 			return -EINVAL;
8679 		}
8680 		break;
8681 	case BPF_MAP_TYPE_BLOOM_FILTER:
8682 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8683 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8684 		break;
8685 	default:
8686 		break;
8687 	}
8688 	return 0;
8689 }
8690 
8691 struct bpf_reg_types {
8692 	const enum bpf_reg_type types[10];
8693 	u32 *btf_id;
8694 };
8695 
8696 static const struct bpf_reg_types sock_types = {
8697 	.types = {
8698 		PTR_TO_SOCK_COMMON,
8699 		PTR_TO_SOCKET,
8700 		PTR_TO_TCP_SOCK,
8701 		PTR_TO_XDP_SOCK,
8702 	},
8703 };
8704 
8705 #ifdef CONFIG_NET
8706 static const struct bpf_reg_types btf_id_sock_common_types = {
8707 	.types = {
8708 		PTR_TO_SOCK_COMMON,
8709 		PTR_TO_SOCKET,
8710 		PTR_TO_TCP_SOCK,
8711 		PTR_TO_XDP_SOCK,
8712 		PTR_TO_BTF_ID,
8713 		PTR_TO_BTF_ID | PTR_TRUSTED,
8714 	},
8715 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8716 };
8717 #endif
8718 
8719 static const struct bpf_reg_types mem_types = {
8720 	.types = {
8721 		PTR_TO_STACK,
8722 		PTR_TO_PACKET,
8723 		PTR_TO_PACKET_META,
8724 		PTR_TO_MAP_KEY,
8725 		PTR_TO_MAP_VALUE,
8726 		PTR_TO_MEM,
8727 		PTR_TO_MEM | MEM_RINGBUF,
8728 		PTR_TO_BUF,
8729 		PTR_TO_BTF_ID | PTR_TRUSTED,
8730 	},
8731 };
8732 
8733 static const struct bpf_reg_types spin_lock_types = {
8734 	.types = {
8735 		PTR_TO_MAP_VALUE,
8736 		PTR_TO_BTF_ID | MEM_ALLOC,
8737 	}
8738 };
8739 
8740 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8741 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8742 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8743 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8744 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8745 static const struct bpf_reg_types btf_ptr_types = {
8746 	.types = {
8747 		PTR_TO_BTF_ID,
8748 		PTR_TO_BTF_ID | PTR_TRUSTED,
8749 		PTR_TO_BTF_ID | MEM_RCU,
8750 	},
8751 };
8752 static const struct bpf_reg_types percpu_btf_ptr_types = {
8753 	.types = {
8754 		PTR_TO_BTF_ID | MEM_PERCPU,
8755 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8756 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8757 	}
8758 };
8759 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8760 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8761 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8762 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8763 static const struct bpf_reg_types kptr_xchg_dest_types = {
8764 	.types = {
8765 		PTR_TO_MAP_VALUE,
8766 		PTR_TO_BTF_ID | MEM_ALLOC
8767 	}
8768 };
8769 static const struct bpf_reg_types dynptr_types = {
8770 	.types = {
8771 		PTR_TO_STACK,
8772 		CONST_PTR_TO_DYNPTR,
8773 	}
8774 };
8775 
8776 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8777 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8778 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8779 	[ARG_CONST_SIZE]		= &scalar_types,
8780 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8781 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8782 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8783 	[ARG_PTR_TO_CTX]		= &context_types,
8784 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8785 #ifdef CONFIG_NET
8786 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8787 #endif
8788 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8789 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8790 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8791 	[ARG_PTR_TO_MEM]		= &mem_types,
8792 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8793 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8794 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8795 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8796 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8797 	[ARG_PTR_TO_TIMER]		= &timer_types,
8798 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
8799 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8800 };
8801 
8802 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8803 			  enum bpf_arg_type arg_type,
8804 			  const u32 *arg_btf_id,
8805 			  struct bpf_call_arg_meta *meta)
8806 {
8807 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8808 	enum bpf_reg_type expected, type = reg->type;
8809 	const struct bpf_reg_types *compatible;
8810 	int i, j;
8811 
8812 	compatible = compatible_reg_types[base_type(arg_type)];
8813 	if (!compatible) {
8814 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8815 		return -EFAULT;
8816 	}
8817 
8818 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8819 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8820 	 *
8821 	 * Same for MAYBE_NULL:
8822 	 *
8823 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8824 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8825 	 *
8826 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8827 	 *
8828 	 * Therefore we fold these flags depending on the arg_type before comparison.
8829 	 */
8830 	if (arg_type & MEM_RDONLY)
8831 		type &= ~MEM_RDONLY;
8832 	if (arg_type & PTR_MAYBE_NULL)
8833 		type &= ~PTR_MAYBE_NULL;
8834 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8835 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8836 
8837 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
8838 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
8839 		type &= ~MEM_ALLOC;
8840 		type &= ~MEM_PERCPU;
8841 	}
8842 
8843 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8844 		expected = compatible->types[i];
8845 		if (expected == NOT_INIT)
8846 			break;
8847 
8848 		if (type == expected)
8849 			goto found;
8850 	}
8851 
8852 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8853 	for (j = 0; j + 1 < i; j++)
8854 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8855 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8856 	return -EACCES;
8857 
8858 found:
8859 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8860 		return 0;
8861 
8862 	if (compatible == &mem_types) {
8863 		if (!(arg_type & MEM_RDONLY)) {
8864 			verbose(env,
8865 				"%s() may write into memory pointed by R%d type=%s\n",
8866 				func_id_name(meta->func_id),
8867 				regno, reg_type_str(env, reg->type));
8868 			return -EACCES;
8869 		}
8870 		return 0;
8871 	}
8872 
8873 	switch ((int)reg->type) {
8874 	case PTR_TO_BTF_ID:
8875 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8876 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
8877 	case PTR_TO_BTF_ID | MEM_RCU:
8878 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8879 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8880 	{
8881 		/* For bpf_sk_release, it needs to match against first member
8882 		 * 'struct sock_common', hence make an exception for it. This
8883 		 * allows bpf_sk_release to work for multiple socket types.
8884 		 */
8885 		bool strict_type_match = arg_type_is_release(arg_type) &&
8886 					 meta->func_id != BPF_FUNC_sk_release;
8887 
8888 		if (type_may_be_null(reg->type) &&
8889 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8890 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8891 			return -EACCES;
8892 		}
8893 
8894 		if (!arg_btf_id) {
8895 			if (!compatible->btf_id) {
8896 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8897 				return -EFAULT;
8898 			}
8899 			arg_btf_id = compatible->btf_id;
8900 		}
8901 
8902 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8903 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8904 				return -EACCES;
8905 		} else {
8906 			if (arg_btf_id == BPF_PTR_POISON) {
8907 				verbose(env, "verifier internal error:");
8908 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8909 					regno);
8910 				return -EACCES;
8911 			}
8912 
8913 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8914 						  btf_vmlinux, *arg_btf_id,
8915 						  strict_type_match)) {
8916 				verbose(env, "R%d is of type %s but %s is expected\n",
8917 					regno, btf_type_name(reg->btf, reg->btf_id),
8918 					btf_type_name(btf_vmlinux, *arg_btf_id));
8919 				return -EACCES;
8920 			}
8921 		}
8922 		break;
8923 	}
8924 	case PTR_TO_BTF_ID | MEM_ALLOC:
8925 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8926 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8927 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8928 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8929 			return -EFAULT;
8930 		}
8931 		/* Check if local kptr in src arg matches kptr in dst arg */
8932 		if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
8933 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8934 				return -EACCES;
8935 		}
8936 		break;
8937 	case PTR_TO_BTF_ID | MEM_PERCPU:
8938 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8939 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8940 		/* Handled by helper specific checks */
8941 		break;
8942 	default:
8943 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8944 		return -EFAULT;
8945 	}
8946 	return 0;
8947 }
8948 
8949 static struct btf_field *
8950 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8951 {
8952 	struct btf_field *field;
8953 	struct btf_record *rec;
8954 
8955 	rec = reg_btf_record(reg);
8956 	if (!rec)
8957 		return NULL;
8958 
8959 	field = btf_record_find(rec, off, fields);
8960 	if (!field)
8961 		return NULL;
8962 
8963 	return field;
8964 }
8965 
8966 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8967 				  const struct bpf_reg_state *reg, int regno,
8968 				  enum bpf_arg_type arg_type)
8969 {
8970 	u32 type = reg->type;
8971 
8972 	/* When referenced register is passed to release function, its fixed
8973 	 * offset must be 0.
8974 	 *
8975 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8976 	 * meta->release_regno.
8977 	 */
8978 	if (arg_type_is_release(arg_type)) {
8979 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8980 		 * may not directly point to the object being released, but to
8981 		 * dynptr pointing to such object, which might be at some offset
8982 		 * on the stack. In that case, we simply to fallback to the
8983 		 * default handling.
8984 		 */
8985 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8986 			return 0;
8987 
8988 		/* Doing check_ptr_off_reg check for the offset will catch this
8989 		 * because fixed_off_ok is false, but checking here allows us
8990 		 * to give the user a better error message.
8991 		 */
8992 		if (reg->off) {
8993 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8994 				regno);
8995 			return -EINVAL;
8996 		}
8997 		return __check_ptr_off_reg(env, reg, regno, false);
8998 	}
8999 
9000 	switch (type) {
9001 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9002 	case PTR_TO_STACK:
9003 	case PTR_TO_PACKET:
9004 	case PTR_TO_PACKET_META:
9005 	case PTR_TO_MAP_KEY:
9006 	case PTR_TO_MAP_VALUE:
9007 	case PTR_TO_MEM:
9008 	case PTR_TO_MEM | MEM_RDONLY:
9009 	case PTR_TO_MEM | MEM_RINGBUF:
9010 	case PTR_TO_BUF:
9011 	case PTR_TO_BUF | MEM_RDONLY:
9012 	case PTR_TO_ARENA:
9013 	case SCALAR_VALUE:
9014 		return 0;
9015 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9016 	 * fixed offset.
9017 	 */
9018 	case PTR_TO_BTF_ID:
9019 	case PTR_TO_BTF_ID | MEM_ALLOC:
9020 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9021 	case PTR_TO_BTF_ID | MEM_RCU:
9022 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9023 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9024 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9025 		 * its fixed offset must be 0. In the other cases, fixed offset
9026 		 * can be non-zero. This was already checked above. So pass
9027 		 * fixed_off_ok as true to allow fixed offset for all other
9028 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
9029 		 * still need to do checks instead of returning.
9030 		 */
9031 		return __check_ptr_off_reg(env, reg, regno, true);
9032 	default:
9033 		return __check_ptr_off_reg(env, reg, regno, false);
9034 	}
9035 }
9036 
9037 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
9038 						const struct bpf_func_proto *fn,
9039 						struct bpf_reg_state *regs)
9040 {
9041 	struct bpf_reg_state *state = NULL;
9042 	int i;
9043 
9044 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
9045 		if (arg_type_is_dynptr(fn->arg_type[i])) {
9046 			if (state) {
9047 				verbose(env, "verifier internal error: multiple dynptr args\n");
9048 				return NULL;
9049 			}
9050 			state = &regs[BPF_REG_1 + i];
9051 		}
9052 
9053 	if (!state)
9054 		verbose(env, "verifier internal error: no dynptr arg found\n");
9055 
9056 	return state;
9057 }
9058 
9059 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9060 {
9061 	struct bpf_func_state *state = func(env, reg);
9062 	int spi;
9063 
9064 	if (reg->type == CONST_PTR_TO_DYNPTR)
9065 		return reg->id;
9066 	spi = dynptr_get_spi(env, reg);
9067 	if (spi < 0)
9068 		return spi;
9069 	return state->stack[spi].spilled_ptr.id;
9070 }
9071 
9072 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9073 {
9074 	struct bpf_func_state *state = func(env, reg);
9075 	int spi;
9076 
9077 	if (reg->type == CONST_PTR_TO_DYNPTR)
9078 		return reg->ref_obj_id;
9079 	spi = dynptr_get_spi(env, reg);
9080 	if (spi < 0)
9081 		return spi;
9082 	return state->stack[spi].spilled_ptr.ref_obj_id;
9083 }
9084 
9085 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
9086 					    struct bpf_reg_state *reg)
9087 {
9088 	struct bpf_func_state *state = func(env, reg);
9089 	int spi;
9090 
9091 	if (reg->type == CONST_PTR_TO_DYNPTR)
9092 		return reg->dynptr.type;
9093 
9094 	spi = __get_spi(reg->off);
9095 	if (spi < 0) {
9096 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
9097 		return BPF_DYNPTR_TYPE_INVALID;
9098 	}
9099 
9100 	return state->stack[spi].spilled_ptr.dynptr.type;
9101 }
9102 
9103 static int check_reg_const_str(struct bpf_verifier_env *env,
9104 			       struct bpf_reg_state *reg, u32 regno)
9105 {
9106 	struct bpf_map *map = reg->map_ptr;
9107 	int err;
9108 	int map_off;
9109 	u64 map_addr;
9110 	char *str_ptr;
9111 
9112 	if (reg->type != PTR_TO_MAP_VALUE)
9113 		return -EINVAL;
9114 
9115 	if (!bpf_map_is_rdonly(map)) {
9116 		verbose(env, "R%d does not point to a readonly map'\n", regno);
9117 		return -EACCES;
9118 	}
9119 
9120 	if (!tnum_is_const(reg->var_off)) {
9121 		verbose(env, "R%d is not a constant address'\n", regno);
9122 		return -EACCES;
9123 	}
9124 
9125 	if (!map->ops->map_direct_value_addr) {
9126 		verbose(env, "no direct value access support for this map type\n");
9127 		return -EACCES;
9128 	}
9129 
9130 	err = check_map_access(env, regno, reg->off,
9131 			       map->value_size - reg->off, false,
9132 			       ACCESS_HELPER);
9133 	if (err)
9134 		return err;
9135 
9136 	map_off = reg->off + reg->var_off.value;
9137 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9138 	if (err) {
9139 		verbose(env, "direct value access on string failed\n");
9140 		return err;
9141 	}
9142 
9143 	str_ptr = (char *)(long)(map_addr);
9144 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9145 		verbose(env, "string is not zero-terminated\n");
9146 		return -EINVAL;
9147 	}
9148 	return 0;
9149 }
9150 
9151 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9152 			  struct bpf_call_arg_meta *meta,
9153 			  const struct bpf_func_proto *fn,
9154 			  int insn_idx)
9155 {
9156 	u32 regno = BPF_REG_1 + arg;
9157 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9158 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9159 	enum bpf_reg_type type = reg->type;
9160 	u32 *arg_btf_id = NULL;
9161 	int err = 0;
9162 
9163 	if (arg_type == ARG_DONTCARE)
9164 		return 0;
9165 
9166 	err = check_reg_arg(env, regno, SRC_OP);
9167 	if (err)
9168 		return err;
9169 
9170 	if (arg_type == ARG_ANYTHING) {
9171 		if (is_pointer_value(env, regno)) {
9172 			verbose(env, "R%d leaks addr into helper function\n",
9173 				regno);
9174 			return -EACCES;
9175 		}
9176 		return 0;
9177 	}
9178 
9179 	if (type_is_pkt_pointer(type) &&
9180 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9181 		verbose(env, "helper access to the packet is not allowed\n");
9182 		return -EACCES;
9183 	}
9184 
9185 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9186 		err = resolve_map_arg_type(env, meta, &arg_type);
9187 		if (err)
9188 			return err;
9189 	}
9190 
9191 	if (register_is_null(reg) && type_may_be_null(arg_type))
9192 		/* A NULL register has a SCALAR_VALUE type, so skip
9193 		 * type checking.
9194 		 */
9195 		goto skip_type_check;
9196 
9197 	/* arg_btf_id and arg_size are in a union. */
9198 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9199 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9200 		arg_btf_id = fn->arg_btf_id[arg];
9201 
9202 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9203 	if (err)
9204 		return err;
9205 
9206 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
9207 	if (err)
9208 		return err;
9209 
9210 skip_type_check:
9211 	if (arg_type_is_release(arg_type)) {
9212 		if (arg_type_is_dynptr(arg_type)) {
9213 			struct bpf_func_state *state = func(env, reg);
9214 			int spi;
9215 
9216 			/* Only dynptr created on stack can be released, thus
9217 			 * the get_spi and stack state checks for spilled_ptr
9218 			 * should only be done before process_dynptr_func for
9219 			 * PTR_TO_STACK.
9220 			 */
9221 			if (reg->type == PTR_TO_STACK) {
9222 				spi = dynptr_get_spi(env, reg);
9223 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9224 					verbose(env, "arg %d is an unacquired reference\n", regno);
9225 					return -EINVAL;
9226 				}
9227 			} else {
9228 				verbose(env, "cannot release unowned const bpf_dynptr\n");
9229 				return -EINVAL;
9230 			}
9231 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
9232 			verbose(env, "R%d must be referenced when passed to release function\n",
9233 				regno);
9234 			return -EINVAL;
9235 		}
9236 		if (meta->release_regno) {
9237 			verbose(env, "verifier internal error: more than one release argument\n");
9238 			return -EFAULT;
9239 		}
9240 		meta->release_regno = regno;
9241 	}
9242 
9243 	if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9244 		if (meta->ref_obj_id) {
9245 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
9246 				regno, reg->ref_obj_id,
9247 				meta->ref_obj_id);
9248 			return -EFAULT;
9249 		}
9250 		meta->ref_obj_id = reg->ref_obj_id;
9251 	}
9252 
9253 	switch (base_type(arg_type)) {
9254 	case ARG_CONST_MAP_PTR:
9255 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9256 		if (meta->map_ptr) {
9257 			/* Use map_uid (which is unique id of inner map) to reject:
9258 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9259 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9260 			 * if (inner_map1 && inner_map2) {
9261 			 *     timer = bpf_map_lookup_elem(inner_map1);
9262 			 *     if (timer)
9263 			 *         // mismatch would have been allowed
9264 			 *         bpf_timer_init(timer, inner_map2);
9265 			 * }
9266 			 *
9267 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
9268 			 */
9269 			if (meta->map_ptr != reg->map_ptr ||
9270 			    meta->map_uid != reg->map_uid) {
9271 				verbose(env,
9272 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9273 					meta->map_uid, reg->map_uid);
9274 				return -EINVAL;
9275 			}
9276 		}
9277 		meta->map_ptr = reg->map_ptr;
9278 		meta->map_uid = reg->map_uid;
9279 		break;
9280 	case ARG_PTR_TO_MAP_KEY:
9281 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9282 		 * check that [key, key + map->key_size) are within
9283 		 * stack limits and initialized
9284 		 */
9285 		if (!meta->map_ptr) {
9286 			/* in function declaration map_ptr must come before
9287 			 * map_key, so that it's verified and known before
9288 			 * we have to check map_key here. Otherwise it means
9289 			 * that kernel subsystem misconfigured verifier
9290 			 */
9291 			verbose(env, "invalid map_ptr to access map->key\n");
9292 			return -EACCES;
9293 		}
9294 		err = check_helper_mem_access(env, regno, meta->map_ptr->key_size,
9295 					      BPF_READ, false, NULL);
9296 		break;
9297 	case ARG_PTR_TO_MAP_VALUE:
9298 		if (type_may_be_null(arg_type) && register_is_null(reg))
9299 			return 0;
9300 
9301 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9302 		 * check [value, value + map->value_size) validity
9303 		 */
9304 		if (!meta->map_ptr) {
9305 			/* kernel subsystem misconfigured verifier */
9306 			verbose(env, "invalid map_ptr to access map->value\n");
9307 			return -EACCES;
9308 		}
9309 		meta->raw_mode = arg_type & MEM_UNINIT;
9310 		err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
9311 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9312 					      false, meta);
9313 		break;
9314 	case ARG_PTR_TO_PERCPU_BTF_ID:
9315 		if (!reg->btf_id) {
9316 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9317 			return -EACCES;
9318 		}
9319 		meta->ret_btf = reg->btf;
9320 		meta->ret_btf_id = reg->btf_id;
9321 		break;
9322 	case ARG_PTR_TO_SPIN_LOCK:
9323 		if (in_rbtree_lock_required_cb(env)) {
9324 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9325 			return -EACCES;
9326 		}
9327 		if (meta->func_id == BPF_FUNC_spin_lock) {
9328 			err = process_spin_lock(env, regno, true);
9329 			if (err)
9330 				return err;
9331 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
9332 			err = process_spin_lock(env, regno, false);
9333 			if (err)
9334 				return err;
9335 		} else {
9336 			verbose(env, "verifier internal error\n");
9337 			return -EFAULT;
9338 		}
9339 		break;
9340 	case ARG_PTR_TO_TIMER:
9341 		err = process_timer_func(env, regno, meta);
9342 		if (err)
9343 			return err;
9344 		break;
9345 	case ARG_PTR_TO_FUNC:
9346 		meta->subprogno = reg->subprogno;
9347 		break;
9348 	case ARG_PTR_TO_MEM:
9349 		/* The access to this pointer is only checked when we hit the
9350 		 * next is_mem_size argument below.
9351 		 */
9352 		meta->raw_mode = arg_type & MEM_UNINIT;
9353 		if (arg_type & MEM_FIXED_SIZE) {
9354 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
9355 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9356 						      false, meta);
9357 			if (err)
9358 				return err;
9359 			if (arg_type & MEM_ALIGNED)
9360 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9361 		}
9362 		break;
9363 	case ARG_CONST_SIZE:
9364 		err = check_mem_size_reg(env, reg, regno,
9365 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9366 					 BPF_WRITE : BPF_READ,
9367 					 false, meta);
9368 		break;
9369 	case ARG_CONST_SIZE_OR_ZERO:
9370 		err = check_mem_size_reg(env, reg, regno,
9371 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9372 					 BPF_WRITE : BPF_READ,
9373 					 true, meta);
9374 		break;
9375 	case ARG_PTR_TO_DYNPTR:
9376 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9377 		if (err)
9378 			return err;
9379 		break;
9380 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9381 		if (!tnum_is_const(reg->var_off)) {
9382 			verbose(env, "R%d is not a known constant'\n",
9383 				regno);
9384 			return -EACCES;
9385 		}
9386 		meta->mem_size = reg->var_off.value;
9387 		err = mark_chain_precision(env, regno);
9388 		if (err)
9389 			return err;
9390 		break;
9391 	case ARG_PTR_TO_CONST_STR:
9392 	{
9393 		err = check_reg_const_str(env, reg, regno);
9394 		if (err)
9395 			return err;
9396 		break;
9397 	}
9398 	case ARG_KPTR_XCHG_DEST:
9399 		err = process_kptr_func(env, regno, meta);
9400 		if (err)
9401 			return err;
9402 		break;
9403 	}
9404 
9405 	return err;
9406 }
9407 
9408 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9409 {
9410 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
9411 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9412 
9413 	if (func_id != BPF_FUNC_map_update_elem &&
9414 	    func_id != BPF_FUNC_map_delete_elem)
9415 		return false;
9416 
9417 	/* It's not possible to get access to a locked struct sock in these
9418 	 * contexts, so updating is safe.
9419 	 */
9420 	switch (type) {
9421 	case BPF_PROG_TYPE_TRACING:
9422 		if (eatype == BPF_TRACE_ITER)
9423 			return true;
9424 		break;
9425 	case BPF_PROG_TYPE_SOCK_OPS:
9426 		/* map_update allowed only via dedicated helpers with event type checks */
9427 		if (func_id == BPF_FUNC_map_delete_elem)
9428 			return true;
9429 		break;
9430 	case BPF_PROG_TYPE_SOCKET_FILTER:
9431 	case BPF_PROG_TYPE_SCHED_CLS:
9432 	case BPF_PROG_TYPE_SCHED_ACT:
9433 	case BPF_PROG_TYPE_XDP:
9434 	case BPF_PROG_TYPE_SK_REUSEPORT:
9435 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
9436 	case BPF_PROG_TYPE_SK_LOOKUP:
9437 		return true;
9438 	default:
9439 		break;
9440 	}
9441 
9442 	verbose(env, "cannot update sockmap in this context\n");
9443 	return false;
9444 }
9445 
9446 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
9447 {
9448 	return env->prog->jit_requested &&
9449 	       bpf_jit_supports_subprog_tailcalls();
9450 }
9451 
9452 static int check_map_func_compatibility(struct bpf_verifier_env *env,
9453 					struct bpf_map *map, int func_id)
9454 {
9455 	if (!map)
9456 		return 0;
9457 
9458 	/* We need a two way check, first is from map perspective ... */
9459 	switch (map->map_type) {
9460 	case BPF_MAP_TYPE_PROG_ARRAY:
9461 		if (func_id != BPF_FUNC_tail_call)
9462 			goto error;
9463 		break;
9464 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
9465 		if (func_id != BPF_FUNC_perf_event_read &&
9466 		    func_id != BPF_FUNC_perf_event_output &&
9467 		    func_id != BPF_FUNC_skb_output &&
9468 		    func_id != BPF_FUNC_perf_event_read_value &&
9469 		    func_id != BPF_FUNC_xdp_output)
9470 			goto error;
9471 		break;
9472 	case BPF_MAP_TYPE_RINGBUF:
9473 		if (func_id != BPF_FUNC_ringbuf_output &&
9474 		    func_id != BPF_FUNC_ringbuf_reserve &&
9475 		    func_id != BPF_FUNC_ringbuf_query &&
9476 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
9477 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
9478 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
9479 			goto error;
9480 		break;
9481 	case BPF_MAP_TYPE_USER_RINGBUF:
9482 		if (func_id != BPF_FUNC_user_ringbuf_drain)
9483 			goto error;
9484 		break;
9485 	case BPF_MAP_TYPE_STACK_TRACE:
9486 		if (func_id != BPF_FUNC_get_stackid)
9487 			goto error;
9488 		break;
9489 	case BPF_MAP_TYPE_CGROUP_ARRAY:
9490 		if (func_id != BPF_FUNC_skb_under_cgroup &&
9491 		    func_id != BPF_FUNC_current_task_under_cgroup)
9492 			goto error;
9493 		break;
9494 	case BPF_MAP_TYPE_CGROUP_STORAGE:
9495 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
9496 		if (func_id != BPF_FUNC_get_local_storage)
9497 			goto error;
9498 		break;
9499 	case BPF_MAP_TYPE_DEVMAP:
9500 	case BPF_MAP_TYPE_DEVMAP_HASH:
9501 		if (func_id != BPF_FUNC_redirect_map &&
9502 		    func_id != BPF_FUNC_map_lookup_elem)
9503 			goto error;
9504 		break;
9505 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
9506 	 * appear.
9507 	 */
9508 	case BPF_MAP_TYPE_CPUMAP:
9509 		if (func_id != BPF_FUNC_redirect_map)
9510 			goto error;
9511 		break;
9512 	case BPF_MAP_TYPE_XSKMAP:
9513 		if (func_id != BPF_FUNC_redirect_map &&
9514 		    func_id != BPF_FUNC_map_lookup_elem)
9515 			goto error;
9516 		break;
9517 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
9518 	case BPF_MAP_TYPE_HASH_OF_MAPS:
9519 		if (func_id != BPF_FUNC_map_lookup_elem)
9520 			goto error;
9521 		break;
9522 	case BPF_MAP_TYPE_SOCKMAP:
9523 		if (func_id != BPF_FUNC_sk_redirect_map &&
9524 		    func_id != BPF_FUNC_sock_map_update &&
9525 		    func_id != BPF_FUNC_msg_redirect_map &&
9526 		    func_id != BPF_FUNC_sk_select_reuseport &&
9527 		    func_id != BPF_FUNC_map_lookup_elem &&
9528 		    !may_update_sockmap(env, func_id))
9529 			goto error;
9530 		break;
9531 	case BPF_MAP_TYPE_SOCKHASH:
9532 		if (func_id != BPF_FUNC_sk_redirect_hash &&
9533 		    func_id != BPF_FUNC_sock_hash_update &&
9534 		    func_id != BPF_FUNC_msg_redirect_hash &&
9535 		    func_id != BPF_FUNC_sk_select_reuseport &&
9536 		    func_id != BPF_FUNC_map_lookup_elem &&
9537 		    !may_update_sockmap(env, func_id))
9538 			goto error;
9539 		break;
9540 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
9541 		if (func_id != BPF_FUNC_sk_select_reuseport)
9542 			goto error;
9543 		break;
9544 	case BPF_MAP_TYPE_QUEUE:
9545 	case BPF_MAP_TYPE_STACK:
9546 		if (func_id != BPF_FUNC_map_peek_elem &&
9547 		    func_id != BPF_FUNC_map_pop_elem &&
9548 		    func_id != BPF_FUNC_map_push_elem)
9549 			goto error;
9550 		break;
9551 	case BPF_MAP_TYPE_SK_STORAGE:
9552 		if (func_id != BPF_FUNC_sk_storage_get &&
9553 		    func_id != BPF_FUNC_sk_storage_delete &&
9554 		    func_id != BPF_FUNC_kptr_xchg)
9555 			goto error;
9556 		break;
9557 	case BPF_MAP_TYPE_INODE_STORAGE:
9558 		if (func_id != BPF_FUNC_inode_storage_get &&
9559 		    func_id != BPF_FUNC_inode_storage_delete &&
9560 		    func_id != BPF_FUNC_kptr_xchg)
9561 			goto error;
9562 		break;
9563 	case BPF_MAP_TYPE_TASK_STORAGE:
9564 		if (func_id != BPF_FUNC_task_storage_get &&
9565 		    func_id != BPF_FUNC_task_storage_delete &&
9566 		    func_id != BPF_FUNC_kptr_xchg)
9567 			goto error;
9568 		break;
9569 	case BPF_MAP_TYPE_CGRP_STORAGE:
9570 		if (func_id != BPF_FUNC_cgrp_storage_get &&
9571 		    func_id != BPF_FUNC_cgrp_storage_delete &&
9572 		    func_id != BPF_FUNC_kptr_xchg)
9573 			goto error;
9574 		break;
9575 	case BPF_MAP_TYPE_BLOOM_FILTER:
9576 		if (func_id != BPF_FUNC_map_peek_elem &&
9577 		    func_id != BPF_FUNC_map_push_elem)
9578 			goto error;
9579 		break;
9580 	default:
9581 		break;
9582 	}
9583 
9584 	/* ... and second from the function itself. */
9585 	switch (func_id) {
9586 	case BPF_FUNC_tail_call:
9587 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
9588 			goto error;
9589 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
9590 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
9591 			return -EINVAL;
9592 		}
9593 		break;
9594 	case BPF_FUNC_perf_event_read:
9595 	case BPF_FUNC_perf_event_output:
9596 	case BPF_FUNC_perf_event_read_value:
9597 	case BPF_FUNC_skb_output:
9598 	case BPF_FUNC_xdp_output:
9599 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9600 			goto error;
9601 		break;
9602 	case BPF_FUNC_ringbuf_output:
9603 	case BPF_FUNC_ringbuf_reserve:
9604 	case BPF_FUNC_ringbuf_query:
9605 	case BPF_FUNC_ringbuf_reserve_dynptr:
9606 	case BPF_FUNC_ringbuf_submit_dynptr:
9607 	case BPF_FUNC_ringbuf_discard_dynptr:
9608 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9609 			goto error;
9610 		break;
9611 	case BPF_FUNC_user_ringbuf_drain:
9612 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9613 			goto error;
9614 		break;
9615 	case BPF_FUNC_get_stackid:
9616 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9617 			goto error;
9618 		break;
9619 	case BPF_FUNC_current_task_under_cgroup:
9620 	case BPF_FUNC_skb_under_cgroup:
9621 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9622 			goto error;
9623 		break;
9624 	case BPF_FUNC_redirect_map:
9625 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9626 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9627 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
9628 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
9629 			goto error;
9630 		break;
9631 	case BPF_FUNC_sk_redirect_map:
9632 	case BPF_FUNC_msg_redirect_map:
9633 	case BPF_FUNC_sock_map_update:
9634 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9635 			goto error;
9636 		break;
9637 	case BPF_FUNC_sk_redirect_hash:
9638 	case BPF_FUNC_msg_redirect_hash:
9639 	case BPF_FUNC_sock_hash_update:
9640 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9641 			goto error;
9642 		break;
9643 	case BPF_FUNC_get_local_storage:
9644 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9645 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9646 			goto error;
9647 		break;
9648 	case BPF_FUNC_sk_select_reuseport:
9649 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9650 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9651 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
9652 			goto error;
9653 		break;
9654 	case BPF_FUNC_map_pop_elem:
9655 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9656 		    map->map_type != BPF_MAP_TYPE_STACK)
9657 			goto error;
9658 		break;
9659 	case BPF_FUNC_map_peek_elem:
9660 	case BPF_FUNC_map_push_elem:
9661 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9662 		    map->map_type != BPF_MAP_TYPE_STACK &&
9663 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9664 			goto error;
9665 		break;
9666 	case BPF_FUNC_map_lookup_percpu_elem:
9667 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9668 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9669 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9670 			goto error;
9671 		break;
9672 	case BPF_FUNC_sk_storage_get:
9673 	case BPF_FUNC_sk_storage_delete:
9674 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9675 			goto error;
9676 		break;
9677 	case BPF_FUNC_inode_storage_get:
9678 	case BPF_FUNC_inode_storage_delete:
9679 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9680 			goto error;
9681 		break;
9682 	case BPF_FUNC_task_storage_get:
9683 	case BPF_FUNC_task_storage_delete:
9684 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9685 			goto error;
9686 		break;
9687 	case BPF_FUNC_cgrp_storage_get:
9688 	case BPF_FUNC_cgrp_storage_delete:
9689 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9690 			goto error;
9691 		break;
9692 	default:
9693 		break;
9694 	}
9695 
9696 	return 0;
9697 error:
9698 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9699 		map->map_type, func_id_name(func_id), func_id);
9700 	return -EINVAL;
9701 }
9702 
9703 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9704 {
9705 	int count = 0;
9706 
9707 	if (arg_type_is_raw_mem(fn->arg1_type))
9708 		count++;
9709 	if (arg_type_is_raw_mem(fn->arg2_type))
9710 		count++;
9711 	if (arg_type_is_raw_mem(fn->arg3_type))
9712 		count++;
9713 	if (arg_type_is_raw_mem(fn->arg4_type))
9714 		count++;
9715 	if (arg_type_is_raw_mem(fn->arg5_type))
9716 		count++;
9717 
9718 	/* We only support one arg being in raw mode at the moment,
9719 	 * which is sufficient for the helper functions we have
9720 	 * right now.
9721 	 */
9722 	return count <= 1;
9723 }
9724 
9725 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9726 {
9727 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9728 	bool has_size = fn->arg_size[arg] != 0;
9729 	bool is_next_size = false;
9730 
9731 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9732 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9733 
9734 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9735 		return is_next_size;
9736 
9737 	return has_size == is_next_size || is_next_size == is_fixed;
9738 }
9739 
9740 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9741 {
9742 	/* bpf_xxx(..., buf, len) call will access 'len'
9743 	 * bytes from memory 'buf'. Both arg types need
9744 	 * to be paired, so make sure there's no buggy
9745 	 * helper function specification.
9746 	 */
9747 	if (arg_type_is_mem_size(fn->arg1_type) ||
9748 	    check_args_pair_invalid(fn, 0) ||
9749 	    check_args_pair_invalid(fn, 1) ||
9750 	    check_args_pair_invalid(fn, 2) ||
9751 	    check_args_pair_invalid(fn, 3) ||
9752 	    check_args_pair_invalid(fn, 4))
9753 		return false;
9754 
9755 	return true;
9756 }
9757 
9758 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9759 {
9760 	int i;
9761 
9762 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9763 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9764 			return !!fn->arg_btf_id[i];
9765 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9766 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9767 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9768 		    /* arg_btf_id and arg_size are in a union. */
9769 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9770 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9771 			return false;
9772 	}
9773 
9774 	return true;
9775 }
9776 
9777 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9778 {
9779 	return check_raw_mode_ok(fn) &&
9780 	       check_arg_pair_ok(fn) &&
9781 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9782 }
9783 
9784 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9785  * are now invalid, so turn them into unknown SCALAR_VALUE.
9786  *
9787  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9788  * since these slices point to packet data.
9789  */
9790 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9791 {
9792 	struct bpf_func_state *state;
9793 	struct bpf_reg_state *reg;
9794 
9795 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9796 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9797 			mark_reg_invalid(env, reg);
9798 	}));
9799 }
9800 
9801 enum {
9802 	AT_PKT_END = -1,
9803 	BEYOND_PKT_END = -2,
9804 };
9805 
9806 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9807 {
9808 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9809 	struct bpf_reg_state *reg = &state->regs[regn];
9810 
9811 	if (reg->type != PTR_TO_PACKET)
9812 		/* PTR_TO_PACKET_META is not supported yet */
9813 		return;
9814 
9815 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9816 	 * How far beyond pkt_end it goes is unknown.
9817 	 * if (!range_open) it's the case of pkt >= pkt_end
9818 	 * if (range_open) it's the case of pkt > pkt_end
9819 	 * hence this pointer is at least 1 byte bigger than pkt_end
9820 	 */
9821 	if (range_open)
9822 		reg->range = BEYOND_PKT_END;
9823 	else
9824 		reg->range = AT_PKT_END;
9825 }
9826 
9827 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id)
9828 {
9829 	int i;
9830 
9831 	for (i = 0; i < state->acquired_refs; i++) {
9832 		if (state->refs[i].type != REF_TYPE_PTR)
9833 			continue;
9834 		if (state->refs[i].id == ref_obj_id) {
9835 			release_reference_state(state, i);
9836 			return 0;
9837 		}
9838 	}
9839 	return -EINVAL;
9840 }
9841 
9842 /* The pointer with the specified id has released its reference to kernel
9843  * resources. Identify all copies of the same pointer and clear the reference.
9844  *
9845  * This is the release function corresponding to acquire_reference(). Idempotent.
9846  */
9847 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id)
9848 {
9849 	struct bpf_verifier_state *vstate = env->cur_state;
9850 	struct bpf_func_state *state;
9851 	struct bpf_reg_state *reg;
9852 	int err;
9853 
9854 	err = release_reference_nomark(vstate, ref_obj_id);
9855 	if (err)
9856 		return err;
9857 
9858 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9859 		if (reg->ref_obj_id == ref_obj_id)
9860 			mark_reg_invalid(env, reg);
9861 	}));
9862 
9863 	return 0;
9864 }
9865 
9866 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9867 {
9868 	struct bpf_func_state *unused;
9869 	struct bpf_reg_state *reg;
9870 
9871 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9872 		if (type_is_non_owning_ref(reg->type))
9873 			mark_reg_invalid(env, reg);
9874 	}));
9875 }
9876 
9877 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9878 				    struct bpf_reg_state *regs)
9879 {
9880 	int i;
9881 
9882 	/* after the call registers r0 - r5 were scratched */
9883 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9884 		mark_reg_not_init(env, regs, caller_saved[i]);
9885 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9886 	}
9887 }
9888 
9889 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9890 				   struct bpf_func_state *caller,
9891 				   struct bpf_func_state *callee,
9892 				   int insn_idx);
9893 
9894 static int set_callee_state(struct bpf_verifier_env *env,
9895 			    struct bpf_func_state *caller,
9896 			    struct bpf_func_state *callee, int insn_idx);
9897 
9898 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9899 			    set_callee_state_fn set_callee_state_cb,
9900 			    struct bpf_verifier_state *state)
9901 {
9902 	struct bpf_func_state *caller, *callee;
9903 	int err;
9904 
9905 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9906 		verbose(env, "the call stack of %d frames is too deep\n",
9907 			state->curframe + 2);
9908 		return -E2BIG;
9909 	}
9910 
9911 	if (state->frame[state->curframe + 1]) {
9912 		verbose(env, "verifier bug. Frame %d already allocated\n",
9913 			state->curframe + 1);
9914 		return -EFAULT;
9915 	}
9916 
9917 	caller = state->frame[state->curframe];
9918 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9919 	if (!callee)
9920 		return -ENOMEM;
9921 	state->frame[state->curframe + 1] = callee;
9922 
9923 	/* callee cannot access r0, r6 - r9 for reading and has to write
9924 	 * into its own stack before reading from it.
9925 	 * callee can read/write into caller's stack
9926 	 */
9927 	init_func_state(env, callee,
9928 			/* remember the callsite, it will be used by bpf_exit */
9929 			callsite,
9930 			state->curframe + 1 /* frameno within this callchain */,
9931 			subprog /* subprog number within this prog */);
9932 	err = set_callee_state_cb(env, caller, callee, callsite);
9933 	if (err)
9934 		goto err_out;
9935 
9936 	/* only increment it after check_reg_arg() finished */
9937 	state->curframe++;
9938 
9939 	return 0;
9940 
9941 err_out:
9942 	free_func_state(callee);
9943 	state->frame[state->curframe + 1] = NULL;
9944 	return err;
9945 }
9946 
9947 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9948 				    const struct btf *btf,
9949 				    struct bpf_reg_state *regs)
9950 {
9951 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
9952 	struct bpf_verifier_log *log = &env->log;
9953 	u32 i;
9954 	int ret;
9955 
9956 	ret = btf_prepare_func_args(env, subprog);
9957 	if (ret)
9958 		return ret;
9959 
9960 	/* check that BTF function arguments match actual types that the
9961 	 * verifier sees.
9962 	 */
9963 	for (i = 0; i < sub->arg_cnt; i++) {
9964 		u32 regno = i + 1;
9965 		struct bpf_reg_state *reg = &regs[regno];
9966 		struct bpf_subprog_arg_info *arg = &sub->args[i];
9967 
9968 		if (arg->arg_type == ARG_ANYTHING) {
9969 			if (reg->type != SCALAR_VALUE) {
9970 				bpf_log(log, "R%d is not a scalar\n", regno);
9971 				return -EINVAL;
9972 			}
9973 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
9974 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9975 			if (ret < 0)
9976 				return ret;
9977 			/* If function expects ctx type in BTF check that caller
9978 			 * is passing PTR_TO_CTX.
9979 			 */
9980 			if (reg->type != PTR_TO_CTX) {
9981 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9982 				return -EINVAL;
9983 			}
9984 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9985 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9986 			if (ret < 0)
9987 				return ret;
9988 			if (check_mem_reg(env, reg, regno, arg->mem_size))
9989 				return -EINVAL;
9990 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9991 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9992 				return -EINVAL;
9993 			}
9994 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
9995 			/*
9996 			 * Can pass any value and the kernel won't crash, but
9997 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
9998 			 * else is a bug in the bpf program. Point it out to
9999 			 * the user at the verification time instead of
10000 			 * run-time debug nightmare.
10001 			 */
10002 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
10003 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
10004 				return -EINVAL;
10005 			}
10006 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
10007 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
10008 			if (ret)
10009 				return ret;
10010 
10011 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
10012 			if (ret)
10013 				return ret;
10014 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
10015 			struct bpf_call_arg_meta meta;
10016 			int err;
10017 
10018 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
10019 				continue;
10020 
10021 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
10022 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
10023 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
10024 			if (err)
10025 				return err;
10026 		} else {
10027 			bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
10028 				i, arg->arg_type);
10029 			return -EFAULT;
10030 		}
10031 	}
10032 
10033 	return 0;
10034 }
10035 
10036 /* Compare BTF of a function call with given bpf_reg_state.
10037  * Returns:
10038  * EFAULT - there is a verifier bug. Abort verification.
10039  * EINVAL - there is a type mismatch or BTF is not available.
10040  * 0 - BTF matches with what bpf_reg_state expects.
10041  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
10042  */
10043 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
10044 				  struct bpf_reg_state *regs)
10045 {
10046 	struct bpf_prog *prog = env->prog;
10047 	struct btf *btf = prog->aux->btf;
10048 	u32 btf_id;
10049 	int err;
10050 
10051 	if (!prog->aux->func_info)
10052 		return -EINVAL;
10053 
10054 	btf_id = prog->aux->func_info[subprog].type_id;
10055 	if (!btf_id)
10056 		return -EFAULT;
10057 
10058 	if (prog->aux->func_info_aux[subprog].unreliable)
10059 		return -EINVAL;
10060 
10061 	err = btf_check_func_arg_match(env, subprog, btf, regs);
10062 	/* Compiler optimizations can remove arguments from static functions
10063 	 * or mismatched type can be passed into a global function.
10064 	 * In such cases mark the function as unreliable from BTF point of view.
10065 	 */
10066 	if (err)
10067 		prog->aux->func_info_aux[subprog].unreliable = true;
10068 	return err;
10069 }
10070 
10071 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10072 			      int insn_idx, int subprog,
10073 			      set_callee_state_fn set_callee_state_cb)
10074 {
10075 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
10076 	struct bpf_func_state *caller, *callee;
10077 	int err;
10078 
10079 	caller = state->frame[state->curframe];
10080 	err = btf_check_subprog_call(env, subprog, caller->regs);
10081 	if (err == -EFAULT)
10082 		return err;
10083 
10084 	/* set_callee_state is used for direct subprog calls, but we are
10085 	 * interested in validating only BPF helpers that can call subprogs as
10086 	 * callbacks
10087 	 */
10088 	env->subprog_info[subprog].is_cb = true;
10089 	if (bpf_pseudo_kfunc_call(insn) &&
10090 	    !is_callback_calling_kfunc(insn->imm)) {
10091 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
10092 			func_id_name(insn->imm), insn->imm);
10093 		return -EFAULT;
10094 	} else if (!bpf_pseudo_kfunc_call(insn) &&
10095 		   !is_callback_calling_function(insn->imm)) { /* helper */
10096 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
10097 			func_id_name(insn->imm), insn->imm);
10098 		return -EFAULT;
10099 	}
10100 
10101 	if (is_async_callback_calling_insn(insn)) {
10102 		struct bpf_verifier_state *async_cb;
10103 
10104 		/* there is no real recursion here. timer and workqueue callbacks are async */
10105 		env->subprog_info[subprog].is_async_cb = true;
10106 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
10107 					 insn_idx, subprog,
10108 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm));
10109 		if (!async_cb)
10110 			return -EFAULT;
10111 		callee = async_cb->frame[0];
10112 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
10113 
10114 		/* Convert bpf_timer_set_callback() args into timer callback args */
10115 		err = set_callee_state_cb(env, caller, callee, insn_idx);
10116 		if (err)
10117 			return err;
10118 
10119 		return 0;
10120 	}
10121 
10122 	/* for callback functions enqueue entry to callback and
10123 	 * proceed with next instruction within current frame.
10124 	 */
10125 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
10126 	if (!callback_state)
10127 		return -ENOMEM;
10128 
10129 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
10130 			       callback_state);
10131 	if (err)
10132 		return err;
10133 
10134 	callback_state->callback_unroll_depth++;
10135 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
10136 	caller->callback_depth = 0;
10137 	return 0;
10138 }
10139 
10140 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10141 			   int *insn_idx)
10142 {
10143 	struct bpf_verifier_state *state = env->cur_state;
10144 	struct bpf_func_state *caller;
10145 	int err, subprog, target_insn;
10146 
10147 	target_insn = *insn_idx + insn->imm + 1;
10148 	subprog = find_subprog(env, target_insn);
10149 	if (subprog < 0) {
10150 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
10151 		return -EFAULT;
10152 	}
10153 
10154 	caller = state->frame[state->curframe];
10155 	err = btf_check_subprog_call(env, subprog, caller->regs);
10156 	if (err == -EFAULT)
10157 		return err;
10158 	if (subprog_is_global(env, subprog)) {
10159 		const char *sub_name = subprog_name(env, subprog);
10160 
10161 		/* Only global subprogs cannot be called with a lock held. */
10162 		if (env->cur_state->active_locks) {
10163 			verbose(env, "global function calls are not allowed while holding a lock,\n"
10164 				     "use static function instead\n");
10165 			return -EINVAL;
10166 		}
10167 
10168 		/* Only global subprogs cannot be called with preemption disabled. */
10169 		if (env->cur_state->active_preempt_locks) {
10170 			verbose(env, "global function calls are not allowed with preemption disabled,\n"
10171 				     "use static function instead\n");
10172 			return -EINVAL;
10173 		}
10174 
10175 		if (env->cur_state->active_irq_id) {
10176 			verbose(env, "global function calls are not allowed with IRQs disabled,\n"
10177 				     "use static function instead\n");
10178 			return -EINVAL;
10179 		}
10180 
10181 		if (err) {
10182 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10183 				subprog, sub_name);
10184 			return err;
10185 		}
10186 
10187 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10188 			subprog, sub_name);
10189 		if (env->subprog_info[subprog].changes_pkt_data)
10190 			clear_all_pkt_pointers(env);
10191 		/* mark global subprog for verifying after main prog */
10192 		subprog_aux(env, subprog)->called = true;
10193 		clear_caller_saved_regs(env, caller->regs);
10194 
10195 		/* All global functions return a 64-bit SCALAR_VALUE */
10196 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
10197 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10198 
10199 		/* continue with next insn after call */
10200 		return 0;
10201 	}
10202 
10203 	/* for regular function entry setup new frame and continue
10204 	 * from that frame.
10205 	 */
10206 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10207 	if (err)
10208 		return err;
10209 
10210 	clear_caller_saved_regs(env, caller->regs);
10211 
10212 	/* and go analyze first insn of the callee */
10213 	*insn_idx = env->subprog_info[subprog].start - 1;
10214 
10215 	if (env->log.level & BPF_LOG_LEVEL) {
10216 		verbose(env, "caller:\n");
10217 		print_verifier_state(env, state, caller->frameno, true);
10218 		verbose(env, "callee:\n");
10219 		print_verifier_state(env, state, state->curframe, true);
10220 	}
10221 
10222 	return 0;
10223 }
10224 
10225 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10226 				   struct bpf_func_state *caller,
10227 				   struct bpf_func_state *callee)
10228 {
10229 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10230 	 *      void *callback_ctx, u64 flags);
10231 	 * callback_fn(struct bpf_map *map, void *key, void *value,
10232 	 *      void *callback_ctx);
10233 	 */
10234 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10235 
10236 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10237 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10238 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10239 
10240 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10241 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10242 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10243 
10244 	/* pointer to stack or null */
10245 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10246 
10247 	/* unused */
10248 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10249 	return 0;
10250 }
10251 
10252 static int set_callee_state(struct bpf_verifier_env *env,
10253 			    struct bpf_func_state *caller,
10254 			    struct bpf_func_state *callee, int insn_idx)
10255 {
10256 	int i;
10257 
10258 	/* copy r1 - r5 args that callee can access.  The copy includes parent
10259 	 * pointers, which connects us up to the liveness chain
10260 	 */
10261 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10262 		callee->regs[i] = caller->regs[i];
10263 	return 0;
10264 }
10265 
10266 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10267 				       struct bpf_func_state *caller,
10268 				       struct bpf_func_state *callee,
10269 				       int insn_idx)
10270 {
10271 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10272 	struct bpf_map *map;
10273 	int err;
10274 
10275 	/* valid map_ptr and poison value does not matter */
10276 	map = insn_aux->map_ptr_state.map_ptr;
10277 	if (!map->ops->map_set_for_each_callback_args ||
10278 	    !map->ops->map_for_each_callback) {
10279 		verbose(env, "callback function not allowed for map\n");
10280 		return -ENOTSUPP;
10281 	}
10282 
10283 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10284 	if (err)
10285 		return err;
10286 
10287 	callee->in_callback_fn = true;
10288 	callee->callback_ret_range = retval_range(0, 1);
10289 	return 0;
10290 }
10291 
10292 static int set_loop_callback_state(struct bpf_verifier_env *env,
10293 				   struct bpf_func_state *caller,
10294 				   struct bpf_func_state *callee,
10295 				   int insn_idx)
10296 {
10297 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10298 	 *	    u64 flags);
10299 	 * callback_fn(u64 index, void *callback_ctx);
10300 	 */
10301 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10302 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10303 
10304 	/* unused */
10305 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10306 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10307 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10308 
10309 	callee->in_callback_fn = true;
10310 	callee->callback_ret_range = retval_range(0, 1);
10311 	return 0;
10312 }
10313 
10314 static int set_timer_callback_state(struct bpf_verifier_env *env,
10315 				    struct bpf_func_state *caller,
10316 				    struct bpf_func_state *callee,
10317 				    int insn_idx)
10318 {
10319 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10320 
10321 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10322 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10323 	 */
10324 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10325 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10326 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10327 
10328 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10329 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10330 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10331 
10332 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10333 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10334 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10335 
10336 	/* unused */
10337 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10338 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10339 	callee->in_async_callback_fn = true;
10340 	callee->callback_ret_range = retval_range(0, 1);
10341 	return 0;
10342 }
10343 
10344 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
10345 				       struct bpf_func_state *caller,
10346 				       struct bpf_func_state *callee,
10347 				       int insn_idx)
10348 {
10349 	/* bpf_find_vma(struct task_struct *task, u64 addr,
10350 	 *               void *callback_fn, void *callback_ctx, u64 flags)
10351 	 * (callback_fn)(struct task_struct *task,
10352 	 *               struct vm_area_struct *vma, void *callback_ctx);
10353 	 */
10354 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10355 
10356 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
10357 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10358 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
10359 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
10360 
10361 	/* pointer to stack or null */
10362 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
10363 
10364 	/* unused */
10365 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10366 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10367 	callee->in_callback_fn = true;
10368 	callee->callback_ret_range = retval_range(0, 1);
10369 	return 0;
10370 }
10371 
10372 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10373 					   struct bpf_func_state *caller,
10374 					   struct bpf_func_state *callee,
10375 					   int insn_idx)
10376 {
10377 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10378 	 *			  callback_ctx, u64 flags);
10379 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10380 	 */
10381 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10382 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10383 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10384 
10385 	/* unused */
10386 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10387 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10388 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10389 
10390 	callee->in_callback_fn = true;
10391 	callee->callback_ret_range = retval_range(0, 1);
10392 	return 0;
10393 }
10394 
10395 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10396 					 struct bpf_func_state *caller,
10397 					 struct bpf_func_state *callee,
10398 					 int insn_idx)
10399 {
10400 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10401 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10402 	 *
10403 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10404 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10405 	 * by this point, so look at 'root'
10406 	 */
10407 	struct btf_field *field;
10408 
10409 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10410 				      BPF_RB_ROOT);
10411 	if (!field || !field->graph_root.value_btf_id)
10412 		return -EFAULT;
10413 
10414 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10415 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10416 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10417 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10418 
10419 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10420 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10421 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10422 	callee->in_callback_fn = true;
10423 	callee->callback_ret_range = retval_range(0, 1);
10424 	return 0;
10425 }
10426 
10427 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
10428 
10429 /* Are we currently verifying the callback for a rbtree helper that must
10430  * be called with lock held? If so, no need to complain about unreleased
10431  * lock
10432  */
10433 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
10434 {
10435 	struct bpf_verifier_state *state = env->cur_state;
10436 	struct bpf_insn *insn = env->prog->insnsi;
10437 	struct bpf_func_state *callee;
10438 	int kfunc_btf_id;
10439 
10440 	if (!state->curframe)
10441 		return false;
10442 
10443 	callee = state->frame[state->curframe];
10444 
10445 	if (!callee->in_callback_fn)
10446 		return false;
10447 
10448 	kfunc_btf_id = insn[callee->callsite].imm;
10449 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
10450 }
10451 
10452 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
10453 				bool return_32bit)
10454 {
10455 	if (return_32bit)
10456 		return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
10457 	else
10458 		return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
10459 }
10460 
10461 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
10462 {
10463 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
10464 	struct bpf_func_state *caller, *callee;
10465 	struct bpf_reg_state *r0;
10466 	bool in_callback_fn;
10467 	int err;
10468 
10469 	callee = state->frame[state->curframe];
10470 	r0 = &callee->regs[BPF_REG_0];
10471 	if (r0->type == PTR_TO_STACK) {
10472 		/* technically it's ok to return caller's stack pointer
10473 		 * (or caller's caller's pointer) back to the caller,
10474 		 * since these pointers are valid. Only current stack
10475 		 * pointer will be invalid as soon as function exits,
10476 		 * but let's be conservative
10477 		 */
10478 		verbose(env, "cannot return stack pointer to the caller\n");
10479 		return -EINVAL;
10480 	}
10481 
10482 	caller = state->frame[state->curframe - 1];
10483 	if (callee->in_callback_fn) {
10484 		if (r0->type != SCALAR_VALUE) {
10485 			verbose(env, "R0 not a scalar value\n");
10486 			return -EACCES;
10487 		}
10488 
10489 		/* we are going to rely on register's precise value */
10490 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
10491 		err = err ?: mark_chain_precision(env, BPF_REG_0);
10492 		if (err)
10493 			return err;
10494 
10495 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
10496 		if (!retval_range_within(callee->callback_ret_range, r0, false)) {
10497 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
10498 					       "At callback return", "R0");
10499 			return -EINVAL;
10500 		}
10501 		if (!calls_callback(env, callee->callsite)) {
10502 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
10503 				*insn_idx, callee->callsite);
10504 			return -EFAULT;
10505 		}
10506 	} else {
10507 		/* return to the caller whatever r0 had in the callee */
10508 		caller->regs[BPF_REG_0] = *r0;
10509 	}
10510 
10511 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
10512 	 * there function call logic would reschedule callback visit. If iteration
10513 	 * converges is_state_visited() would prune that visit eventually.
10514 	 */
10515 	in_callback_fn = callee->in_callback_fn;
10516 	if (in_callback_fn)
10517 		*insn_idx = callee->callsite;
10518 	else
10519 		*insn_idx = callee->callsite + 1;
10520 
10521 	if (env->log.level & BPF_LOG_LEVEL) {
10522 		verbose(env, "returning from callee:\n");
10523 		print_verifier_state(env, state, callee->frameno, true);
10524 		verbose(env, "to caller at %d:\n", *insn_idx);
10525 		print_verifier_state(env, state, caller->frameno, true);
10526 	}
10527 	/* clear everything in the callee. In case of exceptional exits using
10528 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
10529 	free_func_state(callee);
10530 	state->frame[state->curframe--] = NULL;
10531 
10532 	/* for callbacks widen imprecise scalars to make programs like below verify:
10533 	 *
10534 	 *   struct ctx { int i; }
10535 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
10536 	 *   ...
10537 	 *   struct ctx = { .i = 0; }
10538 	 *   bpf_loop(100, cb, &ctx, 0);
10539 	 *
10540 	 * This is similar to what is done in process_iter_next_call() for open
10541 	 * coded iterators.
10542 	 */
10543 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
10544 	if (prev_st) {
10545 		err = widen_imprecise_scalars(env, prev_st, state);
10546 		if (err)
10547 			return err;
10548 	}
10549 	return 0;
10550 }
10551 
10552 static int do_refine_retval_range(struct bpf_verifier_env *env,
10553 				  struct bpf_reg_state *regs, int ret_type,
10554 				  int func_id,
10555 				  struct bpf_call_arg_meta *meta)
10556 {
10557 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
10558 
10559 	if (ret_type != RET_INTEGER)
10560 		return 0;
10561 
10562 	switch (func_id) {
10563 	case BPF_FUNC_get_stack:
10564 	case BPF_FUNC_get_task_stack:
10565 	case BPF_FUNC_probe_read_str:
10566 	case BPF_FUNC_probe_read_kernel_str:
10567 	case BPF_FUNC_probe_read_user_str:
10568 		ret_reg->smax_value = meta->msize_max_value;
10569 		ret_reg->s32_max_value = meta->msize_max_value;
10570 		ret_reg->smin_value = -MAX_ERRNO;
10571 		ret_reg->s32_min_value = -MAX_ERRNO;
10572 		reg_bounds_sync(ret_reg);
10573 		break;
10574 	case BPF_FUNC_get_smp_processor_id:
10575 		ret_reg->umax_value = nr_cpu_ids - 1;
10576 		ret_reg->u32_max_value = nr_cpu_ids - 1;
10577 		ret_reg->smax_value = nr_cpu_ids - 1;
10578 		ret_reg->s32_max_value = nr_cpu_ids - 1;
10579 		ret_reg->umin_value = 0;
10580 		ret_reg->u32_min_value = 0;
10581 		ret_reg->smin_value = 0;
10582 		ret_reg->s32_min_value = 0;
10583 		reg_bounds_sync(ret_reg);
10584 		break;
10585 	}
10586 
10587 	return reg_bounds_sanity_check(env, ret_reg, "retval");
10588 }
10589 
10590 static int
10591 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10592 		int func_id, int insn_idx)
10593 {
10594 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10595 	struct bpf_map *map = meta->map_ptr;
10596 
10597 	if (func_id != BPF_FUNC_tail_call &&
10598 	    func_id != BPF_FUNC_map_lookup_elem &&
10599 	    func_id != BPF_FUNC_map_update_elem &&
10600 	    func_id != BPF_FUNC_map_delete_elem &&
10601 	    func_id != BPF_FUNC_map_push_elem &&
10602 	    func_id != BPF_FUNC_map_pop_elem &&
10603 	    func_id != BPF_FUNC_map_peek_elem &&
10604 	    func_id != BPF_FUNC_for_each_map_elem &&
10605 	    func_id != BPF_FUNC_redirect_map &&
10606 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
10607 		return 0;
10608 
10609 	if (map == NULL) {
10610 		verbose(env, "kernel subsystem misconfigured verifier\n");
10611 		return -EINVAL;
10612 	}
10613 
10614 	/* In case of read-only, some additional restrictions
10615 	 * need to be applied in order to prevent altering the
10616 	 * state of the map from program side.
10617 	 */
10618 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
10619 	    (func_id == BPF_FUNC_map_delete_elem ||
10620 	     func_id == BPF_FUNC_map_update_elem ||
10621 	     func_id == BPF_FUNC_map_push_elem ||
10622 	     func_id == BPF_FUNC_map_pop_elem)) {
10623 		verbose(env, "write into map forbidden\n");
10624 		return -EACCES;
10625 	}
10626 
10627 	if (!aux->map_ptr_state.map_ptr)
10628 		bpf_map_ptr_store(aux, meta->map_ptr,
10629 				  !meta->map_ptr->bypass_spec_v1, false);
10630 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
10631 		bpf_map_ptr_store(aux, meta->map_ptr,
10632 				  !meta->map_ptr->bypass_spec_v1, true);
10633 	return 0;
10634 }
10635 
10636 static int
10637 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10638 		int func_id, int insn_idx)
10639 {
10640 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10641 	struct bpf_reg_state *regs = cur_regs(env), *reg;
10642 	struct bpf_map *map = meta->map_ptr;
10643 	u64 val, max;
10644 	int err;
10645 
10646 	if (func_id != BPF_FUNC_tail_call)
10647 		return 0;
10648 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
10649 		verbose(env, "kernel subsystem misconfigured verifier\n");
10650 		return -EINVAL;
10651 	}
10652 
10653 	reg = &regs[BPF_REG_3];
10654 	val = reg->var_off.value;
10655 	max = map->max_entries;
10656 
10657 	if (!(is_reg_const(reg, false) && val < max)) {
10658 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10659 		return 0;
10660 	}
10661 
10662 	err = mark_chain_precision(env, BPF_REG_3);
10663 	if (err)
10664 		return err;
10665 	if (bpf_map_key_unseen(aux))
10666 		bpf_map_key_store(aux, val);
10667 	else if (!bpf_map_key_poisoned(aux) &&
10668 		  bpf_map_key_immediate(aux) != val)
10669 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10670 	return 0;
10671 }
10672 
10673 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
10674 {
10675 	struct bpf_verifier_state *state = env->cur_state;
10676 	bool refs_lingering = false;
10677 	int i;
10678 
10679 	if (!exception_exit && cur_func(env)->frameno)
10680 		return 0;
10681 
10682 	for (i = 0; i < state->acquired_refs; i++) {
10683 		if (state->refs[i].type != REF_TYPE_PTR)
10684 			continue;
10685 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10686 			state->refs[i].id, state->refs[i].insn_idx);
10687 		refs_lingering = true;
10688 	}
10689 	return refs_lingering ? -EINVAL : 0;
10690 }
10691 
10692 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
10693 {
10694 	int err;
10695 
10696 	if (check_lock && env->cur_state->active_locks) {
10697 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
10698 		return -EINVAL;
10699 	}
10700 
10701 	err = check_reference_leak(env, exception_exit);
10702 	if (err) {
10703 		verbose(env, "%s would lead to reference leak\n", prefix);
10704 		return err;
10705 	}
10706 
10707 	if (check_lock && env->cur_state->active_irq_id) {
10708 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
10709 		return -EINVAL;
10710 	}
10711 
10712 	if (check_lock && env->cur_state->active_rcu_lock) {
10713 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
10714 		return -EINVAL;
10715 	}
10716 
10717 	if (check_lock && env->cur_state->active_preempt_locks) {
10718 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
10719 		return -EINVAL;
10720 	}
10721 
10722 	return 0;
10723 }
10724 
10725 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10726 				   struct bpf_reg_state *regs)
10727 {
10728 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
10729 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
10730 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
10731 	struct bpf_bprintf_data data = {};
10732 	int err, fmt_map_off, num_args;
10733 	u64 fmt_addr;
10734 	char *fmt;
10735 
10736 	/* data must be an array of u64 */
10737 	if (data_len_reg->var_off.value % 8)
10738 		return -EINVAL;
10739 	num_args = data_len_reg->var_off.value / 8;
10740 
10741 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10742 	 * and map_direct_value_addr is set.
10743 	 */
10744 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10745 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10746 						  fmt_map_off);
10747 	if (err) {
10748 		verbose(env, "verifier bug\n");
10749 		return -EFAULT;
10750 	}
10751 	fmt = (char *)(long)fmt_addr + fmt_map_off;
10752 
10753 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10754 	 * can focus on validating the format specifiers.
10755 	 */
10756 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10757 	if (err < 0)
10758 		verbose(env, "Invalid format string\n");
10759 
10760 	return err;
10761 }
10762 
10763 static int check_get_func_ip(struct bpf_verifier_env *env)
10764 {
10765 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10766 	int func_id = BPF_FUNC_get_func_ip;
10767 
10768 	if (type == BPF_PROG_TYPE_TRACING) {
10769 		if (!bpf_prog_has_trampoline(env->prog)) {
10770 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10771 				func_id_name(func_id), func_id);
10772 			return -ENOTSUPP;
10773 		}
10774 		return 0;
10775 	} else if (type == BPF_PROG_TYPE_KPROBE) {
10776 		return 0;
10777 	}
10778 
10779 	verbose(env, "func %s#%d not supported for program type %d\n",
10780 		func_id_name(func_id), func_id, type);
10781 	return -ENOTSUPP;
10782 }
10783 
10784 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10785 {
10786 	return &env->insn_aux_data[env->insn_idx];
10787 }
10788 
10789 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10790 {
10791 	struct bpf_reg_state *regs = cur_regs(env);
10792 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
10793 	bool reg_is_null = register_is_null(reg);
10794 
10795 	if (reg_is_null)
10796 		mark_chain_precision(env, BPF_REG_4);
10797 
10798 	return reg_is_null;
10799 }
10800 
10801 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10802 {
10803 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10804 
10805 	if (!state->initialized) {
10806 		state->initialized = 1;
10807 		state->fit_for_inline = loop_flag_is_zero(env);
10808 		state->callback_subprogno = subprogno;
10809 		return;
10810 	}
10811 
10812 	if (!state->fit_for_inline)
10813 		return;
10814 
10815 	state->fit_for_inline = (loop_flag_is_zero(env) &&
10816 				 state->callback_subprogno == subprogno);
10817 }
10818 
10819 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
10820 			    const struct bpf_func_proto **ptr)
10821 {
10822 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
10823 		return -ERANGE;
10824 
10825 	if (!env->ops->get_func_proto)
10826 		return -EINVAL;
10827 
10828 	*ptr = env->ops->get_func_proto(func_id, env->prog);
10829 	return *ptr ? 0 : -EINVAL;
10830 }
10831 
10832 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10833 			     int *insn_idx_p)
10834 {
10835 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10836 	bool returns_cpu_specific_alloc_ptr = false;
10837 	const struct bpf_func_proto *fn = NULL;
10838 	enum bpf_return_type ret_type;
10839 	enum bpf_type_flag ret_flag;
10840 	struct bpf_reg_state *regs;
10841 	struct bpf_call_arg_meta meta;
10842 	int insn_idx = *insn_idx_p;
10843 	bool changes_data;
10844 	int i, err, func_id;
10845 
10846 	/* find function prototype */
10847 	func_id = insn->imm;
10848 	err = get_helper_proto(env, insn->imm, &fn);
10849 	if (err == -ERANGE) {
10850 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
10851 		return -EINVAL;
10852 	}
10853 
10854 	if (err) {
10855 		verbose(env, "program of this type cannot use helper %s#%d\n",
10856 			func_id_name(func_id), func_id);
10857 		return err;
10858 	}
10859 
10860 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
10861 	if (!env->prog->gpl_compatible && fn->gpl_only) {
10862 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10863 		return -EINVAL;
10864 	}
10865 
10866 	if (fn->allowed && !fn->allowed(env->prog)) {
10867 		verbose(env, "helper call is not allowed in probe\n");
10868 		return -EINVAL;
10869 	}
10870 
10871 	if (!in_sleepable(env) && fn->might_sleep) {
10872 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
10873 		return -EINVAL;
10874 	}
10875 
10876 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10877 	changes_data = bpf_helper_changes_pkt_data(func_id);
10878 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10879 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10880 			func_id_name(func_id), func_id);
10881 		return -EINVAL;
10882 	}
10883 
10884 	memset(&meta, 0, sizeof(meta));
10885 	meta.pkt_access = fn->pkt_access;
10886 
10887 	err = check_func_proto(fn, func_id);
10888 	if (err) {
10889 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10890 			func_id_name(func_id), func_id);
10891 		return err;
10892 	}
10893 
10894 	if (env->cur_state->active_rcu_lock) {
10895 		if (fn->might_sleep) {
10896 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10897 				func_id_name(func_id), func_id);
10898 			return -EINVAL;
10899 		}
10900 
10901 		if (in_sleepable(env) && is_storage_get_function(func_id))
10902 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10903 	}
10904 
10905 	if (env->cur_state->active_preempt_locks) {
10906 		if (fn->might_sleep) {
10907 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
10908 				func_id_name(func_id), func_id);
10909 			return -EINVAL;
10910 		}
10911 
10912 		if (in_sleepable(env) && is_storage_get_function(func_id))
10913 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10914 	}
10915 
10916 	if (env->cur_state->active_irq_id) {
10917 		if (fn->might_sleep) {
10918 			verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n",
10919 				func_id_name(func_id), func_id);
10920 			return -EINVAL;
10921 		}
10922 
10923 		if (in_sleepable(env) && is_storage_get_function(func_id))
10924 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10925 	}
10926 
10927 	meta.func_id = func_id;
10928 	/* check args */
10929 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10930 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10931 		if (err)
10932 			return err;
10933 	}
10934 
10935 	err = record_func_map(env, &meta, func_id, insn_idx);
10936 	if (err)
10937 		return err;
10938 
10939 	err = record_func_key(env, &meta, func_id, insn_idx);
10940 	if (err)
10941 		return err;
10942 
10943 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10944 	 * is inferred from register state.
10945 	 */
10946 	for (i = 0; i < meta.access_size; i++) {
10947 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10948 				       BPF_WRITE, -1, false, false);
10949 		if (err)
10950 			return err;
10951 	}
10952 
10953 	regs = cur_regs(env);
10954 
10955 	if (meta.release_regno) {
10956 		err = -EINVAL;
10957 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10958 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10959 		 * is safe to do directly.
10960 		 */
10961 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10962 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10963 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10964 				return -EFAULT;
10965 			}
10966 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10967 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10968 			u32 ref_obj_id = meta.ref_obj_id;
10969 			bool in_rcu = in_rcu_cs(env);
10970 			struct bpf_func_state *state;
10971 			struct bpf_reg_state *reg;
10972 
10973 			err = release_reference_nomark(env->cur_state, ref_obj_id);
10974 			if (!err) {
10975 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10976 					if (reg->ref_obj_id == ref_obj_id) {
10977 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10978 							reg->ref_obj_id = 0;
10979 							reg->type &= ~MEM_ALLOC;
10980 							reg->type |= MEM_RCU;
10981 						} else {
10982 							mark_reg_invalid(env, reg);
10983 						}
10984 					}
10985 				}));
10986 			}
10987 		} else if (meta.ref_obj_id) {
10988 			err = release_reference(env, meta.ref_obj_id);
10989 		} else if (register_is_null(&regs[meta.release_regno])) {
10990 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10991 			 * released is NULL, which must be > R0.
10992 			 */
10993 			err = 0;
10994 		}
10995 		if (err) {
10996 			verbose(env, "func %s#%d reference has not been acquired before\n",
10997 				func_id_name(func_id), func_id);
10998 			return err;
10999 		}
11000 	}
11001 
11002 	switch (func_id) {
11003 	case BPF_FUNC_tail_call:
11004 		err = check_resource_leak(env, false, true, "tail_call");
11005 		if (err)
11006 			return err;
11007 		break;
11008 	case BPF_FUNC_get_local_storage:
11009 		/* check that flags argument in get_local_storage(map, flags) is 0,
11010 		 * this is required because get_local_storage() can't return an error.
11011 		 */
11012 		if (!register_is_null(&regs[BPF_REG_2])) {
11013 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
11014 			return -EINVAL;
11015 		}
11016 		break;
11017 	case BPF_FUNC_for_each_map_elem:
11018 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11019 					 set_map_elem_callback_state);
11020 		break;
11021 	case BPF_FUNC_timer_set_callback:
11022 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11023 					 set_timer_callback_state);
11024 		break;
11025 	case BPF_FUNC_find_vma:
11026 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11027 					 set_find_vma_callback_state);
11028 		break;
11029 	case BPF_FUNC_snprintf:
11030 		err = check_bpf_snprintf_call(env, regs);
11031 		break;
11032 	case BPF_FUNC_loop:
11033 		update_loop_inline_state(env, meta.subprogno);
11034 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
11035 		 * is finished, thus mark it precise.
11036 		 */
11037 		err = mark_chain_precision(env, BPF_REG_1);
11038 		if (err)
11039 			return err;
11040 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
11041 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11042 						 set_loop_callback_state);
11043 		} else {
11044 			cur_func(env)->callback_depth = 0;
11045 			if (env->log.level & BPF_LOG_LEVEL2)
11046 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
11047 					env->cur_state->curframe);
11048 		}
11049 		break;
11050 	case BPF_FUNC_dynptr_from_mem:
11051 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
11052 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
11053 				reg_type_str(env, regs[BPF_REG_1].type));
11054 			return -EACCES;
11055 		}
11056 		break;
11057 	case BPF_FUNC_set_retval:
11058 		if (prog_type == BPF_PROG_TYPE_LSM &&
11059 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11060 			if (!env->prog->aux->attach_func_proto->type) {
11061 				/* Make sure programs that attach to void
11062 				 * hooks don't try to modify return value.
11063 				 */
11064 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11065 				return -EINVAL;
11066 			}
11067 		}
11068 		break;
11069 	case BPF_FUNC_dynptr_data:
11070 	{
11071 		struct bpf_reg_state *reg;
11072 		int id, ref_obj_id;
11073 
11074 		reg = get_dynptr_arg_reg(env, fn, regs);
11075 		if (!reg)
11076 			return -EFAULT;
11077 
11078 
11079 		if (meta.dynptr_id) {
11080 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
11081 			return -EFAULT;
11082 		}
11083 		if (meta.ref_obj_id) {
11084 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
11085 			return -EFAULT;
11086 		}
11087 
11088 		id = dynptr_id(env, reg);
11089 		if (id < 0) {
11090 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11091 			return id;
11092 		}
11093 
11094 		ref_obj_id = dynptr_ref_obj_id(env, reg);
11095 		if (ref_obj_id < 0) {
11096 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
11097 			return ref_obj_id;
11098 		}
11099 
11100 		meta.dynptr_id = id;
11101 		meta.ref_obj_id = ref_obj_id;
11102 
11103 		break;
11104 	}
11105 	case BPF_FUNC_dynptr_write:
11106 	{
11107 		enum bpf_dynptr_type dynptr_type;
11108 		struct bpf_reg_state *reg;
11109 
11110 		reg = get_dynptr_arg_reg(env, fn, regs);
11111 		if (!reg)
11112 			return -EFAULT;
11113 
11114 		dynptr_type = dynptr_get_type(env, reg);
11115 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11116 			return -EFAULT;
11117 
11118 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
11119 			/* this will trigger clear_all_pkt_pointers(), which will
11120 			 * invalidate all dynptr slices associated with the skb
11121 			 */
11122 			changes_data = true;
11123 
11124 		break;
11125 	}
11126 	case BPF_FUNC_per_cpu_ptr:
11127 	case BPF_FUNC_this_cpu_ptr:
11128 	{
11129 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
11130 		const struct btf_type *type;
11131 
11132 		if (reg->type & MEM_RCU) {
11133 			type = btf_type_by_id(reg->btf, reg->btf_id);
11134 			if (!type || !btf_type_is_struct(type)) {
11135 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
11136 				return -EFAULT;
11137 			}
11138 			returns_cpu_specific_alloc_ptr = true;
11139 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11140 		}
11141 		break;
11142 	}
11143 	case BPF_FUNC_user_ringbuf_drain:
11144 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11145 					 set_user_ringbuf_callback_state);
11146 		break;
11147 	}
11148 
11149 	if (err)
11150 		return err;
11151 
11152 	/* reset caller saved regs */
11153 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11154 		mark_reg_not_init(env, regs, caller_saved[i]);
11155 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11156 	}
11157 
11158 	/* helper call returns 64-bit value. */
11159 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
11160 
11161 	/* update return register (already marked as written above) */
11162 	ret_type = fn->ret_type;
11163 	ret_flag = type_flag(ret_type);
11164 
11165 	switch (base_type(ret_type)) {
11166 	case RET_INTEGER:
11167 		/* sets type to SCALAR_VALUE */
11168 		mark_reg_unknown(env, regs, BPF_REG_0);
11169 		break;
11170 	case RET_VOID:
11171 		regs[BPF_REG_0].type = NOT_INIT;
11172 		break;
11173 	case RET_PTR_TO_MAP_VALUE:
11174 		/* There is no offset yet applied, variable or fixed */
11175 		mark_reg_known_zero(env, regs, BPF_REG_0);
11176 		/* remember map_ptr, so that check_map_access()
11177 		 * can check 'value_size' boundary of memory access
11178 		 * to map element returned from bpf_map_lookup_elem()
11179 		 */
11180 		if (meta.map_ptr == NULL) {
11181 			verbose(env,
11182 				"kernel subsystem misconfigured verifier\n");
11183 			return -EINVAL;
11184 		}
11185 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
11186 		regs[BPF_REG_0].map_uid = meta.map_uid;
11187 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11188 		if (!type_may_be_null(ret_type) &&
11189 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
11190 			regs[BPF_REG_0].id = ++env->id_gen;
11191 		}
11192 		break;
11193 	case RET_PTR_TO_SOCKET:
11194 		mark_reg_known_zero(env, regs, BPF_REG_0);
11195 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11196 		break;
11197 	case RET_PTR_TO_SOCK_COMMON:
11198 		mark_reg_known_zero(env, regs, BPF_REG_0);
11199 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11200 		break;
11201 	case RET_PTR_TO_TCP_SOCK:
11202 		mark_reg_known_zero(env, regs, BPF_REG_0);
11203 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11204 		break;
11205 	case RET_PTR_TO_MEM:
11206 		mark_reg_known_zero(env, regs, BPF_REG_0);
11207 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11208 		regs[BPF_REG_0].mem_size = meta.mem_size;
11209 		break;
11210 	case RET_PTR_TO_MEM_OR_BTF_ID:
11211 	{
11212 		const struct btf_type *t;
11213 
11214 		mark_reg_known_zero(env, regs, BPF_REG_0);
11215 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11216 		if (!btf_type_is_struct(t)) {
11217 			u32 tsize;
11218 			const struct btf_type *ret;
11219 			const char *tname;
11220 
11221 			/* resolve the type size of ksym. */
11222 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11223 			if (IS_ERR(ret)) {
11224 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11225 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
11226 					tname, PTR_ERR(ret));
11227 				return -EINVAL;
11228 			}
11229 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11230 			regs[BPF_REG_0].mem_size = tsize;
11231 		} else {
11232 			if (returns_cpu_specific_alloc_ptr) {
11233 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11234 			} else {
11235 				/* MEM_RDONLY may be carried from ret_flag, but it
11236 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11237 				 * it will confuse the check of PTR_TO_BTF_ID in
11238 				 * check_mem_access().
11239 				 */
11240 				ret_flag &= ~MEM_RDONLY;
11241 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11242 			}
11243 
11244 			regs[BPF_REG_0].btf = meta.ret_btf;
11245 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11246 		}
11247 		break;
11248 	}
11249 	case RET_PTR_TO_BTF_ID:
11250 	{
11251 		struct btf *ret_btf;
11252 		int ret_btf_id;
11253 
11254 		mark_reg_known_zero(env, regs, BPF_REG_0);
11255 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11256 		if (func_id == BPF_FUNC_kptr_xchg) {
11257 			ret_btf = meta.kptr_field->kptr.btf;
11258 			ret_btf_id = meta.kptr_field->kptr.btf_id;
11259 			if (!btf_is_kernel(ret_btf)) {
11260 				regs[BPF_REG_0].type |= MEM_ALLOC;
11261 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11262 					regs[BPF_REG_0].type |= MEM_PERCPU;
11263 			}
11264 		} else {
11265 			if (fn->ret_btf_id == BPF_PTR_POISON) {
11266 				verbose(env, "verifier internal error:");
11267 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
11268 					func_id_name(func_id));
11269 				return -EINVAL;
11270 			}
11271 			ret_btf = btf_vmlinux;
11272 			ret_btf_id = *fn->ret_btf_id;
11273 		}
11274 		if (ret_btf_id == 0) {
11275 			verbose(env, "invalid return type %u of func %s#%d\n",
11276 				base_type(ret_type), func_id_name(func_id),
11277 				func_id);
11278 			return -EINVAL;
11279 		}
11280 		regs[BPF_REG_0].btf = ret_btf;
11281 		regs[BPF_REG_0].btf_id = ret_btf_id;
11282 		break;
11283 	}
11284 	default:
11285 		verbose(env, "unknown return type %u of func %s#%d\n",
11286 			base_type(ret_type), func_id_name(func_id), func_id);
11287 		return -EINVAL;
11288 	}
11289 
11290 	if (type_may_be_null(regs[BPF_REG_0].type))
11291 		regs[BPF_REG_0].id = ++env->id_gen;
11292 
11293 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
11294 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
11295 			func_id_name(func_id), func_id);
11296 		return -EFAULT;
11297 	}
11298 
11299 	if (is_dynptr_ref_function(func_id))
11300 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
11301 
11302 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
11303 		/* For release_reference() */
11304 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11305 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
11306 		int id = acquire_reference(env, insn_idx);
11307 
11308 		if (id < 0)
11309 			return id;
11310 		/* For mark_ptr_or_null_reg() */
11311 		regs[BPF_REG_0].id = id;
11312 		/* For release_reference() */
11313 		regs[BPF_REG_0].ref_obj_id = id;
11314 	}
11315 
11316 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
11317 	if (err)
11318 		return err;
11319 
11320 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
11321 	if (err)
11322 		return err;
11323 
11324 	if ((func_id == BPF_FUNC_get_stack ||
11325 	     func_id == BPF_FUNC_get_task_stack) &&
11326 	    !env->prog->has_callchain_buf) {
11327 		const char *err_str;
11328 
11329 #ifdef CONFIG_PERF_EVENTS
11330 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
11331 		err_str = "cannot get callchain buffer for func %s#%d\n";
11332 #else
11333 		err = -ENOTSUPP;
11334 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
11335 #endif
11336 		if (err) {
11337 			verbose(env, err_str, func_id_name(func_id), func_id);
11338 			return err;
11339 		}
11340 
11341 		env->prog->has_callchain_buf = true;
11342 	}
11343 
11344 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
11345 		env->prog->call_get_stack = true;
11346 
11347 	if (func_id == BPF_FUNC_get_func_ip) {
11348 		if (check_get_func_ip(env))
11349 			return -ENOTSUPP;
11350 		env->prog->call_get_func_ip = true;
11351 	}
11352 
11353 	if (changes_data)
11354 		clear_all_pkt_pointers(env);
11355 	return 0;
11356 }
11357 
11358 /* mark_btf_func_reg_size() is used when the reg size is determined by
11359  * the BTF func_proto's return value size and argument.
11360  */
11361 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
11362 				   size_t reg_size)
11363 {
11364 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
11365 
11366 	if (regno == BPF_REG_0) {
11367 		/* Function return value */
11368 		reg->live |= REG_LIVE_WRITTEN;
11369 		reg->subreg_def = reg_size == sizeof(u64) ?
11370 			DEF_NOT_SUBREG : env->insn_idx + 1;
11371 	} else {
11372 		/* Function argument */
11373 		if (reg_size == sizeof(u64)) {
11374 			mark_insn_zext(env, reg);
11375 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
11376 		} else {
11377 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
11378 		}
11379 	}
11380 }
11381 
11382 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
11383 {
11384 	return meta->kfunc_flags & KF_ACQUIRE;
11385 }
11386 
11387 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
11388 {
11389 	return meta->kfunc_flags & KF_RELEASE;
11390 }
11391 
11392 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
11393 {
11394 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
11395 }
11396 
11397 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
11398 {
11399 	return meta->kfunc_flags & KF_SLEEPABLE;
11400 }
11401 
11402 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
11403 {
11404 	return meta->kfunc_flags & KF_DESTRUCTIVE;
11405 }
11406 
11407 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
11408 {
11409 	return meta->kfunc_flags & KF_RCU;
11410 }
11411 
11412 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
11413 {
11414 	return meta->kfunc_flags & KF_RCU_PROTECTED;
11415 }
11416 
11417 static bool is_kfunc_arg_mem_size(const struct btf *btf,
11418 				  const struct btf_param *arg,
11419 				  const struct bpf_reg_state *reg)
11420 {
11421 	const struct btf_type *t;
11422 
11423 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11424 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11425 		return false;
11426 
11427 	return btf_param_match_suffix(btf, arg, "__sz");
11428 }
11429 
11430 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
11431 					const struct btf_param *arg,
11432 					const struct bpf_reg_state *reg)
11433 {
11434 	const struct btf_type *t;
11435 
11436 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11437 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11438 		return false;
11439 
11440 	return btf_param_match_suffix(btf, arg, "__szk");
11441 }
11442 
11443 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
11444 {
11445 	return btf_param_match_suffix(btf, arg, "__opt");
11446 }
11447 
11448 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
11449 {
11450 	return btf_param_match_suffix(btf, arg, "__k");
11451 }
11452 
11453 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
11454 {
11455 	return btf_param_match_suffix(btf, arg, "__ign");
11456 }
11457 
11458 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
11459 {
11460 	return btf_param_match_suffix(btf, arg, "__map");
11461 }
11462 
11463 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
11464 {
11465 	return btf_param_match_suffix(btf, arg, "__alloc");
11466 }
11467 
11468 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
11469 {
11470 	return btf_param_match_suffix(btf, arg, "__uninit");
11471 }
11472 
11473 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
11474 {
11475 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
11476 }
11477 
11478 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
11479 {
11480 	return btf_param_match_suffix(btf, arg, "__nullable");
11481 }
11482 
11483 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
11484 {
11485 	return btf_param_match_suffix(btf, arg, "__str");
11486 }
11487 
11488 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
11489 {
11490 	return btf_param_match_suffix(btf, arg, "__irq_flag");
11491 }
11492 
11493 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
11494 					  const struct btf_param *arg,
11495 					  const char *name)
11496 {
11497 	int len, target_len = strlen(name);
11498 	const char *param_name;
11499 
11500 	param_name = btf_name_by_offset(btf, arg->name_off);
11501 	if (str_is_empty(param_name))
11502 		return false;
11503 	len = strlen(param_name);
11504 	if (len != target_len)
11505 		return false;
11506 	if (strcmp(param_name, name))
11507 		return false;
11508 
11509 	return true;
11510 }
11511 
11512 enum {
11513 	KF_ARG_DYNPTR_ID,
11514 	KF_ARG_LIST_HEAD_ID,
11515 	KF_ARG_LIST_NODE_ID,
11516 	KF_ARG_RB_ROOT_ID,
11517 	KF_ARG_RB_NODE_ID,
11518 	KF_ARG_WORKQUEUE_ID,
11519 };
11520 
11521 BTF_ID_LIST(kf_arg_btf_ids)
11522 BTF_ID(struct, bpf_dynptr)
11523 BTF_ID(struct, bpf_list_head)
11524 BTF_ID(struct, bpf_list_node)
11525 BTF_ID(struct, bpf_rb_root)
11526 BTF_ID(struct, bpf_rb_node)
11527 BTF_ID(struct, bpf_wq)
11528 
11529 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
11530 				    const struct btf_param *arg, int type)
11531 {
11532 	const struct btf_type *t;
11533 	u32 res_id;
11534 
11535 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11536 	if (!t)
11537 		return false;
11538 	if (!btf_type_is_ptr(t))
11539 		return false;
11540 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
11541 	if (!t)
11542 		return false;
11543 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
11544 }
11545 
11546 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
11547 {
11548 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
11549 }
11550 
11551 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
11552 {
11553 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
11554 }
11555 
11556 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
11557 {
11558 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
11559 }
11560 
11561 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
11562 {
11563 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
11564 }
11565 
11566 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
11567 {
11568 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
11569 }
11570 
11571 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
11572 {
11573 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
11574 }
11575 
11576 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
11577 				  const struct btf_param *arg)
11578 {
11579 	const struct btf_type *t;
11580 
11581 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
11582 	if (!t)
11583 		return false;
11584 
11585 	return true;
11586 }
11587 
11588 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
11589 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
11590 					const struct btf *btf,
11591 					const struct btf_type *t, int rec)
11592 {
11593 	const struct btf_type *member_type;
11594 	const struct btf_member *member;
11595 	u32 i;
11596 
11597 	if (!btf_type_is_struct(t))
11598 		return false;
11599 
11600 	for_each_member(i, t, member) {
11601 		const struct btf_array *array;
11602 
11603 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
11604 		if (btf_type_is_struct(member_type)) {
11605 			if (rec >= 3) {
11606 				verbose(env, "max struct nesting depth exceeded\n");
11607 				return false;
11608 			}
11609 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
11610 				return false;
11611 			continue;
11612 		}
11613 		if (btf_type_is_array(member_type)) {
11614 			array = btf_array(member_type);
11615 			if (!array->nelems)
11616 				return false;
11617 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
11618 			if (!btf_type_is_scalar(member_type))
11619 				return false;
11620 			continue;
11621 		}
11622 		if (!btf_type_is_scalar(member_type))
11623 			return false;
11624 	}
11625 	return true;
11626 }
11627 
11628 enum kfunc_ptr_arg_type {
11629 	KF_ARG_PTR_TO_CTX,
11630 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
11631 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
11632 	KF_ARG_PTR_TO_DYNPTR,
11633 	KF_ARG_PTR_TO_ITER,
11634 	KF_ARG_PTR_TO_LIST_HEAD,
11635 	KF_ARG_PTR_TO_LIST_NODE,
11636 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
11637 	KF_ARG_PTR_TO_MEM,
11638 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
11639 	KF_ARG_PTR_TO_CALLBACK,
11640 	KF_ARG_PTR_TO_RB_ROOT,
11641 	KF_ARG_PTR_TO_RB_NODE,
11642 	KF_ARG_PTR_TO_NULL,
11643 	KF_ARG_PTR_TO_CONST_STR,
11644 	KF_ARG_PTR_TO_MAP,
11645 	KF_ARG_PTR_TO_WORKQUEUE,
11646 	KF_ARG_PTR_TO_IRQ_FLAG,
11647 };
11648 
11649 enum special_kfunc_type {
11650 	KF_bpf_obj_new_impl,
11651 	KF_bpf_obj_drop_impl,
11652 	KF_bpf_refcount_acquire_impl,
11653 	KF_bpf_list_push_front_impl,
11654 	KF_bpf_list_push_back_impl,
11655 	KF_bpf_list_pop_front,
11656 	KF_bpf_list_pop_back,
11657 	KF_bpf_cast_to_kern_ctx,
11658 	KF_bpf_rdonly_cast,
11659 	KF_bpf_rcu_read_lock,
11660 	KF_bpf_rcu_read_unlock,
11661 	KF_bpf_rbtree_remove,
11662 	KF_bpf_rbtree_add_impl,
11663 	KF_bpf_rbtree_first,
11664 	KF_bpf_dynptr_from_skb,
11665 	KF_bpf_dynptr_from_xdp,
11666 	KF_bpf_dynptr_slice,
11667 	KF_bpf_dynptr_slice_rdwr,
11668 	KF_bpf_dynptr_clone,
11669 	KF_bpf_percpu_obj_new_impl,
11670 	KF_bpf_percpu_obj_drop_impl,
11671 	KF_bpf_throw,
11672 	KF_bpf_wq_set_callback_impl,
11673 	KF_bpf_preempt_disable,
11674 	KF_bpf_preempt_enable,
11675 	KF_bpf_iter_css_task_new,
11676 	KF_bpf_session_cookie,
11677 	KF_bpf_get_kmem_cache,
11678 	KF_bpf_local_irq_save,
11679 	KF_bpf_local_irq_restore,
11680 	KF_bpf_iter_num_new,
11681 	KF_bpf_iter_num_next,
11682 	KF_bpf_iter_num_destroy,
11683 };
11684 
11685 BTF_SET_START(special_kfunc_set)
11686 BTF_ID(func, bpf_obj_new_impl)
11687 BTF_ID(func, bpf_obj_drop_impl)
11688 BTF_ID(func, bpf_refcount_acquire_impl)
11689 BTF_ID(func, bpf_list_push_front_impl)
11690 BTF_ID(func, bpf_list_push_back_impl)
11691 BTF_ID(func, bpf_list_pop_front)
11692 BTF_ID(func, bpf_list_pop_back)
11693 BTF_ID(func, bpf_cast_to_kern_ctx)
11694 BTF_ID(func, bpf_rdonly_cast)
11695 BTF_ID(func, bpf_rbtree_remove)
11696 BTF_ID(func, bpf_rbtree_add_impl)
11697 BTF_ID(func, bpf_rbtree_first)
11698 #ifdef CONFIG_NET
11699 BTF_ID(func, bpf_dynptr_from_skb)
11700 BTF_ID(func, bpf_dynptr_from_xdp)
11701 #endif
11702 BTF_ID(func, bpf_dynptr_slice)
11703 BTF_ID(func, bpf_dynptr_slice_rdwr)
11704 BTF_ID(func, bpf_dynptr_clone)
11705 BTF_ID(func, bpf_percpu_obj_new_impl)
11706 BTF_ID(func, bpf_percpu_obj_drop_impl)
11707 BTF_ID(func, bpf_throw)
11708 BTF_ID(func, bpf_wq_set_callback_impl)
11709 #ifdef CONFIG_CGROUPS
11710 BTF_ID(func, bpf_iter_css_task_new)
11711 #endif
11712 BTF_SET_END(special_kfunc_set)
11713 
11714 BTF_ID_LIST(special_kfunc_list)
11715 BTF_ID(func, bpf_obj_new_impl)
11716 BTF_ID(func, bpf_obj_drop_impl)
11717 BTF_ID(func, bpf_refcount_acquire_impl)
11718 BTF_ID(func, bpf_list_push_front_impl)
11719 BTF_ID(func, bpf_list_push_back_impl)
11720 BTF_ID(func, bpf_list_pop_front)
11721 BTF_ID(func, bpf_list_pop_back)
11722 BTF_ID(func, bpf_cast_to_kern_ctx)
11723 BTF_ID(func, bpf_rdonly_cast)
11724 BTF_ID(func, bpf_rcu_read_lock)
11725 BTF_ID(func, bpf_rcu_read_unlock)
11726 BTF_ID(func, bpf_rbtree_remove)
11727 BTF_ID(func, bpf_rbtree_add_impl)
11728 BTF_ID(func, bpf_rbtree_first)
11729 #ifdef CONFIG_NET
11730 BTF_ID(func, bpf_dynptr_from_skb)
11731 BTF_ID(func, bpf_dynptr_from_xdp)
11732 #else
11733 BTF_ID_UNUSED
11734 BTF_ID_UNUSED
11735 #endif
11736 BTF_ID(func, bpf_dynptr_slice)
11737 BTF_ID(func, bpf_dynptr_slice_rdwr)
11738 BTF_ID(func, bpf_dynptr_clone)
11739 BTF_ID(func, bpf_percpu_obj_new_impl)
11740 BTF_ID(func, bpf_percpu_obj_drop_impl)
11741 BTF_ID(func, bpf_throw)
11742 BTF_ID(func, bpf_wq_set_callback_impl)
11743 BTF_ID(func, bpf_preempt_disable)
11744 BTF_ID(func, bpf_preempt_enable)
11745 #ifdef CONFIG_CGROUPS
11746 BTF_ID(func, bpf_iter_css_task_new)
11747 #else
11748 BTF_ID_UNUSED
11749 #endif
11750 #ifdef CONFIG_BPF_EVENTS
11751 BTF_ID(func, bpf_session_cookie)
11752 #else
11753 BTF_ID_UNUSED
11754 #endif
11755 BTF_ID(func, bpf_get_kmem_cache)
11756 BTF_ID(func, bpf_local_irq_save)
11757 BTF_ID(func, bpf_local_irq_restore)
11758 BTF_ID(func, bpf_iter_num_new)
11759 BTF_ID(func, bpf_iter_num_next)
11760 BTF_ID(func, bpf_iter_num_destroy)
11761 
11762 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
11763 {
11764 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
11765 	    meta->arg_owning_ref) {
11766 		return false;
11767 	}
11768 
11769 	return meta->kfunc_flags & KF_RET_NULL;
11770 }
11771 
11772 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
11773 {
11774 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11775 }
11776 
11777 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11778 {
11779 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11780 }
11781 
11782 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
11783 {
11784 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
11785 }
11786 
11787 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
11788 {
11789 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
11790 }
11791 
11792 static enum kfunc_ptr_arg_type
11793 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
11794 		       struct bpf_kfunc_call_arg_meta *meta,
11795 		       const struct btf_type *t, const struct btf_type *ref_t,
11796 		       const char *ref_tname, const struct btf_param *args,
11797 		       int argno, int nargs)
11798 {
11799 	u32 regno = argno + 1;
11800 	struct bpf_reg_state *regs = cur_regs(env);
11801 	struct bpf_reg_state *reg = &regs[regno];
11802 	bool arg_mem_size = false;
11803 
11804 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11805 		return KF_ARG_PTR_TO_CTX;
11806 
11807 	/* In this function, we verify the kfunc's BTF as per the argument type,
11808 	 * leaving the rest of the verification with respect to the register
11809 	 * type to our caller. When a set of conditions hold in the BTF type of
11810 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11811 	 */
11812 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11813 		return KF_ARG_PTR_TO_CTX;
11814 
11815 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11816 		return KF_ARG_PTR_TO_NULL;
11817 
11818 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11819 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11820 
11821 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11822 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11823 
11824 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11825 		return KF_ARG_PTR_TO_DYNPTR;
11826 
11827 	if (is_kfunc_arg_iter(meta, argno, &args[argno]))
11828 		return KF_ARG_PTR_TO_ITER;
11829 
11830 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11831 		return KF_ARG_PTR_TO_LIST_HEAD;
11832 
11833 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11834 		return KF_ARG_PTR_TO_LIST_NODE;
11835 
11836 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11837 		return KF_ARG_PTR_TO_RB_ROOT;
11838 
11839 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11840 		return KF_ARG_PTR_TO_RB_NODE;
11841 
11842 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11843 		return KF_ARG_PTR_TO_CONST_STR;
11844 
11845 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
11846 		return KF_ARG_PTR_TO_MAP;
11847 
11848 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
11849 		return KF_ARG_PTR_TO_WORKQUEUE;
11850 
11851 	if (is_kfunc_arg_irq_flag(meta->btf, &args[argno]))
11852 		return KF_ARG_PTR_TO_IRQ_FLAG;
11853 
11854 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11855 		if (!btf_type_is_struct(ref_t)) {
11856 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11857 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11858 			return -EINVAL;
11859 		}
11860 		return KF_ARG_PTR_TO_BTF_ID;
11861 	}
11862 
11863 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11864 		return KF_ARG_PTR_TO_CALLBACK;
11865 
11866 	if (argno + 1 < nargs &&
11867 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
11868 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
11869 		arg_mem_size = true;
11870 
11871 	/* This is the catch all argument type of register types supported by
11872 	 * check_helper_mem_access. However, we only allow when argument type is
11873 	 * pointer to scalar, or struct composed (recursively) of scalars. When
11874 	 * arg_mem_size is true, the pointer can be void *.
11875 	 */
11876 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11877 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11878 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11879 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11880 		return -EINVAL;
11881 	}
11882 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11883 }
11884 
11885 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11886 					struct bpf_reg_state *reg,
11887 					const struct btf_type *ref_t,
11888 					const char *ref_tname, u32 ref_id,
11889 					struct bpf_kfunc_call_arg_meta *meta,
11890 					int argno)
11891 {
11892 	const struct btf_type *reg_ref_t;
11893 	bool strict_type_match = false;
11894 	const struct btf *reg_btf;
11895 	const char *reg_ref_tname;
11896 	bool taking_projection;
11897 	bool struct_same;
11898 	u32 reg_ref_id;
11899 
11900 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
11901 		reg_btf = reg->btf;
11902 		reg_ref_id = reg->btf_id;
11903 	} else {
11904 		reg_btf = btf_vmlinux;
11905 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11906 	}
11907 
11908 	/* Enforce strict type matching for calls to kfuncs that are acquiring
11909 	 * or releasing a reference, or are no-cast aliases. We do _not_
11910 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11911 	 * as we want to enable BPF programs to pass types that are bitwise
11912 	 * equivalent without forcing them to explicitly cast with something
11913 	 * like bpf_cast_to_kern_ctx().
11914 	 *
11915 	 * For example, say we had a type like the following:
11916 	 *
11917 	 * struct bpf_cpumask {
11918 	 *	cpumask_t cpumask;
11919 	 *	refcount_t usage;
11920 	 * };
11921 	 *
11922 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11923 	 * to a struct cpumask, so it would be safe to pass a struct
11924 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11925 	 *
11926 	 * The philosophy here is similar to how we allow scalars of different
11927 	 * types to be passed to kfuncs as long as the size is the same. The
11928 	 * only difference here is that we're simply allowing
11929 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11930 	 * resolve types.
11931 	 */
11932 	if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
11933 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11934 		strict_type_match = true;
11935 
11936 	WARN_ON_ONCE(is_kfunc_release(meta) &&
11937 		     (reg->off || !tnum_is_const(reg->var_off) ||
11938 		      reg->var_off.value));
11939 
11940 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
11941 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11942 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
11943 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
11944 	 * actually use it -- it must cast to the underlying type. So we allow
11945 	 * caller to pass in the underlying type.
11946 	 */
11947 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
11948 	if (!taking_projection && !struct_same) {
11949 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11950 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11951 			btf_type_str(reg_ref_t), reg_ref_tname);
11952 		return -EINVAL;
11953 	}
11954 	return 0;
11955 }
11956 
11957 static int process_irq_flag(struct bpf_verifier_env *env, int regno,
11958 			     struct bpf_kfunc_call_arg_meta *meta)
11959 {
11960 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
11961 	bool irq_save;
11962 	int err;
11963 
11964 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save]) {
11965 		irq_save = true;
11966 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore]) {
11967 		irq_save = false;
11968 	} else {
11969 		verbose(env, "verifier internal error: unknown irq flags kfunc\n");
11970 		return -EFAULT;
11971 	}
11972 
11973 	if (irq_save) {
11974 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
11975 			verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1);
11976 			return -EINVAL;
11977 		}
11978 
11979 		err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false);
11980 		if (err)
11981 			return err;
11982 
11983 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx);
11984 		if (err)
11985 			return err;
11986 	} else {
11987 		err = is_irq_flag_reg_valid_init(env, reg);
11988 		if (err) {
11989 			verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1);
11990 			return err;
11991 		}
11992 
11993 		err = mark_irq_flag_read(env, reg);
11994 		if (err)
11995 			return err;
11996 
11997 		err = unmark_stack_slot_irq_flag(env, reg);
11998 		if (err)
11999 			return err;
12000 	}
12001 	return 0;
12002 }
12003 
12004 
12005 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12006 {
12007 	struct btf_record *rec = reg_btf_record(reg);
12008 
12009 	if (!env->cur_state->active_locks) {
12010 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
12011 		return -EFAULT;
12012 	}
12013 
12014 	if (type_flag(reg->type) & NON_OWN_REF) {
12015 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
12016 		return -EFAULT;
12017 	}
12018 
12019 	reg->type |= NON_OWN_REF;
12020 	if (rec->refcount_off >= 0)
12021 		reg->type |= MEM_RCU;
12022 
12023 	return 0;
12024 }
12025 
12026 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
12027 {
12028 	struct bpf_verifier_state *state = env->cur_state;
12029 	struct bpf_func_state *unused;
12030 	struct bpf_reg_state *reg;
12031 	int i;
12032 
12033 	if (!ref_obj_id) {
12034 		verbose(env, "verifier internal error: ref_obj_id is zero for "
12035 			     "owning -> non-owning conversion\n");
12036 		return -EFAULT;
12037 	}
12038 
12039 	for (i = 0; i < state->acquired_refs; i++) {
12040 		if (state->refs[i].id != ref_obj_id)
12041 			continue;
12042 
12043 		/* Clear ref_obj_id here so release_reference doesn't clobber
12044 		 * the whole reg
12045 		 */
12046 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12047 			if (reg->ref_obj_id == ref_obj_id) {
12048 				reg->ref_obj_id = 0;
12049 				ref_set_non_owning(env, reg);
12050 			}
12051 		}));
12052 		return 0;
12053 	}
12054 
12055 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
12056 	return -EFAULT;
12057 }
12058 
12059 /* Implementation details:
12060  *
12061  * Each register points to some region of memory, which we define as an
12062  * allocation. Each allocation may embed a bpf_spin_lock which protects any
12063  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12064  * allocation. The lock and the data it protects are colocated in the same
12065  * memory region.
12066  *
12067  * Hence, everytime a register holds a pointer value pointing to such
12068  * allocation, the verifier preserves a unique reg->id for it.
12069  *
12070  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12071  * bpf_spin_lock is called.
12072  *
12073  * To enable this, lock state in the verifier captures two values:
12074  *	active_lock.ptr = Register's type specific pointer
12075  *	active_lock.id  = A unique ID for each register pointer value
12076  *
12077  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12078  * supported register types.
12079  *
12080  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12081  * allocated objects is the reg->btf pointer.
12082  *
12083  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12084  * can establish the provenance of the map value statically for each distinct
12085  * lookup into such maps. They always contain a single map value hence unique
12086  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12087  *
12088  * So, in case of global variables, they use array maps with max_entries = 1,
12089  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12090  * into the same map value as max_entries is 1, as described above).
12091  *
12092  * In case of inner map lookups, the inner map pointer has same map_ptr as the
12093  * outer map pointer (in verifier context), but each lookup into an inner map
12094  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12095  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12096  * will get different reg->id assigned to each lookup, hence different
12097  * active_lock.id.
12098  *
12099  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12100  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12101  * returned from bpf_obj_new. Each allocation receives a new reg->id.
12102  */
12103 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12104 {
12105 	struct bpf_reference_state *s;
12106 	void *ptr;
12107 	u32 id;
12108 
12109 	switch ((int)reg->type) {
12110 	case PTR_TO_MAP_VALUE:
12111 		ptr = reg->map_ptr;
12112 		break;
12113 	case PTR_TO_BTF_ID | MEM_ALLOC:
12114 		ptr = reg->btf;
12115 		break;
12116 	default:
12117 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
12118 		return -EFAULT;
12119 	}
12120 	id = reg->id;
12121 
12122 	if (!env->cur_state->active_locks)
12123 		return -EINVAL;
12124 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK, id, ptr);
12125 	if (!s) {
12126 		verbose(env, "held lock and object are not in the same allocation\n");
12127 		return -EINVAL;
12128 	}
12129 	return 0;
12130 }
12131 
12132 static bool is_bpf_list_api_kfunc(u32 btf_id)
12133 {
12134 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12135 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12136 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12137 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
12138 }
12139 
12140 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
12141 {
12142 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12143 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12144 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
12145 }
12146 
12147 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
12148 {
12149 	return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
12150 	       btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
12151 	       btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
12152 }
12153 
12154 static bool is_bpf_graph_api_kfunc(u32 btf_id)
12155 {
12156 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
12157 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
12158 }
12159 
12160 static bool kfunc_spin_allowed(u32 btf_id)
12161 {
12162 	return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id);
12163 }
12164 
12165 static bool is_sync_callback_calling_kfunc(u32 btf_id)
12166 {
12167 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
12168 }
12169 
12170 static bool is_async_callback_calling_kfunc(u32 btf_id)
12171 {
12172 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12173 }
12174 
12175 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
12176 {
12177 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
12178 	       insn->imm == special_kfunc_list[KF_bpf_throw];
12179 }
12180 
12181 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
12182 {
12183 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12184 }
12185 
12186 static bool is_callback_calling_kfunc(u32 btf_id)
12187 {
12188 	return is_sync_callback_calling_kfunc(btf_id) ||
12189 	       is_async_callback_calling_kfunc(btf_id);
12190 }
12191 
12192 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
12193 {
12194 	return is_bpf_rbtree_api_kfunc(btf_id);
12195 }
12196 
12197 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
12198 					  enum btf_field_type head_field_type,
12199 					  u32 kfunc_btf_id)
12200 {
12201 	bool ret;
12202 
12203 	switch (head_field_type) {
12204 	case BPF_LIST_HEAD:
12205 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
12206 		break;
12207 	case BPF_RB_ROOT:
12208 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
12209 		break;
12210 	default:
12211 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
12212 			btf_field_type_name(head_field_type));
12213 		return false;
12214 	}
12215 
12216 	if (!ret)
12217 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
12218 			btf_field_type_name(head_field_type));
12219 	return ret;
12220 }
12221 
12222 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
12223 					  enum btf_field_type node_field_type,
12224 					  u32 kfunc_btf_id)
12225 {
12226 	bool ret;
12227 
12228 	switch (node_field_type) {
12229 	case BPF_LIST_NODE:
12230 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12231 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
12232 		break;
12233 	case BPF_RB_NODE:
12234 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12235 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
12236 		break;
12237 	default:
12238 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
12239 			btf_field_type_name(node_field_type));
12240 		return false;
12241 	}
12242 
12243 	if (!ret)
12244 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
12245 			btf_field_type_name(node_field_type));
12246 	return ret;
12247 }
12248 
12249 static int
12250 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
12251 				   struct bpf_reg_state *reg, u32 regno,
12252 				   struct bpf_kfunc_call_arg_meta *meta,
12253 				   enum btf_field_type head_field_type,
12254 				   struct btf_field **head_field)
12255 {
12256 	const char *head_type_name;
12257 	struct btf_field *field;
12258 	struct btf_record *rec;
12259 	u32 head_off;
12260 
12261 	if (meta->btf != btf_vmlinux) {
12262 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
12263 		return -EFAULT;
12264 	}
12265 
12266 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
12267 		return -EFAULT;
12268 
12269 	head_type_name = btf_field_type_name(head_field_type);
12270 	if (!tnum_is_const(reg->var_off)) {
12271 		verbose(env,
12272 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12273 			regno, head_type_name);
12274 		return -EINVAL;
12275 	}
12276 
12277 	rec = reg_btf_record(reg);
12278 	head_off = reg->off + reg->var_off.value;
12279 	field = btf_record_find(rec, head_off, head_field_type);
12280 	if (!field) {
12281 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
12282 		return -EINVAL;
12283 	}
12284 
12285 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
12286 	if (check_reg_allocation_locked(env, reg)) {
12287 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
12288 			rec->spin_lock_off, head_type_name);
12289 		return -EINVAL;
12290 	}
12291 
12292 	if (*head_field) {
12293 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
12294 		return -EFAULT;
12295 	}
12296 	*head_field = field;
12297 	return 0;
12298 }
12299 
12300 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
12301 					   struct bpf_reg_state *reg, u32 regno,
12302 					   struct bpf_kfunc_call_arg_meta *meta)
12303 {
12304 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
12305 							  &meta->arg_list_head.field);
12306 }
12307 
12308 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
12309 					     struct bpf_reg_state *reg, u32 regno,
12310 					     struct bpf_kfunc_call_arg_meta *meta)
12311 {
12312 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
12313 							  &meta->arg_rbtree_root.field);
12314 }
12315 
12316 static int
12317 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
12318 				   struct bpf_reg_state *reg, u32 regno,
12319 				   struct bpf_kfunc_call_arg_meta *meta,
12320 				   enum btf_field_type head_field_type,
12321 				   enum btf_field_type node_field_type,
12322 				   struct btf_field **node_field)
12323 {
12324 	const char *node_type_name;
12325 	const struct btf_type *et, *t;
12326 	struct btf_field *field;
12327 	u32 node_off;
12328 
12329 	if (meta->btf != btf_vmlinux) {
12330 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
12331 		return -EFAULT;
12332 	}
12333 
12334 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
12335 		return -EFAULT;
12336 
12337 	node_type_name = btf_field_type_name(node_field_type);
12338 	if (!tnum_is_const(reg->var_off)) {
12339 		verbose(env,
12340 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12341 			regno, node_type_name);
12342 		return -EINVAL;
12343 	}
12344 
12345 	node_off = reg->off + reg->var_off.value;
12346 	field = reg_find_field_offset(reg, node_off, node_field_type);
12347 	if (!field) {
12348 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
12349 		return -EINVAL;
12350 	}
12351 
12352 	field = *node_field;
12353 
12354 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
12355 	t = btf_type_by_id(reg->btf, reg->btf_id);
12356 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
12357 				  field->graph_root.value_btf_id, true)) {
12358 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
12359 			"in struct %s, but arg is at offset=%d in struct %s\n",
12360 			btf_field_type_name(head_field_type),
12361 			btf_field_type_name(node_field_type),
12362 			field->graph_root.node_offset,
12363 			btf_name_by_offset(field->graph_root.btf, et->name_off),
12364 			node_off, btf_name_by_offset(reg->btf, t->name_off));
12365 		return -EINVAL;
12366 	}
12367 	meta->arg_btf = reg->btf;
12368 	meta->arg_btf_id = reg->btf_id;
12369 
12370 	if (node_off != field->graph_root.node_offset) {
12371 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
12372 			node_off, btf_field_type_name(node_field_type),
12373 			field->graph_root.node_offset,
12374 			btf_name_by_offset(field->graph_root.btf, et->name_off));
12375 		return -EINVAL;
12376 	}
12377 
12378 	return 0;
12379 }
12380 
12381 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
12382 					   struct bpf_reg_state *reg, u32 regno,
12383 					   struct bpf_kfunc_call_arg_meta *meta)
12384 {
12385 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
12386 						  BPF_LIST_HEAD, BPF_LIST_NODE,
12387 						  &meta->arg_list_head.field);
12388 }
12389 
12390 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
12391 					     struct bpf_reg_state *reg, u32 regno,
12392 					     struct bpf_kfunc_call_arg_meta *meta)
12393 {
12394 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
12395 						  BPF_RB_ROOT, BPF_RB_NODE,
12396 						  &meta->arg_rbtree_root.field);
12397 }
12398 
12399 /*
12400  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
12401  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
12402  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
12403  * them can only be attached to some specific hook points.
12404  */
12405 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
12406 {
12407 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12408 
12409 	switch (prog_type) {
12410 	case BPF_PROG_TYPE_LSM:
12411 		return true;
12412 	case BPF_PROG_TYPE_TRACING:
12413 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
12414 			return true;
12415 		fallthrough;
12416 	default:
12417 		return in_sleepable(env);
12418 	}
12419 }
12420 
12421 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
12422 			    int insn_idx)
12423 {
12424 	const char *func_name = meta->func_name, *ref_tname;
12425 	const struct btf *btf = meta->btf;
12426 	const struct btf_param *args;
12427 	struct btf_record *rec;
12428 	u32 i, nargs;
12429 	int ret;
12430 
12431 	args = (const struct btf_param *)(meta->func_proto + 1);
12432 	nargs = btf_type_vlen(meta->func_proto);
12433 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
12434 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
12435 			MAX_BPF_FUNC_REG_ARGS);
12436 		return -EINVAL;
12437 	}
12438 
12439 	/* Check that BTF function arguments match actual types that the
12440 	 * verifier sees.
12441 	 */
12442 	for (i = 0; i < nargs; i++) {
12443 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
12444 		const struct btf_type *t, *ref_t, *resolve_ret;
12445 		enum bpf_arg_type arg_type = ARG_DONTCARE;
12446 		u32 regno = i + 1, ref_id, type_size;
12447 		bool is_ret_buf_sz = false;
12448 		int kf_arg_type;
12449 
12450 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
12451 
12452 		if (is_kfunc_arg_ignore(btf, &args[i]))
12453 			continue;
12454 
12455 		if (btf_type_is_scalar(t)) {
12456 			if (reg->type != SCALAR_VALUE) {
12457 				verbose(env, "R%d is not a scalar\n", regno);
12458 				return -EINVAL;
12459 			}
12460 
12461 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
12462 				if (meta->arg_constant.found) {
12463 					verbose(env, "verifier internal error: only one constant argument permitted\n");
12464 					return -EFAULT;
12465 				}
12466 				if (!tnum_is_const(reg->var_off)) {
12467 					verbose(env, "R%d must be a known constant\n", regno);
12468 					return -EINVAL;
12469 				}
12470 				ret = mark_chain_precision(env, regno);
12471 				if (ret < 0)
12472 					return ret;
12473 				meta->arg_constant.found = true;
12474 				meta->arg_constant.value = reg->var_off.value;
12475 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
12476 				meta->r0_rdonly = true;
12477 				is_ret_buf_sz = true;
12478 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
12479 				is_ret_buf_sz = true;
12480 			}
12481 
12482 			if (is_ret_buf_sz) {
12483 				if (meta->r0_size) {
12484 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
12485 					return -EINVAL;
12486 				}
12487 
12488 				if (!tnum_is_const(reg->var_off)) {
12489 					verbose(env, "R%d is not a const\n", regno);
12490 					return -EINVAL;
12491 				}
12492 
12493 				meta->r0_size = reg->var_off.value;
12494 				ret = mark_chain_precision(env, regno);
12495 				if (ret)
12496 					return ret;
12497 			}
12498 			continue;
12499 		}
12500 
12501 		if (!btf_type_is_ptr(t)) {
12502 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
12503 			return -EINVAL;
12504 		}
12505 
12506 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
12507 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
12508 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
12509 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
12510 			return -EACCES;
12511 		}
12512 
12513 		if (reg->ref_obj_id) {
12514 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
12515 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
12516 					regno, reg->ref_obj_id,
12517 					meta->ref_obj_id);
12518 				return -EFAULT;
12519 			}
12520 			meta->ref_obj_id = reg->ref_obj_id;
12521 			if (is_kfunc_release(meta))
12522 				meta->release_regno = regno;
12523 		}
12524 
12525 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
12526 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12527 
12528 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
12529 		if (kf_arg_type < 0)
12530 			return kf_arg_type;
12531 
12532 		switch (kf_arg_type) {
12533 		case KF_ARG_PTR_TO_NULL:
12534 			continue;
12535 		case KF_ARG_PTR_TO_MAP:
12536 			if (!reg->map_ptr) {
12537 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
12538 				return -EINVAL;
12539 			}
12540 			if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) {
12541 				/* Use map_uid (which is unique id of inner map) to reject:
12542 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
12543 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
12544 				 * if (inner_map1 && inner_map2) {
12545 				 *     wq = bpf_map_lookup_elem(inner_map1);
12546 				 *     if (wq)
12547 				 *         // mismatch would have been allowed
12548 				 *         bpf_wq_init(wq, inner_map2);
12549 				 * }
12550 				 *
12551 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
12552 				 */
12553 				if (meta->map.ptr != reg->map_ptr ||
12554 				    meta->map.uid != reg->map_uid) {
12555 					verbose(env,
12556 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
12557 						meta->map.uid, reg->map_uid);
12558 					return -EINVAL;
12559 				}
12560 			}
12561 			meta->map.ptr = reg->map_ptr;
12562 			meta->map.uid = reg->map_uid;
12563 			fallthrough;
12564 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12565 		case KF_ARG_PTR_TO_BTF_ID:
12566 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
12567 				break;
12568 
12569 			if (!is_trusted_reg(reg)) {
12570 				if (!is_kfunc_rcu(meta)) {
12571 					verbose(env, "R%d must be referenced or trusted\n", regno);
12572 					return -EINVAL;
12573 				}
12574 				if (!is_rcu_reg(reg)) {
12575 					verbose(env, "R%d must be a rcu pointer\n", regno);
12576 					return -EINVAL;
12577 				}
12578 			}
12579 			fallthrough;
12580 		case KF_ARG_PTR_TO_CTX:
12581 		case KF_ARG_PTR_TO_DYNPTR:
12582 		case KF_ARG_PTR_TO_ITER:
12583 		case KF_ARG_PTR_TO_LIST_HEAD:
12584 		case KF_ARG_PTR_TO_LIST_NODE:
12585 		case KF_ARG_PTR_TO_RB_ROOT:
12586 		case KF_ARG_PTR_TO_RB_NODE:
12587 		case KF_ARG_PTR_TO_MEM:
12588 		case KF_ARG_PTR_TO_MEM_SIZE:
12589 		case KF_ARG_PTR_TO_CALLBACK:
12590 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12591 		case KF_ARG_PTR_TO_CONST_STR:
12592 		case KF_ARG_PTR_TO_WORKQUEUE:
12593 		case KF_ARG_PTR_TO_IRQ_FLAG:
12594 			break;
12595 		default:
12596 			WARN_ON_ONCE(1);
12597 			return -EFAULT;
12598 		}
12599 
12600 		if (is_kfunc_release(meta) && reg->ref_obj_id)
12601 			arg_type |= OBJ_RELEASE;
12602 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
12603 		if (ret < 0)
12604 			return ret;
12605 
12606 		switch (kf_arg_type) {
12607 		case KF_ARG_PTR_TO_CTX:
12608 			if (reg->type != PTR_TO_CTX) {
12609 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
12610 					i, reg_type_str(env, reg->type));
12611 				return -EINVAL;
12612 			}
12613 
12614 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12615 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
12616 				if (ret < 0)
12617 					return -EINVAL;
12618 				meta->ret_btf_id  = ret;
12619 			}
12620 			break;
12621 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12622 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
12623 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
12624 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
12625 					return -EINVAL;
12626 				}
12627 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
12628 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12629 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
12630 					return -EINVAL;
12631 				}
12632 			} else {
12633 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
12634 				return -EINVAL;
12635 			}
12636 			if (!reg->ref_obj_id) {
12637 				verbose(env, "allocated object must be referenced\n");
12638 				return -EINVAL;
12639 			}
12640 			if (meta->btf == btf_vmlinux) {
12641 				meta->arg_btf = reg->btf;
12642 				meta->arg_btf_id = reg->btf_id;
12643 			}
12644 			break;
12645 		case KF_ARG_PTR_TO_DYNPTR:
12646 		{
12647 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
12648 			int clone_ref_obj_id = 0;
12649 
12650 			if (reg->type == CONST_PTR_TO_DYNPTR)
12651 				dynptr_arg_type |= MEM_RDONLY;
12652 
12653 			if (is_kfunc_arg_uninit(btf, &args[i]))
12654 				dynptr_arg_type |= MEM_UNINIT;
12655 
12656 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
12657 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
12658 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
12659 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
12660 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
12661 				   (dynptr_arg_type & MEM_UNINIT)) {
12662 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
12663 
12664 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
12665 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
12666 					return -EFAULT;
12667 				}
12668 
12669 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
12670 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
12671 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
12672 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
12673 					return -EFAULT;
12674 				}
12675 			}
12676 
12677 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
12678 			if (ret < 0)
12679 				return ret;
12680 
12681 			if (!(dynptr_arg_type & MEM_UNINIT)) {
12682 				int id = dynptr_id(env, reg);
12683 
12684 				if (id < 0) {
12685 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
12686 					return id;
12687 				}
12688 				meta->initialized_dynptr.id = id;
12689 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
12690 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
12691 			}
12692 
12693 			break;
12694 		}
12695 		case KF_ARG_PTR_TO_ITER:
12696 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
12697 				if (!check_css_task_iter_allowlist(env)) {
12698 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
12699 					return -EINVAL;
12700 				}
12701 			}
12702 			ret = process_iter_arg(env, regno, insn_idx, meta);
12703 			if (ret < 0)
12704 				return ret;
12705 			break;
12706 		case KF_ARG_PTR_TO_LIST_HEAD:
12707 			if (reg->type != PTR_TO_MAP_VALUE &&
12708 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12709 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12710 				return -EINVAL;
12711 			}
12712 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12713 				verbose(env, "allocated object must be referenced\n");
12714 				return -EINVAL;
12715 			}
12716 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
12717 			if (ret < 0)
12718 				return ret;
12719 			break;
12720 		case KF_ARG_PTR_TO_RB_ROOT:
12721 			if (reg->type != PTR_TO_MAP_VALUE &&
12722 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12723 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12724 				return -EINVAL;
12725 			}
12726 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12727 				verbose(env, "allocated object must be referenced\n");
12728 				return -EINVAL;
12729 			}
12730 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
12731 			if (ret < 0)
12732 				return ret;
12733 			break;
12734 		case KF_ARG_PTR_TO_LIST_NODE:
12735 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12736 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
12737 				return -EINVAL;
12738 			}
12739 			if (!reg->ref_obj_id) {
12740 				verbose(env, "allocated object must be referenced\n");
12741 				return -EINVAL;
12742 			}
12743 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
12744 			if (ret < 0)
12745 				return ret;
12746 			break;
12747 		case KF_ARG_PTR_TO_RB_NODE:
12748 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
12749 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
12750 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
12751 					return -EINVAL;
12752 				}
12753 				if (in_rbtree_lock_required_cb(env)) {
12754 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
12755 					return -EINVAL;
12756 				}
12757 			} else {
12758 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12759 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
12760 					return -EINVAL;
12761 				}
12762 				if (!reg->ref_obj_id) {
12763 					verbose(env, "allocated object must be referenced\n");
12764 					return -EINVAL;
12765 				}
12766 			}
12767 
12768 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
12769 			if (ret < 0)
12770 				return ret;
12771 			break;
12772 		case KF_ARG_PTR_TO_MAP:
12773 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
12774 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
12775 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
12776 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12777 			fallthrough;
12778 		case KF_ARG_PTR_TO_BTF_ID:
12779 			/* Only base_type is checked, further checks are done here */
12780 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
12781 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
12782 			    !reg2btf_ids[base_type(reg->type)]) {
12783 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
12784 				verbose(env, "expected %s or socket\n",
12785 					reg_type_str(env, base_type(reg->type) |
12786 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
12787 				return -EINVAL;
12788 			}
12789 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
12790 			if (ret < 0)
12791 				return ret;
12792 			break;
12793 		case KF_ARG_PTR_TO_MEM:
12794 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
12795 			if (IS_ERR(resolve_ret)) {
12796 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
12797 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
12798 				return -EINVAL;
12799 			}
12800 			ret = check_mem_reg(env, reg, regno, type_size);
12801 			if (ret < 0)
12802 				return ret;
12803 			break;
12804 		case KF_ARG_PTR_TO_MEM_SIZE:
12805 		{
12806 			struct bpf_reg_state *buff_reg = &regs[regno];
12807 			const struct btf_param *buff_arg = &args[i];
12808 			struct bpf_reg_state *size_reg = &regs[regno + 1];
12809 			const struct btf_param *size_arg = &args[i + 1];
12810 
12811 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
12812 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
12813 				if (ret < 0) {
12814 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
12815 					return ret;
12816 				}
12817 			}
12818 
12819 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
12820 				if (meta->arg_constant.found) {
12821 					verbose(env, "verifier internal error: only one constant argument permitted\n");
12822 					return -EFAULT;
12823 				}
12824 				if (!tnum_is_const(size_reg->var_off)) {
12825 					verbose(env, "R%d must be a known constant\n", regno + 1);
12826 					return -EINVAL;
12827 				}
12828 				meta->arg_constant.found = true;
12829 				meta->arg_constant.value = size_reg->var_off.value;
12830 			}
12831 
12832 			/* Skip next '__sz' or '__szk' argument */
12833 			i++;
12834 			break;
12835 		}
12836 		case KF_ARG_PTR_TO_CALLBACK:
12837 			if (reg->type != PTR_TO_FUNC) {
12838 				verbose(env, "arg%d expected pointer to func\n", i);
12839 				return -EINVAL;
12840 			}
12841 			meta->subprogno = reg->subprogno;
12842 			break;
12843 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12844 			if (!type_is_ptr_alloc_obj(reg->type)) {
12845 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
12846 				return -EINVAL;
12847 			}
12848 			if (!type_is_non_owning_ref(reg->type))
12849 				meta->arg_owning_ref = true;
12850 
12851 			rec = reg_btf_record(reg);
12852 			if (!rec) {
12853 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
12854 				return -EFAULT;
12855 			}
12856 
12857 			if (rec->refcount_off < 0) {
12858 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
12859 				return -EINVAL;
12860 			}
12861 
12862 			meta->arg_btf = reg->btf;
12863 			meta->arg_btf_id = reg->btf_id;
12864 			break;
12865 		case KF_ARG_PTR_TO_CONST_STR:
12866 			if (reg->type != PTR_TO_MAP_VALUE) {
12867 				verbose(env, "arg#%d doesn't point to a const string\n", i);
12868 				return -EINVAL;
12869 			}
12870 			ret = check_reg_const_str(env, reg, regno);
12871 			if (ret)
12872 				return ret;
12873 			break;
12874 		case KF_ARG_PTR_TO_WORKQUEUE:
12875 			if (reg->type != PTR_TO_MAP_VALUE) {
12876 				verbose(env, "arg#%d doesn't point to a map value\n", i);
12877 				return -EINVAL;
12878 			}
12879 			ret = process_wq_func(env, regno, meta);
12880 			if (ret < 0)
12881 				return ret;
12882 			break;
12883 		case KF_ARG_PTR_TO_IRQ_FLAG:
12884 			if (reg->type != PTR_TO_STACK) {
12885 				verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i);
12886 				return -EINVAL;
12887 			}
12888 			ret = process_irq_flag(env, regno, meta);
12889 			if (ret < 0)
12890 				return ret;
12891 			break;
12892 		}
12893 	}
12894 
12895 	if (is_kfunc_release(meta) && !meta->release_regno) {
12896 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
12897 			func_name);
12898 		return -EINVAL;
12899 	}
12900 
12901 	return 0;
12902 }
12903 
12904 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
12905 			    struct bpf_insn *insn,
12906 			    struct bpf_kfunc_call_arg_meta *meta,
12907 			    const char **kfunc_name)
12908 {
12909 	const struct btf_type *func, *func_proto;
12910 	u32 func_id, *kfunc_flags;
12911 	const char *func_name;
12912 	struct btf *desc_btf;
12913 
12914 	if (kfunc_name)
12915 		*kfunc_name = NULL;
12916 
12917 	if (!insn->imm)
12918 		return -EINVAL;
12919 
12920 	desc_btf = find_kfunc_desc_btf(env, insn->off);
12921 	if (IS_ERR(desc_btf))
12922 		return PTR_ERR(desc_btf);
12923 
12924 	func_id = insn->imm;
12925 	func = btf_type_by_id(desc_btf, func_id);
12926 	func_name = btf_name_by_offset(desc_btf, func->name_off);
12927 	if (kfunc_name)
12928 		*kfunc_name = func_name;
12929 	func_proto = btf_type_by_id(desc_btf, func->type);
12930 
12931 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
12932 	if (!kfunc_flags) {
12933 		return -EACCES;
12934 	}
12935 
12936 	memset(meta, 0, sizeof(*meta));
12937 	meta->btf = desc_btf;
12938 	meta->func_id = func_id;
12939 	meta->kfunc_flags = *kfunc_flags;
12940 	meta->func_proto = func_proto;
12941 	meta->func_name = func_name;
12942 
12943 	return 0;
12944 }
12945 
12946 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12947 
12948 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12949 			    int *insn_idx_p)
12950 {
12951 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
12952 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
12953 	struct bpf_reg_state *regs = cur_regs(env);
12954 	const char *func_name, *ptr_type_name;
12955 	const struct btf_type *t, *ptr_type;
12956 	struct bpf_kfunc_call_arg_meta meta;
12957 	struct bpf_insn_aux_data *insn_aux;
12958 	int err, insn_idx = *insn_idx_p;
12959 	const struct btf_param *args;
12960 	const struct btf_type *ret_t;
12961 	struct btf *desc_btf;
12962 
12963 	/* skip for now, but return error when we find this in fixup_kfunc_call */
12964 	if (!insn->imm)
12965 		return 0;
12966 
12967 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
12968 	if (err == -EACCES && func_name)
12969 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
12970 	if (err)
12971 		return err;
12972 	desc_btf = meta.btf;
12973 	insn_aux = &env->insn_aux_data[insn_idx];
12974 
12975 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
12976 
12977 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12978 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12979 		return -EACCES;
12980 	}
12981 
12982 	sleepable = is_kfunc_sleepable(&meta);
12983 	if (sleepable && !in_sleepable(env)) {
12984 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12985 		return -EACCES;
12986 	}
12987 
12988 	/* Check the arguments */
12989 	err = check_kfunc_args(env, &meta, insn_idx);
12990 	if (err < 0)
12991 		return err;
12992 
12993 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12994 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12995 					 set_rbtree_add_callback_state);
12996 		if (err) {
12997 			verbose(env, "kfunc %s#%d failed callback verification\n",
12998 				func_name, meta.func_id);
12999 			return err;
13000 		}
13001 	}
13002 
13003 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
13004 		meta.r0_size = sizeof(u64);
13005 		meta.r0_rdonly = false;
13006 	}
13007 
13008 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
13009 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13010 					 set_timer_callback_state);
13011 		if (err) {
13012 			verbose(env, "kfunc %s#%d failed callback verification\n",
13013 				func_name, meta.func_id);
13014 			return err;
13015 		}
13016 	}
13017 
13018 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
13019 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
13020 
13021 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
13022 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
13023 
13024 	if (env->cur_state->active_rcu_lock) {
13025 		struct bpf_func_state *state;
13026 		struct bpf_reg_state *reg;
13027 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
13028 
13029 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
13030 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
13031 			return -EACCES;
13032 		}
13033 
13034 		if (rcu_lock) {
13035 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
13036 			return -EINVAL;
13037 		} else if (rcu_unlock) {
13038 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
13039 				if (reg->type & MEM_RCU) {
13040 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
13041 					reg->type |= PTR_UNTRUSTED;
13042 				}
13043 			}));
13044 			env->cur_state->active_rcu_lock = false;
13045 		} else if (sleepable) {
13046 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
13047 			return -EACCES;
13048 		}
13049 	} else if (rcu_lock) {
13050 		env->cur_state->active_rcu_lock = true;
13051 	} else if (rcu_unlock) {
13052 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
13053 		return -EINVAL;
13054 	}
13055 
13056 	if (env->cur_state->active_preempt_locks) {
13057 		if (preempt_disable) {
13058 			env->cur_state->active_preempt_locks++;
13059 		} else if (preempt_enable) {
13060 			env->cur_state->active_preempt_locks--;
13061 		} else if (sleepable) {
13062 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
13063 			return -EACCES;
13064 		}
13065 	} else if (preempt_disable) {
13066 		env->cur_state->active_preempt_locks++;
13067 	} else if (preempt_enable) {
13068 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
13069 		return -EINVAL;
13070 	}
13071 
13072 	if (env->cur_state->active_irq_id && sleepable) {
13073 		verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name);
13074 		return -EACCES;
13075 	}
13076 
13077 	/* In case of release function, we get register number of refcounted
13078 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
13079 	 */
13080 	if (meta.release_regno) {
13081 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
13082 		if (err) {
13083 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13084 				func_name, meta.func_id);
13085 			return err;
13086 		}
13087 	}
13088 
13089 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
13090 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
13091 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13092 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
13093 		insn_aux->insert_off = regs[BPF_REG_2].off;
13094 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
13095 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
13096 		if (err) {
13097 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
13098 				func_name, meta.func_id);
13099 			return err;
13100 		}
13101 
13102 		err = release_reference(env, release_ref_obj_id);
13103 		if (err) {
13104 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13105 				func_name, meta.func_id);
13106 			return err;
13107 		}
13108 	}
13109 
13110 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
13111 		if (!bpf_jit_supports_exceptions()) {
13112 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
13113 				func_name, meta.func_id);
13114 			return -ENOTSUPP;
13115 		}
13116 		env->seen_exception = true;
13117 
13118 		/* In the case of the default callback, the cookie value passed
13119 		 * to bpf_throw becomes the return value of the program.
13120 		 */
13121 		if (!env->exception_callback_subprog) {
13122 			err = check_return_code(env, BPF_REG_1, "R1");
13123 			if (err < 0)
13124 				return err;
13125 		}
13126 	}
13127 
13128 	for (i = 0; i < CALLER_SAVED_REGS; i++)
13129 		mark_reg_not_init(env, regs, caller_saved[i]);
13130 
13131 	/* Check return type */
13132 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
13133 
13134 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
13135 		/* Only exception is bpf_obj_new_impl */
13136 		if (meta.btf != btf_vmlinux ||
13137 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
13138 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
13139 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
13140 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
13141 			return -EINVAL;
13142 		}
13143 	}
13144 
13145 	if (btf_type_is_scalar(t)) {
13146 		mark_reg_unknown(env, regs, BPF_REG_0);
13147 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
13148 	} else if (btf_type_is_ptr(t)) {
13149 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
13150 
13151 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
13152 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
13153 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13154 				struct btf_struct_meta *struct_meta;
13155 				struct btf *ret_btf;
13156 				u32 ret_btf_id;
13157 
13158 				if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
13159 					return -ENOMEM;
13160 
13161 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
13162 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13163 					return -EINVAL;
13164 				}
13165 
13166 				ret_btf = env->prog->aux->btf;
13167 				ret_btf_id = meta.arg_constant.value;
13168 
13169 				/* This may be NULL due to user not supplying a BTF */
13170 				if (!ret_btf) {
13171 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13172 					return -EINVAL;
13173 				}
13174 
13175 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13176 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
13177 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13178 					return -EINVAL;
13179 				}
13180 
13181 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13182 					if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13183 						verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13184 							ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13185 						return -EINVAL;
13186 					}
13187 
13188 					if (!bpf_global_percpu_ma_set) {
13189 						mutex_lock(&bpf_percpu_ma_lock);
13190 						if (!bpf_global_percpu_ma_set) {
13191 							/* Charge memory allocated with bpf_global_percpu_ma to
13192 							 * root memcg. The obj_cgroup for root memcg is NULL.
13193 							 */
13194 							err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13195 							if (!err)
13196 								bpf_global_percpu_ma_set = true;
13197 						}
13198 						mutex_unlock(&bpf_percpu_ma_lock);
13199 						if (err)
13200 							return err;
13201 					}
13202 
13203 					mutex_lock(&bpf_percpu_ma_lock);
13204 					err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13205 					mutex_unlock(&bpf_percpu_ma_lock);
13206 					if (err)
13207 						return err;
13208 				}
13209 
13210 				struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13211 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13212 					if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13213 						verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13214 						return -EINVAL;
13215 					}
13216 
13217 					if (struct_meta) {
13218 						verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13219 						return -EINVAL;
13220 					}
13221 				}
13222 
13223 				mark_reg_known_zero(env, regs, BPF_REG_0);
13224 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13225 				regs[BPF_REG_0].btf = ret_btf;
13226 				regs[BPF_REG_0].btf_id = ret_btf_id;
13227 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
13228 					regs[BPF_REG_0].type |= MEM_PERCPU;
13229 
13230 				insn_aux->obj_new_size = ret_t->size;
13231 				insn_aux->kptr_struct_meta = struct_meta;
13232 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
13233 				mark_reg_known_zero(env, regs, BPF_REG_0);
13234 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13235 				regs[BPF_REG_0].btf = meta.arg_btf;
13236 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
13237 
13238 				insn_aux->kptr_struct_meta =
13239 					btf_find_struct_meta(meta.arg_btf,
13240 							     meta.arg_btf_id);
13241 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
13242 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
13243 				struct btf_field *field = meta.arg_list_head.field;
13244 
13245 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13246 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
13247 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
13248 				struct btf_field *field = meta.arg_rbtree_root.field;
13249 
13250 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13251 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13252 				mark_reg_known_zero(env, regs, BPF_REG_0);
13253 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13254 				regs[BPF_REG_0].btf = desc_btf;
13255 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
13256 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
13257 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
13258 				if (!ret_t || !btf_type_is_struct(ret_t)) {
13259 					verbose(env,
13260 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
13261 					return -EINVAL;
13262 				}
13263 
13264 				mark_reg_known_zero(env, regs, BPF_REG_0);
13265 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13266 				regs[BPF_REG_0].btf = desc_btf;
13267 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
13268 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13269 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13270 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
13271 
13272 				mark_reg_known_zero(env, regs, BPF_REG_0);
13273 
13274 				if (!meta.arg_constant.found) {
13275 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
13276 					return -EFAULT;
13277 				}
13278 
13279 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
13280 
13281 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
13282 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
13283 
13284 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
13285 					regs[BPF_REG_0].type |= MEM_RDONLY;
13286 				} else {
13287 					/* this will set env->seen_direct_write to true */
13288 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
13289 						verbose(env, "the prog does not allow writes to packet data\n");
13290 						return -EINVAL;
13291 					}
13292 				}
13293 
13294 				if (!meta.initialized_dynptr.id) {
13295 					verbose(env, "verifier internal error: no dynptr id\n");
13296 					return -EFAULT;
13297 				}
13298 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
13299 
13300 				/* we don't need to set BPF_REG_0's ref obj id
13301 				 * because packet slices are not refcounted (see
13302 				 * dynptr_type_refcounted)
13303 				 */
13304 			} else {
13305 				verbose(env, "kernel function %s unhandled dynamic return type\n",
13306 					meta.func_name);
13307 				return -EFAULT;
13308 			}
13309 		} else if (btf_type_is_void(ptr_type)) {
13310 			/* kfunc returning 'void *' is equivalent to returning scalar */
13311 			mark_reg_unknown(env, regs, BPF_REG_0);
13312 		} else if (!__btf_type_is_struct(ptr_type)) {
13313 			if (!meta.r0_size) {
13314 				__u32 sz;
13315 
13316 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
13317 					meta.r0_size = sz;
13318 					meta.r0_rdonly = true;
13319 				}
13320 			}
13321 			if (!meta.r0_size) {
13322 				ptr_type_name = btf_name_by_offset(desc_btf,
13323 								   ptr_type->name_off);
13324 				verbose(env,
13325 					"kernel function %s returns pointer type %s %s is not supported\n",
13326 					func_name,
13327 					btf_type_str(ptr_type),
13328 					ptr_type_name);
13329 				return -EINVAL;
13330 			}
13331 
13332 			mark_reg_known_zero(env, regs, BPF_REG_0);
13333 			regs[BPF_REG_0].type = PTR_TO_MEM;
13334 			regs[BPF_REG_0].mem_size = meta.r0_size;
13335 
13336 			if (meta.r0_rdonly)
13337 				regs[BPF_REG_0].type |= MEM_RDONLY;
13338 
13339 			/* Ensures we don't access the memory after a release_reference() */
13340 			if (meta.ref_obj_id)
13341 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
13342 		} else {
13343 			mark_reg_known_zero(env, regs, BPF_REG_0);
13344 			regs[BPF_REG_0].btf = desc_btf;
13345 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
13346 			regs[BPF_REG_0].btf_id = ptr_type_id;
13347 
13348 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
13349 				regs[BPF_REG_0].type |= PTR_UNTRUSTED;
13350 
13351 			if (is_iter_next_kfunc(&meta)) {
13352 				struct bpf_reg_state *cur_iter;
13353 
13354 				cur_iter = get_iter_from_state(env->cur_state, &meta);
13355 
13356 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
13357 					regs[BPF_REG_0].type |= MEM_RCU;
13358 				else
13359 					regs[BPF_REG_0].type |= PTR_TRUSTED;
13360 			}
13361 		}
13362 
13363 		if (is_kfunc_ret_null(&meta)) {
13364 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
13365 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
13366 			regs[BPF_REG_0].id = ++env->id_gen;
13367 		}
13368 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
13369 		if (is_kfunc_acquire(&meta)) {
13370 			int id = acquire_reference(env, insn_idx);
13371 
13372 			if (id < 0)
13373 				return id;
13374 			if (is_kfunc_ret_null(&meta))
13375 				regs[BPF_REG_0].id = id;
13376 			regs[BPF_REG_0].ref_obj_id = id;
13377 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
13378 			ref_set_non_owning(env, &regs[BPF_REG_0]);
13379 		}
13380 
13381 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
13382 			regs[BPF_REG_0].id = ++env->id_gen;
13383 	} else if (btf_type_is_void(t)) {
13384 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
13385 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
13386 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13387 				insn_aux->kptr_struct_meta =
13388 					btf_find_struct_meta(meta.arg_btf,
13389 							     meta.arg_btf_id);
13390 			}
13391 		}
13392 	}
13393 
13394 	nargs = btf_type_vlen(meta.func_proto);
13395 	args = (const struct btf_param *)(meta.func_proto + 1);
13396 	for (i = 0; i < nargs; i++) {
13397 		u32 regno = i + 1;
13398 
13399 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
13400 		if (btf_type_is_ptr(t))
13401 			mark_btf_func_reg_size(env, regno, sizeof(void *));
13402 		else
13403 			/* scalar. ensured by btf_check_kfunc_arg_match() */
13404 			mark_btf_func_reg_size(env, regno, t->size);
13405 	}
13406 
13407 	if (is_iter_next_kfunc(&meta)) {
13408 		err = process_iter_next_call(env, insn_idx, &meta);
13409 		if (err)
13410 			return err;
13411 	}
13412 
13413 	return 0;
13414 }
13415 
13416 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
13417 				  const struct bpf_reg_state *reg,
13418 				  enum bpf_reg_type type)
13419 {
13420 	bool known = tnum_is_const(reg->var_off);
13421 	s64 val = reg->var_off.value;
13422 	s64 smin = reg->smin_value;
13423 
13424 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
13425 		verbose(env, "math between %s pointer and %lld is not allowed\n",
13426 			reg_type_str(env, type), val);
13427 		return false;
13428 	}
13429 
13430 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
13431 		verbose(env, "%s pointer offset %d is not allowed\n",
13432 			reg_type_str(env, type), reg->off);
13433 		return false;
13434 	}
13435 
13436 	if (smin == S64_MIN) {
13437 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
13438 			reg_type_str(env, type));
13439 		return false;
13440 	}
13441 
13442 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
13443 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
13444 			smin, reg_type_str(env, type));
13445 		return false;
13446 	}
13447 
13448 	return true;
13449 }
13450 
13451 enum {
13452 	REASON_BOUNDS	= -1,
13453 	REASON_TYPE	= -2,
13454 	REASON_PATHS	= -3,
13455 	REASON_LIMIT	= -4,
13456 	REASON_STACK	= -5,
13457 };
13458 
13459 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
13460 			      u32 *alu_limit, bool mask_to_left)
13461 {
13462 	u32 max = 0, ptr_limit = 0;
13463 
13464 	switch (ptr_reg->type) {
13465 	case PTR_TO_STACK:
13466 		/* Offset 0 is out-of-bounds, but acceptable start for the
13467 		 * left direction, see BPF_REG_FP. Also, unknown scalar
13468 		 * offset where we would need to deal with min/max bounds is
13469 		 * currently prohibited for unprivileged.
13470 		 */
13471 		max = MAX_BPF_STACK + mask_to_left;
13472 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
13473 		break;
13474 	case PTR_TO_MAP_VALUE:
13475 		max = ptr_reg->map_ptr->value_size;
13476 		ptr_limit = (mask_to_left ?
13477 			     ptr_reg->smin_value :
13478 			     ptr_reg->umax_value) + ptr_reg->off;
13479 		break;
13480 	default:
13481 		return REASON_TYPE;
13482 	}
13483 
13484 	if (ptr_limit >= max)
13485 		return REASON_LIMIT;
13486 	*alu_limit = ptr_limit;
13487 	return 0;
13488 }
13489 
13490 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
13491 				    const struct bpf_insn *insn)
13492 {
13493 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
13494 }
13495 
13496 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
13497 				       u32 alu_state, u32 alu_limit)
13498 {
13499 	/* If we arrived here from different branches with different
13500 	 * state or limits to sanitize, then this won't work.
13501 	 */
13502 	if (aux->alu_state &&
13503 	    (aux->alu_state != alu_state ||
13504 	     aux->alu_limit != alu_limit))
13505 		return REASON_PATHS;
13506 
13507 	/* Corresponding fixup done in do_misc_fixups(). */
13508 	aux->alu_state = alu_state;
13509 	aux->alu_limit = alu_limit;
13510 	return 0;
13511 }
13512 
13513 static int sanitize_val_alu(struct bpf_verifier_env *env,
13514 			    struct bpf_insn *insn)
13515 {
13516 	struct bpf_insn_aux_data *aux = cur_aux(env);
13517 
13518 	if (can_skip_alu_sanitation(env, insn))
13519 		return 0;
13520 
13521 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
13522 }
13523 
13524 static bool sanitize_needed(u8 opcode)
13525 {
13526 	return opcode == BPF_ADD || opcode == BPF_SUB;
13527 }
13528 
13529 struct bpf_sanitize_info {
13530 	struct bpf_insn_aux_data aux;
13531 	bool mask_to_left;
13532 };
13533 
13534 static struct bpf_verifier_state *
13535 sanitize_speculative_path(struct bpf_verifier_env *env,
13536 			  const struct bpf_insn *insn,
13537 			  u32 next_idx, u32 curr_idx)
13538 {
13539 	struct bpf_verifier_state *branch;
13540 	struct bpf_reg_state *regs;
13541 
13542 	branch = push_stack(env, next_idx, curr_idx, true);
13543 	if (branch && insn) {
13544 		regs = branch->frame[branch->curframe]->regs;
13545 		if (BPF_SRC(insn->code) == BPF_K) {
13546 			mark_reg_unknown(env, regs, insn->dst_reg);
13547 		} else if (BPF_SRC(insn->code) == BPF_X) {
13548 			mark_reg_unknown(env, regs, insn->dst_reg);
13549 			mark_reg_unknown(env, regs, insn->src_reg);
13550 		}
13551 	}
13552 	return branch;
13553 }
13554 
13555 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
13556 			    struct bpf_insn *insn,
13557 			    const struct bpf_reg_state *ptr_reg,
13558 			    const struct bpf_reg_state *off_reg,
13559 			    struct bpf_reg_state *dst_reg,
13560 			    struct bpf_sanitize_info *info,
13561 			    const bool commit_window)
13562 {
13563 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
13564 	struct bpf_verifier_state *vstate = env->cur_state;
13565 	bool off_is_imm = tnum_is_const(off_reg->var_off);
13566 	bool off_is_neg = off_reg->smin_value < 0;
13567 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
13568 	u8 opcode = BPF_OP(insn->code);
13569 	u32 alu_state, alu_limit;
13570 	struct bpf_reg_state tmp;
13571 	bool ret;
13572 	int err;
13573 
13574 	if (can_skip_alu_sanitation(env, insn))
13575 		return 0;
13576 
13577 	/* We already marked aux for masking from non-speculative
13578 	 * paths, thus we got here in the first place. We only care
13579 	 * to explore bad access from here.
13580 	 */
13581 	if (vstate->speculative)
13582 		goto do_sim;
13583 
13584 	if (!commit_window) {
13585 		if (!tnum_is_const(off_reg->var_off) &&
13586 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
13587 			return REASON_BOUNDS;
13588 
13589 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
13590 				     (opcode == BPF_SUB && !off_is_neg);
13591 	}
13592 
13593 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
13594 	if (err < 0)
13595 		return err;
13596 
13597 	if (commit_window) {
13598 		/* In commit phase we narrow the masking window based on
13599 		 * the observed pointer move after the simulated operation.
13600 		 */
13601 		alu_state = info->aux.alu_state;
13602 		alu_limit = abs(info->aux.alu_limit - alu_limit);
13603 	} else {
13604 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
13605 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
13606 		alu_state |= ptr_is_dst_reg ?
13607 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
13608 
13609 		/* Limit pruning on unknown scalars to enable deep search for
13610 		 * potential masking differences from other program paths.
13611 		 */
13612 		if (!off_is_imm)
13613 			env->explore_alu_limits = true;
13614 	}
13615 
13616 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
13617 	if (err < 0)
13618 		return err;
13619 do_sim:
13620 	/* If we're in commit phase, we're done here given we already
13621 	 * pushed the truncated dst_reg into the speculative verification
13622 	 * stack.
13623 	 *
13624 	 * Also, when register is a known constant, we rewrite register-based
13625 	 * operation to immediate-based, and thus do not need masking (and as
13626 	 * a consequence, do not need to simulate the zero-truncation either).
13627 	 */
13628 	if (commit_window || off_is_imm)
13629 		return 0;
13630 
13631 	/* Simulate and find potential out-of-bounds access under
13632 	 * speculative execution from truncation as a result of
13633 	 * masking when off was not within expected range. If off
13634 	 * sits in dst, then we temporarily need to move ptr there
13635 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
13636 	 * for cases where we use K-based arithmetic in one direction
13637 	 * and truncated reg-based in the other in order to explore
13638 	 * bad access.
13639 	 */
13640 	if (!ptr_is_dst_reg) {
13641 		tmp = *dst_reg;
13642 		copy_register_state(dst_reg, ptr_reg);
13643 	}
13644 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
13645 					env->insn_idx);
13646 	if (!ptr_is_dst_reg && ret)
13647 		*dst_reg = tmp;
13648 	return !ret ? REASON_STACK : 0;
13649 }
13650 
13651 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
13652 {
13653 	struct bpf_verifier_state *vstate = env->cur_state;
13654 
13655 	/* If we simulate paths under speculation, we don't update the
13656 	 * insn as 'seen' such that when we verify unreachable paths in
13657 	 * the non-speculative domain, sanitize_dead_code() can still
13658 	 * rewrite/sanitize them.
13659 	 */
13660 	if (!vstate->speculative)
13661 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
13662 }
13663 
13664 static int sanitize_err(struct bpf_verifier_env *env,
13665 			const struct bpf_insn *insn, int reason,
13666 			const struct bpf_reg_state *off_reg,
13667 			const struct bpf_reg_state *dst_reg)
13668 {
13669 	static const char *err = "pointer arithmetic with it prohibited for !root";
13670 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
13671 	u32 dst = insn->dst_reg, src = insn->src_reg;
13672 
13673 	switch (reason) {
13674 	case REASON_BOUNDS:
13675 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
13676 			off_reg == dst_reg ? dst : src, err);
13677 		break;
13678 	case REASON_TYPE:
13679 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
13680 			off_reg == dst_reg ? src : dst, err);
13681 		break;
13682 	case REASON_PATHS:
13683 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
13684 			dst, op, err);
13685 		break;
13686 	case REASON_LIMIT:
13687 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
13688 			dst, op, err);
13689 		break;
13690 	case REASON_STACK:
13691 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
13692 			dst, err);
13693 		break;
13694 	default:
13695 		verbose(env, "verifier internal error: unknown reason (%d)\n",
13696 			reason);
13697 		break;
13698 	}
13699 
13700 	return -EACCES;
13701 }
13702 
13703 /* check that stack access falls within stack limits and that 'reg' doesn't
13704  * have a variable offset.
13705  *
13706  * Variable offset is prohibited for unprivileged mode for simplicity since it
13707  * requires corresponding support in Spectre masking for stack ALU.  See also
13708  * retrieve_ptr_limit().
13709  *
13710  *
13711  * 'off' includes 'reg->off'.
13712  */
13713 static int check_stack_access_for_ptr_arithmetic(
13714 				struct bpf_verifier_env *env,
13715 				int regno,
13716 				const struct bpf_reg_state *reg,
13717 				int off)
13718 {
13719 	if (!tnum_is_const(reg->var_off)) {
13720 		char tn_buf[48];
13721 
13722 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
13723 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
13724 			regno, tn_buf, off);
13725 		return -EACCES;
13726 	}
13727 
13728 	if (off >= 0 || off < -MAX_BPF_STACK) {
13729 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
13730 			"prohibited for !root; off=%d\n", regno, off);
13731 		return -EACCES;
13732 	}
13733 
13734 	return 0;
13735 }
13736 
13737 static int sanitize_check_bounds(struct bpf_verifier_env *env,
13738 				 const struct bpf_insn *insn,
13739 				 const struct bpf_reg_state *dst_reg)
13740 {
13741 	u32 dst = insn->dst_reg;
13742 
13743 	/* For unprivileged we require that resulting offset must be in bounds
13744 	 * in order to be able to sanitize access later on.
13745 	 */
13746 	if (env->bypass_spec_v1)
13747 		return 0;
13748 
13749 	switch (dst_reg->type) {
13750 	case PTR_TO_STACK:
13751 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
13752 					dst_reg->off + dst_reg->var_off.value))
13753 			return -EACCES;
13754 		break;
13755 	case PTR_TO_MAP_VALUE:
13756 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
13757 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
13758 				"prohibited for !root\n", dst);
13759 			return -EACCES;
13760 		}
13761 		break;
13762 	default:
13763 		break;
13764 	}
13765 
13766 	return 0;
13767 }
13768 
13769 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
13770  * Caller should also handle BPF_MOV case separately.
13771  * If we return -EACCES, caller may want to try again treating pointer as a
13772  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
13773  */
13774 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
13775 				   struct bpf_insn *insn,
13776 				   const struct bpf_reg_state *ptr_reg,
13777 				   const struct bpf_reg_state *off_reg)
13778 {
13779 	struct bpf_verifier_state *vstate = env->cur_state;
13780 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13781 	struct bpf_reg_state *regs = state->regs, *dst_reg;
13782 	bool known = tnum_is_const(off_reg->var_off);
13783 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
13784 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
13785 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
13786 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
13787 	struct bpf_sanitize_info info = {};
13788 	u8 opcode = BPF_OP(insn->code);
13789 	u32 dst = insn->dst_reg;
13790 	int ret;
13791 
13792 	dst_reg = &regs[dst];
13793 
13794 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
13795 	    smin_val > smax_val || umin_val > umax_val) {
13796 		/* Taint dst register if offset had invalid bounds derived from
13797 		 * e.g. dead branches.
13798 		 */
13799 		__mark_reg_unknown(env, dst_reg);
13800 		return 0;
13801 	}
13802 
13803 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
13804 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
13805 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13806 			__mark_reg_unknown(env, dst_reg);
13807 			return 0;
13808 		}
13809 
13810 		verbose(env,
13811 			"R%d 32-bit pointer arithmetic prohibited\n",
13812 			dst);
13813 		return -EACCES;
13814 	}
13815 
13816 	if (ptr_reg->type & PTR_MAYBE_NULL) {
13817 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
13818 			dst, reg_type_str(env, ptr_reg->type));
13819 		return -EACCES;
13820 	}
13821 
13822 	switch (base_type(ptr_reg->type)) {
13823 	case PTR_TO_CTX:
13824 	case PTR_TO_MAP_VALUE:
13825 	case PTR_TO_MAP_KEY:
13826 	case PTR_TO_STACK:
13827 	case PTR_TO_PACKET_META:
13828 	case PTR_TO_PACKET:
13829 	case PTR_TO_TP_BUFFER:
13830 	case PTR_TO_BTF_ID:
13831 	case PTR_TO_MEM:
13832 	case PTR_TO_BUF:
13833 	case PTR_TO_FUNC:
13834 	case CONST_PTR_TO_DYNPTR:
13835 		break;
13836 	case PTR_TO_FLOW_KEYS:
13837 		if (known)
13838 			break;
13839 		fallthrough;
13840 	case CONST_PTR_TO_MAP:
13841 		/* smin_val represents the known value */
13842 		if (known && smin_val == 0 && opcode == BPF_ADD)
13843 			break;
13844 		fallthrough;
13845 	default:
13846 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
13847 			dst, reg_type_str(env, ptr_reg->type));
13848 		return -EACCES;
13849 	}
13850 
13851 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
13852 	 * The id may be overwritten later if we create a new variable offset.
13853 	 */
13854 	dst_reg->type = ptr_reg->type;
13855 	dst_reg->id = ptr_reg->id;
13856 
13857 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
13858 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
13859 		return -EINVAL;
13860 
13861 	/* pointer types do not carry 32-bit bounds at the moment. */
13862 	__mark_reg32_unbounded(dst_reg);
13863 
13864 	if (sanitize_needed(opcode)) {
13865 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
13866 				       &info, false);
13867 		if (ret < 0)
13868 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13869 	}
13870 
13871 	switch (opcode) {
13872 	case BPF_ADD:
13873 		/* We can take a fixed offset as long as it doesn't overflow
13874 		 * the s32 'off' field
13875 		 */
13876 		if (known && (ptr_reg->off + smin_val ==
13877 			      (s64)(s32)(ptr_reg->off + smin_val))) {
13878 			/* pointer += K.  Accumulate it into fixed offset */
13879 			dst_reg->smin_value = smin_ptr;
13880 			dst_reg->smax_value = smax_ptr;
13881 			dst_reg->umin_value = umin_ptr;
13882 			dst_reg->umax_value = umax_ptr;
13883 			dst_reg->var_off = ptr_reg->var_off;
13884 			dst_reg->off = ptr_reg->off + smin_val;
13885 			dst_reg->raw = ptr_reg->raw;
13886 			break;
13887 		}
13888 		/* A new variable offset is created.  Note that off_reg->off
13889 		 * == 0, since it's a scalar.
13890 		 * dst_reg gets the pointer type and since some positive
13891 		 * integer value was added to the pointer, give it a new 'id'
13892 		 * if it's a PTR_TO_PACKET.
13893 		 * this creates a new 'base' pointer, off_reg (variable) gets
13894 		 * added into the variable offset, and we copy the fixed offset
13895 		 * from ptr_reg.
13896 		 */
13897 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
13898 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
13899 			dst_reg->smin_value = S64_MIN;
13900 			dst_reg->smax_value = S64_MAX;
13901 		}
13902 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
13903 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
13904 			dst_reg->umin_value = 0;
13905 			dst_reg->umax_value = U64_MAX;
13906 		}
13907 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
13908 		dst_reg->off = ptr_reg->off;
13909 		dst_reg->raw = ptr_reg->raw;
13910 		if (reg_is_pkt_pointer(ptr_reg)) {
13911 			dst_reg->id = ++env->id_gen;
13912 			/* something was added to pkt_ptr, set range to zero */
13913 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13914 		}
13915 		break;
13916 	case BPF_SUB:
13917 		if (dst_reg == off_reg) {
13918 			/* scalar -= pointer.  Creates an unknown scalar */
13919 			verbose(env, "R%d tried to subtract pointer from scalar\n",
13920 				dst);
13921 			return -EACCES;
13922 		}
13923 		/* We don't allow subtraction from FP, because (according to
13924 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
13925 		 * be able to deal with it.
13926 		 */
13927 		if (ptr_reg->type == PTR_TO_STACK) {
13928 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
13929 				dst);
13930 			return -EACCES;
13931 		}
13932 		if (known && (ptr_reg->off - smin_val ==
13933 			      (s64)(s32)(ptr_reg->off - smin_val))) {
13934 			/* pointer -= K.  Subtract it from fixed offset */
13935 			dst_reg->smin_value = smin_ptr;
13936 			dst_reg->smax_value = smax_ptr;
13937 			dst_reg->umin_value = umin_ptr;
13938 			dst_reg->umax_value = umax_ptr;
13939 			dst_reg->var_off = ptr_reg->var_off;
13940 			dst_reg->id = ptr_reg->id;
13941 			dst_reg->off = ptr_reg->off - smin_val;
13942 			dst_reg->raw = ptr_reg->raw;
13943 			break;
13944 		}
13945 		/* A new variable offset is created.  If the subtrahend is known
13946 		 * nonnegative, then any reg->range we had before is still good.
13947 		 */
13948 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
13949 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
13950 			/* Overflow possible, we know nothing */
13951 			dst_reg->smin_value = S64_MIN;
13952 			dst_reg->smax_value = S64_MAX;
13953 		}
13954 		if (umin_ptr < umax_val) {
13955 			/* Overflow possible, we know nothing */
13956 			dst_reg->umin_value = 0;
13957 			dst_reg->umax_value = U64_MAX;
13958 		} else {
13959 			/* Cannot overflow (as long as bounds are consistent) */
13960 			dst_reg->umin_value = umin_ptr - umax_val;
13961 			dst_reg->umax_value = umax_ptr - umin_val;
13962 		}
13963 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13964 		dst_reg->off = ptr_reg->off;
13965 		dst_reg->raw = ptr_reg->raw;
13966 		if (reg_is_pkt_pointer(ptr_reg)) {
13967 			dst_reg->id = ++env->id_gen;
13968 			/* something was added to pkt_ptr, set range to zero */
13969 			if (smin_val < 0)
13970 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13971 		}
13972 		break;
13973 	case BPF_AND:
13974 	case BPF_OR:
13975 	case BPF_XOR:
13976 		/* bitwise ops on pointers are troublesome, prohibit. */
13977 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13978 			dst, bpf_alu_string[opcode >> 4]);
13979 		return -EACCES;
13980 	default:
13981 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
13982 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13983 			dst, bpf_alu_string[opcode >> 4]);
13984 		return -EACCES;
13985 	}
13986 
13987 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
13988 		return -EINVAL;
13989 	reg_bounds_sync(dst_reg);
13990 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13991 		return -EACCES;
13992 	if (sanitize_needed(opcode)) {
13993 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13994 				       &info, true);
13995 		if (ret < 0)
13996 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13997 	}
13998 
13999 	return 0;
14000 }
14001 
14002 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
14003 				 struct bpf_reg_state *src_reg)
14004 {
14005 	s32 *dst_smin = &dst_reg->s32_min_value;
14006 	s32 *dst_smax = &dst_reg->s32_max_value;
14007 	u32 *dst_umin = &dst_reg->u32_min_value;
14008 	u32 *dst_umax = &dst_reg->u32_max_value;
14009 
14010 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
14011 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
14012 		*dst_smin = S32_MIN;
14013 		*dst_smax = S32_MAX;
14014 	}
14015 	if (check_add_overflow(*dst_umin, src_reg->u32_min_value, dst_umin) ||
14016 	    check_add_overflow(*dst_umax, src_reg->u32_max_value, dst_umax)) {
14017 		*dst_umin = 0;
14018 		*dst_umax = U32_MAX;
14019 	}
14020 }
14021 
14022 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
14023 			       struct bpf_reg_state *src_reg)
14024 {
14025 	s64 *dst_smin = &dst_reg->smin_value;
14026 	s64 *dst_smax = &dst_reg->smax_value;
14027 	u64 *dst_umin = &dst_reg->umin_value;
14028 	u64 *dst_umax = &dst_reg->umax_value;
14029 
14030 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
14031 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
14032 		*dst_smin = S64_MIN;
14033 		*dst_smax = S64_MAX;
14034 	}
14035 	if (check_add_overflow(*dst_umin, src_reg->umin_value, dst_umin) ||
14036 	    check_add_overflow(*dst_umax, src_reg->umax_value, dst_umax)) {
14037 		*dst_umin = 0;
14038 		*dst_umax = U64_MAX;
14039 	}
14040 }
14041 
14042 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
14043 				 struct bpf_reg_state *src_reg)
14044 {
14045 	s32 *dst_smin = &dst_reg->s32_min_value;
14046 	s32 *dst_smax = &dst_reg->s32_max_value;
14047 	u32 umin_val = src_reg->u32_min_value;
14048 	u32 umax_val = src_reg->u32_max_value;
14049 
14050 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
14051 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
14052 		/* Overflow possible, we know nothing */
14053 		*dst_smin = S32_MIN;
14054 		*dst_smax = S32_MAX;
14055 	}
14056 	if (dst_reg->u32_min_value < umax_val) {
14057 		/* Overflow possible, we know nothing */
14058 		dst_reg->u32_min_value = 0;
14059 		dst_reg->u32_max_value = U32_MAX;
14060 	} else {
14061 		/* Cannot overflow (as long as bounds are consistent) */
14062 		dst_reg->u32_min_value -= umax_val;
14063 		dst_reg->u32_max_value -= umin_val;
14064 	}
14065 }
14066 
14067 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
14068 			       struct bpf_reg_state *src_reg)
14069 {
14070 	s64 *dst_smin = &dst_reg->smin_value;
14071 	s64 *dst_smax = &dst_reg->smax_value;
14072 	u64 umin_val = src_reg->umin_value;
14073 	u64 umax_val = src_reg->umax_value;
14074 
14075 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
14076 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
14077 		/* Overflow possible, we know nothing */
14078 		*dst_smin = S64_MIN;
14079 		*dst_smax = S64_MAX;
14080 	}
14081 	if (dst_reg->umin_value < umax_val) {
14082 		/* Overflow possible, we know nothing */
14083 		dst_reg->umin_value = 0;
14084 		dst_reg->umax_value = U64_MAX;
14085 	} else {
14086 		/* Cannot overflow (as long as bounds are consistent) */
14087 		dst_reg->umin_value -= umax_val;
14088 		dst_reg->umax_value -= umin_val;
14089 	}
14090 }
14091 
14092 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
14093 				 struct bpf_reg_state *src_reg)
14094 {
14095 	s32 *dst_smin = &dst_reg->s32_min_value;
14096 	s32 *dst_smax = &dst_reg->s32_max_value;
14097 	u32 *dst_umin = &dst_reg->u32_min_value;
14098 	u32 *dst_umax = &dst_reg->u32_max_value;
14099 	s32 tmp_prod[4];
14100 
14101 	if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) ||
14102 	    check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) {
14103 		/* Overflow possible, we know nothing */
14104 		*dst_umin = 0;
14105 		*dst_umax = U32_MAX;
14106 	}
14107 	if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) ||
14108 	    check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) ||
14109 	    check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) ||
14110 	    check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) {
14111 		/* Overflow possible, we know nothing */
14112 		*dst_smin = S32_MIN;
14113 		*dst_smax = S32_MAX;
14114 	} else {
14115 		*dst_smin = min_array(tmp_prod, 4);
14116 		*dst_smax = max_array(tmp_prod, 4);
14117 	}
14118 }
14119 
14120 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
14121 			       struct bpf_reg_state *src_reg)
14122 {
14123 	s64 *dst_smin = &dst_reg->smin_value;
14124 	s64 *dst_smax = &dst_reg->smax_value;
14125 	u64 *dst_umin = &dst_reg->umin_value;
14126 	u64 *dst_umax = &dst_reg->umax_value;
14127 	s64 tmp_prod[4];
14128 
14129 	if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) ||
14130 	    check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) {
14131 		/* Overflow possible, we know nothing */
14132 		*dst_umin = 0;
14133 		*dst_umax = U64_MAX;
14134 	}
14135 	if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) ||
14136 	    check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) ||
14137 	    check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) ||
14138 	    check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) {
14139 		/* Overflow possible, we know nothing */
14140 		*dst_smin = S64_MIN;
14141 		*dst_smax = S64_MAX;
14142 	} else {
14143 		*dst_smin = min_array(tmp_prod, 4);
14144 		*dst_smax = max_array(tmp_prod, 4);
14145 	}
14146 }
14147 
14148 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
14149 				 struct bpf_reg_state *src_reg)
14150 {
14151 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14152 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14153 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14154 	u32 umax_val = src_reg->u32_max_value;
14155 
14156 	if (src_known && dst_known) {
14157 		__mark_reg32_known(dst_reg, var32_off.value);
14158 		return;
14159 	}
14160 
14161 	/* We get our minimum from the var_off, since that's inherently
14162 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14163 	 */
14164 	dst_reg->u32_min_value = var32_off.value;
14165 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
14166 
14167 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14168 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14169 	 */
14170 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14171 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14172 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14173 	} else {
14174 		dst_reg->s32_min_value = S32_MIN;
14175 		dst_reg->s32_max_value = S32_MAX;
14176 	}
14177 }
14178 
14179 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
14180 			       struct bpf_reg_state *src_reg)
14181 {
14182 	bool src_known = tnum_is_const(src_reg->var_off);
14183 	bool dst_known = tnum_is_const(dst_reg->var_off);
14184 	u64 umax_val = src_reg->umax_value;
14185 
14186 	if (src_known && dst_known) {
14187 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14188 		return;
14189 	}
14190 
14191 	/* We get our minimum from the var_off, since that's inherently
14192 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14193 	 */
14194 	dst_reg->umin_value = dst_reg->var_off.value;
14195 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
14196 
14197 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14198 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14199 	 */
14200 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
14201 		dst_reg->smin_value = dst_reg->umin_value;
14202 		dst_reg->smax_value = dst_reg->umax_value;
14203 	} else {
14204 		dst_reg->smin_value = S64_MIN;
14205 		dst_reg->smax_value = S64_MAX;
14206 	}
14207 	/* We may learn something more from the var_off */
14208 	__update_reg_bounds(dst_reg);
14209 }
14210 
14211 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
14212 				struct bpf_reg_state *src_reg)
14213 {
14214 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14215 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14216 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14217 	u32 umin_val = src_reg->u32_min_value;
14218 
14219 	if (src_known && dst_known) {
14220 		__mark_reg32_known(dst_reg, var32_off.value);
14221 		return;
14222 	}
14223 
14224 	/* We get our maximum from the var_off, and our minimum is the
14225 	 * maximum of the operands' minima
14226 	 */
14227 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
14228 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
14229 
14230 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14231 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14232 	 */
14233 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14234 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14235 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14236 	} else {
14237 		dst_reg->s32_min_value = S32_MIN;
14238 		dst_reg->s32_max_value = S32_MAX;
14239 	}
14240 }
14241 
14242 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
14243 			      struct bpf_reg_state *src_reg)
14244 {
14245 	bool src_known = tnum_is_const(src_reg->var_off);
14246 	bool dst_known = tnum_is_const(dst_reg->var_off);
14247 	u64 umin_val = src_reg->umin_value;
14248 
14249 	if (src_known && dst_known) {
14250 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14251 		return;
14252 	}
14253 
14254 	/* We get our maximum from the var_off, and our minimum is the
14255 	 * maximum of the operands' minima
14256 	 */
14257 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
14258 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
14259 
14260 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14261 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14262 	 */
14263 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
14264 		dst_reg->smin_value = dst_reg->umin_value;
14265 		dst_reg->smax_value = dst_reg->umax_value;
14266 	} else {
14267 		dst_reg->smin_value = S64_MIN;
14268 		dst_reg->smax_value = S64_MAX;
14269 	}
14270 	/* We may learn something more from the var_off */
14271 	__update_reg_bounds(dst_reg);
14272 }
14273 
14274 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
14275 				 struct bpf_reg_state *src_reg)
14276 {
14277 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14278 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14279 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14280 
14281 	if (src_known && dst_known) {
14282 		__mark_reg32_known(dst_reg, var32_off.value);
14283 		return;
14284 	}
14285 
14286 	/* We get both minimum and maximum from the var32_off. */
14287 	dst_reg->u32_min_value = var32_off.value;
14288 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
14289 
14290 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14291 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14292 	 */
14293 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14294 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14295 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14296 	} else {
14297 		dst_reg->s32_min_value = S32_MIN;
14298 		dst_reg->s32_max_value = S32_MAX;
14299 	}
14300 }
14301 
14302 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
14303 			       struct bpf_reg_state *src_reg)
14304 {
14305 	bool src_known = tnum_is_const(src_reg->var_off);
14306 	bool dst_known = tnum_is_const(dst_reg->var_off);
14307 
14308 	if (src_known && dst_known) {
14309 		/* dst_reg->var_off.value has been updated earlier */
14310 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14311 		return;
14312 	}
14313 
14314 	/* We get both minimum and maximum from the var_off. */
14315 	dst_reg->umin_value = dst_reg->var_off.value;
14316 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
14317 
14318 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14319 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14320 	 */
14321 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
14322 		dst_reg->smin_value = dst_reg->umin_value;
14323 		dst_reg->smax_value = dst_reg->umax_value;
14324 	} else {
14325 		dst_reg->smin_value = S64_MIN;
14326 		dst_reg->smax_value = S64_MAX;
14327 	}
14328 
14329 	__update_reg_bounds(dst_reg);
14330 }
14331 
14332 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
14333 				   u64 umin_val, u64 umax_val)
14334 {
14335 	/* We lose all sign bit information (except what we can pick
14336 	 * up from var_off)
14337 	 */
14338 	dst_reg->s32_min_value = S32_MIN;
14339 	dst_reg->s32_max_value = S32_MAX;
14340 	/* If we might shift our top bit out, then we know nothing */
14341 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
14342 		dst_reg->u32_min_value = 0;
14343 		dst_reg->u32_max_value = U32_MAX;
14344 	} else {
14345 		dst_reg->u32_min_value <<= umin_val;
14346 		dst_reg->u32_max_value <<= umax_val;
14347 	}
14348 }
14349 
14350 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
14351 				 struct bpf_reg_state *src_reg)
14352 {
14353 	u32 umax_val = src_reg->u32_max_value;
14354 	u32 umin_val = src_reg->u32_min_value;
14355 	/* u32 alu operation will zext upper bits */
14356 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
14357 
14358 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
14359 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
14360 	/* Not required but being careful mark reg64 bounds as unknown so
14361 	 * that we are forced to pick them up from tnum and zext later and
14362 	 * if some path skips this step we are still safe.
14363 	 */
14364 	__mark_reg64_unbounded(dst_reg);
14365 	__update_reg32_bounds(dst_reg);
14366 }
14367 
14368 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
14369 				   u64 umin_val, u64 umax_val)
14370 {
14371 	/* Special case <<32 because it is a common compiler pattern to sign
14372 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
14373 	 * positive we know this shift will also be positive so we can track
14374 	 * bounds correctly. Otherwise we lose all sign bit information except
14375 	 * what we can pick up from var_off. Perhaps we can generalize this
14376 	 * later to shifts of any length.
14377 	 */
14378 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
14379 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
14380 	else
14381 		dst_reg->smax_value = S64_MAX;
14382 
14383 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
14384 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
14385 	else
14386 		dst_reg->smin_value = S64_MIN;
14387 
14388 	/* If we might shift our top bit out, then we know nothing */
14389 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
14390 		dst_reg->umin_value = 0;
14391 		dst_reg->umax_value = U64_MAX;
14392 	} else {
14393 		dst_reg->umin_value <<= umin_val;
14394 		dst_reg->umax_value <<= umax_val;
14395 	}
14396 }
14397 
14398 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
14399 			       struct bpf_reg_state *src_reg)
14400 {
14401 	u64 umax_val = src_reg->umax_value;
14402 	u64 umin_val = src_reg->umin_value;
14403 
14404 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
14405 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
14406 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
14407 
14408 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
14409 	/* We may learn something more from the var_off */
14410 	__update_reg_bounds(dst_reg);
14411 }
14412 
14413 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
14414 				 struct bpf_reg_state *src_reg)
14415 {
14416 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
14417 	u32 umax_val = src_reg->u32_max_value;
14418 	u32 umin_val = src_reg->u32_min_value;
14419 
14420 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
14421 	 * be negative, then either:
14422 	 * 1) src_reg might be zero, so the sign bit of the result is
14423 	 *    unknown, so we lose our signed bounds
14424 	 * 2) it's known negative, thus the unsigned bounds capture the
14425 	 *    signed bounds
14426 	 * 3) the signed bounds cross zero, so they tell us nothing
14427 	 *    about the result
14428 	 * If the value in dst_reg is known nonnegative, then again the
14429 	 * unsigned bounds capture the signed bounds.
14430 	 * Thus, in all cases it suffices to blow away our signed bounds
14431 	 * and rely on inferring new ones from the unsigned bounds and
14432 	 * var_off of the result.
14433 	 */
14434 	dst_reg->s32_min_value = S32_MIN;
14435 	dst_reg->s32_max_value = S32_MAX;
14436 
14437 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
14438 	dst_reg->u32_min_value >>= umax_val;
14439 	dst_reg->u32_max_value >>= umin_val;
14440 
14441 	__mark_reg64_unbounded(dst_reg);
14442 	__update_reg32_bounds(dst_reg);
14443 }
14444 
14445 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
14446 			       struct bpf_reg_state *src_reg)
14447 {
14448 	u64 umax_val = src_reg->umax_value;
14449 	u64 umin_val = src_reg->umin_value;
14450 
14451 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
14452 	 * be negative, then either:
14453 	 * 1) src_reg might be zero, so the sign bit of the result is
14454 	 *    unknown, so we lose our signed bounds
14455 	 * 2) it's known negative, thus the unsigned bounds capture the
14456 	 *    signed bounds
14457 	 * 3) the signed bounds cross zero, so they tell us nothing
14458 	 *    about the result
14459 	 * If the value in dst_reg is known nonnegative, then again the
14460 	 * unsigned bounds capture the signed bounds.
14461 	 * Thus, in all cases it suffices to blow away our signed bounds
14462 	 * and rely on inferring new ones from the unsigned bounds and
14463 	 * var_off of the result.
14464 	 */
14465 	dst_reg->smin_value = S64_MIN;
14466 	dst_reg->smax_value = S64_MAX;
14467 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
14468 	dst_reg->umin_value >>= umax_val;
14469 	dst_reg->umax_value >>= umin_val;
14470 
14471 	/* Its not easy to operate on alu32 bounds here because it depends
14472 	 * on bits being shifted in. Take easy way out and mark unbounded
14473 	 * so we can recalculate later from tnum.
14474 	 */
14475 	__mark_reg32_unbounded(dst_reg);
14476 	__update_reg_bounds(dst_reg);
14477 }
14478 
14479 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
14480 				  struct bpf_reg_state *src_reg)
14481 {
14482 	u64 umin_val = src_reg->u32_min_value;
14483 
14484 	/* Upon reaching here, src_known is true and
14485 	 * umax_val is equal to umin_val.
14486 	 */
14487 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
14488 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
14489 
14490 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
14491 
14492 	/* blow away the dst_reg umin_value/umax_value and rely on
14493 	 * dst_reg var_off to refine the result.
14494 	 */
14495 	dst_reg->u32_min_value = 0;
14496 	dst_reg->u32_max_value = U32_MAX;
14497 
14498 	__mark_reg64_unbounded(dst_reg);
14499 	__update_reg32_bounds(dst_reg);
14500 }
14501 
14502 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
14503 				struct bpf_reg_state *src_reg)
14504 {
14505 	u64 umin_val = src_reg->umin_value;
14506 
14507 	/* Upon reaching here, src_known is true and umax_val is equal
14508 	 * to umin_val.
14509 	 */
14510 	dst_reg->smin_value >>= umin_val;
14511 	dst_reg->smax_value >>= umin_val;
14512 
14513 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
14514 
14515 	/* blow away the dst_reg umin_value/umax_value and rely on
14516 	 * dst_reg var_off to refine the result.
14517 	 */
14518 	dst_reg->umin_value = 0;
14519 	dst_reg->umax_value = U64_MAX;
14520 
14521 	/* Its not easy to operate on alu32 bounds here because it depends
14522 	 * on bits being shifted in from upper 32-bits. Take easy way out
14523 	 * and mark unbounded so we can recalculate later from tnum.
14524 	 */
14525 	__mark_reg32_unbounded(dst_reg);
14526 	__update_reg_bounds(dst_reg);
14527 }
14528 
14529 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
14530 					     const struct bpf_reg_state *src_reg)
14531 {
14532 	bool src_is_const = false;
14533 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
14534 
14535 	if (insn_bitness == 32) {
14536 		if (tnum_subreg_is_const(src_reg->var_off)
14537 		    && src_reg->s32_min_value == src_reg->s32_max_value
14538 		    && src_reg->u32_min_value == src_reg->u32_max_value)
14539 			src_is_const = true;
14540 	} else {
14541 		if (tnum_is_const(src_reg->var_off)
14542 		    && src_reg->smin_value == src_reg->smax_value
14543 		    && src_reg->umin_value == src_reg->umax_value)
14544 			src_is_const = true;
14545 	}
14546 
14547 	switch (BPF_OP(insn->code)) {
14548 	case BPF_ADD:
14549 	case BPF_SUB:
14550 	case BPF_AND:
14551 	case BPF_XOR:
14552 	case BPF_OR:
14553 	case BPF_MUL:
14554 		return true;
14555 
14556 	/* Shift operators range is only computable if shift dimension operand
14557 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
14558 	 * includes shifts by a negative number.
14559 	 */
14560 	case BPF_LSH:
14561 	case BPF_RSH:
14562 	case BPF_ARSH:
14563 		return (src_is_const && src_reg->umax_value < insn_bitness);
14564 	default:
14565 		return false;
14566 	}
14567 }
14568 
14569 /* WARNING: This function does calculations on 64-bit values, but the actual
14570  * execution may occur on 32-bit values. Therefore, things like bitshifts
14571  * need extra checks in the 32-bit case.
14572  */
14573 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
14574 				      struct bpf_insn *insn,
14575 				      struct bpf_reg_state *dst_reg,
14576 				      struct bpf_reg_state src_reg)
14577 {
14578 	u8 opcode = BPF_OP(insn->code);
14579 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
14580 	int ret;
14581 
14582 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
14583 		__mark_reg_unknown(env, dst_reg);
14584 		return 0;
14585 	}
14586 
14587 	if (sanitize_needed(opcode)) {
14588 		ret = sanitize_val_alu(env, insn);
14589 		if (ret < 0)
14590 			return sanitize_err(env, insn, ret, NULL, NULL);
14591 	}
14592 
14593 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
14594 	 * There are two classes of instructions: The first class we track both
14595 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
14596 	 * greatest amount of precision when alu operations are mixed with jmp32
14597 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
14598 	 * and BPF_OR. This is possible because these ops have fairly easy to
14599 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
14600 	 * See alu32 verifier tests for examples. The second class of
14601 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
14602 	 * with regards to tracking sign/unsigned bounds because the bits may
14603 	 * cross subreg boundaries in the alu64 case. When this happens we mark
14604 	 * the reg unbounded in the subreg bound space and use the resulting
14605 	 * tnum to calculate an approximation of the sign/unsigned bounds.
14606 	 */
14607 	switch (opcode) {
14608 	case BPF_ADD:
14609 		scalar32_min_max_add(dst_reg, &src_reg);
14610 		scalar_min_max_add(dst_reg, &src_reg);
14611 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
14612 		break;
14613 	case BPF_SUB:
14614 		scalar32_min_max_sub(dst_reg, &src_reg);
14615 		scalar_min_max_sub(dst_reg, &src_reg);
14616 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
14617 		break;
14618 	case BPF_MUL:
14619 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
14620 		scalar32_min_max_mul(dst_reg, &src_reg);
14621 		scalar_min_max_mul(dst_reg, &src_reg);
14622 		break;
14623 	case BPF_AND:
14624 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
14625 		scalar32_min_max_and(dst_reg, &src_reg);
14626 		scalar_min_max_and(dst_reg, &src_reg);
14627 		break;
14628 	case BPF_OR:
14629 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
14630 		scalar32_min_max_or(dst_reg, &src_reg);
14631 		scalar_min_max_or(dst_reg, &src_reg);
14632 		break;
14633 	case BPF_XOR:
14634 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
14635 		scalar32_min_max_xor(dst_reg, &src_reg);
14636 		scalar_min_max_xor(dst_reg, &src_reg);
14637 		break;
14638 	case BPF_LSH:
14639 		if (alu32)
14640 			scalar32_min_max_lsh(dst_reg, &src_reg);
14641 		else
14642 			scalar_min_max_lsh(dst_reg, &src_reg);
14643 		break;
14644 	case BPF_RSH:
14645 		if (alu32)
14646 			scalar32_min_max_rsh(dst_reg, &src_reg);
14647 		else
14648 			scalar_min_max_rsh(dst_reg, &src_reg);
14649 		break;
14650 	case BPF_ARSH:
14651 		if (alu32)
14652 			scalar32_min_max_arsh(dst_reg, &src_reg);
14653 		else
14654 			scalar_min_max_arsh(dst_reg, &src_reg);
14655 		break;
14656 	default:
14657 		break;
14658 	}
14659 
14660 	/* ALU32 ops are zero extended into 64bit register */
14661 	if (alu32)
14662 		zext_32_to_64(dst_reg);
14663 	reg_bounds_sync(dst_reg);
14664 	return 0;
14665 }
14666 
14667 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
14668  * and var_off.
14669  */
14670 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
14671 				   struct bpf_insn *insn)
14672 {
14673 	struct bpf_verifier_state *vstate = env->cur_state;
14674 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14675 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
14676 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
14677 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
14678 	u8 opcode = BPF_OP(insn->code);
14679 	int err;
14680 
14681 	dst_reg = &regs[insn->dst_reg];
14682 	src_reg = NULL;
14683 
14684 	if (dst_reg->type == PTR_TO_ARENA) {
14685 		struct bpf_insn_aux_data *aux = cur_aux(env);
14686 
14687 		if (BPF_CLASS(insn->code) == BPF_ALU64)
14688 			/*
14689 			 * 32-bit operations zero upper bits automatically.
14690 			 * 64-bit operations need to be converted to 32.
14691 			 */
14692 			aux->needs_zext = true;
14693 
14694 		/* Any arithmetic operations are allowed on arena pointers */
14695 		return 0;
14696 	}
14697 
14698 	if (dst_reg->type != SCALAR_VALUE)
14699 		ptr_reg = dst_reg;
14700 
14701 	if (BPF_SRC(insn->code) == BPF_X) {
14702 		src_reg = &regs[insn->src_reg];
14703 		if (src_reg->type != SCALAR_VALUE) {
14704 			if (dst_reg->type != SCALAR_VALUE) {
14705 				/* Combining two pointers by any ALU op yields
14706 				 * an arbitrary scalar. Disallow all math except
14707 				 * pointer subtraction
14708 				 */
14709 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14710 					mark_reg_unknown(env, regs, insn->dst_reg);
14711 					return 0;
14712 				}
14713 				verbose(env, "R%d pointer %s pointer prohibited\n",
14714 					insn->dst_reg,
14715 					bpf_alu_string[opcode >> 4]);
14716 				return -EACCES;
14717 			} else {
14718 				/* scalar += pointer
14719 				 * This is legal, but we have to reverse our
14720 				 * src/dest handling in computing the range
14721 				 */
14722 				err = mark_chain_precision(env, insn->dst_reg);
14723 				if (err)
14724 					return err;
14725 				return adjust_ptr_min_max_vals(env, insn,
14726 							       src_reg, dst_reg);
14727 			}
14728 		} else if (ptr_reg) {
14729 			/* pointer += scalar */
14730 			err = mark_chain_precision(env, insn->src_reg);
14731 			if (err)
14732 				return err;
14733 			return adjust_ptr_min_max_vals(env, insn,
14734 						       dst_reg, src_reg);
14735 		} else if (dst_reg->precise) {
14736 			/* if dst_reg is precise, src_reg should be precise as well */
14737 			err = mark_chain_precision(env, insn->src_reg);
14738 			if (err)
14739 				return err;
14740 		}
14741 	} else {
14742 		/* Pretend the src is a reg with a known value, since we only
14743 		 * need to be able to read from this state.
14744 		 */
14745 		off_reg.type = SCALAR_VALUE;
14746 		__mark_reg_known(&off_reg, insn->imm);
14747 		src_reg = &off_reg;
14748 		if (ptr_reg) /* pointer += K */
14749 			return adjust_ptr_min_max_vals(env, insn,
14750 						       ptr_reg, src_reg);
14751 	}
14752 
14753 	/* Got here implies adding two SCALAR_VALUEs */
14754 	if (WARN_ON_ONCE(ptr_reg)) {
14755 		print_verifier_state(env, vstate, vstate->curframe, true);
14756 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
14757 		return -EINVAL;
14758 	}
14759 	if (WARN_ON(!src_reg)) {
14760 		print_verifier_state(env, vstate, vstate->curframe, true);
14761 		verbose(env, "verifier internal error: no src_reg\n");
14762 		return -EINVAL;
14763 	}
14764 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
14765 	if (err)
14766 		return err;
14767 	/*
14768 	 * Compilers can generate the code
14769 	 * r1 = r2
14770 	 * r1 += 0x1
14771 	 * if r2 < 1000 goto ...
14772 	 * use r1 in memory access
14773 	 * So for 64-bit alu remember constant delta between r2 and r1 and
14774 	 * update r1 after 'if' condition.
14775 	 */
14776 	if (env->bpf_capable &&
14777 	    BPF_OP(insn->code) == BPF_ADD && !alu32 &&
14778 	    dst_reg->id && is_reg_const(src_reg, false)) {
14779 		u64 val = reg_const_value(src_reg, false);
14780 
14781 		if ((dst_reg->id & BPF_ADD_CONST) ||
14782 		    /* prevent overflow in sync_linked_regs() later */
14783 		    val > (u32)S32_MAX) {
14784 			/*
14785 			 * If the register already went through rX += val
14786 			 * we cannot accumulate another val into rx->off.
14787 			 */
14788 			dst_reg->off = 0;
14789 			dst_reg->id = 0;
14790 		} else {
14791 			dst_reg->id |= BPF_ADD_CONST;
14792 			dst_reg->off = val;
14793 		}
14794 	} else {
14795 		/*
14796 		 * Make sure ID is cleared otherwise dst_reg min/max could be
14797 		 * incorrectly propagated into other registers by sync_linked_regs()
14798 		 */
14799 		dst_reg->id = 0;
14800 	}
14801 	return 0;
14802 }
14803 
14804 /* check validity of 32-bit and 64-bit arithmetic operations */
14805 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
14806 {
14807 	struct bpf_reg_state *regs = cur_regs(env);
14808 	u8 opcode = BPF_OP(insn->code);
14809 	int err;
14810 
14811 	if (opcode == BPF_END || opcode == BPF_NEG) {
14812 		if (opcode == BPF_NEG) {
14813 			if (BPF_SRC(insn->code) != BPF_K ||
14814 			    insn->src_reg != BPF_REG_0 ||
14815 			    insn->off != 0 || insn->imm != 0) {
14816 				verbose(env, "BPF_NEG uses reserved fields\n");
14817 				return -EINVAL;
14818 			}
14819 		} else {
14820 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
14821 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
14822 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
14823 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
14824 				verbose(env, "BPF_END uses reserved fields\n");
14825 				return -EINVAL;
14826 			}
14827 		}
14828 
14829 		/* check src operand */
14830 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14831 		if (err)
14832 			return err;
14833 
14834 		if (is_pointer_value(env, insn->dst_reg)) {
14835 			verbose(env, "R%d pointer arithmetic prohibited\n",
14836 				insn->dst_reg);
14837 			return -EACCES;
14838 		}
14839 
14840 		/* check dest operand */
14841 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
14842 		if (err)
14843 			return err;
14844 
14845 	} else if (opcode == BPF_MOV) {
14846 
14847 		if (BPF_SRC(insn->code) == BPF_X) {
14848 			if (BPF_CLASS(insn->code) == BPF_ALU) {
14849 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
14850 				    insn->imm) {
14851 					verbose(env, "BPF_MOV uses reserved fields\n");
14852 					return -EINVAL;
14853 				}
14854 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
14855 				if (insn->imm != 1 && insn->imm != 1u << 16) {
14856 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
14857 					return -EINVAL;
14858 				}
14859 				if (!env->prog->aux->arena) {
14860 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
14861 					return -EINVAL;
14862 				}
14863 			} else {
14864 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
14865 				     insn->off != 32) || insn->imm) {
14866 					verbose(env, "BPF_MOV uses reserved fields\n");
14867 					return -EINVAL;
14868 				}
14869 			}
14870 
14871 			/* check src operand */
14872 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14873 			if (err)
14874 				return err;
14875 		} else {
14876 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
14877 				verbose(env, "BPF_MOV uses reserved fields\n");
14878 				return -EINVAL;
14879 			}
14880 		}
14881 
14882 		/* check dest operand, mark as required later */
14883 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14884 		if (err)
14885 			return err;
14886 
14887 		if (BPF_SRC(insn->code) == BPF_X) {
14888 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
14889 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
14890 
14891 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14892 				if (insn->imm) {
14893 					/* off == BPF_ADDR_SPACE_CAST */
14894 					mark_reg_unknown(env, regs, insn->dst_reg);
14895 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
14896 						dst_reg->type = PTR_TO_ARENA;
14897 						/* PTR_TO_ARENA is 32-bit */
14898 						dst_reg->subreg_def = env->insn_idx + 1;
14899 					}
14900 				} else if (insn->off == 0) {
14901 					/* case: R1 = R2
14902 					 * copy register state to dest reg
14903 					 */
14904 					assign_scalar_id_before_mov(env, src_reg);
14905 					copy_register_state(dst_reg, src_reg);
14906 					dst_reg->live |= REG_LIVE_WRITTEN;
14907 					dst_reg->subreg_def = DEF_NOT_SUBREG;
14908 				} else {
14909 					/* case: R1 = (s8, s16 s32)R2 */
14910 					if (is_pointer_value(env, insn->src_reg)) {
14911 						verbose(env,
14912 							"R%d sign-extension part of pointer\n",
14913 							insn->src_reg);
14914 						return -EACCES;
14915 					} else if (src_reg->type == SCALAR_VALUE) {
14916 						bool no_sext;
14917 
14918 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14919 						if (no_sext)
14920 							assign_scalar_id_before_mov(env, src_reg);
14921 						copy_register_state(dst_reg, src_reg);
14922 						if (!no_sext)
14923 							dst_reg->id = 0;
14924 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
14925 						dst_reg->live |= REG_LIVE_WRITTEN;
14926 						dst_reg->subreg_def = DEF_NOT_SUBREG;
14927 					} else {
14928 						mark_reg_unknown(env, regs, insn->dst_reg);
14929 					}
14930 				}
14931 			} else {
14932 				/* R1 = (u32) R2 */
14933 				if (is_pointer_value(env, insn->src_reg)) {
14934 					verbose(env,
14935 						"R%d partial copy of pointer\n",
14936 						insn->src_reg);
14937 					return -EACCES;
14938 				} else if (src_reg->type == SCALAR_VALUE) {
14939 					if (insn->off == 0) {
14940 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
14941 
14942 						if (is_src_reg_u32)
14943 							assign_scalar_id_before_mov(env, src_reg);
14944 						copy_register_state(dst_reg, src_reg);
14945 						/* Make sure ID is cleared if src_reg is not in u32
14946 						 * range otherwise dst_reg min/max could be incorrectly
14947 						 * propagated into src_reg by sync_linked_regs()
14948 						 */
14949 						if (!is_src_reg_u32)
14950 							dst_reg->id = 0;
14951 						dst_reg->live |= REG_LIVE_WRITTEN;
14952 						dst_reg->subreg_def = env->insn_idx + 1;
14953 					} else {
14954 						/* case: W1 = (s8, s16)W2 */
14955 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14956 
14957 						if (no_sext)
14958 							assign_scalar_id_before_mov(env, src_reg);
14959 						copy_register_state(dst_reg, src_reg);
14960 						if (!no_sext)
14961 							dst_reg->id = 0;
14962 						dst_reg->live |= REG_LIVE_WRITTEN;
14963 						dst_reg->subreg_def = env->insn_idx + 1;
14964 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
14965 					}
14966 				} else {
14967 					mark_reg_unknown(env, regs,
14968 							 insn->dst_reg);
14969 				}
14970 				zext_32_to_64(dst_reg);
14971 				reg_bounds_sync(dst_reg);
14972 			}
14973 		} else {
14974 			/* case: R = imm
14975 			 * remember the value we stored into this reg
14976 			 */
14977 			/* clear any state __mark_reg_known doesn't set */
14978 			mark_reg_unknown(env, regs, insn->dst_reg);
14979 			regs[insn->dst_reg].type = SCALAR_VALUE;
14980 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14981 				__mark_reg_known(regs + insn->dst_reg,
14982 						 insn->imm);
14983 			} else {
14984 				__mark_reg_known(regs + insn->dst_reg,
14985 						 (u32)insn->imm);
14986 			}
14987 		}
14988 
14989 	} else if (opcode > BPF_END) {
14990 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14991 		return -EINVAL;
14992 
14993 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
14994 
14995 		if (BPF_SRC(insn->code) == BPF_X) {
14996 			if (insn->imm != 0 || insn->off > 1 ||
14997 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14998 				verbose(env, "BPF_ALU uses reserved fields\n");
14999 				return -EINVAL;
15000 			}
15001 			/* check src1 operand */
15002 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15003 			if (err)
15004 				return err;
15005 		} else {
15006 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
15007 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15008 				verbose(env, "BPF_ALU uses reserved fields\n");
15009 				return -EINVAL;
15010 			}
15011 		}
15012 
15013 		/* check src2 operand */
15014 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15015 		if (err)
15016 			return err;
15017 
15018 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
15019 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
15020 			verbose(env, "div by zero\n");
15021 			return -EINVAL;
15022 		}
15023 
15024 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
15025 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
15026 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
15027 
15028 			if (insn->imm < 0 || insn->imm >= size) {
15029 				verbose(env, "invalid shift %d\n", insn->imm);
15030 				return -EINVAL;
15031 			}
15032 		}
15033 
15034 		/* check dest operand */
15035 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15036 		err = err ?: adjust_reg_min_max_vals(env, insn);
15037 		if (err)
15038 			return err;
15039 	}
15040 
15041 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
15042 }
15043 
15044 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
15045 				   struct bpf_reg_state *dst_reg,
15046 				   enum bpf_reg_type type,
15047 				   bool range_right_open)
15048 {
15049 	struct bpf_func_state *state;
15050 	struct bpf_reg_state *reg;
15051 	int new_range;
15052 
15053 	if (dst_reg->off < 0 ||
15054 	    (dst_reg->off == 0 && range_right_open))
15055 		/* This doesn't give us any range */
15056 		return;
15057 
15058 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
15059 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
15060 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
15061 		 * than pkt_end, but that's because it's also less than pkt.
15062 		 */
15063 		return;
15064 
15065 	new_range = dst_reg->off;
15066 	if (range_right_open)
15067 		new_range++;
15068 
15069 	/* Examples for register markings:
15070 	 *
15071 	 * pkt_data in dst register:
15072 	 *
15073 	 *   r2 = r3;
15074 	 *   r2 += 8;
15075 	 *   if (r2 > pkt_end) goto <handle exception>
15076 	 *   <access okay>
15077 	 *
15078 	 *   r2 = r3;
15079 	 *   r2 += 8;
15080 	 *   if (r2 < pkt_end) goto <access okay>
15081 	 *   <handle exception>
15082 	 *
15083 	 *   Where:
15084 	 *     r2 == dst_reg, pkt_end == src_reg
15085 	 *     r2=pkt(id=n,off=8,r=0)
15086 	 *     r3=pkt(id=n,off=0,r=0)
15087 	 *
15088 	 * pkt_data in src register:
15089 	 *
15090 	 *   r2 = r3;
15091 	 *   r2 += 8;
15092 	 *   if (pkt_end >= r2) goto <access okay>
15093 	 *   <handle exception>
15094 	 *
15095 	 *   r2 = r3;
15096 	 *   r2 += 8;
15097 	 *   if (pkt_end <= r2) goto <handle exception>
15098 	 *   <access okay>
15099 	 *
15100 	 *   Where:
15101 	 *     pkt_end == dst_reg, r2 == src_reg
15102 	 *     r2=pkt(id=n,off=8,r=0)
15103 	 *     r3=pkt(id=n,off=0,r=0)
15104 	 *
15105 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
15106 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
15107 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
15108 	 * the check.
15109 	 */
15110 
15111 	/* If our ids match, then we must have the same max_value.  And we
15112 	 * don't care about the other reg's fixed offset, since if it's too big
15113 	 * the range won't allow anything.
15114 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
15115 	 */
15116 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15117 		if (reg->type == type && reg->id == dst_reg->id)
15118 			/* keep the maximum range already checked */
15119 			reg->range = max(reg->range, new_range);
15120 	}));
15121 }
15122 
15123 /*
15124  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
15125  */
15126 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15127 				  u8 opcode, bool is_jmp32)
15128 {
15129 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
15130 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
15131 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
15132 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
15133 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
15134 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
15135 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
15136 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
15137 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
15138 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
15139 
15140 	switch (opcode) {
15141 	case BPF_JEQ:
15142 		/* constants, umin/umax and smin/smax checks would be
15143 		 * redundant in this case because they all should match
15144 		 */
15145 		if (tnum_is_const(t1) && tnum_is_const(t2))
15146 			return t1.value == t2.value;
15147 		/* non-overlapping ranges */
15148 		if (umin1 > umax2 || umax1 < umin2)
15149 			return 0;
15150 		if (smin1 > smax2 || smax1 < smin2)
15151 			return 0;
15152 		if (!is_jmp32) {
15153 			/* if 64-bit ranges are inconclusive, see if we can
15154 			 * utilize 32-bit subrange knowledge to eliminate
15155 			 * branches that can't be taken a priori
15156 			 */
15157 			if (reg1->u32_min_value > reg2->u32_max_value ||
15158 			    reg1->u32_max_value < reg2->u32_min_value)
15159 				return 0;
15160 			if (reg1->s32_min_value > reg2->s32_max_value ||
15161 			    reg1->s32_max_value < reg2->s32_min_value)
15162 				return 0;
15163 		}
15164 		break;
15165 	case BPF_JNE:
15166 		/* constants, umin/umax and smin/smax checks would be
15167 		 * redundant in this case because they all should match
15168 		 */
15169 		if (tnum_is_const(t1) && tnum_is_const(t2))
15170 			return t1.value != t2.value;
15171 		/* non-overlapping ranges */
15172 		if (umin1 > umax2 || umax1 < umin2)
15173 			return 1;
15174 		if (smin1 > smax2 || smax1 < smin2)
15175 			return 1;
15176 		if (!is_jmp32) {
15177 			/* if 64-bit ranges are inconclusive, see if we can
15178 			 * utilize 32-bit subrange knowledge to eliminate
15179 			 * branches that can't be taken a priori
15180 			 */
15181 			if (reg1->u32_min_value > reg2->u32_max_value ||
15182 			    reg1->u32_max_value < reg2->u32_min_value)
15183 				return 1;
15184 			if (reg1->s32_min_value > reg2->s32_max_value ||
15185 			    reg1->s32_max_value < reg2->s32_min_value)
15186 				return 1;
15187 		}
15188 		break;
15189 	case BPF_JSET:
15190 		if (!is_reg_const(reg2, is_jmp32)) {
15191 			swap(reg1, reg2);
15192 			swap(t1, t2);
15193 		}
15194 		if (!is_reg_const(reg2, is_jmp32))
15195 			return -1;
15196 		if ((~t1.mask & t1.value) & t2.value)
15197 			return 1;
15198 		if (!((t1.mask | t1.value) & t2.value))
15199 			return 0;
15200 		break;
15201 	case BPF_JGT:
15202 		if (umin1 > umax2)
15203 			return 1;
15204 		else if (umax1 <= umin2)
15205 			return 0;
15206 		break;
15207 	case BPF_JSGT:
15208 		if (smin1 > smax2)
15209 			return 1;
15210 		else if (smax1 <= smin2)
15211 			return 0;
15212 		break;
15213 	case BPF_JLT:
15214 		if (umax1 < umin2)
15215 			return 1;
15216 		else if (umin1 >= umax2)
15217 			return 0;
15218 		break;
15219 	case BPF_JSLT:
15220 		if (smax1 < smin2)
15221 			return 1;
15222 		else if (smin1 >= smax2)
15223 			return 0;
15224 		break;
15225 	case BPF_JGE:
15226 		if (umin1 >= umax2)
15227 			return 1;
15228 		else if (umax1 < umin2)
15229 			return 0;
15230 		break;
15231 	case BPF_JSGE:
15232 		if (smin1 >= smax2)
15233 			return 1;
15234 		else if (smax1 < smin2)
15235 			return 0;
15236 		break;
15237 	case BPF_JLE:
15238 		if (umax1 <= umin2)
15239 			return 1;
15240 		else if (umin1 > umax2)
15241 			return 0;
15242 		break;
15243 	case BPF_JSLE:
15244 		if (smax1 <= smin2)
15245 			return 1;
15246 		else if (smin1 > smax2)
15247 			return 0;
15248 		break;
15249 	}
15250 
15251 	return -1;
15252 }
15253 
15254 static int flip_opcode(u32 opcode)
15255 {
15256 	/* How can we transform "a <op> b" into "b <op> a"? */
15257 	static const u8 opcode_flip[16] = {
15258 		/* these stay the same */
15259 		[BPF_JEQ  >> 4] = BPF_JEQ,
15260 		[BPF_JNE  >> 4] = BPF_JNE,
15261 		[BPF_JSET >> 4] = BPF_JSET,
15262 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
15263 		[BPF_JGE  >> 4] = BPF_JLE,
15264 		[BPF_JGT  >> 4] = BPF_JLT,
15265 		[BPF_JLE  >> 4] = BPF_JGE,
15266 		[BPF_JLT  >> 4] = BPF_JGT,
15267 		[BPF_JSGE >> 4] = BPF_JSLE,
15268 		[BPF_JSGT >> 4] = BPF_JSLT,
15269 		[BPF_JSLE >> 4] = BPF_JSGE,
15270 		[BPF_JSLT >> 4] = BPF_JSGT
15271 	};
15272 	return opcode_flip[opcode >> 4];
15273 }
15274 
15275 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
15276 				   struct bpf_reg_state *src_reg,
15277 				   u8 opcode)
15278 {
15279 	struct bpf_reg_state *pkt;
15280 
15281 	if (src_reg->type == PTR_TO_PACKET_END) {
15282 		pkt = dst_reg;
15283 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
15284 		pkt = src_reg;
15285 		opcode = flip_opcode(opcode);
15286 	} else {
15287 		return -1;
15288 	}
15289 
15290 	if (pkt->range >= 0)
15291 		return -1;
15292 
15293 	switch (opcode) {
15294 	case BPF_JLE:
15295 		/* pkt <= pkt_end */
15296 		fallthrough;
15297 	case BPF_JGT:
15298 		/* pkt > pkt_end */
15299 		if (pkt->range == BEYOND_PKT_END)
15300 			/* pkt has at last one extra byte beyond pkt_end */
15301 			return opcode == BPF_JGT;
15302 		break;
15303 	case BPF_JLT:
15304 		/* pkt < pkt_end */
15305 		fallthrough;
15306 	case BPF_JGE:
15307 		/* pkt >= pkt_end */
15308 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
15309 			return opcode == BPF_JGE;
15310 		break;
15311 	}
15312 	return -1;
15313 }
15314 
15315 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
15316  * and return:
15317  *  1 - branch will be taken and "goto target" will be executed
15318  *  0 - branch will not be taken and fall-through to next insn
15319  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
15320  *      range [0,10]
15321  */
15322 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15323 			   u8 opcode, bool is_jmp32)
15324 {
15325 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
15326 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
15327 
15328 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
15329 		u64 val;
15330 
15331 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
15332 		if (!is_reg_const(reg2, is_jmp32)) {
15333 			opcode = flip_opcode(opcode);
15334 			swap(reg1, reg2);
15335 		}
15336 		/* and ensure that reg2 is a constant */
15337 		if (!is_reg_const(reg2, is_jmp32))
15338 			return -1;
15339 
15340 		if (!reg_not_null(reg1))
15341 			return -1;
15342 
15343 		/* If pointer is valid tests against zero will fail so we can
15344 		 * use this to direct branch taken.
15345 		 */
15346 		val = reg_const_value(reg2, is_jmp32);
15347 		if (val != 0)
15348 			return -1;
15349 
15350 		switch (opcode) {
15351 		case BPF_JEQ:
15352 			return 0;
15353 		case BPF_JNE:
15354 			return 1;
15355 		default:
15356 			return -1;
15357 		}
15358 	}
15359 
15360 	/* now deal with two scalars, but not necessarily constants */
15361 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
15362 }
15363 
15364 /* Opcode that corresponds to a *false* branch condition.
15365  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
15366  */
15367 static u8 rev_opcode(u8 opcode)
15368 {
15369 	switch (opcode) {
15370 	case BPF_JEQ:		return BPF_JNE;
15371 	case BPF_JNE:		return BPF_JEQ;
15372 	/* JSET doesn't have it's reverse opcode in BPF, so add
15373 	 * BPF_X flag to denote the reverse of that operation
15374 	 */
15375 	case BPF_JSET:		return BPF_JSET | BPF_X;
15376 	case BPF_JSET | BPF_X:	return BPF_JSET;
15377 	case BPF_JGE:		return BPF_JLT;
15378 	case BPF_JGT:		return BPF_JLE;
15379 	case BPF_JLE:		return BPF_JGT;
15380 	case BPF_JLT:		return BPF_JGE;
15381 	case BPF_JSGE:		return BPF_JSLT;
15382 	case BPF_JSGT:		return BPF_JSLE;
15383 	case BPF_JSLE:		return BPF_JSGT;
15384 	case BPF_JSLT:		return BPF_JSGE;
15385 	default:		return 0;
15386 	}
15387 }
15388 
15389 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
15390 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15391 				u8 opcode, bool is_jmp32)
15392 {
15393 	struct tnum t;
15394 	u64 val;
15395 
15396 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
15397 	switch (opcode) {
15398 	case BPF_JGE:
15399 	case BPF_JGT:
15400 	case BPF_JSGE:
15401 	case BPF_JSGT:
15402 		opcode = flip_opcode(opcode);
15403 		swap(reg1, reg2);
15404 		break;
15405 	default:
15406 		break;
15407 	}
15408 
15409 	switch (opcode) {
15410 	case BPF_JEQ:
15411 		if (is_jmp32) {
15412 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
15413 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
15414 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
15415 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
15416 			reg2->u32_min_value = reg1->u32_min_value;
15417 			reg2->u32_max_value = reg1->u32_max_value;
15418 			reg2->s32_min_value = reg1->s32_min_value;
15419 			reg2->s32_max_value = reg1->s32_max_value;
15420 
15421 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
15422 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15423 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
15424 		} else {
15425 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
15426 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
15427 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
15428 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
15429 			reg2->umin_value = reg1->umin_value;
15430 			reg2->umax_value = reg1->umax_value;
15431 			reg2->smin_value = reg1->smin_value;
15432 			reg2->smax_value = reg1->smax_value;
15433 
15434 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
15435 			reg2->var_off = reg1->var_off;
15436 		}
15437 		break;
15438 	case BPF_JNE:
15439 		if (!is_reg_const(reg2, is_jmp32))
15440 			swap(reg1, reg2);
15441 		if (!is_reg_const(reg2, is_jmp32))
15442 			break;
15443 
15444 		/* try to recompute the bound of reg1 if reg2 is a const and
15445 		 * is exactly the edge of reg1.
15446 		 */
15447 		val = reg_const_value(reg2, is_jmp32);
15448 		if (is_jmp32) {
15449 			/* u32_min_value is not equal to 0xffffffff at this point,
15450 			 * because otherwise u32_max_value is 0xffffffff as well,
15451 			 * in such a case both reg1 and reg2 would be constants,
15452 			 * jump would be predicted and reg_set_min_max() won't
15453 			 * be called.
15454 			 *
15455 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
15456 			 * below.
15457 			 */
15458 			if (reg1->u32_min_value == (u32)val)
15459 				reg1->u32_min_value++;
15460 			if (reg1->u32_max_value == (u32)val)
15461 				reg1->u32_max_value--;
15462 			if (reg1->s32_min_value == (s32)val)
15463 				reg1->s32_min_value++;
15464 			if (reg1->s32_max_value == (s32)val)
15465 				reg1->s32_max_value--;
15466 		} else {
15467 			if (reg1->umin_value == (u64)val)
15468 				reg1->umin_value++;
15469 			if (reg1->umax_value == (u64)val)
15470 				reg1->umax_value--;
15471 			if (reg1->smin_value == (s64)val)
15472 				reg1->smin_value++;
15473 			if (reg1->smax_value == (s64)val)
15474 				reg1->smax_value--;
15475 		}
15476 		break;
15477 	case BPF_JSET:
15478 		if (!is_reg_const(reg2, is_jmp32))
15479 			swap(reg1, reg2);
15480 		if (!is_reg_const(reg2, is_jmp32))
15481 			break;
15482 		val = reg_const_value(reg2, is_jmp32);
15483 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
15484 		 * requires single bit to learn something useful. E.g., if we
15485 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
15486 		 * are actually set? We can learn something definite only if
15487 		 * it's a single-bit value to begin with.
15488 		 *
15489 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
15490 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
15491 		 * bit 1 is set, which we can readily use in adjustments.
15492 		 */
15493 		if (!is_power_of_2(val))
15494 			break;
15495 		if (is_jmp32) {
15496 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
15497 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15498 		} else {
15499 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
15500 		}
15501 		break;
15502 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
15503 		if (!is_reg_const(reg2, is_jmp32))
15504 			swap(reg1, reg2);
15505 		if (!is_reg_const(reg2, is_jmp32))
15506 			break;
15507 		val = reg_const_value(reg2, is_jmp32);
15508 		if (is_jmp32) {
15509 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
15510 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15511 		} else {
15512 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
15513 		}
15514 		break;
15515 	case BPF_JLE:
15516 		if (is_jmp32) {
15517 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
15518 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
15519 		} else {
15520 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
15521 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
15522 		}
15523 		break;
15524 	case BPF_JLT:
15525 		if (is_jmp32) {
15526 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
15527 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
15528 		} else {
15529 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
15530 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
15531 		}
15532 		break;
15533 	case BPF_JSLE:
15534 		if (is_jmp32) {
15535 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
15536 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
15537 		} else {
15538 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
15539 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
15540 		}
15541 		break;
15542 	case BPF_JSLT:
15543 		if (is_jmp32) {
15544 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
15545 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
15546 		} else {
15547 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
15548 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
15549 		}
15550 		break;
15551 	default:
15552 		return;
15553 	}
15554 }
15555 
15556 /* Adjusts the register min/max values in the case that the dst_reg and
15557  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
15558  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
15559  * Technically we can do similar adjustments for pointers to the same object,
15560  * but we don't support that right now.
15561  */
15562 static int reg_set_min_max(struct bpf_verifier_env *env,
15563 			   struct bpf_reg_state *true_reg1,
15564 			   struct bpf_reg_state *true_reg2,
15565 			   struct bpf_reg_state *false_reg1,
15566 			   struct bpf_reg_state *false_reg2,
15567 			   u8 opcode, bool is_jmp32)
15568 {
15569 	int err;
15570 
15571 	/* If either register is a pointer, we can't learn anything about its
15572 	 * variable offset from the compare (unless they were a pointer into
15573 	 * the same object, but we don't bother with that).
15574 	 */
15575 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
15576 		return 0;
15577 
15578 	/* fallthrough (FALSE) branch */
15579 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
15580 	reg_bounds_sync(false_reg1);
15581 	reg_bounds_sync(false_reg2);
15582 
15583 	/* jump (TRUE) branch */
15584 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
15585 	reg_bounds_sync(true_reg1);
15586 	reg_bounds_sync(true_reg2);
15587 
15588 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
15589 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
15590 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
15591 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
15592 	return err;
15593 }
15594 
15595 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
15596 				 struct bpf_reg_state *reg, u32 id,
15597 				 bool is_null)
15598 {
15599 	if (type_may_be_null(reg->type) && reg->id == id &&
15600 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
15601 		/* Old offset (both fixed and variable parts) should have been
15602 		 * known-zero, because we don't allow pointer arithmetic on
15603 		 * pointers that might be NULL. If we see this happening, don't
15604 		 * convert the register.
15605 		 *
15606 		 * But in some cases, some helpers that return local kptrs
15607 		 * advance offset for the returned pointer. In those cases, it
15608 		 * is fine to expect to see reg->off.
15609 		 */
15610 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
15611 			return;
15612 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
15613 		    WARN_ON_ONCE(reg->off))
15614 			return;
15615 
15616 		if (is_null) {
15617 			reg->type = SCALAR_VALUE;
15618 			/* We don't need id and ref_obj_id from this point
15619 			 * onwards anymore, thus we should better reset it,
15620 			 * so that state pruning has chances to take effect.
15621 			 */
15622 			reg->id = 0;
15623 			reg->ref_obj_id = 0;
15624 
15625 			return;
15626 		}
15627 
15628 		mark_ptr_not_null_reg(reg);
15629 
15630 		if (!reg_may_point_to_spin_lock(reg)) {
15631 			/* For not-NULL ptr, reg->ref_obj_id will be reset
15632 			 * in release_reference().
15633 			 *
15634 			 * reg->id is still used by spin_lock ptr. Other
15635 			 * than spin_lock ptr type, reg->id can be reset.
15636 			 */
15637 			reg->id = 0;
15638 		}
15639 	}
15640 }
15641 
15642 /* The logic is similar to find_good_pkt_pointers(), both could eventually
15643  * be folded together at some point.
15644  */
15645 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
15646 				  bool is_null)
15647 {
15648 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15649 	struct bpf_reg_state *regs = state->regs, *reg;
15650 	u32 ref_obj_id = regs[regno].ref_obj_id;
15651 	u32 id = regs[regno].id;
15652 
15653 	if (ref_obj_id && ref_obj_id == id && is_null)
15654 		/* regs[regno] is in the " == NULL" branch.
15655 		 * No one could have freed the reference state before
15656 		 * doing the NULL check.
15657 		 */
15658 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
15659 
15660 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15661 		mark_ptr_or_null_reg(state, reg, id, is_null);
15662 	}));
15663 }
15664 
15665 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
15666 				   struct bpf_reg_state *dst_reg,
15667 				   struct bpf_reg_state *src_reg,
15668 				   struct bpf_verifier_state *this_branch,
15669 				   struct bpf_verifier_state *other_branch)
15670 {
15671 	if (BPF_SRC(insn->code) != BPF_X)
15672 		return false;
15673 
15674 	/* Pointers are always 64-bit. */
15675 	if (BPF_CLASS(insn->code) == BPF_JMP32)
15676 		return false;
15677 
15678 	switch (BPF_OP(insn->code)) {
15679 	case BPF_JGT:
15680 		if ((dst_reg->type == PTR_TO_PACKET &&
15681 		     src_reg->type == PTR_TO_PACKET_END) ||
15682 		    (dst_reg->type == PTR_TO_PACKET_META &&
15683 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15684 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
15685 			find_good_pkt_pointers(this_branch, dst_reg,
15686 					       dst_reg->type, false);
15687 			mark_pkt_end(other_branch, insn->dst_reg, true);
15688 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15689 			    src_reg->type == PTR_TO_PACKET) ||
15690 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15691 			    src_reg->type == PTR_TO_PACKET_META)) {
15692 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
15693 			find_good_pkt_pointers(other_branch, src_reg,
15694 					       src_reg->type, true);
15695 			mark_pkt_end(this_branch, insn->src_reg, false);
15696 		} else {
15697 			return false;
15698 		}
15699 		break;
15700 	case BPF_JLT:
15701 		if ((dst_reg->type == PTR_TO_PACKET &&
15702 		     src_reg->type == PTR_TO_PACKET_END) ||
15703 		    (dst_reg->type == PTR_TO_PACKET_META &&
15704 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15705 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
15706 			find_good_pkt_pointers(other_branch, dst_reg,
15707 					       dst_reg->type, true);
15708 			mark_pkt_end(this_branch, insn->dst_reg, false);
15709 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15710 			    src_reg->type == PTR_TO_PACKET) ||
15711 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15712 			    src_reg->type == PTR_TO_PACKET_META)) {
15713 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
15714 			find_good_pkt_pointers(this_branch, src_reg,
15715 					       src_reg->type, false);
15716 			mark_pkt_end(other_branch, insn->src_reg, true);
15717 		} else {
15718 			return false;
15719 		}
15720 		break;
15721 	case BPF_JGE:
15722 		if ((dst_reg->type == PTR_TO_PACKET &&
15723 		     src_reg->type == PTR_TO_PACKET_END) ||
15724 		    (dst_reg->type == PTR_TO_PACKET_META &&
15725 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15726 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
15727 			find_good_pkt_pointers(this_branch, dst_reg,
15728 					       dst_reg->type, true);
15729 			mark_pkt_end(other_branch, insn->dst_reg, false);
15730 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15731 			    src_reg->type == PTR_TO_PACKET) ||
15732 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15733 			    src_reg->type == PTR_TO_PACKET_META)) {
15734 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
15735 			find_good_pkt_pointers(other_branch, src_reg,
15736 					       src_reg->type, false);
15737 			mark_pkt_end(this_branch, insn->src_reg, true);
15738 		} else {
15739 			return false;
15740 		}
15741 		break;
15742 	case BPF_JLE:
15743 		if ((dst_reg->type == PTR_TO_PACKET &&
15744 		     src_reg->type == PTR_TO_PACKET_END) ||
15745 		    (dst_reg->type == PTR_TO_PACKET_META &&
15746 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15747 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
15748 			find_good_pkt_pointers(other_branch, dst_reg,
15749 					       dst_reg->type, false);
15750 			mark_pkt_end(this_branch, insn->dst_reg, true);
15751 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15752 			    src_reg->type == PTR_TO_PACKET) ||
15753 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15754 			    src_reg->type == PTR_TO_PACKET_META)) {
15755 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
15756 			find_good_pkt_pointers(this_branch, src_reg,
15757 					       src_reg->type, true);
15758 			mark_pkt_end(other_branch, insn->src_reg, false);
15759 		} else {
15760 			return false;
15761 		}
15762 		break;
15763 	default:
15764 		return false;
15765 	}
15766 
15767 	return true;
15768 }
15769 
15770 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
15771 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
15772 {
15773 	struct linked_reg *e;
15774 
15775 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
15776 		return;
15777 
15778 	e = linked_regs_push(reg_set);
15779 	if (e) {
15780 		e->frameno = frameno;
15781 		e->is_reg = is_reg;
15782 		e->regno = spi_or_reg;
15783 	} else {
15784 		reg->id = 0;
15785 	}
15786 }
15787 
15788 /* For all R being scalar registers or spilled scalar registers
15789  * in verifier state, save R in linked_regs if R->id == id.
15790  * If there are too many Rs sharing same id, reset id for leftover Rs.
15791  */
15792 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
15793 				struct linked_regs *linked_regs)
15794 {
15795 	struct bpf_func_state *func;
15796 	struct bpf_reg_state *reg;
15797 	int i, j;
15798 
15799 	id = id & ~BPF_ADD_CONST;
15800 	for (i = vstate->curframe; i >= 0; i--) {
15801 		func = vstate->frame[i];
15802 		for (j = 0; j < BPF_REG_FP; j++) {
15803 			reg = &func->regs[j];
15804 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
15805 		}
15806 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
15807 			if (!is_spilled_reg(&func->stack[j]))
15808 				continue;
15809 			reg = &func->stack[j].spilled_ptr;
15810 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
15811 		}
15812 	}
15813 }
15814 
15815 /* For all R in linked_regs, copy known_reg range into R
15816  * if R->id == known_reg->id.
15817  */
15818 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
15819 			     struct linked_regs *linked_regs)
15820 {
15821 	struct bpf_reg_state fake_reg;
15822 	struct bpf_reg_state *reg;
15823 	struct linked_reg *e;
15824 	int i;
15825 
15826 	for (i = 0; i < linked_regs->cnt; ++i) {
15827 		e = &linked_regs->entries[i];
15828 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
15829 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
15830 		if (reg->type != SCALAR_VALUE || reg == known_reg)
15831 			continue;
15832 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
15833 			continue;
15834 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
15835 		    reg->off == known_reg->off) {
15836 			s32 saved_subreg_def = reg->subreg_def;
15837 
15838 			copy_register_state(reg, known_reg);
15839 			reg->subreg_def = saved_subreg_def;
15840 		} else {
15841 			s32 saved_subreg_def = reg->subreg_def;
15842 			s32 saved_off = reg->off;
15843 
15844 			fake_reg.type = SCALAR_VALUE;
15845 			__mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
15846 
15847 			/* reg = known_reg; reg += delta */
15848 			copy_register_state(reg, known_reg);
15849 			/*
15850 			 * Must preserve off, id and add_const flag,
15851 			 * otherwise another sync_linked_regs() will be incorrect.
15852 			 */
15853 			reg->off = saved_off;
15854 			reg->subreg_def = saved_subreg_def;
15855 
15856 			scalar32_min_max_add(reg, &fake_reg);
15857 			scalar_min_max_add(reg, &fake_reg);
15858 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
15859 		}
15860 	}
15861 }
15862 
15863 static int check_cond_jmp_op(struct bpf_verifier_env *env,
15864 			     struct bpf_insn *insn, int *insn_idx)
15865 {
15866 	struct bpf_verifier_state *this_branch = env->cur_state;
15867 	struct bpf_verifier_state *other_branch;
15868 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
15869 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
15870 	struct bpf_reg_state *eq_branch_regs;
15871 	struct linked_regs linked_regs = {};
15872 	u8 opcode = BPF_OP(insn->code);
15873 	bool is_jmp32;
15874 	int pred = -1;
15875 	int err;
15876 
15877 	/* Only conditional jumps are expected to reach here. */
15878 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
15879 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
15880 		return -EINVAL;
15881 	}
15882 
15883 	if (opcode == BPF_JCOND) {
15884 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
15885 		int idx = *insn_idx;
15886 
15887 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
15888 		    insn->src_reg != BPF_MAY_GOTO ||
15889 		    insn->dst_reg || insn->imm || insn->off == 0) {
15890 			verbose(env, "invalid may_goto off %d imm %d\n",
15891 				insn->off, insn->imm);
15892 			return -EINVAL;
15893 		}
15894 		prev_st = find_prev_entry(env, cur_st->parent, idx);
15895 
15896 		/* branch out 'fallthrough' insn as a new state to explore */
15897 		queued_st = push_stack(env, idx + 1, idx, false);
15898 		if (!queued_st)
15899 			return -ENOMEM;
15900 
15901 		queued_st->may_goto_depth++;
15902 		if (prev_st)
15903 			widen_imprecise_scalars(env, prev_st, queued_st);
15904 		*insn_idx += insn->off;
15905 		return 0;
15906 	}
15907 
15908 	/* check src2 operand */
15909 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15910 	if (err)
15911 		return err;
15912 
15913 	dst_reg = &regs[insn->dst_reg];
15914 	if (BPF_SRC(insn->code) == BPF_X) {
15915 		if (insn->imm != 0) {
15916 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15917 			return -EINVAL;
15918 		}
15919 
15920 		/* check src1 operand */
15921 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15922 		if (err)
15923 			return err;
15924 
15925 		src_reg = &regs[insn->src_reg];
15926 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
15927 		    is_pointer_value(env, insn->src_reg)) {
15928 			verbose(env, "R%d pointer comparison prohibited\n",
15929 				insn->src_reg);
15930 			return -EACCES;
15931 		}
15932 	} else {
15933 		if (insn->src_reg != BPF_REG_0) {
15934 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15935 			return -EINVAL;
15936 		}
15937 		src_reg = &env->fake_reg[0];
15938 		memset(src_reg, 0, sizeof(*src_reg));
15939 		src_reg->type = SCALAR_VALUE;
15940 		__mark_reg_known(src_reg, insn->imm);
15941 	}
15942 
15943 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
15944 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
15945 	if (pred >= 0) {
15946 		/* If we get here with a dst_reg pointer type it is because
15947 		 * above is_branch_taken() special cased the 0 comparison.
15948 		 */
15949 		if (!__is_pointer_value(false, dst_reg))
15950 			err = mark_chain_precision(env, insn->dst_reg);
15951 		if (BPF_SRC(insn->code) == BPF_X && !err &&
15952 		    !__is_pointer_value(false, src_reg))
15953 			err = mark_chain_precision(env, insn->src_reg);
15954 		if (err)
15955 			return err;
15956 	}
15957 
15958 	if (pred == 1) {
15959 		/* Only follow the goto, ignore fall-through. If needed, push
15960 		 * the fall-through branch for simulation under speculative
15961 		 * execution.
15962 		 */
15963 		if (!env->bypass_spec_v1 &&
15964 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
15965 					       *insn_idx))
15966 			return -EFAULT;
15967 		if (env->log.level & BPF_LOG_LEVEL)
15968 			print_insn_state(env, this_branch, this_branch->curframe);
15969 		*insn_idx += insn->off;
15970 		return 0;
15971 	} else if (pred == 0) {
15972 		/* Only follow the fall-through branch, since that's where the
15973 		 * program will go. If needed, push the goto branch for
15974 		 * simulation under speculative execution.
15975 		 */
15976 		if (!env->bypass_spec_v1 &&
15977 		    !sanitize_speculative_path(env, insn,
15978 					       *insn_idx + insn->off + 1,
15979 					       *insn_idx))
15980 			return -EFAULT;
15981 		if (env->log.level & BPF_LOG_LEVEL)
15982 			print_insn_state(env, this_branch, this_branch->curframe);
15983 		return 0;
15984 	}
15985 
15986 	/* Push scalar registers sharing same ID to jump history,
15987 	 * do this before creating 'other_branch', so that both
15988 	 * 'this_branch' and 'other_branch' share this history
15989 	 * if parent state is created.
15990 	 */
15991 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
15992 		collect_linked_regs(this_branch, src_reg->id, &linked_regs);
15993 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
15994 		collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
15995 	if (linked_regs.cnt > 1) {
15996 		err = push_insn_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
15997 		if (err)
15998 			return err;
15999 	}
16000 
16001 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
16002 				  false);
16003 	if (!other_branch)
16004 		return -EFAULT;
16005 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
16006 
16007 	if (BPF_SRC(insn->code) == BPF_X) {
16008 		err = reg_set_min_max(env,
16009 				      &other_branch_regs[insn->dst_reg],
16010 				      &other_branch_regs[insn->src_reg],
16011 				      dst_reg, src_reg, opcode, is_jmp32);
16012 	} else /* BPF_SRC(insn->code) == BPF_K */ {
16013 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
16014 		 * so that these are two different memory locations. The
16015 		 * src_reg is not used beyond here in context of K.
16016 		 */
16017 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
16018 		       sizeof(env->fake_reg[0]));
16019 		err = reg_set_min_max(env,
16020 				      &other_branch_regs[insn->dst_reg],
16021 				      &env->fake_reg[0],
16022 				      dst_reg, &env->fake_reg[1],
16023 				      opcode, is_jmp32);
16024 	}
16025 	if (err)
16026 		return err;
16027 
16028 	if (BPF_SRC(insn->code) == BPF_X &&
16029 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
16030 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
16031 		sync_linked_regs(this_branch, src_reg, &linked_regs);
16032 		sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
16033 	}
16034 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
16035 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
16036 		sync_linked_regs(this_branch, dst_reg, &linked_regs);
16037 		sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
16038 	}
16039 
16040 	/* if one pointer register is compared to another pointer
16041 	 * register check if PTR_MAYBE_NULL could be lifted.
16042 	 * E.g. register A - maybe null
16043 	 *      register B - not null
16044 	 * for JNE A, B, ... - A is not null in the false branch;
16045 	 * for JEQ A, B, ... - A is not null in the true branch.
16046 	 *
16047 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
16048 	 * not need to be null checked by the BPF program, i.e.,
16049 	 * could be null even without PTR_MAYBE_NULL marking, so
16050 	 * only propagate nullness when neither reg is that type.
16051 	 */
16052 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
16053 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
16054 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
16055 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
16056 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
16057 		eq_branch_regs = NULL;
16058 		switch (opcode) {
16059 		case BPF_JEQ:
16060 			eq_branch_regs = other_branch_regs;
16061 			break;
16062 		case BPF_JNE:
16063 			eq_branch_regs = regs;
16064 			break;
16065 		default:
16066 			/* do nothing */
16067 			break;
16068 		}
16069 		if (eq_branch_regs) {
16070 			if (type_may_be_null(src_reg->type))
16071 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
16072 			else
16073 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
16074 		}
16075 	}
16076 
16077 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
16078 	 * NOTE: these optimizations below are related with pointer comparison
16079 	 *       which will never be JMP32.
16080 	 */
16081 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
16082 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
16083 	    type_may_be_null(dst_reg->type)) {
16084 		/* Mark all identical registers in each branch as either
16085 		 * safe or unknown depending R == 0 or R != 0 conditional.
16086 		 */
16087 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
16088 				      opcode == BPF_JNE);
16089 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
16090 				      opcode == BPF_JEQ);
16091 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
16092 					   this_branch, other_branch) &&
16093 		   is_pointer_value(env, insn->dst_reg)) {
16094 		verbose(env, "R%d pointer comparison prohibited\n",
16095 			insn->dst_reg);
16096 		return -EACCES;
16097 	}
16098 	if (env->log.level & BPF_LOG_LEVEL)
16099 		print_insn_state(env, this_branch, this_branch->curframe);
16100 	return 0;
16101 }
16102 
16103 /* verify BPF_LD_IMM64 instruction */
16104 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
16105 {
16106 	struct bpf_insn_aux_data *aux = cur_aux(env);
16107 	struct bpf_reg_state *regs = cur_regs(env);
16108 	struct bpf_reg_state *dst_reg;
16109 	struct bpf_map *map;
16110 	int err;
16111 
16112 	if (BPF_SIZE(insn->code) != BPF_DW) {
16113 		verbose(env, "invalid BPF_LD_IMM insn\n");
16114 		return -EINVAL;
16115 	}
16116 	if (insn->off != 0) {
16117 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
16118 		return -EINVAL;
16119 	}
16120 
16121 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
16122 	if (err)
16123 		return err;
16124 
16125 	dst_reg = &regs[insn->dst_reg];
16126 	if (insn->src_reg == 0) {
16127 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
16128 
16129 		dst_reg->type = SCALAR_VALUE;
16130 		__mark_reg_known(&regs[insn->dst_reg], imm);
16131 		return 0;
16132 	}
16133 
16134 	/* All special src_reg cases are listed below. From this point onwards
16135 	 * we either succeed and assign a corresponding dst_reg->type after
16136 	 * zeroing the offset, or fail and reject the program.
16137 	 */
16138 	mark_reg_known_zero(env, regs, insn->dst_reg);
16139 
16140 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
16141 		dst_reg->type = aux->btf_var.reg_type;
16142 		switch (base_type(dst_reg->type)) {
16143 		case PTR_TO_MEM:
16144 			dst_reg->mem_size = aux->btf_var.mem_size;
16145 			break;
16146 		case PTR_TO_BTF_ID:
16147 			dst_reg->btf = aux->btf_var.btf;
16148 			dst_reg->btf_id = aux->btf_var.btf_id;
16149 			break;
16150 		default:
16151 			verbose(env, "bpf verifier is misconfigured\n");
16152 			return -EFAULT;
16153 		}
16154 		return 0;
16155 	}
16156 
16157 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
16158 		struct bpf_prog_aux *aux = env->prog->aux;
16159 		u32 subprogno = find_subprog(env,
16160 					     env->insn_idx + insn->imm + 1);
16161 
16162 		if (!aux->func_info) {
16163 			verbose(env, "missing btf func_info\n");
16164 			return -EINVAL;
16165 		}
16166 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
16167 			verbose(env, "callback function not static\n");
16168 			return -EINVAL;
16169 		}
16170 
16171 		dst_reg->type = PTR_TO_FUNC;
16172 		dst_reg->subprogno = subprogno;
16173 		return 0;
16174 	}
16175 
16176 	map = env->used_maps[aux->map_index];
16177 	dst_reg->map_ptr = map;
16178 
16179 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
16180 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
16181 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
16182 			__mark_reg_unknown(env, dst_reg);
16183 			return 0;
16184 		}
16185 		dst_reg->type = PTR_TO_MAP_VALUE;
16186 		dst_reg->off = aux->map_off;
16187 		WARN_ON_ONCE(map->max_entries != 1);
16188 		/* We want reg->id to be same (0) as map_value is not distinct */
16189 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
16190 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
16191 		dst_reg->type = CONST_PTR_TO_MAP;
16192 	} else {
16193 		verbose(env, "bpf verifier is misconfigured\n");
16194 		return -EINVAL;
16195 	}
16196 
16197 	return 0;
16198 }
16199 
16200 static bool may_access_skb(enum bpf_prog_type type)
16201 {
16202 	switch (type) {
16203 	case BPF_PROG_TYPE_SOCKET_FILTER:
16204 	case BPF_PROG_TYPE_SCHED_CLS:
16205 	case BPF_PROG_TYPE_SCHED_ACT:
16206 		return true;
16207 	default:
16208 		return false;
16209 	}
16210 }
16211 
16212 /* verify safety of LD_ABS|LD_IND instructions:
16213  * - they can only appear in the programs where ctx == skb
16214  * - since they are wrappers of function calls, they scratch R1-R5 registers,
16215  *   preserve R6-R9, and store return value into R0
16216  *
16217  * Implicit input:
16218  *   ctx == skb == R6 == CTX
16219  *
16220  * Explicit input:
16221  *   SRC == any register
16222  *   IMM == 32-bit immediate
16223  *
16224  * Output:
16225  *   R0 - 8/16/32-bit skb data converted to cpu endianness
16226  */
16227 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
16228 {
16229 	struct bpf_reg_state *regs = cur_regs(env);
16230 	static const int ctx_reg = BPF_REG_6;
16231 	u8 mode = BPF_MODE(insn->code);
16232 	int i, err;
16233 
16234 	if (!may_access_skb(resolve_prog_type(env->prog))) {
16235 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
16236 		return -EINVAL;
16237 	}
16238 
16239 	if (!env->ops->gen_ld_abs) {
16240 		verbose(env, "bpf verifier is misconfigured\n");
16241 		return -EINVAL;
16242 	}
16243 
16244 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
16245 	    BPF_SIZE(insn->code) == BPF_DW ||
16246 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
16247 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
16248 		return -EINVAL;
16249 	}
16250 
16251 	/* check whether implicit source operand (register R6) is readable */
16252 	err = check_reg_arg(env, ctx_reg, SRC_OP);
16253 	if (err)
16254 		return err;
16255 
16256 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
16257 	 * gen_ld_abs() may terminate the program at runtime, leading to
16258 	 * reference leak.
16259 	 */
16260 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
16261 	if (err)
16262 		return err;
16263 
16264 	if (regs[ctx_reg].type != PTR_TO_CTX) {
16265 		verbose(env,
16266 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
16267 		return -EINVAL;
16268 	}
16269 
16270 	if (mode == BPF_IND) {
16271 		/* check explicit source operand */
16272 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16273 		if (err)
16274 			return err;
16275 	}
16276 
16277 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
16278 	if (err < 0)
16279 		return err;
16280 
16281 	/* reset caller saved regs to unreadable */
16282 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
16283 		mark_reg_not_init(env, regs, caller_saved[i]);
16284 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
16285 	}
16286 
16287 	/* mark destination R0 register as readable, since it contains
16288 	 * the value fetched from the packet.
16289 	 * Already marked as written above.
16290 	 */
16291 	mark_reg_unknown(env, regs, BPF_REG_0);
16292 	/* ld_abs load up to 32-bit skb data. */
16293 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
16294 	return 0;
16295 }
16296 
16297 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
16298 {
16299 	const char *exit_ctx = "At program exit";
16300 	struct tnum enforce_attach_type_range = tnum_unknown;
16301 	const struct bpf_prog *prog = env->prog;
16302 	struct bpf_reg_state *reg;
16303 	struct bpf_retval_range range = retval_range(0, 1);
16304 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
16305 	int err;
16306 	struct bpf_func_state *frame = env->cur_state->frame[0];
16307 	const bool is_subprog = frame->subprogno;
16308 	bool return_32bit = false;
16309 
16310 	/* LSM and struct_ops func-ptr's return type could be "void" */
16311 	if (!is_subprog || frame->in_exception_callback_fn) {
16312 		switch (prog_type) {
16313 		case BPF_PROG_TYPE_LSM:
16314 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
16315 				/* See below, can be 0 or 0-1 depending on hook. */
16316 				break;
16317 			fallthrough;
16318 		case BPF_PROG_TYPE_STRUCT_OPS:
16319 			if (!prog->aux->attach_func_proto->type)
16320 				return 0;
16321 			break;
16322 		default:
16323 			break;
16324 		}
16325 	}
16326 
16327 	/* eBPF calling convention is such that R0 is used
16328 	 * to return the value from eBPF program.
16329 	 * Make sure that it's readable at this time
16330 	 * of bpf_exit, which means that program wrote
16331 	 * something into it earlier
16332 	 */
16333 	err = check_reg_arg(env, regno, SRC_OP);
16334 	if (err)
16335 		return err;
16336 
16337 	if (is_pointer_value(env, regno)) {
16338 		verbose(env, "R%d leaks addr as return value\n", regno);
16339 		return -EACCES;
16340 	}
16341 
16342 	reg = cur_regs(env) + regno;
16343 
16344 	if (frame->in_async_callback_fn) {
16345 		/* enforce return zero from async callbacks like timer */
16346 		exit_ctx = "At async callback return";
16347 		range = retval_range(0, 0);
16348 		goto enforce_retval;
16349 	}
16350 
16351 	if (is_subprog && !frame->in_exception_callback_fn) {
16352 		if (reg->type != SCALAR_VALUE) {
16353 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
16354 				regno, reg_type_str(env, reg->type));
16355 			return -EINVAL;
16356 		}
16357 		return 0;
16358 	}
16359 
16360 	switch (prog_type) {
16361 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
16362 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
16363 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
16364 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
16365 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
16366 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
16367 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
16368 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
16369 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
16370 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
16371 			range = retval_range(1, 1);
16372 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
16373 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
16374 			range = retval_range(0, 3);
16375 		break;
16376 	case BPF_PROG_TYPE_CGROUP_SKB:
16377 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
16378 			range = retval_range(0, 3);
16379 			enforce_attach_type_range = tnum_range(2, 3);
16380 		}
16381 		break;
16382 	case BPF_PROG_TYPE_CGROUP_SOCK:
16383 	case BPF_PROG_TYPE_SOCK_OPS:
16384 	case BPF_PROG_TYPE_CGROUP_DEVICE:
16385 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
16386 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
16387 		break;
16388 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
16389 		if (!env->prog->aux->attach_btf_id)
16390 			return 0;
16391 		range = retval_range(0, 0);
16392 		break;
16393 	case BPF_PROG_TYPE_TRACING:
16394 		switch (env->prog->expected_attach_type) {
16395 		case BPF_TRACE_FENTRY:
16396 		case BPF_TRACE_FEXIT:
16397 			range = retval_range(0, 0);
16398 			break;
16399 		case BPF_TRACE_RAW_TP:
16400 		case BPF_MODIFY_RETURN:
16401 			return 0;
16402 		case BPF_TRACE_ITER:
16403 			break;
16404 		default:
16405 			return -ENOTSUPP;
16406 		}
16407 		break;
16408 	case BPF_PROG_TYPE_KPROBE:
16409 		switch (env->prog->expected_attach_type) {
16410 		case BPF_TRACE_KPROBE_SESSION:
16411 		case BPF_TRACE_UPROBE_SESSION:
16412 			range = retval_range(0, 1);
16413 			break;
16414 		default:
16415 			return 0;
16416 		}
16417 		break;
16418 	case BPF_PROG_TYPE_SK_LOOKUP:
16419 		range = retval_range(SK_DROP, SK_PASS);
16420 		break;
16421 
16422 	case BPF_PROG_TYPE_LSM:
16423 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
16424 			/* no range found, any return value is allowed */
16425 			if (!get_func_retval_range(env->prog, &range))
16426 				return 0;
16427 			/* no restricted range, any return value is allowed */
16428 			if (range.minval == S32_MIN && range.maxval == S32_MAX)
16429 				return 0;
16430 			return_32bit = true;
16431 		} else if (!env->prog->aux->attach_func_proto->type) {
16432 			/* Make sure programs that attach to void
16433 			 * hooks don't try to modify return value.
16434 			 */
16435 			range = retval_range(1, 1);
16436 		}
16437 		break;
16438 
16439 	case BPF_PROG_TYPE_NETFILTER:
16440 		range = retval_range(NF_DROP, NF_ACCEPT);
16441 		break;
16442 	case BPF_PROG_TYPE_EXT:
16443 		/* freplace program can return anything as its return value
16444 		 * depends on the to-be-replaced kernel func or bpf program.
16445 		 */
16446 	default:
16447 		return 0;
16448 	}
16449 
16450 enforce_retval:
16451 	if (reg->type != SCALAR_VALUE) {
16452 		verbose(env, "%s the register R%d is not a known value (%s)\n",
16453 			exit_ctx, regno, reg_type_str(env, reg->type));
16454 		return -EINVAL;
16455 	}
16456 
16457 	err = mark_chain_precision(env, regno);
16458 	if (err)
16459 		return err;
16460 
16461 	if (!retval_range_within(range, reg, return_32bit)) {
16462 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
16463 		if (!is_subprog &&
16464 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
16465 		    prog_type == BPF_PROG_TYPE_LSM &&
16466 		    !prog->aux->attach_func_proto->type)
16467 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
16468 		return -EINVAL;
16469 	}
16470 
16471 	if (!tnum_is_unknown(enforce_attach_type_range) &&
16472 	    tnum_in(enforce_attach_type_range, reg->var_off))
16473 		env->prog->enforce_expected_attach_type = 1;
16474 	return 0;
16475 }
16476 
16477 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
16478 {
16479 	struct bpf_subprog_info *subprog;
16480 
16481 	subprog = find_containing_subprog(env, off);
16482 	subprog->changes_pkt_data = true;
16483 }
16484 
16485 /* 't' is an index of a call-site.
16486  * 'w' is a callee entry point.
16487  * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
16488  * Rely on DFS traversal order and absence of recursive calls to guarantee that
16489  * callee's change_pkt_data marks would be correct at that moment.
16490  */
16491 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
16492 {
16493 	struct bpf_subprog_info *caller, *callee;
16494 
16495 	caller = find_containing_subprog(env, t);
16496 	callee = find_containing_subprog(env, w);
16497 	caller->changes_pkt_data |= callee->changes_pkt_data;
16498 }
16499 
16500 /* non-recursive DFS pseudo code
16501  * 1  procedure DFS-iterative(G,v):
16502  * 2      label v as discovered
16503  * 3      let S be a stack
16504  * 4      S.push(v)
16505  * 5      while S is not empty
16506  * 6            t <- S.peek()
16507  * 7            if t is what we're looking for:
16508  * 8                return t
16509  * 9            for all edges e in G.adjacentEdges(t) do
16510  * 10               if edge e is already labelled
16511  * 11                   continue with the next edge
16512  * 12               w <- G.adjacentVertex(t,e)
16513  * 13               if vertex w is not discovered and not explored
16514  * 14                   label e as tree-edge
16515  * 15                   label w as discovered
16516  * 16                   S.push(w)
16517  * 17                   continue at 5
16518  * 18               else if vertex w is discovered
16519  * 19                   label e as back-edge
16520  * 20               else
16521  * 21                   // vertex w is explored
16522  * 22                   label e as forward- or cross-edge
16523  * 23           label t as explored
16524  * 24           S.pop()
16525  *
16526  * convention:
16527  * 0x10 - discovered
16528  * 0x11 - discovered and fall-through edge labelled
16529  * 0x12 - discovered and fall-through and branch edges labelled
16530  * 0x20 - explored
16531  */
16532 
16533 enum {
16534 	DISCOVERED = 0x10,
16535 	EXPLORED = 0x20,
16536 	FALLTHROUGH = 1,
16537 	BRANCH = 2,
16538 };
16539 
16540 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
16541 {
16542 	env->insn_aux_data[idx].prune_point = true;
16543 }
16544 
16545 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
16546 {
16547 	return env->insn_aux_data[insn_idx].prune_point;
16548 }
16549 
16550 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
16551 {
16552 	env->insn_aux_data[idx].force_checkpoint = true;
16553 }
16554 
16555 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
16556 {
16557 	return env->insn_aux_data[insn_idx].force_checkpoint;
16558 }
16559 
16560 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
16561 {
16562 	env->insn_aux_data[idx].calls_callback = true;
16563 }
16564 
16565 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
16566 {
16567 	return env->insn_aux_data[insn_idx].calls_callback;
16568 }
16569 
16570 enum {
16571 	DONE_EXPLORING = 0,
16572 	KEEP_EXPLORING = 1,
16573 };
16574 
16575 /* t, w, e - match pseudo-code above:
16576  * t - index of current instruction
16577  * w - next instruction
16578  * e - edge
16579  */
16580 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
16581 {
16582 	int *insn_stack = env->cfg.insn_stack;
16583 	int *insn_state = env->cfg.insn_state;
16584 
16585 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
16586 		return DONE_EXPLORING;
16587 
16588 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
16589 		return DONE_EXPLORING;
16590 
16591 	if (w < 0 || w >= env->prog->len) {
16592 		verbose_linfo(env, t, "%d: ", t);
16593 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
16594 		return -EINVAL;
16595 	}
16596 
16597 	if (e == BRANCH) {
16598 		/* mark branch target for state pruning */
16599 		mark_prune_point(env, w);
16600 		mark_jmp_point(env, w);
16601 	}
16602 
16603 	if (insn_state[w] == 0) {
16604 		/* tree-edge */
16605 		insn_state[t] = DISCOVERED | e;
16606 		insn_state[w] = DISCOVERED;
16607 		if (env->cfg.cur_stack >= env->prog->len)
16608 			return -E2BIG;
16609 		insn_stack[env->cfg.cur_stack++] = w;
16610 		return KEEP_EXPLORING;
16611 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
16612 		if (env->bpf_capable)
16613 			return DONE_EXPLORING;
16614 		verbose_linfo(env, t, "%d: ", t);
16615 		verbose_linfo(env, w, "%d: ", w);
16616 		verbose(env, "back-edge from insn %d to %d\n", t, w);
16617 		return -EINVAL;
16618 	} else if (insn_state[w] == EXPLORED) {
16619 		/* forward- or cross-edge */
16620 		insn_state[t] = DISCOVERED | e;
16621 	} else {
16622 		verbose(env, "insn state internal bug\n");
16623 		return -EFAULT;
16624 	}
16625 	return DONE_EXPLORING;
16626 }
16627 
16628 static int visit_func_call_insn(int t, struct bpf_insn *insns,
16629 				struct bpf_verifier_env *env,
16630 				bool visit_callee)
16631 {
16632 	int ret, insn_sz;
16633 	int w;
16634 
16635 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
16636 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
16637 	if (ret)
16638 		return ret;
16639 
16640 	mark_prune_point(env, t + insn_sz);
16641 	/* when we exit from subprog, we need to record non-linear history */
16642 	mark_jmp_point(env, t + insn_sz);
16643 
16644 	if (visit_callee) {
16645 		w = t + insns[t].imm + 1;
16646 		mark_prune_point(env, t);
16647 		merge_callee_effects(env, t, w);
16648 		ret = push_insn(t, w, BRANCH, env);
16649 	}
16650 	return ret;
16651 }
16652 
16653 /* Bitmask with 1s for all caller saved registers */
16654 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
16655 
16656 /* Return a bitmask specifying which caller saved registers are
16657  * clobbered by a call to a helper *as if* this helper follows
16658  * bpf_fastcall contract:
16659  * - includes R0 if function is non-void;
16660  * - includes R1-R5 if corresponding parameter has is described
16661  *   in the function prototype.
16662  */
16663 static u32 helper_fastcall_clobber_mask(const struct bpf_func_proto *fn)
16664 {
16665 	u32 mask;
16666 	int i;
16667 
16668 	mask = 0;
16669 	if (fn->ret_type != RET_VOID)
16670 		mask |= BIT(BPF_REG_0);
16671 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i)
16672 		if (fn->arg_type[i] != ARG_DONTCARE)
16673 			mask |= BIT(BPF_REG_1 + i);
16674 	return mask;
16675 }
16676 
16677 /* True if do_misc_fixups() replaces calls to helper number 'imm',
16678  * replacement patch is presumed to follow bpf_fastcall contract
16679  * (see mark_fastcall_pattern_for_call() below).
16680  */
16681 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
16682 {
16683 	switch (imm) {
16684 #ifdef CONFIG_X86_64
16685 	case BPF_FUNC_get_smp_processor_id:
16686 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
16687 #endif
16688 	default:
16689 		return false;
16690 	}
16691 }
16692 
16693 /* Same as helper_fastcall_clobber_mask() but for kfuncs, see comment above */
16694 static u32 kfunc_fastcall_clobber_mask(struct bpf_kfunc_call_arg_meta *meta)
16695 {
16696 	u32 vlen, i, mask;
16697 
16698 	vlen = btf_type_vlen(meta->func_proto);
16699 	mask = 0;
16700 	if (!btf_type_is_void(btf_type_by_id(meta->btf, meta->func_proto->type)))
16701 		mask |= BIT(BPF_REG_0);
16702 	for (i = 0; i < vlen; ++i)
16703 		mask |= BIT(BPF_REG_1 + i);
16704 	return mask;
16705 }
16706 
16707 /* Same as verifier_inlines_helper_call() but for kfuncs, see comment above */
16708 static bool is_fastcall_kfunc_call(struct bpf_kfunc_call_arg_meta *meta)
16709 {
16710 	return meta->kfunc_flags & KF_FASTCALL;
16711 }
16712 
16713 /* LLVM define a bpf_fastcall function attribute.
16714  * This attribute means that function scratches only some of
16715  * the caller saved registers defined by ABI.
16716  * For BPF the set of such registers could be defined as follows:
16717  * - R0 is scratched only if function is non-void;
16718  * - R1-R5 are scratched only if corresponding parameter type is defined
16719  *   in the function prototype.
16720  *
16721  * The contract between kernel and clang allows to simultaneously use
16722  * such functions and maintain backwards compatibility with old
16723  * kernels that don't understand bpf_fastcall calls:
16724  *
16725  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
16726  *   registers are not scratched by the call;
16727  *
16728  * - as a post-processing step, clang visits each bpf_fastcall call and adds
16729  *   spill/fill for every live r0-r5;
16730  *
16731  * - stack offsets used for the spill/fill are allocated as lowest
16732  *   stack offsets in whole function and are not used for any other
16733  *   purposes;
16734  *
16735  * - when kernel loads a program, it looks for such patterns
16736  *   (bpf_fastcall function surrounded by spills/fills) and checks if
16737  *   spill/fill stack offsets are used exclusively in fastcall patterns;
16738  *
16739  * - if so, and if verifier or current JIT inlines the call to the
16740  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
16741  *   spill/fill pairs;
16742  *
16743  * - when old kernel loads a program, presence of spill/fill pairs
16744  *   keeps BPF program valid, albeit slightly less efficient.
16745  *
16746  * For example:
16747  *
16748  *   r1 = 1;
16749  *   r2 = 2;
16750  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
16751  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
16752  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
16753  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
16754  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
16755  *   r0 = r1;                            exit;
16756  *   r0 += r2;
16757  *   exit;
16758  *
16759  * The purpose of mark_fastcall_pattern_for_call is to:
16760  * - look for such patterns;
16761  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
16762  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
16763  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
16764  *   at which bpf_fastcall spill/fill stack slots start;
16765  * - update env->subprog_info[*]->keep_fastcall_stack.
16766  *
16767  * The .fastcall_pattern and .fastcall_stack_off are used by
16768  * check_fastcall_stack_contract() to check if every stack access to
16769  * fastcall spill/fill stack slot originates from spill/fill
16770  * instructions, members of fastcall patterns.
16771  *
16772  * If such condition holds true for a subprogram, fastcall patterns could
16773  * be rewritten by remove_fastcall_spills_fills().
16774  * Otherwise bpf_fastcall patterns are not changed in the subprogram
16775  * (code, presumably, generated by an older clang version).
16776  *
16777  * For example, it is *not* safe to remove spill/fill below:
16778  *
16779  *   r1 = 1;
16780  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
16781  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
16782  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
16783  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
16784  *   r0 += r1;                           exit;
16785  *   exit;
16786  */
16787 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
16788 					   struct bpf_subprog_info *subprog,
16789 					   int insn_idx, s16 lowest_off)
16790 {
16791 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
16792 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
16793 	const struct bpf_func_proto *fn;
16794 	u32 clobbered_regs_mask = ALL_CALLER_SAVED_REGS;
16795 	u32 expected_regs_mask;
16796 	bool can_be_inlined = false;
16797 	s16 off;
16798 	int i;
16799 
16800 	if (bpf_helper_call(call)) {
16801 		if (get_helper_proto(env, call->imm, &fn) < 0)
16802 			/* error would be reported later */
16803 			return;
16804 		clobbered_regs_mask = helper_fastcall_clobber_mask(fn);
16805 		can_be_inlined = fn->allow_fastcall &&
16806 				 (verifier_inlines_helper_call(env, call->imm) ||
16807 				  bpf_jit_inlines_helper_call(call->imm));
16808 	}
16809 
16810 	if (bpf_pseudo_kfunc_call(call)) {
16811 		struct bpf_kfunc_call_arg_meta meta;
16812 		int err;
16813 
16814 		err = fetch_kfunc_meta(env, call, &meta, NULL);
16815 		if (err < 0)
16816 			/* error would be reported later */
16817 			return;
16818 
16819 		clobbered_regs_mask = kfunc_fastcall_clobber_mask(&meta);
16820 		can_be_inlined = is_fastcall_kfunc_call(&meta);
16821 	}
16822 
16823 	if (clobbered_regs_mask == ALL_CALLER_SAVED_REGS)
16824 		return;
16825 
16826 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
16827 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
16828 
16829 	/* match pairs of form:
16830 	 *
16831 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
16832 	 * ...
16833 	 * call %[to_be_inlined]
16834 	 * ...
16835 	 * rX = *(u64 *)(r10 - Y)
16836 	 */
16837 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
16838 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
16839 			break;
16840 		stx = &insns[insn_idx - i];
16841 		ldx = &insns[insn_idx + i];
16842 		/* must be a stack spill/fill pair */
16843 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
16844 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
16845 		    stx->dst_reg != BPF_REG_10 ||
16846 		    ldx->src_reg != BPF_REG_10)
16847 			break;
16848 		/* must be a spill/fill for the same reg */
16849 		if (stx->src_reg != ldx->dst_reg)
16850 			break;
16851 		/* must be one of the previously unseen registers */
16852 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
16853 			break;
16854 		/* must be a spill/fill for the same expected offset,
16855 		 * no need to check offset alignment, BPF_DW stack access
16856 		 * is always 8-byte aligned.
16857 		 */
16858 		if (stx->off != off || ldx->off != off)
16859 			break;
16860 		expected_regs_mask &= ~BIT(stx->src_reg);
16861 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
16862 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
16863 	}
16864 	if (i == 1)
16865 		return;
16866 
16867 	/* Conditionally set 'fastcall_spills_num' to allow forward
16868 	 * compatibility when more helper functions are marked as
16869 	 * bpf_fastcall at compile time than current kernel supports, e.g:
16870 	 *
16871 	 *   1: *(u64 *)(r10 - 8) = r1
16872 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
16873 	 *   3: r1 = *(u64 *)(r10 - 8)
16874 	 *   4: *(u64 *)(r10 - 8) = r1
16875 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
16876 	 *   6: r1 = *(u64 *)(r10 - 8)
16877 	 *
16878 	 * There is no need to block bpf_fastcall rewrite for such program.
16879 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
16880 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
16881 	 * does not remove spill/fill pair {4,6}.
16882 	 */
16883 	if (can_be_inlined)
16884 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
16885 	else
16886 		subprog->keep_fastcall_stack = 1;
16887 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
16888 }
16889 
16890 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
16891 {
16892 	struct bpf_subprog_info *subprog = env->subprog_info;
16893 	struct bpf_insn *insn;
16894 	s16 lowest_off;
16895 	int s, i;
16896 
16897 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
16898 		/* find lowest stack spill offset used in this subprog */
16899 		lowest_off = 0;
16900 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
16901 			insn = env->prog->insnsi + i;
16902 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
16903 			    insn->dst_reg != BPF_REG_10)
16904 				continue;
16905 			lowest_off = min(lowest_off, insn->off);
16906 		}
16907 		/* use this offset to find fastcall patterns */
16908 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
16909 			insn = env->prog->insnsi + i;
16910 			if (insn->code != (BPF_JMP | BPF_CALL))
16911 				continue;
16912 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
16913 		}
16914 	}
16915 	return 0;
16916 }
16917 
16918 /* Visits the instruction at index t and returns one of the following:
16919  *  < 0 - an error occurred
16920  *  DONE_EXPLORING - the instruction was fully explored
16921  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
16922  */
16923 static int visit_insn(int t, struct bpf_verifier_env *env)
16924 {
16925 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
16926 	int ret, off, insn_sz;
16927 
16928 	if (bpf_pseudo_func(insn))
16929 		return visit_func_call_insn(t, insns, env, true);
16930 
16931 	/* All non-branch instructions have a single fall-through edge. */
16932 	if (BPF_CLASS(insn->code) != BPF_JMP &&
16933 	    BPF_CLASS(insn->code) != BPF_JMP32) {
16934 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
16935 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
16936 	}
16937 
16938 	switch (BPF_OP(insn->code)) {
16939 	case BPF_EXIT:
16940 		return DONE_EXPLORING;
16941 
16942 	case BPF_CALL:
16943 		if (is_async_callback_calling_insn(insn))
16944 			/* Mark this call insn as a prune point to trigger
16945 			 * is_state_visited() check before call itself is
16946 			 * processed by __check_func_call(). Otherwise new
16947 			 * async state will be pushed for further exploration.
16948 			 */
16949 			mark_prune_point(env, t);
16950 		/* For functions that invoke callbacks it is not known how many times
16951 		 * callback would be called. Verifier models callback calling functions
16952 		 * by repeatedly visiting callback bodies and returning to origin call
16953 		 * instruction.
16954 		 * In order to stop such iteration verifier needs to identify when a
16955 		 * state identical some state from a previous iteration is reached.
16956 		 * Check below forces creation of checkpoint before callback calling
16957 		 * instruction to allow search for such identical states.
16958 		 */
16959 		if (is_sync_callback_calling_insn(insn)) {
16960 			mark_calls_callback(env, t);
16961 			mark_force_checkpoint(env, t);
16962 			mark_prune_point(env, t);
16963 			mark_jmp_point(env, t);
16964 		}
16965 		if (bpf_helper_call(insn) && bpf_helper_changes_pkt_data(insn->imm))
16966 			mark_subprog_changes_pkt_data(env, t);
16967 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
16968 			struct bpf_kfunc_call_arg_meta meta;
16969 
16970 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
16971 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
16972 				mark_prune_point(env, t);
16973 				/* Checking and saving state checkpoints at iter_next() call
16974 				 * is crucial for fast convergence of open-coded iterator loop
16975 				 * logic, so we need to force it. If we don't do that,
16976 				 * is_state_visited() might skip saving a checkpoint, causing
16977 				 * unnecessarily long sequence of not checkpointed
16978 				 * instructions and jumps, leading to exhaustion of jump
16979 				 * history buffer, and potentially other undesired outcomes.
16980 				 * It is expected that with correct open-coded iterators
16981 				 * convergence will happen quickly, so we don't run a risk of
16982 				 * exhausting memory.
16983 				 */
16984 				mark_force_checkpoint(env, t);
16985 			}
16986 		}
16987 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
16988 
16989 	case BPF_JA:
16990 		if (BPF_SRC(insn->code) != BPF_K)
16991 			return -EINVAL;
16992 
16993 		if (BPF_CLASS(insn->code) == BPF_JMP)
16994 			off = insn->off;
16995 		else
16996 			off = insn->imm;
16997 
16998 		/* unconditional jump with single edge */
16999 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
17000 		if (ret)
17001 			return ret;
17002 
17003 		mark_prune_point(env, t + off + 1);
17004 		mark_jmp_point(env, t + off + 1);
17005 
17006 		return ret;
17007 
17008 	default:
17009 		/* conditional jump with two edges */
17010 		mark_prune_point(env, t);
17011 		if (is_may_goto_insn(insn))
17012 			mark_force_checkpoint(env, t);
17013 
17014 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
17015 		if (ret)
17016 			return ret;
17017 
17018 		return push_insn(t, t + insn->off + 1, BRANCH, env);
17019 	}
17020 }
17021 
17022 /* non-recursive depth-first-search to detect loops in BPF program
17023  * loop == back-edge in directed graph
17024  */
17025 static int check_cfg(struct bpf_verifier_env *env)
17026 {
17027 	int insn_cnt = env->prog->len;
17028 	int *insn_stack, *insn_state;
17029 	int ex_insn_beg, i, ret = 0;
17030 	bool ex_done = false;
17031 
17032 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
17033 	if (!insn_state)
17034 		return -ENOMEM;
17035 
17036 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
17037 	if (!insn_stack) {
17038 		kvfree(insn_state);
17039 		return -ENOMEM;
17040 	}
17041 
17042 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
17043 	insn_stack[0] = 0; /* 0 is the first instruction */
17044 	env->cfg.cur_stack = 1;
17045 
17046 walk_cfg:
17047 	while (env->cfg.cur_stack > 0) {
17048 		int t = insn_stack[env->cfg.cur_stack - 1];
17049 
17050 		ret = visit_insn(t, env);
17051 		switch (ret) {
17052 		case DONE_EXPLORING:
17053 			insn_state[t] = EXPLORED;
17054 			env->cfg.cur_stack--;
17055 			break;
17056 		case KEEP_EXPLORING:
17057 			break;
17058 		default:
17059 			if (ret > 0) {
17060 				verbose(env, "visit_insn internal bug\n");
17061 				ret = -EFAULT;
17062 			}
17063 			goto err_free;
17064 		}
17065 	}
17066 
17067 	if (env->cfg.cur_stack < 0) {
17068 		verbose(env, "pop stack internal bug\n");
17069 		ret = -EFAULT;
17070 		goto err_free;
17071 	}
17072 
17073 	if (env->exception_callback_subprog && !ex_done) {
17074 		ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
17075 
17076 		insn_state[ex_insn_beg] = DISCOVERED;
17077 		insn_stack[0] = ex_insn_beg;
17078 		env->cfg.cur_stack = 1;
17079 		ex_done = true;
17080 		goto walk_cfg;
17081 	}
17082 
17083 	for (i = 0; i < insn_cnt; i++) {
17084 		struct bpf_insn *insn = &env->prog->insnsi[i];
17085 
17086 		if (insn_state[i] != EXPLORED) {
17087 			verbose(env, "unreachable insn %d\n", i);
17088 			ret = -EINVAL;
17089 			goto err_free;
17090 		}
17091 		if (bpf_is_ldimm64(insn)) {
17092 			if (insn_state[i + 1] != 0) {
17093 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
17094 				ret = -EINVAL;
17095 				goto err_free;
17096 			}
17097 			i++; /* skip second half of ldimm64 */
17098 		}
17099 	}
17100 	ret = 0; /* cfg looks good */
17101 	env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
17102 
17103 err_free:
17104 	kvfree(insn_state);
17105 	kvfree(insn_stack);
17106 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
17107 	return ret;
17108 }
17109 
17110 static int check_abnormal_return(struct bpf_verifier_env *env)
17111 {
17112 	int i;
17113 
17114 	for (i = 1; i < env->subprog_cnt; i++) {
17115 		if (env->subprog_info[i].has_ld_abs) {
17116 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
17117 			return -EINVAL;
17118 		}
17119 		if (env->subprog_info[i].has_tail_call) {
17120 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
17121 			return -EINVAL;
17122 		}
17123 	}
17124 	return 0;
17125 }
17126 
17127 /* The minimum supported BTF func info size */
17128 #define MIN_BPF_FUNCINFO_SIZE	8
17129 #define MAX_FUNCINFO_REC_SIZE	252
17130 
17131 static int check_btf_func_early(struct bpf_verifier_env *env,
17132 				const union bpf_attr *attr,
17133 				bpfptr_t uattr)
17134 {
17135 	u32 krec_size = sizeof(struct bpf_func_info);
17136 	const struct btf_type *type, *func_proto;
17137 	u32 i, nfuncs, urec_size, min_size;
17138 	struct bpf_func_info *krecord;
17139 	struct bpf_prog *prog;
17140 	const struct btf *btf;
17141 	u32 prev_offset = 0;
17142 	bpfptr_t urecord;
17143 	int ret = -ENOMEM;
17144 
17145 	nfuncs = attr->func_info_cnt;
17146 	if (!nfuncs) {
17147 		if (check_abnormal_return(env))
17148 			return -EINVAL;
17149 		return 0;
17150 	}
17151 
17152 	urec_size = attr->func_info_rec_size;
17153 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
17154 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
17155 	    urec_size % sizeof(u32)) {
17156 		verbose(env, "invalid func info rec size %u\n", urec_size);
17157 		return -EINVAL;
17158 	}
17159 
17160 	prog = env->prog;
17161 	btf = prog->aux->btf;
17162 
17163 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
17164 	min_size = min_t(u32, krec_size, urec_size);
17165 
17166 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
17167 	if (!krecord)
17168 		return -ENOMEM;
17169 
17170 	for (i = 0; i < nfuncs; i++) {
17171 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
17172 		if (ret) {
17173 			if (ret == -E2BIG) {
17174 				verbose(env, "nonzero tailing record in func info");
17175 				/* set the size kernel expects so loader can zero
17176 				 * out the rest of the record.
17177 				 */
17178 				if (copy_to_bpfptr_offset(uattr,
17179 							  offsetof(union bpf_attr, func_info_rec_size),
17180 							  &min_size, sizeof(min_size)))
17181 					ret = -EFAULT;
17182 			}
17183 			goto err_free;
17184 		}
17185 
17186 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
17187 			ret = -EFAULT;
17188 			goto err_free;
17189 		}
17190 
17191 		/* check insn_off */
17192 		ret = -EINVAL;
17193 		if (i == 0) {
17194 			if (krecord[i].insn_off) {
17195 				verbose(env,
17196 					"nonzero insn_off %u for the first func info record",
17197 					krecord[i].insn_off);
17198 				goto err_free;
17199 			}
17200 		} else if (krecord[i].insn_off <= prev_offset) {
17201 			verbose(env,
17202 				"same or smaller insn offset (%u) than previous func info record (%u)",
17203 				krecord[i].insn_off, prev_offset);
17204 			goto err_free;
17205 		}
17206 
17207 		/* check type_id */
17208 		type = btf_type_by_id(btf, krecord[i].type_id);
17209 		if (!type || !btf_type_is_func(type)) {
17210 			verbose(env, "invalid type id %d in func info",
17211 				krecord[i].type_id);
17212 			goto err_free;
17213 		}
17214 
17215 		func_proto = btf_type_by_id(btf, type->type);
17216 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
17217 			/* btf_func_check() already verified it during BTF load */
17218 			goto err_free;
17219 
17220 		prev_offset = krecord[i].insn_off;
17221 		bpfptr_add(&urecord, urec_size);
17222 	}
17223 
17224 	prog->aux->func_info = krecord;
17225 	prog->aux->func_info_cnt = nfuncs;
17226 	return 0;
17227 
17228 err_free:
17229 	kvfree(krecord);
17230 	return ret;
17231 }
17232 
17233 static int check_btf_func(struct bpf_verifier_env *env,
17234 			  const union bpf_attr *attr,
17235 			  bpfptr_t uattr)
17236 {
17237 	const struct btf_type *type, *func_proto, *ret_type;
17238 	u32 i, nfuncs, urec_size;
17239 	struct bpf_func_info *krecord;
17240 	struct bpf_func_info_aux *info_aux = NULL;
17241 	struct bpf_prog *prog;
17242 	const struct btf *btf;
17243 	bpfptr_t urecord;
17244 	bool scalar_return;
17245 	int ret = -ENOMEM;
17246 
17247 	nfuncs = attr->func_info_cnt;
17248 	if (!nfuncs) {
17249 		if (check_abnormal_return(env))
17250 			return -EINVAL;
17251 		return 0;
17252 	}
17253 	if (nfuncs != env->subprog_cnt) {
17254 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
17255 		return -EINVAL;
17256 	}
17257 
17258 	urec_size = attr->func_info_rec_size;
17259 
17260 	prog = env->prog;
17261 	btf = prog->aux->btf;
17262 
17263 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
17264 
17265 	krecord = prog->aux->func_info;
17266 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
17267 	if (!info_aux)
17268 		return -ENOMEM;
17269 
17270 	for (i = 0; i < nfuncs; i++) {
17271 		/* check insn_off */
17272 		ret = -EINVAL;
17273 
17274 		if (env->subprog_info[i].start != krecord[i].insn_off) {
17275 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
17276 			goto err_free;
17277 		}
17278 
17279 		/* Already checked type_id */
17280 		type = btf_type_by_id(btf, krecord[i].type_id);
17281 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
17282 		/* Already checked func_proto */
17283 		func_proto = btf_type_by_id(btf, type->type);
17284 
17285 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
17286 		scalar_return =
17287 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
17288 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
17289 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
17290 			goto err_free;
17291 		}
17292 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
17293 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
17294 			goto err_free;
17295 		}
17296 
17297 		bpfptr_add(&urecord, urec_size);
17298 	}
17299 
17300 	prog->aux->func_info_aux = info_aux;
17301 	return 0;
17302 
17303 err_free:
17304 	kfree(info_aux);
17305 	return ret;
17306 }
17307 
17308 static void adjust_btf_func(struct bpf_verifier_env *env)
17309 {
17310 	struct bpf_prog_aux *aux = env->prog->aux;
17311 	int i;
17312 
17313 	if (!aux->func_info)
17314 		return;
17315 
17316 	/* func_info is not available for hidden subprogs */
17317 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
17318 		aux->func_info[i].insn_off = env->subprog_info[i].start;
17319 }
17320 
17321 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
17322 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
17323 
17324 static int check_btf_line(struct bpf_verifier_env *env,
17325 			  const union bpf_attr *attr,
17326 			  bpfptr_t uattr)
17327 {
17328 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
17329 	struct bpf_subprog_info *sub;
17330 	struct bpf_line_info *linfo;
17331 	struct bpf_prog *prog;
17332 	const struct btf *btf;
17333 	bpfptr_t ulinfo;
17334 	int err;
17335 
17336 	nr_linfo = attr->line_info_cnt;
17337 	if (!nr_linfo)
17338 		return 0;
17339 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
17340 		return -EINVAL;
17341 
17342 	rec_size = attr->line_info_rec_size;
17343 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
17344 	    rec_size > MAX_LINEINFO_REC_SIZE ||
17345 	    rec_size & (sizeof(u32) - 1))
17346 		return -EINVAL;
17347 
17348 	/* Need to zero it in case the userspace may
17349 	 * pass in a smaller bpf_line_info object.
17350 	 */
17351 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
17352 			 GFP_KERNEL | __GFP_NOWARN);
17353 	if (!linfo)
17354 		return -ENOMEM;
17355 
17356 	prog = env->prog;
17357 	btf = prog->aux->btf;
17358 
17359 	s = 0;
17360 	sub = env->subprog_info;
17361 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
17362 	expected_size = sizeof(struct bpf_line_info);
17363 	ncopy = min_t(u32, expected_size, rec_size);
17364 	for (i = 0; i < nr_linfo; i++) {
17365 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
17366 		if (err) {
17367 			if (err == -E2BIG) {
17368 				verbose(env, "nonzero tailing record in line_info");
17369 				if (copy_to_bpfptr_offset(uattr,
17370 							  offsetof(union bpf_attr, line_info_rec_size),
17371 							  &expected_size, sizeof(expected_size)))
17372 					err = -EFAULT;
17373 			}
17374 			goto err_free;
17375 		}
17376 
17377 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
17378 			err = -EFAULT;
17379 			goto err_free;
17380 		}
17381 
17382 		/*
17383 		 * Check insn_off to ensure
17384 		 * 1) strictly increasing AND
17385 		 * 2) bounded by prog->len
17386 		 *
17387 		 * The linfo[0].insn_off == 0 check logically falls into
17388 		 * the later "missing bpf_line_info for func..." case
17389 		 * because the first linfo[0].insn_off must be the
17390 		 * first sub also and the first sub must have
17391 		 * subprog_info[0].start == 0.
17392 		 */
17393 		if ((i && linfo[i].insn_off <= prev_offset) ||
17394 		    linfo[i].insn_off >= prog->len) {
17395 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
17396 				i, linfo[i].insn_off, prev_offset,
17397 				prog->len);
17398 			err = -EINVAL;
17399 			goto err_free;
17400 		}
17401 
17402 		if (!prog->insnsi[linfo[i].insn_off].code) {
17403 			verbose(env,
17404 				"Invalid insn code at line_info[%u].insn_off\n",
17405 				i);
17406 			err = -EINVAL;
17407 			goto err_free;
17408 		}
17409 
17410 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
17411 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
17412 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
17413 			err = -EINVAL;
17414 			goto err_free;
17415 		}
17416 
17417 		if (s != env->subprog_cnt) {
17418 			if (linfo[i].insn_off == sub[s].start) {
17419 				sub[s].linfo_idx = i;
17420 				s++;
17421 			} else if (sub[s].start < linfo[i].insn_off) {
17422 				verbose(env, "missing bpf_line_info for func#%u\n", s);
17423 				err = -EINVAL;
17424 				goto err_free;
17425 			}
17426 		}
17427 
17428 		prev_offset = linfo[i].insn_off;
17429 		bpfptr_add(&ulinfo, rec_size);
17430 	}
17431 
17432 	if (s != env->subprog_cnt) {
17433 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
17434 			env->subprog_cnt - s, s);
17435 		err = -EINVAL;
17436 		goto err_free;
17437 	}
17438 
17439 	prog->aux->linfo = linfo;
17440 	prog->aux->nr_linfo = nr_linfo;
17441 
17442 	return 0;
17443 
17444 err_free:
17445 	kvfree(linfo);
17446 	return err;
17447 }
17448 
17449 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
17450 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
17451 
17452 static int check_core_relo(struct bpf_verifier_env *env,
17453 			   const union bpf_attr *attr,
17454 			   bpfptr_t uattr)
17455 {
17456 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
17457 	struct bpf_core_relo core_relo = {};
17458 	struct bpf_prog *prog = env->prog;
17459 	const struct btf *btf = prog->aux->btf;
17460 	struct bpf_core_ctx ctx = {
17461 		.log = &env->log,
17462 		.btf = btf,
17463 	};
17464 	bpfptr_t u_core_relo;
17465 	int err;
17466 
17467 	nr_core_relo = attr->core_relo_cnt;
17468 	if (!nr_core_relo)
17469 		return 0;
17470 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
17471 		return -EINVAL;
17472 
17473 	rec_size = attr->core_relo_rec_size;
17474 	if (rec_size < MIN_CORE_RELO_SIZE ||
17475 	    rec_size > MAX_CORE_RELO_SIZE ||
17476 	    rec_size % sizeof(u32))
17477 		return -EINVAL;
17478 
17479 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
17480 	expected_size = sizeof(struct bpf_core_relo);
17481 	ncopy = min_t(u32, expected_size, rec_size);
17482 
17483 	/* Unlike func_info and line_info, copy and apply each CO-RE
17484 	 * relocation record one at a time.
17485 	 */
17486 	for (i = 0; i < nr_core_relo; i++) {
17487 		/* future proofing when sizeof(bpf_core_relo) changes */
17488 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
17489 		if (err) {
17490 			if (err == -E2BIG) {
17491 				verbose(env, "nonzero tailing record in core_relo");
17492 				if (copy_to_bpfptr_offset(uattr,
17493 							  offsetof(union bpf_attr, core_relo_rec_size),
17494 							  &expected_size, sizeof(expected_size)))
17495 					err = -EFAULT;
17496 			}
17497 			break;
17498 		}
17499 
17500 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
17501 			err = -EFAULT;
17502 			break;
17503 		}
17504 
17505 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
17506 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
17507 				i, core_relo.insn_off, prog->len);
17508 			err = -EINVAL;
17509 			break;
17510 		}
17511 
17512 		err = bpf_core_apply(&ctx, &core_relo, i,
17513 				     &prog->insnsi[core_relo.insn_off / 8]);
17514 		if (err)
17515 			break;
17516 		bpfptr_add(&u_core_relo, rec_size);
17517 	}
17518 	return err;
17519 }
17520 
17521 static int check_btf_info_early(struct bpf_verifier_env *env,
17522 				const union bpf_attr *attr,
17523 				bpfptr_t uattr)
17524 {
17525 	struct btf *btf;
17526 	int err;
17527 
17528 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
17529 		if (check_abnormal_return(env))
17530 			return -EINVAL;
17531 		return 0;
17532 	}
17533 
17534 	btf = btf_get_by_fd(attr->prog_btf_fd);
17535 	if (IS_ERR(btf))
17536 		return PTR_ERR(btf);
17537 	if (btf_is_kernel(btf)) {
17538 		btf_put(btf);
17539 		return -EACCES;
17540 	}
17541 	env->prog->aux->btf = btf;
17542 
17543 	err = check_btf_func_early(env, attr, uattr);
17544 	if (err)
17545 		return err;
17546 	return 0;
17547 }
17548 
17549 static int check_btf_info(struct bpf_verifier_env *env,
17550 			  const union bpf_attr *attr,
17551 			  bpfptr_t uattr)
17552 {
17553 	int err;
17554 
17555 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
17556 		if (check_abnormal_return(env))
17557 			return -EINVAL;
17558 		return 0;
17559 	}
17560 
17561 	err = check_btf_func(env, attr, uattr);
17562 	if (err)
17563 		return err;
17564 
17565 	err = check_btf_line(env, attr, uattr);
17566 	if (err)
17567 		return err;
17568 
17569 	err = check_core_relo(env, attr, uattr);
17570 	if (err)
17571 		return err;
17572 
17573 	return 0;
17574 }
17575 
17576 /* check %cur's range satisfies %old's */
17577 static bool range_within(const struct bpf_reg_state *old,
17578 			 const struct bpf_reg_state *cur)
17579 {
17580 	return old->umin_value <= cur->umin_value &&
17581 	       old->umax_value >= cur->umax_value &&
17582 	       old->smin_value <= cur->smin_value &&
17583 	       old->smax_value >= cur->smax_value &&
17584 	       old->u32_min_value <= cur->u32_min_value &&
17585 	       old->u32_max_value >= cur->u32_max_value &&
17586 	       old->s32_min_value <= cur->s32_min_value &&
17587 	       old->s32_max_value >= cur->s32_max_value;
17588 }
17589 
17590 /* If in the old state two registers had the same id, then they need to have
17591  * the same id in the new state as well.  But that id could be different from
17592  * the old state, so we need to track the mapping from old to new ids.
17593  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
17594  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
17595  * regs with a different old id could still have new id 9, we don't care about
17596  * that.
17597  * So we look through our idmap to see if this old id has been seen before.  If
17598  * so, we require the new id to match; otherwise, we add the id pair to the map.
17599  */
17600 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
17601 {
17602 	struct bpf_id_pair *map = idmap->map;
17603 	unsigned int i;
17604 
17605 	/* either both IDs should be set or both should be zero */
17606 	if (!!old_id != !!cur_id)
17607 		return false;
17608 
17609 	if (old_id == 0) /* cur_id == 0 as well */
17610 		return true;
17611 
17612 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
17613 		if (!map[i].old) {
17614 			/* Reached an empty slot; haven't seen this id before */
17615 			map[i].old = old_id;
17616 			map[i].cur = cur_id;
17617 			return true;
17618 		}
17619 		if (map[i].old == old_id)
17620 			return map[i].cur == cur_id;
17621 		if (map[i].cur == cur_id)
17622 			return false;
17623 	}
17624 	/* We ran out of idmap slots, which should be impossible */
17625 	WARN_ON_ONCE(1);
17626 	return false;
17627 }
17628 
17629 /* Similar to check_ids(), but allocate a unique temporary ID
17630  * for 'old_id' or 'cur_id' of zero.
17631  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
17632  */
17633 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
17634 {
17635 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
17636 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
17637 
17638 	return check_ids(old_id, cur_id, idmap);
17639 }
17640 
17641 static void clean_func_state(struct bpf_verifier_env *env,
17642 			     struct bpf_func_state *st)
17643 {
17644 	enum bpf_reg_liveness live;
17645 	int i, j;
17646 
17647 	for (i = 0; i < BPF_REG_FP; i++) {
17648 		live = st->regs[i].live;
17649 		/* liveness must not touch this register anymore */
17650 		st->regs[i].live |= REG_LIVE_DONE;
17651 		if (!(live & REG_LIVE_READ))
17652 			/* since the register is unused, clear its state
17653 			 * to make further comparison simpler
17654 			 */
17655 			__mark_reg_not_init(env, &st->regs[i]);
17656 	}
17657 
17658 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
17659 		live = st->stack[i].spilled_ptr.live;
17660 		/* liveness must not touch this stack slot anymore */
17661 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
17662 		if (!(live & REG_LIVE_READ)) {
17663 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
17664 			for (j = 0; j < BPF_REG_SIZE; j++)
17665 				st->stack[i].slot_type[j] = STACK_INVALID;
17666 		}
17667 	}
17668 }
17669 
17670 static void clean_verifier_state(struct bpf_verifier_env *env,
17671 				 struct bpf_verifier_state *st)
17672 {
17673 	int i;
17674 
17675 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
17676 		/* all regs in this state in all frames were already marked */
17677 		return;
17678 
17679 	for (i = 0; i <= st->curframe; i++)
17680 		clean_func_state(env, st->frame[i]);
17681 }
17682 
17683 /* the parentage chains form a tree.
17684  * the verifier states are added to state lists at given insn and
17685  * pushed into state stack for future exploration.
17686  * when the verifier reaches bpf_exit insn some of the verifer states
17687  * stored in the state lists have their final liveness state already,
17688  * but a lot of states will get revised from liveness point of view when
17689  * the verifier explores other branches.
17690  * Example:
17691  * 1: r0 = 1
17692  * 2: if r1 == 100 goto pc+1
17693  * 3: r0 = 2
17694  * 4: exit
17695  * when the verifier reaches exit insn the register r0 in the state list of
17696  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
17697  * of insn 2 and goes exploring further. At the insn 4 it will walk the
17698  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
17699  *
17700  * Since the verifier pushes the branch states as it sees them while exploring
17701  * the program the condition of walking the branch instruction for the second
17702  * time means that all states below this branch were already explored and
17703  * their final liveness marks are already propagated.
17704  * Hence when the verifier completes the search of state list in is_state_visited()
17705  * we can call this clean_live_states() function to mark all liveness states
17706  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
17707  * will not be used.
17708  * This function also clears the registers and stack for states that !READ
17709  * to simplify state merging.
17710  *
17711  * Important note here that walking the same branch instruction in the callee
17712  * doesn't meant that the states are DONE. The verifier has to compare
17713  * the callsites
17714  */
17715 static void clean_live_states(struct bpf_verifier_env *env, int insn,
17716 			      struct bpf_verifier_state *cur)
17717 {
17718 	struct bpf_verifier_state_list *sl;
17719 
17720 	sl = *explored_state(env, insn);
17721 	while (sl) {
17722 		if (sl->state.branches)
17723 			goto next;
17724 		if (sl->state.insn_idx != insn ||
17725 		    !same_callsites(&sl->state, cur))
17726 			goto next;
17727 		clean_verifier_state(env, &sl->state);
17728 next:
17729 		sl = sl->next;
17730 	}
17731 }
17732 
17733 static bool regs_exact(const struct bpf_reg_state *rold,
17734 		       const struct bpf_reg_state *rcur,
17735 		       struct bpf_idmap *idmap)
17736 {
17737 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
17738 	       check_ids(rold->id, rcur->id, idmap) &&
17739 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
17740 }
17741 
17742 enum exact_level {
17743 	NOT_EXACT,
17744 	EXACT,
17745 	RANGE_WITHIN
17746 };
17747 
17748 /* Returns true if (rold safe implies rcur safe) */
17749 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
17750 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
17751 		    enum exact_level exact)
17752 {
17753 	if (exact == EXACT)
17754 		return regs_exact(rold, rcur, idmap);
17755 
17756 	if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
17757 		/* explored state didn't use this */
17758 		return true;
17759 	if (rold->type == NOT_INIT) {
17760 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
17761 			/* explored state can't have used this */
17762 			return true;
17763 	}
17764 
17765 	/* Enforce that register types have to match exactly, including their
17766 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
17767 	 * rule.
17768 	 *
17769 	 * One can make a point that using a pointer register as unbounded
17770 	 * SCALAR would be technically acceptable, but this could lead to
17771 	 * pointer leaks because scalars are allowed to leak while pointers
17772 	 * are not. We could make this safe in special cases if root is
17773 	 * calling us, but it's probably not worth the hassle.
17774 	 *
17775 	 * Also, register types that are *not* MAYBE_NULL could technically be
17776 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
17777 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
17778 	 * to the same map).
17779 	 * However, if the old MAYBE_NULL register then got NULL checked,
17780 	 * doing so could have affected others with the same id, and we can't
17781 	 * check for that because we lost the id when we converted to
17782 	 * a non-MAYBE_NULL variant.
17783 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
17784 	 * non-MAYBE_NULL registers as well.
17785 	 */
17786 	if (rold->type != rcur->type)
17787 		return false;
17788 
17789 	switch (base_type(rold->type)) {
17790 	case SCALAR_VALUE:
17791 		if (env->explore_alu_limits) {
17792 			/* explore_alu_limits disables tnum_in() and range_within()
17793 			 * logic and requires everything to be strict
17794 			 */
17795 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
17796 			       check_scalar_ids(rold->id, rcur->id, idmap);
17797 		}
17798 		if (!rold->precise && exact == NOT_EXACT)
17799 			return true;
17800 		if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
17801 			return false;
17802 		if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
17803 			return false;
17804 		/* Why check_ids() for scalar registers?
17805 		 *
17806 		 * Consider the following BPF code:
17807 		 *   1: r6 = ... unbound scalar, ID=a ...
17808 		 *   2: r7 = ... unbound scalar, ID=b ...
17809 		 *   3: if (r6 > r7) goto +1
17810 		 *   4: r6 = r7
17811 		 *   5: if (r6 > X) goto ...
17812 		 *   6: ... memory operation using r7 ...
17813 		 *
17814 		 * First verification path is [1-6]:
17815 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
17816 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
17817 		 *   r7 <= X, because r6 and r7 share same id.
17818 		 * Next verification path is [1-4, 6].
17819 		 *
17820 		 * Instruction (6) would be reached in two states:
17821 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
17822 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
17823 		 *
17824 		 * Use check_ids() to distinguish these states.
17825 		 * ---
17826 		 * Also verify that new value satisfies old value range knowledge.
17827 		 */
17828 		return range_within(rold, rcur) &&
17829 		       tnum_in(rold->var_off, rcur->var_off) &&
17830 		       check_scalar_ids(rold->id, rcur->id, idmap);
17831 	case PTR_TO_MAP_KEY:
17832 	case PTR_TO_MAP_VALUE:
17833 	case PTR_TO_MEM:
17834 	case PTR_TO_BUF:
17835 	case PTR_TO_TP_BUFFER:
17836 		/* If the new min/max/var_off satisfy the old ones and
17837 		 * everything else matches, we are OK.
17838 		 */
17839 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
17840 		       range_within(rold, rcur) &&
17841 		       tnum_in(rold->var_off, rcur->var_off) &&
17842 		       check_ids(rold->id, rcur->id, idmap) &&
17843 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
17844 	case PTR_TO_PACKET_META:
17845 	case PTR_TO_PACKET:
17846 		/* We must have at least as much range as the old ptr
17847 		 * did, so that any accesses which were safe before are
17848 		 * still safe.  This is true even if old range < old off,
17849 		 * since someone could have accessed through (ptr - k), or
17850 		 * even done ptr -= k in a register, to get a safe access.
17851 		 */
17852 		if (rold->range > rcur->range)
17853 			return false;
17854 		/* If the offsets don't match, we can't trust our alignment;
17855 		 * nor can we be sure that we won't fall out of range.
17856 		 */
17857 		if (rold->off != rcur->off)
17858 			return false;
17859 		/* id relations must be preserved */
17860 		if (!check_ids(rold->id, rcur->id, idmap))
17861 			return false;
17862 		/* new val must satisfy old val knowledge */
17863 		return range_within(rold, rcur) &&
17864 		       tnum_in(rold->var_off, rcur->var_off);
17865 	case PTR_TO_STACK:
17866 		/* two stack pointers are equal only if they're pointing to
17867 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
17868 		 */
17869 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
17870 	case PTR_TO_ARENA:
17871 		return true;
17872 	default:
17873 		return regs_exact(rold, rcur, idmap);
17874 	}
17875 }
17876 
17877 static struct bpf_reg_state unbound_reg;
17878 
17879 static __init int unbound_reg_init(void)
17880 {
17881 	__mark_reg_unknown_imprecise(&unbound_reg);
17882 	unbound_reg.live |= REG_LIVE_READ;
17883 	return 0;
17884 }
17885 late_initcall(unbound_reg_init);
17886 
17887 static bool is_stack_all_misc(struct bpf_verifier_env *env,
17888 			      struct bpf_stack_state *stack)
17889 {
17890 	u32 i;
17891 
17892 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
17893 		if ((stack->slot_type[i] == STACK_MISC) ||
17894 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
17895 			continue;
17896 		return false;
17897 	}
17898 
17899 	return true;
17900 }
17901 
17902 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
17903 						  struct bpf_stack_state *stack)
17904 {
17905 	if (is_spilled_scalar_reg64(stack))
17906 		return &stack->spilled_ptr;
17907 
17908 	if (is_stack_all_misc(env, stack))
17909 		return &unbound_reg;
17910 
17911 	return NULL;
17912 }
17913 
17914 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
17915 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
17916 		      enum exact_level exact)
17917 {
17918 	int i, spi;
17919 
17920 	/* walk slots of the explored stack and ignore any additional
17921 	 * slots in the current stack, since explored(safe) state
17922 	 * didn't use them
17923 	 */
17924 	for (i = 0; i < old->allocated_stack; i++) {
17925 		struct bpf_reg_state *old_reg, *cur_reg;
17926 
17927 		spi = i / BPF_REG_SIZE;
17928 
17929 		if (exact != NOT_EXACT &&
17930 		    (i >= cur->allocated_stack ||
17931 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
17932 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
17933 			return false;
17934 
17935 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
17936 		    && exact == NOT_EXACT) {
17937 			i += BPF_REG_SIZE - 1;
17938 			/* explored state didn't use this */
17939 			continue;
17940 		}
17941 
17942 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
17943 			continue;
17944 
17945 		if (env->allow_uninit_stack &&
17946 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
17947 			continue;
17948 
17949 		/* explored stack has more populated slots than current stack
17950 		 * and these slots were used
17951 		 */
17952 		if (i >= cur->allocated_stack)
17953 			return false;
17954 
17955 		/* 64-bit scalar spill vs all slots MISC and vice versa.
17956 		 * Load from all slots MISC produces unbound scalar.
17957 		 * Construct a fake register for such stack and call
17958 		 * regsafe() to ensure scalar ids are compared.
17959 		 */
17960 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
17961 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
17962 		if (old_reg && cur_reg) {
17963 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
17964 				return false;
17965 			i += BPF_REG_SIZE - 1;
17966 			continue;
17967 		}
17968 
17969 		/* if old state was safe with misc data in the stack
17970 		 * it will be safe with zero-initialized stack.
17971 		 * The opposite is not true
17972 		 */
17973 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
17974 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
17975 			continue;
17976 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
17977 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
17978 			/* Ex: old explored (safe) state has STACK_SPILL in
17979 			 * this stack slot, but current has STACK_MISC ->
17980 			 * this verifier states are not equivalent,
17981 			 * return false to continue verification of this path
17982 			 */
17983 			return false;
17984 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
17985 			continue;
17986 		/* Both old and cur are having same slot_type */
17987 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
17988 		case STACK_SPILL:
17989 			/* when explored and current stack slot are both storing
17990 			 * spilled registers, check that stored pointers types
17991 			 * are the same as well.
17992 			 * Ex: explored safe path could have stored
17993 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
17994 			 * but current path has stored:
17995 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
17996 			 * such verifier states are not equivalent.
17997 			 * return false to continue verification of this path
17998 			 */
17999 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
18000 				     &cur->stack[spi].spilled_ptr, idmap, exact))
18001 				return false;
18002 			break;
18003 		case STACK_DYNPTR:
18004 			old_reg = &old->stack[spi].spilled_ptr;
18005 			cur_reg = &cur->stack[spi].spilled_ptr;
18006 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
18007 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
18008 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18009 				return false;
18010 			break;
18011 		case STACK_ITER:
18012 			old_reg = &old->stack[spi].spilled_ptr;
18013 			cur_reg = &cur->stack[spi].spilled_ptr;
18014 			/* iter.depth is not compared between states as it
18015 			 * doesn't matter for correctness and would otherwise
18016 			 * prevent convergence; we maintain it only to prevent
18017 			 * infinite loop check triggering, see
18018 			 * iter_active_depths_differ()
18019 			 */
18020 			if (old_reg->iter.btf != cur_reg->iter.btf ||
18021 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
18022 			    old_reg->iter.state != cur_reg->iter.state ||
18023 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
18024 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18025 				return false;
18026 			break;
18027 		case STACK_IRQ_FLAG:
18028 			old_reg = &old->stack[spi].spilled_ptr;
18029 			cur_reg = &cur->stack[spi].spilled_ptr;
18030 			if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18031 				return false;
18032 			break;
18033 		case STACK_MISC:
18034 		case STACK_ZERO:
18035 		case STACK_INVALID:
18036 			continue;
18037 		/* Ensure that new unhandled slot types return false by default */
18038 		default:
18039 			return false;
18040 		}
18041 	}
18042 	return true;
18043 }
18044 
18045 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
18046 		    struct bpf_idmap *idmap)
18047 {
18048 	int i;
18049 
18050 	if (old->acquired_refs != cur->acquired_refs)
18051 		return false;
18052 
18053 	if (old->active_locks != cur->active_locks)
18054 		return false;
18055 
18056 	if (old->active_preempt_locks != cur->active_preempt_locks)
18057 		return false;
18058 
18059 	if (old->active_rcu_lock != cur->active_rcu_lock)
18060 		return false;
18061 
18062 	if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
18063 		return false;
18064 
18065 	for (i = 0; i < old->acquired_refs; i++) {
18066 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
18067 		    old->refs[i].type != cur->refs[i].type)
18068 			return false;
18069 		switch (old->refs[i].type) {
18070 		case REF_TYPE_PTR:
18071 		case REF_TYPE_IRQ:
18072 			break;
18073 		case REF_TYPE_LOCK:
18074 			if (old->refs[i].ptr != cur->refs[i].ptr)
18075 				return false;
18076 			break;
18077 		default:
18078 			WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
18079 			return false;
18080 		}
18081 	}
18082 
18083 	return true;
18084 }
18085 
18086 /* compare two verifier states
18087  *
18088  * all states stored in state_list are known to be valid, since
18089  * verifier reached 'bpf_exit' instruction through them
18090  *
18091  * this function is called when verifier exploring different branches of
18092  * execution popped from the state stack. If it sees an old state that has
18093  * more strict register state and more strict stack state then this execution
18094  * branch doesn't need to be explored further, since verifier already
18095  * concluded that more strict state leads to valid finish.
18096  *
18097  * Therefore two states are equivalent if register state is more conservative
18098  * and explored stack state is more conservative than the current one.
18099  * Example:
18100  *       explored                   current
18101  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
18102  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
18103  *
18104  * In other words if current stack state (one being explored) has more
18105  * valid slots than old one that already passed validation, it means
18106  * the verifier can stop exploring and conclude that current state is valid too
18107  *
18108  * Similarly with registers. If explored state has register type as invalid
18109  * whereas register type in current state is meaningful, it means that
18110  * the current state will reach 'bpf_exit' instruction safely
18111  */
18112 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
18113 			      struct bpf_func_state *cur, enum exact_level exact)
18114 {
18115 	int i;
18116 
18117 	if (old->callback_depth > cur->callback_depth)
18118 		return false;
18119 
18120 	for (i = 0; i < MAX_BPF_REG; i++)
18121 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
18122 			     &env->idmap_scratch, exact))
18123 			return false;
18124 
18125 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
18126 		return false;
18127 
18128 	return true;
18129 }
18130 
18131 static void reset_idmap_scratch(struct bpf_verifier_env *env)
18132 {
18133 	env->idmap_scratch.tmp_id_gen = env->id_gen;
18134 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
18135 }
18136 
18137 static bool states_equal(struct bpf_verifier_env *env,
18138 			 struct bpf_verifier_state *old,
18139 			 struct bpf_verifier_state *cur,
18140 			 enum exact_level exact)
18141 {
18142 	int i;
18143 
18144 	if (old->curframe != cur->curframe)
18145 		return false;
18146 
18147 	reset_idmap_scratch(env);
18148 
18149 	/* Verification state from speculative execution simulation
18150 	 * must never prune a non-speculative execution one.
18151 	 */
18152 	if (old->speculative && !cur->speculative)
18153 		return false;
18154 
18155 	if (old->in_sleepable != cur->in_sleepable)
18156 		return false;
18157 
18158 	if (!refsafe(old, cur, &env->idmap_scratch))
18159 		return false;
18160 
18161 	/* for states to be equal callsites have to be the same
18162 	 * and all frame states need to be equivalent
18163 	 */
18164 	for (i = 0; i <= old->curframe; i++) {
18165 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
18166 			return false;
18167 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
18168 			return false;
18169 	}
18170 	return true;
18171 }
18172 
18173 /* Return 0 if no propagation happened. Return negative error code if error
18174  * happened. Otherwise, return the propagated bit.
18175  */
18176 static int propagate_liveness_reg(struct bpf_verifier_env *env,
18177 				  struct bpf_reg_state *reg,
18178 				  struct bpf_reg_state *parent_reg)
18179 {
18180 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
18181 	u8 flag = reg->live & REG_LIVE_READ;
18182 	int err;
18183 
18184 	/* When comes here, read flags of PARENT_REG or REG could be any of
18185 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
18186 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
18187 	 */
18188 	if (parent_flag == REG_LIVE_READ64 ||
18189 	    /* Or if there is no read flag from REG. */
18190 	    !flag ||
18191 	    /* Or if the read flag from REG is the same as PARENT_REG. */
18192 	    parent_flag == flag)
18193 		return 0;
18194 
18195 	err = mark_reg_read(env, reg, parent_reg, flag);
18196 	if (err)
18197 		return err;
18198 
18199 	return flag;
18200 }
18201 
18202 /* A write screens off any subsequent reads; but write marks come from the
18203  * straight-line code between a state and its parent.  When we arrive at an
18204  * equivalent state (jump target or such) we didn't arrive by the straight-line
18205  * code, so read marks in the state must propagate to the parent regardless
18206  * of the state's write marks. That's what 'parent == state->parent' comparison
18207  * in mark_reg_read() is for.
18208  */
18209 static int propagate_liveness(struct bpf_verifier_env *env,
18210 			      const struct bpf_verifier_state *vstate,
18211 			      struct bpf_verifier_state *vparent)
18212 {
18213 	struct bpf_reg_state *state_reg, *parent_reg;
18214 	struct bpf_func_state *state, *parent;
18215 	int i, frame, err = 0;
18216 
18217 	if (vparent->curframe != vstate->curframe) {
18218 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
18219 		     vparent->curframe, vstate->curframe);
18220 		return -EFAULT;
18221 	}
18222 	/* Propagate read liveness of registers... */
18223 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
18224 	for (frame = 0; frame <= vstate->curframe; frame++) {
18225 		parent = vparent->frame[frame];
18226 		state = vstate->frame[frame];
18227 		parent_reg = parent->regs;
18228 		state_reg = state->regs;
18229 		/* We don't need to worry about FP liveness, it's read-only */
18230 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
18231 			err = propagate_liveness_reg(env, &state_reg[i],
18232 						     &parent_reg[i]);
18233 			if (err < 0)
18234 				return err;
18235 			if (err == REG_LIVE_READ64)
18236 				mark_insn_zext(env, &parent_reg[i]);
18237 		}
18238 
18239 		/* Propagate stack slots. */
18240 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
18241 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
18242 			parent_reg = &parent->stack[i].spilled_ptr;
18243 			state_reg = &state->stack[i].spilled_ptr;
18244 			err = propagate_liveness_reg(env, state_reg,
18245 						     parent_reg);
18246 			if (err < 0)
18247 				return err;
18248 		}
18249 	}
18250 	return 0;
18251 }
18252 
18253 /* find precise scalars in the previous equivalent state and
18254  * propagate them into the current state
18255  */
18256 static int propagate_precision(struct bpf_verifier_env *env,
18257 			       const struct bpf_verifier_state *old)
18258 {
18259 	struct bpf_reg_state *state_reg;
18260 	struct bpf_func_state *state;
18261 	int i, err = 0, fr;
18262 	bool first;
18263 
18264 	for (fr = old->curframe; fr >= 0; fr--) {
18265 		state = old->frame[fr];
18266 		state_reg = state->regs;
18267 		first = true;
18268 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
18269 			if (state_reg->type != SCALAR_VALUE ||
18270 			    !state_reg->precise ||
18271 			    !(state_reg->live & REG_LIVE_READ))
18272 				continue;
18273 			if (env->log.level & BPF_LOG_LEVEL2) {
18274 				if (first)
18275 					verbose(env, "frame %d: propagating r%d", fr, i);
18276 				else
18277 					verbose(env, ",r%d", i);
18278 			}
18279 			bt_set_frame_reg(&env->bt, fr, i);
18280 			first = false;
18281 		}
18282 
18283 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
18284 			if (!is_spilled_reg(&state->stack[i]))
18285 				continue;
18286 			state_reg = &state->stack[i].spilled_ptr;
18287 			if (state_reg->type != SCALAR_VALUE ||
18288 			    !state_reg->precise ||
18289 			    !(state_reg->live & REG_LIVE_READ))
18290 				continue;
18291 			if (env->log.level & BPF_LOG_LEVEL2) {
18292 				if (first)
18293 					verbose(env, "frame %d: propagating fp%d",
18294 						fr, (-i - 1) * BPF_REG_SIZE);
18295 				else
18296 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
18297 			}
18298 			bt_set_frame_slot(&env->bt, fr, i);
18299 			first = false;
18300 		}
18301 		if (!first)
18302 			verbose(env, "\n");
18303 	}
18304 
18305 	err = mark_chain_precision_batch(env);
18306 	if (err < 0)
18307 		return err;
18308 
18309 	return 0;
18310 }
18311 
18312 static bool states_maybe_looping(struct bpf_verifier_state *old,
18313 				 struct bpf_verifier_state *cur)
18314 {
18315 	struct bpf_func_state *fold, *fcur;
18316 	int i, fr = cur->curframe;
18317 
18318 	if (old->curframe != fr)
18319 		return false;
18320 
18321 	fold = old->frame[fr];
18322 	fcur = cur->frame[fr];
18323 	for (i = 0; i < MAX_BPF_REG; i++)
18324 		if (memcmp(&fold->regs[i], &fcur->regs[i],
18325 			   offsetof(struct bpf_reg_state, parent)))
18326 			return false;
18327 	return true;
18328 }
18329 
18330 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
18331 {
18332 	return env->insn_aux_data[insn_idx].is_iter_next;
18333 }
18334 
18335 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
18336  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
18337  * states to match, which otherwise would look like an infinite loop. So while
18338  * iter_next() calls are taken care of, we still need to be careful and
18339  * prevent erroneous and too eager declaration of "ininite loop", when
18340  * iterators are involved.
18341  *
18342  * Here's a situation in pseudo-BPF assembly form:
18343  *
18344  *   0: again:                          ; set up iter_next() call args
18345  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
18346  *   2:   call bpf_iter_num_next        ; this is iter_next() call
18347  *   3:   if r0 == 0 goto done
18348  *   4:   ... something useful here ...
18349  *   5:   goto again                    ; another iteration
18350  *   6: done:
18351  *   7:   r1 = &it
18352  *   8:   call bpf_iter_num_destroy     ; clean up iter state
18353  *   9:   exit
18354  *
18355  * This is a typical loop. Let's assume that we have a prune point at 1:,
18356  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
18357  * again`, assuming other heuristics don't get in a way).
18358  *
18359  * When we first time come to 1:, let's say we have some state X. We proceed
18360  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
18361  * Now we come back to validate that forked ACTIVE state. We proceed through
18362  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
18363  * are converging. But the problem is that we don't know that yet, as this
18364  * convergence has to happen at iter_next() call site only. So if nothing is
18365  * done, at 1: verifier will use bounded loop logic and declare infinite
18366  * looping (and would be *technically* correct, if not for iterator's
18367  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
18368  * don't want that. So what we do in process_iter_next_call() when we go on
18369  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
18370  * a different iteration. So when we suspect an infinite loop, we additionally
18371  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
18372  * pretend we are not looping and wait for next iter_next() call.
18373  *
18374  * This only applies to ACTIVE state. In DRAINED state we don't expect to
18375  * loop, because that would actually mean infinite loop, as DRAINED state is
18376  * "sticky", and so we'll keep returning into the same instruction with the
18377  * same state (at least in one of possible code paths).
18378  *
18379  * This approach allows to keep infinite loop heuristic even in the face of
18380  * active iterator. E.g., C snippet below is and will be detected as
18381  * inifintely looping:
18382  *
18383  *   struct bpf_iter_num it;
18384  *   int *p, x;
18385  *
18386  *   bpf_iter_num_new(&it, 0, 10);
18387  *   while ((p = bpf_iter_num_next(&t))) {
18388  *       x = p;
18389  *       while (x--) {} // <<-- infinite loop here
18390  *   }
18391  *
18392  */
18393 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
18394 {
18395 	struct bpf_reg_state *slot, *cur_slot;
18396 	struct bpf_func_state *state;
18397 	int i, fr;
18398 
18399 	for (fr = old->curframe; fr >= 0; fr--) {
18400 		state = old->frame[fr];
18401 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
18402 			if (state->stack[i].slot_type[0] != STACK_ITER)
18403 				continue;
18404 
18405 			slot = &state->stack[i].spilled_ptr;
18406 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
18407 				continue;
18408 
18409 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
18410 			if (cur_slot->iter.depth != slot->iter.depth)
18411 				return true;
18412 		}
18413 	}
18414 	return false;
18415 }
18416 
18417 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
18418 {
18419 	struct bpf_verifier_state_list *new_sl;
18420 	struct bpf_verifier_state_list *sl, **pprev;
18421 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
18422 	int i, j, n, err, states_cnt = 0;
18423 	bool force_new_state, add_new_state, force_exact;
18424 
18425 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
18426 			  /* Avoid accumulating infinitely long jmp history */
18427 			  cur->insn_hist_end - cur->insn_hist_start > 40;
18428 
18429 	/* bpf progs typically have pruning point every 4 instructions
18430 	 * http://vger.kernel.org/bpfconf2019.html#session-1
18431 	 * Do not add new state for future pruning if the verifier hasn't seen
18432 	 * at least 2 jumps and at least 8 instructions.
18433 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
18434 	 * In tests that amounts to up to 50% reduction into total verifier
18435 	 * memory consumption and 20% verifier time speedup.
18436 	 */
18437 	add_new_state = force_new_state;
18438 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
18439 	    env->insn_processed - env->prev_insn_processed >= 8)
18440 		add_new_state = true;
18441 
18442 	pprev = explored_state(env, insn_idx);
18443 	sl = *pprev;
18444 
18445 	clean_live_states(env, insn_idx, cur);
18446 
18447 	while (sl) {
18448 		states_cnt++;
18449 		if (sl->state.insn_idx != insn_idx)
18450 			goto next;
18451 
18452 		if (sl->state.branches) {
18453 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
18454 
18455 			if (frame->in_async_callback_fn &&
18456 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
18457 				/* Different async_entry_cnt means that the verifier is
18458 				 * processing another entry into async callback.
18459 				 * Seeing the same state is not an indication of infinite
18460 				 * loop or infinite recursion.
18461 				 * But finding the same state doesn't mean that it's safe
18462 				 * to stop processing the current state. The previous state
18463 				 * hasn't yet reached bpf_exit, since state.branches > 0.
18464 				 * Checking in_async_callback_fn alone is not enough either.
18465 				 * Since the verifier still needs to catch infinite loops
18466 				 * inside async callbacks.
18467 				 */
18468 				goto skip_inf_loop_check;
18469 			}
18470 			/* BPF open-coded iterators loop detection is special.
18471 			 * states_maybe_looping() logic is too simplistic in detecting
18472 			 * states that *might* be equivalent, because it doesn't know
18473 			 * about ID remapping, so don't even perform it.
18474 			 * See process_iter_next_call() and iter_active_depths_differ()
18475 			 * for overview of the logic. When current and one of parent
18476 			 * states are detected as equivalent, it's a good thing: we prove
18477 			 * convergence and can stop simulating further iterations.
18478 			 * It's safe to assume that iterator loop will finish, taking into
18479 			 * account iter_next() contract of eventually returning
18480 			 * sticky NULL result.
18481 			 *
18482 			 * Note, that states have to be compared exactly in this case because
18483 			 * read and precision marks might not be finalized inside the loop.
18484 			 * E.g. as in the program below:
18485 			 *
18486 			 *     1. r7 = -16
18487 			 *     2. r6 = bpf_get_prandom_u32()
18488 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
18489 			 *     4.   if (r6 != 42) {
18490 			 *     5.     r7 = -32
18491 			 *     6.     r6 = bpf_get_prandom_u32()
18492 			 *     7.     continue
18493 			 *     8.   }
18494 			 *     9.   r0 = r10
18495 			 *    10.   r0 += r7
18496 			 *    11.   r8 = *(u64 *)(r0 + 0)
18497 			 *    12.   r6 = bpf_get_prandom_u32()
18498 			 *    13. }
18499 			 *
18500 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
18501 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
18502 			 * not have read or precision mark for r7 yet, thus inexact states
18503 			 * comparison would discard current state with r7=-32
18504 			 * => unsafe memory access at 11 would not be caught.
18505 			 */
18506 			if (is_iter_next_insn(env, insn_idx)) {
18507 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
18508 					struct bpf_func_state *cur_frame;
18509 					struct bpf_reg_state *iter_state, *iter_reg;
18510 					int spi;
18511 
18512 					cur_frame = cur->frame[cur->curframe];
18513 					/* btf_check_iter_kfuncs() enforces that
18514 					 * iter state pointer is always the first arg
18515 					 */
18516 					iter_reg = &cur_frame->regs[BPF_REG_1];
18517 					/* current state is valid due to states_equal(),
18518 					 * so we can assume valid iter and reg state,
18519 					 * no need for extra (re-)validations
18520 					 */
18521 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
18522 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
18523 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
18524 						update_loop_entry(cur, &sl->state);
18525 						goto hit;
18526 					}
18527 				}
18528 				goto skip_inf_loop_check;
18529 			}
18530 			if (is_may_goto_insn_at(env, insn_idx)) {
18531 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
18532 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
18533 					update_loop_entry(cur, &sl->state);
18534 					goto hit;
18535 				}
18536 			}
18537 			if (calls_callback(env, insn_idx)) {
18538 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
18539 					goto hit;
18540 				goto skip_inf_loop_check;
18541 			}
18542 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
18543 			if (states_maybe_looping(&sl->state, cur) &&
18544 			    states_equal(env, &sl->state, cur, EXACT) &&
18545 			    !iter_active_depths_differ(&sl->state, cur) &&
18546 			    sl->state.may_goto_depth == cur->may_goto_depth &&
18547 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
18548 				verbose_linfo(env, insn_idx, "; ");
18549 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
18550 				verbose(env, "cur state:");
18551 				print_verifier_state(env, cur, cur->curframe, true);
18552 				verbose(env, "old state:");
18553 				print_verifier_state(env, &sl->state, cur->curframe, true);
18554 				return -EINVAL;
18555 			}
18556 			/* if the verifier is processing a loop, avoid adding new state
18557 			 * too often, since different loop iterations have distinct
18558 			 * states and may not help future pruning.
18559 			 * This threshold shouldn't be too low to make sure that
18560 			 * a loop with large bound will be rejected quickly.
18561 			 * The most abusive loop will be:
18562 			 * r1 += 1
18563 			 * if r1 < 1000000 goto pc-2
18564 			 * 1M insn_procssed limit / 100 == 10k peak states.
18565 			 * This threshold shouldn't be too high either, since states
18566 			 * at the end of the loop are likely to be useful in pruning.
18567 			 */
18568 skip_inf_loop_check:
18569 			if (!force_new_state &&
18570 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
18571 			    env->insn_processed - env->prev_insn_processed < 100)
18572 				add_new_state = false;
18573 			goto miss;
18574 		}
18575 		/* If sl->state is a part of a loop and this loop's entry is a part of
18576 		 * current verification path then states have to be compared exactly.
18577 		 * 'force_exact' is needed to catch the following case:
18578 		 *
18579 		 *                initial     Here state 'succ' was processed first,
18580 		 *                  |         it was eventually tracked to produce a
18581 		 *                  V         state identical to 'hdr'.
18582 		 *     .---------> hdr        All branches from 'succ' had been explored
18583 		 *     |            |         and thus 'succ' has its .branches == 0.
18584 		 *     |            V
18585 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
18586 		 *     |    |       |         to the same instruction + callsites.
18587 		 *     |    V       V         In such case it is necessary to check
18588 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
18589 		 *     |    |       |         If 'succ' and 'cur' are a part of the
18590 		 *     |    V       V         same loop exact flag has to be set.
18591 		 *     |   succ <- cur        To check if that is the case, verify
18592 		 *     |    |                 if loop entry of 'succ' is in current
18593 		 *     |    V                 DFS path.
18594 		 *     |   ...
18595 		 *     |    |
18596 		 *     '----'
18597 		 *
18598 		 * Additional details are in the comment before get_loop_entry().
18599 		 */
18600 		loop_entry = get_loop_entry(&sl->state);
18601 		force_exact = loop_entry && loop_entry->branches > 0;
18602 		if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) {
18603 			if (force_exact)
18604 				update_loop_entry(cur, loop_entry);
18605 hit:
18606 			sl->hit_cnt++;
18607 			/* reached equivalent register/stack state,
18608 			 * prune the search.
18609 			 * Registers read by the continuation are read by us.
18610 			 * If we have any write marks in env->cur_state, they
18611 			 * will prevent corresponding reads in the continuation
18612 			 * from reaching our parent (an explored_state).  Our
18613 			 * own state will get the read marks recorded, but
18614 			 * they'll be immediately forgotten as we're pruning
18615 			 * this state and will pop a new one.
18616 			 */
18617 			err = propagate_liveness(env, &sl->state, cur);
18618 
18619 			/* if previous state reached the exit with precision and
18620 			 * current state is equivalent to it (except precision marks)
18621 			 * the precision needs to be propagated back in
18622 			 * the current state.
18623 			 */
18624 			if (is_jmp_point(env, env->insn_idx))
18625 				err = err ? : push_insn_history(env, cur, 0, 0);
18626 			err = err ? : propagate_precision(env, &sl->state);
18627 			if (err)
18628 				return err;
18629 			return 1;
18630 		}
18631 miss:
18632 		/* when new state is not going to be added do not increase miss count.
18633 		 * Otherwise several loop iterations will remove the state
18634 		 * recorded earlier. The goal of these heuristics is to have
18635 		 * states from some iterations of the loop (some in the beginning
18636 		 * and some at the end) to help pruning.
18637 		 */
18638 		if (add_new_state)
18639 			sl->miss_cnt++;
18640 		/* heuristic to determine whether this state is beneficial
18641 		 * to keep checking from state equivalence point of view.
18642 		 * Higher numbers increase max_states_per_insn and verification time,
18643 		 * but do not meaningfully decrease insn_processed.
18644 		 * 'n' controls how many times state could miss before eviction.
18645 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
18646 		 * too early would hinder iterator convergence.
18647 		 */
18648 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
18649 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
18650 			/* the state is unlikely to be useful. Remove it to
18651 			 * speed up verification
18652 			 */
18653 			*pprev = sl->next;
18654 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
18655 			    !sl->state.used_as_loop_entry) {
18656 				u32 br = sl->state.branches;
18657 
18658 				WARN_ONCE(br,
18659 					  "BUG live_done but branches_to_explore %d\n",
18660 					  br);
18661 				free_verifier_state(&sl->state, false);
18662 				kfree(sl);
18663 				env->peak_states--;
18664 			} else {
18665 				/* cannot free this state, since parentage chain may
18666 				 * walk it later. Add it for free_list instead to
18667 				 * be freed at the end of verification
18668 				 */
18669 				sl->next = env->free_list;
18670 				env->free_list = sl;
18671 			}
18672 			sl = *pprev;
18673 			continue;
18674 		}
18675 next:
18676 		pprev = &sl->next;
18677 		sl = *pprev;
18678 	}
18679 
18680 	if (env->max_states_per_insn < states_cnt)
18681 		env->max_states_per_insn = states_cnt;
18682 
18683 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
18684 		return 0;
18685 
18686 	if (!add_new_state)
18687 		return 0;
18688 
18689 	/* There were no equivalent states, remember the current one.
18690 	 * Technically the current state is not proven to be safe yet,
18691 	 * but it will either reach outer most bpf_exit (which means it's safe)
18692 	 * or it will be rejected. When there are no loops the verifier won't be
18693 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
18694 	 * again on the way to bpf_exit.
18695 	 * When looping the sl->state.branches will be > 0 and this state
18696 	 * will not be considered for equivalence until branches == 0.
18697 	 */
18698 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
18699 	if (!new_sl)
18700 		return -ENOMEM;
18701 	env->total_states++;
18702 	env->peak_states++;
18703 	env->prev_jmps_processed = env->jmps_processed;
18704 	env->prev_insn_processed = env->insn_processed;
18705 
18706 	/* forget precise markings we inherited, see __mark_chain_precision */
18707 	if (env->bpf_capable)
18708 		mark_all_scalars_imprecise(env, cur);
18709 
18710 	/* add new state to the head of linked list */
18711 	new = &new_sl->state;
18712 	err = copy_verifier_state(new, cur);
18713 	if (err) {
18714 		free_verifier_state(new, false);
18715 		kfree(new_sl);
18716 		return err;
18717 	}
18718 	new->insn_idx = insn_idx;
18719 	WARN_ONCE(new->branches != 1,
18720 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
18721 
18722 	cur->parent = new;
18723 	cur->first_insn_idx = insn_idx;
18724 	cur->insn_hist_start = cur->insn_hist_end;
18725 	cur->dfs_depth = new->dfs_depth + 1;
18726 	new_sl->next = *explored_state(env, insn_idx);
18727 	*explored_state(env, insn_idx) = new_sl;
18728 	/* connect new state to parentage chain. Current frame needs all
18729 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
18730 	 * to the stack implicitly by JITs) so in callers' frames connect just
18731 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
18732 	 * the state of the call instruction (with WRITTEN set), and r0 comes
18733 	 * from callee with its full parentage chain, anyway.
18734 	 */
18735 	/* clear write marks in current state: the writes we did are not writes
18736 	 * our child did, so they don't screen off its reads from us.
18737 	 * (There are no read marks in current state, because reads always mark
18738 	 * their parent and current state never has children yet.  Only
18739 	 * explored_states can get read marks.)
18740 	 */
18741 	for (j = 0; j <= cur->curframe; j++) {
18742 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
18743 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
18744 		for (i = 0; i < BPF_REG_FP; i++)
18745 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
18746 	}
18747 
18748 	/* all stack frames are accessible from callee, clear them all */
18749 	for (j = 0; j <= cur->curframe; j++) {
18750 		struct bpf_func_state *frame = cur->frame[j];
18751 		struct bpf_func_state *newframe = new->frame[j];
18752 
18753 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
18754 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
18755 			frame->stack[i].spilled_ptr.parent =
18756 						&newframe->stack[i].spilled_ptr;
18757 		}
18758 	}
18759 	return 0;
18760 }
18761 
18762 /* Return true if it's OK to have the same insn return a different type. */
18763 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
18764 {
18765 	switch (base_type(type)) {
18766 	case PTR_TO_CTX:
18767 	case PTR_TO_SOCKET:
18768 	case PTR_TO_SOCK_COMMON:
18769 	case PTR_TO_TCP_SOCK:
18770 	case PTR_TO_XDP_SOCK:
18771 	case PTR_TO_BTF_ID:
18772 	case PTR_TO_ARENA:
18773 		return false;
18774 	default:
18775 		return true;
18776 	}
18777 }
18778 
18779 /* If an instruction was previously used with particular pointer types, then we
18780  * need to be careful to avoid cases such as the below, where it may be ok
18781  * for one branch accessing the pointer, but not ok for the other branch:
18782  *
18783  * R1 = sock_ptr
18784  * goto X;
18785  * ...
18786  * R1 = some_other_valid_ptr;
18787  * goto X;
18788  * ...
18789  * R2 = *(u32 *)(R1 + 0);
18790  */
18791 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
18792 {
18793 	return src != prev && (!reg_type_mismatch_ok(src) ||
18794 			       !reg_type_mismatch_ok(prev));
18795 }
18796 
18797 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
18798 			     bool allow_trust_mismatch)
18799 {
18800 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
18801 
18802 	if (*prev_type == NOT_INIT) {
18803 		/* Saw a valid insn
18804 		 * dst_reg = *(u32 *)(src_reg + off)
18805 		 * save type to validate intersecting paths
18806 		 */
18807 		*prev_type = type;
18808 	} else if (reg_type_mismatch(type, *prev_type)) {
18809 		/* Abuser program is trying to use the same insn
18810 		 * dst_reg = *(u32*) (src_reg + off)
18811 		 * with different pointer types:
18812 		 * src_reg == ctx in one branch and
18813 		 * src_reg == stack|map in some other branch.
18814 		 * Reject it.
18815 		 */
18816 		if (allow_trust_mismatch &&
18817 		    base_type(type) == PTR_TO_BTF_ID &&
18818 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
18819 			/*
18820 			 * Have to support a use case when one path through
18821 			 * the program yields TRUSTED pointer while another
18822 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
18823 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
18824 			 */
18825 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
18826 		} else {
18827 			verbose(env, "same insn cannot be used with different pointers\n");
18828 			return -EINVAL;
18829 		}
18830 	}
18831 
18832 	return 0;
18833 }
18834 
18835 static int do_check(struct bpf_verifier_env *env)
18836 {
18837 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18838 	struct bpf_verifier_state *state = env->cur_state;
18839 	struct bpf_insn *insns = env->prog->insnsi;
18840 	struct bpf_reg_state *regs;
18841 	int insn_cnt = env->prog->len;
18842 	bool do_print_state = false;
18843 	int prev_insn_idx = -1;
18844 
18845 	for (;;) {
18846 		bool exception_exit = false;
18847 		struct bpf_insn *insn;
18848 		u8 class;
18849 		int err;
18850 
18851 		/* reset current history entry on each new instruction */
18852 		env->cur_hist_ent = NULL;
18853 
18854 		env->prev_insn_idx = prev_insn_idx;
18855 		if (env->insn_idx >= insn_cnt) {
18856 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
18857 				env->insn_idx, insn_cnt);
18858 			return -EFAULT;
18859 		}
18860 
18861 		insn = &insns[env->insn_idx];
18862 		class = BPF_CLASS(insn->code);
18863 
18864 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
18865 			verbose(env,
18866 				"BPF program is too large. Processed %d insn\n",
18867 				env->insn_processed);
18868 			return -E2BIG;
18869 		}
18870 
18871 		state->last_insn_idx = env->prev_insn_idx;
18872 
18873 		if (is_prune_point(env, env->insn_idx)) {
18874 			err = is_state_visited(env, env->insn_idx);
18875 			if (err < 0)
18876 				return err;
18877 			if (err == 1) {
18878 				/* found equivalent state, can prune the search */
18879 				if (env->log.level & BPF_LOG_LEVEL) {
18880 					if (do_print_state)
18881 						verbose(env, "\nfrom %d to %d%s: safe\n",
18882 							env->prev_insn_idx, env->insn_idx,
18883 							env->cur_state->speculative ?
18884 							" (speculative execution)" : "");
18885 					else
18886 						verbose(env, "%d: safe\n", env->insn_idx);
18887 				}
18888 				goto process_bpf_exit;
18889 			}
18890 		}
18891 
18892 		if (is_jmp_point(env, env->insn_idx)) {
18893 			err = push_insn_history(env, state, 0, 0);
18894 			if (err)
18895 				return err;
18896 		}
18897 
18898 		if (signal_pending(current))
18899 			return -EAGAIN;
18900 
18901 		if (need_resched())
18902 			cond_resched();
18903 
18904 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
18905 			verbose(env, "\nfrom %d to %d%s:",
18906 				env->prev_insn_idx, env->insn_idx,
18907 				env->cur_state->speculative ?
18908 				" (speculative execution)" : "");
18909 			print_verifier_state(env, state, state->curframe, true);
18910 			do_print_state = false;
18911 		}
18912 
18913 		if (env->log.level & BPF_LOG_LEVEL) {
18914 			const struct bpf_insn_cbs cbs = {
18915 				.cb_call	= disasm_kfunc_name,
18916 				.cb_print	= verbose,
18917 				.private_data	= env,
18918 			};
18919 
18920 			if (verifier_state_scratched(env))
18921 				print_insn_state(env, state, state->curframe);
18922 
18923 			verbose_linfo(env, env->insn_idx, "; ");
18924 			env->prev_log_pos = env->log.end_pos;
18925 			verbose(env, "%d: ", env->insn_idx);
18926 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
18927 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
18928 			env->prev_log_pos = env->log.end_pos;
18929 		}
18930 
18931 		if (bpf_prog_is_offloaded(env->prog->aux)) {
18932 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
18933 							   env->prev_insn_idx);
18934 			if (err)
18935 				return err;
18936 		}
18937 
18938 		regs = cur_regs(env);
18939 		sanitize_mark_insn_seen(env);
18940 		prev_insn_idx = env->insn_idx;
18941 
18942 		if (class == BPF_ALU || class == BPF_ALU64) {
18943 			err = check_alu_op(env, insn);
18944 			if (err)
18945 				return err;
18946 
18947 		} else if (class == BPF_LDX) {
18948 			enum bpf_reg_type src_reg_type;
18949 
18950 			/* check for reserved fields is already done */
18951 
18952 			/* check src operand */
18953 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
18954 			if (err)
18955 				return err;
18956 
18957 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
18958 			if (err)
18959 				return err;
18960 
18961 			src_reg_type = regs[insn->src_reg].type;
18962 
18963 			/* check that memory (src_reg + off) is readable,
18964 			 * the state of dst_reg will be updated by this func
18965 			 */
18966 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
18967 					       insn->off, BPF_SIZE(insn->code),
18968 					       BPF_READ, insn->dst_reg, false,
18969 					       BPF_MODE(insn->code) == BPF_MEMSX);
18970 			err = err ?: save_aux_ptr_type(env, src_reg_type, true);
18971 			err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], "ldx");
18972 			if (err)
18973 				return err;
18974 		} else if (class == BPF_STX) {
18975 			enum bpf_reg_type dst_reg_type;
18976 
18977 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
18978 				err = check_atomic(env, env->insn_idx, insn);
18979 				if (err)
18980 					return err;
18981 				env->insn_idx++;
18982 				continue;
18983 			}
18984 
18985 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
18986 				verbose(env, "BPF_STX uses reserved fields\n");
18987 				return -EINVAL;
18988 			}
18989 
18990 			/* check src1 operand */
18991 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
18992 			if (err)
18993 				return err;
18994 			/* check src2 operand */
18995 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
18996 			if (err)
18997 				return err;
18998 
18999 			dst_reg_type = regs[insn->dst_reg].type;
19000 
19001 			/* check that memory (dst_reg + off) is writeable */
19002 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
19003 					       insn->off, BPF_SIZE(insn->code),
19004 					       BPF_WRITE, insn->src_reg, false, false);
19005 			if (err)
19006 				return err;
19007 
19008 			err = save_aux_ptr_type(env, dst_reg_type, false);
19009 			if (err)
19010 				return err;
19011 		} else if (class == BPF_ST) {
19012 			enum bpf_reg_type dst_reg_type;
19013 
19014 			if (BPF_MODE(insn->code) != BPF_MEM ||
19015 			    insn->src_reg != BPF_REG_0) {
19016 				verbose(env, "BPF_ST uses reserved fields\n");
19017 				return -EINVAL;
19018 			}
19019 			/* check src operand */
19020 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
19021 			if (err)
19022 				return err;
19023 
19024 			dst_reg_type = regs[insn->dst_reg].type;
19025 
19026 			/* check that memory (dst_reg + off) is writeable */
19027 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
19028 					       insn->off, BPF_SIZE(insn->code),
19029 					       BPF_WRITE, -1, false, false);
19030 			if (err)
19031 				return err;
19032 
19033 			err = save_aux_ptr_type(env, dst_reg_type, false);
19034 			if (err)
19035 				return err;
19036 		} else if (class == BPF_JMP || class == BPF_JMP32) {
19037 			u8 opcode = BPF_OP(insn->code);
19038 
19039 			env->jmps_processed++;
19040 			if (opcode == BPF_CALL) {
19041 				if (BPF_SRC(insn->code) != BPF_K ||
19042 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
19043 				     && insn->off != 0) ||
19044 				    (insn->src_reg != BPF_REG_0 &&
19045 				     insn->src_reg != BPF_PSEUDO_CALL &&
19046 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
19047 				    insn->dst_reg != BPF_REG_0 ||
19048 				    class == BPF_JMP32) {
19049 					verbose(env, "BPF_CALL uses reserved fields\n");
19050 					return -EINVAL;
19051 				}
19052 
19053 				if (env->cur_state->active_locks) {
19054 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
19055 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
19056 					     (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
19057 						verbose(env, "function calls are not allowed while holding a lock\n");
19058 						return -EINVAL;
19059 					}
19060 				}
19061 				if (insn->src_reg == BPF_PSEUDO_CALL) {
19062 					err = check_func_call(env, insn, &env->insn_idx);
19063 				} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19064 					err = check_kfunc_call(env, insn, &env->insn_idx);
19065 					if (!err && is_bpf_throw_kfunc(insn)) {
19066 						exception_exit = true;
19067 						goto process_bpf_exit_full;
19068 					}
19069 				} else {
19070 					err = check_helper_call(env, insn, &env->insn_idx);
19071 				}
19072 				if (err)
19073 					return err;
19074 
19075 				mark_reg_scratched(env, BPF_REG_0);
19076 			} else if (opcode == BPF_JA) {
19077 				if (BPF_SRC(insn->code) != BPF_K ||
19078 				    insn->src_reg != BPF_REG_0 ||
19079 				    insn->dst_reg != BPF_REG_0 ||
19080 				    (class == BPF_JMP && insn->imm != 0) ||
19081 				    (class == BPF_JMP32 && insn->off != 0)) {
19082 					verbose(env, "BPF_JA uses reserved fields\n");
19083 					return -EINVAL;
19084 				}
19085 
19086 				if (class == BPF_JMP)
19087 					env->insn_idx += insn->off + 1;
19088 				else
19089 					env->insn_idx += insn->imm + 1;
19090 				continue;
19091 
19092 			} else if (opcode == BPF_EXIT) {
19093 				if (BPF_SRC(insn->code) != BPF_K ||
19094 				    insn->imm != 0 ||
19095 				    insn->src_reg != BPF_REG_0 ||
19096 				    insn->dst_reg != BPF_REG_0 ||
19097 				    class == BPF_JMP32) {
19098 					verbose(env, "BPF_EXIT uses reserved fields\n");
19099 					return -EINVAL;
19100 				}
19101 process_bpf_exit_full:
19102 				/* We must do check_reference_leak here before
19103 				 * prepare_func_exit to handle the case when
19104 				 * state->curframe > 0, it may be a callback
19105 				 * function, for which reference_state must
19106 				 * match caller reference state when it exits.
19107 				 */
19108 				err = check_resource_leak(env, exception_exit, !env->cur_state->curframe,
19109 							  "BPF_EXIT instruction in main prog");
19110 				if (err)
19111 					return err;
19112 
19113 				/* The side effect of the prepare_func_exit
19114 				 * which is being skipped is that it frees
19115 				 * bpf_func_state. Typically, process_bpf_exit
19116 				 * will only be hit with outermost exit.
19117 				 * copy_verifier_state in pop_stack will handle
19118 				 * freeing of any extra bpf_func_state left over
19119 				 * from not processing all nested function
19120 				 * exits. We also skip return code checks as
19121 				 * they are not needed for exceptional exits.
19122 				 */
19123 				if (exception_exit)
19124 					goto process_bpf_exit;
19125 
19126 				if (state->curframe) {
19127 					/* exit from nested function */
19128 					err = prepare_func_exit(env, &env->insn_idx);
19129 					if (err)
19130 						return err;
19131 					do_print_state = true;
19132 					continue;
19133 				}
19134 
19135 				err = check_return_code(env, BPF_REG_0, "R0");
19136 				if (err)
19137 					return err;
19138 process_bpf_exit:
19139 				mark_verifier_state_scratched(env);
19140 				update_branch_counts(env, env->cur_state);
19141 				err = pop_stack(env, &prev_insn_idx,
19142 						&env->insn_idx, pop_log);
19143 				if (err < 0) {
19144 					if (err != -ENOENT)
19145 						return err;
19146 					break;
19147 				} else {
19148 					do_print_state = true;
19149 					continue;
19150 				}
19151 			} else {
19152 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
19153 				if (err)
19154 					return err;
19155 			}
19156 		} else if (class == BPF_LD) {
19157 			u8 mode = BPF_MODE(insn->code);
19158 
19159 			if (mode == BPF_ABS || mode == BPF_IND) {
19160 				err = check_ld_abs(env, insn);
19161 				if (err)
19162 					return err;
19163 
19164 			} else if (mode == BPF_IMM) {
19165 				err = check_ld_imm(env, insn);
19166 				if (err)
19167 					return err;
19168 
19169 				env->insn_idx++;
19170 				sanitize_mark_insn_seen(env);
19171 			} else {
19172 				verbose(env, "invalid BPF_LD mode\n");
19173 				return -EINVAL;
19174 			}
19175 		} else {
19176 			verbose(env, "unknown insn class %d\n", class);
19177 			return -EINVAL;
19178 		}
19179 
19180 		env->insn_idx++;
19181 	}
19182 
19183 	return 0;
19184 }
19185 
19186 static int find_btf_percpu_datasec(struct btf *btf)
19187 {
19188 	const struct btf_type *t;
19189 	const char *tname;
19190 	int i, n;
19191 
19192 	/*
19193 	 * Both vmlinux and module each have their own ".data..percpu"
19194 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
19195 	 * types to look at only module's own BTF types.
19196 	 */
19197 	n = btf_nr_types(btf);
19198 	if (btf_is_module(btf))
19199 		i = btf_nr_types(btf_vmlinux);
19200 	else
19201 		i = 1;
19202 
19203 	for(; i < n; i++) {
19204 		t = btf_type_by_id(btf, i);
19205 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
19206 			continue;
19207 
19208 		tname = btf_name_by_offset(btf, t->name_off);
19209 		if (!strcmp(tname, ".data..percpu"))
19210 			return i;
19211 	}
19212 
19213 	return -ENOENT;
19214 }
19215 
19216 /*
19217  * Add btf to the used_btfs array and return the index. (If the btf was
19218  * already added, then just return the index.) Upon successful insertion
19219  * increase btf refcnt, and, if present, also refcount the corresponding
19220  * kernel module.
19221  */
19222 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
19223 {
19224 	struct btf_mod_pair *btf_mod;
19225 	int i;
19226 
19227 	/* check whether we recorded this BTF (and maybe module) already */
19228 	for (i = 0; i < env->used_btf_cnt; i++)
19229 		if (env->used_btfs[i].btf == btf)
19230 			return i;
19231 
19232 	if (env->used_btf_cnt >= MAX_USED_BTFS)
19233 		return -E2BIG;
19234 
19235 	btf_get(btf);
19236 
19237 	btf_mod = &env->used_btfs[env->used_btf_cnt];
19238 	btf_mod->btf = btf;
19239 	btf_mod->module = NULL;
19240 
19241 	/* if we reference variables from kernel module, bump its refcount */
19242 	if (btf_is_module(btf)) {
19243 		btf_mod->module = btf_try_get_module(btf);
19244 		if (!btf_mod->module) {
19245 			btf_put(btf);
19246 			return -ENXIO;
19247 		}
19248 	}
19249 
19250 	return env->used_btf_cnt++;
19251 }
19252 
19253 /* replace pseudo btf_id with kernel symbol address */
19254 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
19255 				 struct bpf_insn *insn,
19256 				 struct bpf_insn_aux_data *aux,
19257 				 struct btf *btf)
19258 {
19259 	const struct btf_var_secinfo *vsi;
19260 	const struct btf_type *datasec;
19261 	const struct btf_type *t;
19262 	const char *sym_name;
19263 	bool percpu = false;
19264 	u32 type, id = insn->imm;
19265 	s32 datasec_id;
19266 	u64 addr;
19267 	int i;
19268 
19269 	t = btf_type_by_id(btf, id);
19270 	if (!t) {
19271 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
19272 		return -ENOENT;
19273 	}
19274 
19275 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
19276 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
19277 		return -EINVAL;
19278 	}
19279 
19280 	sym_name = btf_name_by_offset(btf, t->name_off);
19281 	addr = kallsyms_lookup_name(sym_name);
19282 	if (!addr) {
19283 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
19284 			sym_name);
19285 		return -ENOENT;
19286 	}
19287 	insn[0].imm = (u32)addr;
19288 	insn[1].imm = addr >> 32;
19289 
19290 	if (btf_type_is_func(t)) {
19291 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
19292 		aux->btf_var.mem_size = 0;
19293 		return 0;
19294 	}
19295 
19296 	datasec_id = find_btf_percpu_datasec(btf);
19297 	if (datasec_id > 0) {
19298 		datasec = btf_type_by_id(btf, datasec_id);
19299 		for_each_vsi(i, datasec, vsi) {
19300 			if (vsi->type == id) {
19301 				percpu = true;
19302 				break;
19303 			}
19304 		}
19305 	}
19306 
19307 	type = t->type;
19308 	t = btf_type_skip_modifiers(btf, type, NULL);
19309 	if (percpu) {
19310 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
19311 		aux->btf_var.btf = btf;
19312 		aux->btf_var.btf_id = type;
19313 	} else if (!btf_type_is_struct(t)) {
19314 		const struct btf_type *ret;
19315 		const char *tname;
19316 		u32 tsize;
19317 
19318 		/* resolve the type size of ksym. */
19319 		ret = btf_resolve_size(btf, t, &tsize);
19320 		if (IS_ERR(ret)) {
19321 			tname = btf_name_by_offset(btf, t->name_off);
19322 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
19323 				tname, PTR_ERR(ret));
19324 			return -EINVAL;
19325 		}
19326 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
19327 		aux->btf_var.mem_size = tsize;
19328 	} else {
19329 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
19330 		aux->btf_var.btf = btf;
19331 		aux->btf_var.btf_id = type;
19332 	}
19333 
19334 	return 0;
19335 }
19336 
19337 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
19338 			       struct bpf_insn *insn,
19339 			       struct bpf_insn_aux_data *aux)
19340 {
19341 	struct btf *btf;
19342 	int btf_fd;
19343 	int err;
19344 
19345 	btf_fd = insn[1].imm;
19346 	if (btf_fd) {
19347 		CLASS(fd, f)(btf_fd);
19348 
19349 		btf = __btf_get_by_fd(f);
19350 		if (IS_ERR(btf)) {
19351 			verbose(env, "invalid module BTF object FD specified.\n");
19352 			return -EINVAL;
19353 		}
19354 	} else {
19355 		if (!btf_vmlinux) {
19356 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
19357 			return -EINVAL;
19358 		}
19359 		btf = btf_vmlinux;
19360 	}
19361 
19362 	err = __check_pseudo_btf_id(env, insn, aux, btf);
19363 	if (err)
19364 		return err;
19365 
19366 	err = __add_used_btf(env, btf);
19367 	if (err < 0)
19368 		return err;
19369 	return 0;
19370 }
19371 
19372 static bool is_tracing_prog_type(enum bpf_prog_type type)
19373 {
19374 	switch (type) {
19375 	case BPF_PROG_TYPE_KPROBE:
19376 	case BPF_PROG_TYPE_TRACEPOINT:
19377 	case BPF_PROG_TYPE_PERF_EVENT:
19378 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
19379 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
19380 		return true;
19381 	default:
19382 		return false;
19383 	}
19384 }
19385 
19386 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
19387 {
19388 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
19389 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
19390 }
19391 
19392 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
19393 					struct bpf_map *map,
19394 					struct bpf_prog *prog)
19395 
19396 {
19397 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
19398 
19399 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
19400 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
19401 		if (is_tracing_prog_type(prog_type)) {
19402 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
19403 			return -EINVAL;
19404 		}
19405 	}
19406 
19407 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
19408 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
19409 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
19410 			return -EINVAL;
19411 		}
19412 
19413 		if (is_tracing_prog_type(prog_type)) {
19414 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
19415 			return -EINVAL;
19416 		}
19417 	}
19418 
19419 	if (btf_record_has_field(map->record, BPF_TIMER)) {
19420 		if (is_tracing_prog_type(prog_type)) {
19421 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
19422 			return -EINVAL;
19423 		}
19424 	}
19425 
19426 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
19427 		if (is_tracing_prog_type(prog_type)) {
19428 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
19429 			return -EINVAL;
19430 		}
19431 	}
19432 
19433 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
19434 	    !bpf_offload_prog_map_match(prog, map)) {
19435 		verbose(env, "offload device mismatch between prog and map\n");
19436 		return -EINVAL;
19437 	}
19438 
19439 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
19440 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
19441 		return -EINVAL;
19442 	}
19443 
19444 	if (prog->sleepable)
19445 		switch (map->map_type) {
19446 		case BPF_MAP_TYPE_HASH:
19447 		case BPF_MAP_TYPE_LRU_HASH:
19448 		case BPF_MAP_TYPE_ARRAY:
19449 		case BPF_MAP_TYPE_PERCPU_HASH:
19450 		case BPF_MAP_TYPE_PERCPU_ARRAY:
19451 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
19452 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
19453 		case BPF_MAP_TYPE_HASH_OF_MAPS:
19454 		case BPF_MAP_TYPE_RINGBUF:
19455 		case BPF_MAP_TYPE_USER_RINGBUF:
19456 		case BPF_MAP_TYPE_INODE_STORAGE:
19457 		case BPF_MAP_TYPE_SK_STORAGE:
19458 		case BPF_MAP_TYPE_TASK_STORAGE:
19459 		case BPF_MAP_TYPE_CGRP_STORAGE:
19460 		case BPF_MAP_TYPE_QUEUE:
19461 		case BPF_MAP_TYPE_STACK:
19462 		case BPF_MAP_TYPE_ARENA:
19463 			break;
19464 		default:
19465 			verbose(env,
19466 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
19467 			return -EINVAL;
19468 		}
19469 
19470 	if (bpf_map_is_cgroup_storage(map) &&
19471 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
19472 		verbose(env, "only one cgroup storage of each type is allowed\n");
19473 		return -EBUSY;
19474 	}
19475 
19476 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
19477 		if (env->prog->aux->arena) {
19478 			verbose(env, "Only one arena per program\n");
19479 			return -EBUSY;
19480 		}
19481 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
19482 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
19483 			return -EPERM;
19484 		}
19485 		if (!env->prog->jit_requested) {
19486 			verbose(env, "JIT is required to use arena\n");
19487 			return -EOPNOTSUPP;
19488 		}
19489 		if (!bpf_jit_supports_arena()) {
19490 			verbose(env, "JIT doesn't support arena\n");
19491 			return -EOPNOTSUPP;
19492 		}
19493 		env->prog->aux->arena = (void *)map;
19494 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
19495 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
19496 			return -EINVAL;
19497 		}
19498 	}
19499 
19500 	return 0;
19501 }
19502 
19503 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
19504 {
19505 	int i, err;
19506 
19507 	/* check whether we recorded this map already */
19508 	for (i = 0; i < env->used_map_cnt; i++)
19509 		if (env->used_maps[i] == map)
19510 			return i;
19511 
19512 	if (env->used_map_cnt >= MAX_USED_MAPS) {
19513 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
19514 			MAX_USED_MAPS);
19515 		return -E2BIG;
19516 	}
19517 
19518 	err = check_map_prog_compatibility(env, map, env->prog);
19519 	if (err)
19520 		return err;
19521 
19522 	if (env->prog->sleepable)
19523 		atomic64_inc(&map->sleepable_refcnt);
19524 
19525 	/* hold the map. If the program is rejected by verifier,
19526 	 * the map will be released by release_maps() or it
19527 	 * will be used by the valid program until it's unloaded
19528 	 * and all maps are released in bpf_free_used_maps()
19529 	 */
19530 	bpf_map_inc(map);
19531 
19532 	env->used_maps[env->used_map_cnt++] = map;
19533 
19534 	return env->used_map_cnt - 1;
19535 }
19536 
19537 /* Add map behind fd to used maps list, if it's not already there, and return
19538  * its index.
19539  * Returns <0 on error, or >= 0 index, on success.
19540  */
19541 static int add_used_map(struct bpf_verifier_env *env, int fd)
19542 {
19543 	struct bpf_map *map;
19544 	CLASS(fd, f)(fd);
19545 
19546 	map = __bpf_map_get(f);
19547 	if (IS_ERR(map)) {
19548 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
19549 		return PTR_ERR(map);
19550 	}
19551 
19552 	return __add_used_map(env, map);
19553 }
19554 
19555 /* find and rewrite pseudo imm in ld_imm64 instructions:
19556  *
19557  * 1. if it accesses map FD, replace it with actual map pointer.
19558  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
19559  *
19560  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
19561  */
19562 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
19563 {
19564 	struct bpf_insn *insn = env->prog->insnsi;
19565 	int insn_cnt = env->prog->len;
19566 	int i, err;
19567 
19568 	err = bpf_prog_calc_tag(env->prog);
19569 	if (err)
19570 		return err;
19571 
19572 	for (i = 0; i < insn_cnt; i++, insn++) {
19573 		if (BPF_CLASS(insn->code) == BPF_LDX &&
19574 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
19575 		    insn->imm != 0)) {
19576 			verbose(env, "BPF_LDX uses reserved fields\n");
19577 			return -EINVAL;
19578 		}
19579 
19580 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
19581 			struct bpf_insn_aux_data *aux;
19582 			struct bpf_map *map;
19583 			int map_idx;
19584 			u64 addr;
19585 			u32 fd;
19586 
19587 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
19588 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
19589 			    insn[1].off != 0) {
19590 				verbose(env, "invalid bpf_ld_imm64 insn\n");
19591 				return -EINVAL;
19592 			}
19593 
19594 			if (insn[0].src_reg == 0)
19595 				/* valid generic load 64-bit imm */
19596 				goto next_insn;
19597 
19598 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
19599 				aux = &env->insn_aux_data[i];
19600 				err = check_pseudo_btf_id(env, insn, aux);
19601 				if (err)
19602 					return err;
19603 				goto next_insn;
19604 			}
19605 
19606 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
19607 				aux = &env->insn_aux_data[i];
19608 				aux->ptr_type = PTR_TO_FUNC;
19609 				goto next_insn;
19610 			}
19611 
19612 			/* In final convert_pseudo_ld_imm64() step, this is
19613 			 * converted into regular 64-bit imm load insn.
19614 			 */
19615 			switch (insn[0].src_reg) {
19616 			case BPF_PSEUDO_MAP_VALUE:
19617 			case BPF_PSEUDO_MAP_IDX_VALUE:
19618 				break;
19619 			case BPF_PSEUDO_MAP_FD:
19620 			case BPF_PSEUDO_MAP_IDX:
19621 				if (insn[1].imm == 0)
19622 					break;
19623 				fallthrough;
19624 			default:
19625 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
19626 				return -EINVAL;
19627 			}
19628 
19629 			switch (insn[0].src_reg) {
19630 			case BPF_PSEUDO_MAP_IDX_VALUE:
19631 			case BPF_PSEUDO_MAP_IDX:
19632 				if (bpfptr_is_null(env->fd_array)) {
19633 					verbose(env, "fd_idx without fd_array is invalid\n");
19634 					return -EPROTO;
19635 				}
19636 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
19637 							    insn[0].imm * sizeof(fd),
19638 							    sizeof(fd)))
19639 					return -EFAULT;
19640 				break;
19641 			default:
19642 				fd = insn[0].imm;
19643 				break;
19644 			}
19645 
19646 			map_idx = add_used_map(env, fd);
19647 			if (map_idx < 0)
19648 				return map_idx;
19649 			map = env->used_maps[map_idx];
19650 
19651 			aux = &env->insn_aux_data[i];
19652 			aux->map_index = map_idx;
19653 
19654 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
19655 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
19656 				addr = (unsigned long)map;
19657 			} else {
19658 				u32 off = insn[1].imm;
19659 
19660 				if (off >= BPF_MAX_VAR_OFF) {
19661 					verbose(env, "direct value offset of %u is not allowed\n", off);
19662 					return -EINVAL;
19663 				}
19664 
19665 				if (!map->ops->map_direct_value_addr) {
19666 					verbose(env, "no direct value access support for this map type\n");
19667 					return -EINVAL;
19668 				}
19669 
19670 				err = map->ops->map_direct_value_addr(map, &addr, off);
19671 				if (err) {
19672 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
19673 						map->value_size, off);
19674 					return err;
19675 				}
19676 
19677 				aux->map_off = off;
19678 				addr += off;
19679 			}
19680 
19681 			insn[0].imm = (u32)addr;
19682 			insn[1].imm = addr >> 32;
19683 
19684 next_insn:
19685 			insn++;
19686 			i++;
19687 			continue;
19688 		}
19689 
19690 		/* Basic sanity check before we invest more work here. */
19691 		if (!bpf_opcode_in_insntable(insn->code)) {
19692 			verbose(env, "unknown opcode %02x\n", insn->code);
19693 			return -EINVAL;
19694 		}
19695 	}
19696 
19697 	/* now all pseudo BPF_LD_IMM64 instructions load valid
19698 	 * 'struct bpf_map *' into a register instead of user map_fd.
19699 	 * These pointers will be used later by verifier to validate map access.
19700 	 */
19701 	return 0;
19702 }
19703 
19704 /* drop refcnt of maps used by the rejected program */
19705 static void release_maps(struct bpf_verifier_env *env)
19706 {
19707 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
19708 			     env->used_map_cnt);
19709 }
19710 
19711 /* drop refcnt of maps used by the rejected program */
19712 static void release_btfs(struct bpf_verifier_env *env)
19713 {
19714 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
19715 }
19716 
19717 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
19718 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
19719 {
19720 	struct bpf_insn *insn = env->prog->insnsi;
19721 	int insn_cnt = env->prog->len;
19722 	int i;
19723 
19724 	for (i = 0; i < insn_cnt; i++, insn++) {
19725 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
19726 			continue;
19727 		if (insn->src_reg == BPF_PSEUDO_FUNC)
19728 			continue;
19729 		insn->src_reg = 0;
19730 	}
19731 }
19732 
19733 /* single env->prog->insni[off] instruction was replaced with the range
19734  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
19735  * [0, off) and [off, end) to new locations, so the patched range stays zero
19736  */
19737 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
19738 				 struct bpf_insn_aux_data *new_data,
19739 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
19740 {
19741 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
19742 	struct bpf_insn *insn = new_prog->insnsi;
19743 	u32 old_seen = old_data[off].seen;
19744 	u32 prog_len;
19745 	int i;
19746 
19747 	/* aux info at OFF always needs adjustment, no matter fast path
19748 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
19749 	 * original insn at old prog.
19750 	 */
19751 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
19752 
19753 	if (cnt == 1)
19754 		return;
19755 	prog_len = new_prog->len;
19756 
19757 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
19758 	memcpy(new_data + off + cnt - 1, old_data + off,
19759 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
19760 	for (i = off; i < off + cnt - 1; i++) {
19761 		/* Expand insni[off]'s seen count to the patched range. */
19762 		new_data[i].seen = old_seen;
19763 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
19764 	}
19765 	env->insn_aux_data = new_data;
19766 	vfree(old_data);
19767 }
19768 
19769 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
19770 {
19771 	int i;
19772 
19773 	if (len == 1)
19774 		return;
19775 	/* NOTE: fake 'exit' subprog should be updated as well. */
19776 	for (i = 0; i <= env->subprog_cnt; i++) {
19777 		if (env->subprog_info[i].start <= off)
19778 			continue;
19779 		env->subprog_info[i].start += len - 1;
19780 	}
19781 }
19782 
19783 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
19784 {
19785 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
19786 	int i, sz = prog->aux->size_poke_tab;
19787 	struct bpf_jit_poke_descriptor *desc;
19788 
19789 	for (i = 0; i < sz; i++) {
19790 		desc = &tab[i];
19791 		if (desc->insn_idx <= off)
19792 			continue;
19793 		desc->insn_idx += len - 1;
19794 	}
19795 }
19796 
19797 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
19798 					    const struct bpf_insn *patch, u32 len)
19799 {
19800 	struct bpf_prog *new_prog;
19801 	struct bpf_insn_aux_data *new_data = NULL;
19802 
19803 	if (len > 1) {
19804 		new_data = vzalloc(array_size(env->prog->len + len - 1,
19805 					      sizeof(struct bpf_insn_aux_data)));
19806 		if (!new_data)
19807 			return NULL;
19808 	}
19809 
19810 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
19811 	if (IS_ERR(new_prog)) {
19812 		if (PTR_ERR(new_prog) == -ERANGE)
19813 			verbose(env,
19814 				"insn %d cannot be patched due to 16-bit range\n",
19815 				env->insn_aux_data[off].orig_idx);
19816 		vfree(new_data);
19817 		return NULL;
19818 	}
19819 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
19820 	adjust_subprog_starts(env, off, len);
19821 	adjust_poke_descs(new_prog, off, len);
19822 	return new_prog;
19823 }
19824 
19825 /*
19826  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
19827  * jump offset by 'delta'.
19828  */
19829 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
19830 {
19831 	struct bpf_insn *insn = prog->insnsi;
19832 	u32 insn_cnt = prog->len, i;
19833 	s32 imm;
19834 	s16 off;
19835 
19836 	for (i = 0; i < insn_cnt; i++, insn++) {
19837 		u8 code = insn->code;
19838 
19839 		if (tgt_idx <= i && i < tgt_idx + delta)
19840 			continue;
19841 
19842 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
19843 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
19844 			continue;
19845 
19846 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
19847 			if (i + 1 + insn->imm != tgt_idx)
19848 				continue;
19849 			if (check_add_overflow(insn->imm, delta, &imm))
19850 				return -ERANGE;
19851 			insn->imm = imm;
19852 		} else {
19853 			if (i + 1 + insn->off != tgt_idx)
19854 				continue;
19855 			if (check_add_overflow(insn->off, delta, &off))
19856 				return -ERANGE;
19857 			insn->off = off;
19858 		}
19859 	}
19860 	return 0;
19861 }
19862 
19863 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
19864 					      u32 off, u32 cnt)
19865 {
19866 	int i, j;
19867 
19868 	/* find first prog starting at or after off (first to remove) */
19869 	for (i = 0; i < env->subprog_cnt; i++)
19870 		if (env->subprog_info[i].start >= off)
19871 			break;
19872 	/* find first prog starting at or after off + cnt (first to stay) */
19873 	for (j = i; j < env->subprog_cnt; j++)
19874 		if (env->subprog_info[j].start >= off + cnt)
19875 			break;
19876 	/* if j doesn't start exactly at off + cnt, we are just removing
19877 	 * the front of previous prog
19878 	 */
19879 	if (env->subprog_info[j].start != off + cnt)
19880 		j--;
19881 
19882 	if (j > i) {
19883 		struct bpf_prog_aux *aux = env->prog->aux;
19884 		int move;
19885 
19886 		/* move fake 'exit' subprog as well */
19887 		move = env->subprog_cnt + 1 - j;
19888 
19889 		memmove(env->subprog_info + i,
19890 			env->subprog_info + j,
19891 			sizeof(*env->subprog_info) * move);
19892 		env->subprog_cnt -= j - i;
19893 
19894 		/* remove func_info */
19895 		if (aux->func_info) {
19896 			move = aux->func_info_cnt - j;
19897 
19898 			memmove(aux->func_info + i,
19899 				aux->func_info + j,
19900 				sizeof(*aux->func_info) * move);
19901 			aux->func_info_cnt -= j - i;
19902 			/* func_info->insn_off is set after all code rewrites,
19903 			 * in adjust_btf_func() - no need to adjust
19904 			 */
19905 		}
19906 	} else {
19907 		/* convert i from "first prog to remove" to "first to adjust" */
19908 		if (env->subprog_info[i].start == off)
19909 			i++;
19910 	}
19911 
19912 	/* update fake 'exit' subprog as well */
19913 	for (; i <= env->subprog_cnt; i++)
19914 		env->subprog_info[i].start -= cnt;
19915 
19916 	return 0;
19917 }
19918 
19919 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
19920 				      u32 cnt)
19921 {
19922 	struct bpf_prog *prog = env->prog;
19923 	u32 i, l_off, l_cnt, nr_linfo;
19924 	struct bpf_line_info *linfo;
19925 
19926 	nr_linfo = prog->aux->nr_linfo;
19927 	if (!nr_linfo)
19928 		return 0;
19929 
19930 	linfo = prog->aux->linfo;
19931 
19932 	/* find first line info to remove, count lines to be removed */
19933 	for (i = 0; i < nr_linfo; i++)
19934 		if (linfo[i].insn_off >= off)
19935 			break;
19936 
19937 	l_off = i;
19938 	l_cnt = 0;
19939 	for (; i < nr_linfo; i++)
19940 		if (linfo[i].insn_off < off + cnt)
19941 			l_cnt++;
19942 		else
19943 			break;
19944 
19945 	/* First live insn doesn't match first live linfo, it needs to "inherit"
19946 	 * last removed linfo.  prog is already modified, so prog->len == off
19947 	 * means no live instructions after (tail of the program was removed).
19948 	 */
19949 	if (prog->len != off && l_cnt &&
19950 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
19951 		l_cnt--;
19952 		linfo[--i].insn_off = off + cnt;
19953 	}
19954 
19955 	/* remove the line info which refer to the removed instructions */
19956 	if (l_cnt) {
19957 		memmove(linfo + l_off, linfo + i,
19958 			sizeof(*linfo) * (nr_linfo - i));
19959 
19960 		prog->aux->nr_linfo -= l_cnt;
19961 		nr_linfo = prog->aux->nr_linfo;
19962 	}
19963 
19964 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
19965 	for (i = l_off; i < nr_linfo; i++)
19966 		linfo[i].insn_off -= cnt;
19967 
19968 	/* fix up all subprogs (incl. 'exit') which start >= off */
19969 	for (i = 0; i <= env->subprog_cnt; i++)
19970 		if (env->subprog_info[i].linfo_idx > l_off) {
19971 			/* program may have started in the removed region but
19972 			 * may not be fully removed
19973 			 */
19974 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
19975 				env->subprog_info[i].linfo_idx -= l_cnt;
19976 			else
19977 				env->subprog_info[i].linfo_idx = l_off;
19978 		}
19979 
19980 	return 0;
19981 }
19982 
19983 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
19984 {
19985 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19986 	unsigned int orig_prog_len = env->prog->len;
19987 	int err;
19988 
19989 	if (bpf_prog_is_offloaded(env->prog->aux))
19990 		bpf_prog_offload_remove_insns(env, off, cnt);
19991 
19992 	err = bpf_remove_insns(env->prog, off, cnt);
19993 	if (err)
19994 		return err;
19995 
19996 	err = adjust_subprog_starts_after_remove(env, off, cnt);
19997 	if (err)
19998 		return err;
19999 
20000 	err = bpf_adj_linfo_after_remove(env, off, cnt);
20001 	if (err)
20002 		return err;
20003 
20004 	memmove(aux_data + off,	aux_data + off + cnt,
20005 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
20006 
20007 	return 0;
20008 }
20009 
20010 /* The verifier does more data flow analysis than llvm and will not
20011  * explore branches that are dead at run time. Malicious programs can
20012  * have dead code too. Therefore replace all dead at-run-time code
20013  * with 'ja -1'.
20014  *
20015  * Just nops are not optimal, e.g. if they would sit at the end of the
20016  * program and through another bug we would manage to jump there, then
20017  * we'd execute beyond program memory otherwise. Returning exception
20018  * code also wouldn't work since we can have subprogs where the dead
20019  * code could be located.
20020  */
20021 static void sanitize_dead_code(struct bpf_verifier_env *env)
20022 {
20023 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20024 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
20025 	struct bpf_insn *insn = env->prog->insnsi;
20026 	const int insn_cnt = env->prog->len;
20027 	int i;
20028 
20029 	for (i = 0; i < insn_cnt; i++) {
20030 		if (aux_data[i].seen)
20031 			continue;
20032 		memcpy(insn + i, &trap, sizeof(trap));
20033 		aux_data[i].zext_dst = false;
20034 	}
20035 }
20036 
20037 static bool insn_is_cond_jump(u8 code)
20038 {
20039 	u8 op;
20040 
20041 	op = BPF_OP(code);
20042 	if (BPF_CLASS(code) == BPF_JMP32)
20043 		return op != BPF_JA;
20044 
20045 	if (BPF_CLASS(code) != BPF_JMP)
20046 		return false;
20047 
20048 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
20049 }
20050 
20051 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
20052 {
20053 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20054 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
20055 	struct bpf_insn *insn = env->prog->insnsi;
20056 	const int insn_cnt = env->prog->len;
20057 	int i;
20058 
20059 	for (i = 0; i < insn_cnt; i++, insn++) {
20060 		if (!insn_is_cond_jump(insn->code))
20061 			continue;
20062 
20063 		if (!aux_data[i + 1].seen)
20064 			ja.off = insn->off;
20065 		else if (!aux_data[i + 1 + insn->off].seen)
20066 			ja.off = 0;
20067 		else
20068 			continue;
20069 
20070 		if (bpf_prog_is_offloaded(env->prog->aux))
20071 			bpf_prog_offload_replace_insn(env, i, &ja);
20072 
20073 		memcpy(insn, &ja, sizeof(ja));
20074 	}
20075 }
20076 
20077 static int opt_remove_dead_code(struct bpf_verifier_env *env)
20078 {
20079 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20080 	int insn_cnt = env->prog->len;
20081 	int i, err;
20082 
20083 	for (i = 0; i < insn_cnt; i++) {
20084 		int j;
20085 
20086 		j = 0;
20087 		while (i + j < insn_cnt && !aux_data[i + j].seen)
20088 			j++;
20089 		if (!j)
20090 			continue;
20091 
20092 		err = verifier_remove_insns(env, i, j);
20093 		if (err)
20094 			return err;
20095 		insn_cnt = env->prog->len;
20096 	}
20097 
20098 	return 0;
20099 }
20100 
20101 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
20102 
20103 static int opt_remove_nops(struct bpf_verifier_env *env)
20104 {
20105 	const struct bpf_insn ja = NOP;
20106 	struct bpf_insn *insn = env->prog->insnsi;
20107 	int insn_cnt = env->prog->len;
20108 	int i, err;
20109 
20110 	for (i = 0; i < insn_cnt; i++) {
20111 		if (memcmp(&insn[i], &ja, sizeof(ja)))
20112 			continue;
20113 
20114 		err = verifier_remove_insns(env, i, 1);
20115 		if (err)
20116 			return err;
20117 		insn_cnt--;
20118 		i--;
20119 	}
20120 
20121 	return 0;
20122 }
20123 
20124 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
20125 					 const union bpf_attr *attr)
20126 {
20127 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
20128 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
20129 	int i, patch_len, delta = 0, len = env->prog->len;
20130 	struct bpf_insn *insns = env->prog->insnsi;
20131 	struct bpf_prog *new_prog;
20132 	bool rnd_hi32;
20133 
20134 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
20135 	zext_patch[1] = BPF_ZEXT_REG(0);
20136 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
20137 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
20138 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
20139 	for (i = 0; i < len; i++) {
20140 		int adj_idx = i + delta;
20141 		struct bpf_insn insn;
20142 		int load_reg;
20143 
20144 		insn = insns[adj_idx];
20145 		load_reg = insn_def_regno(&insn);
20146 		if (!aux[adj_idx].zext_dst) {
20147 			u8 code, class;
20148 			u32 imm_rnd;
20149 
20150 			if (!rnd_hi32)
20151 				continue;
20152 
20153 			code = insn.code;
20154 			class = BPF_CLASS(code);
20155 			if (load_reg == -1)
20156 				continue;
20157 
20158 			/* NOTE: arg "reg" (the fourth one) is only used for
20159 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
20160 			 *       here.
20161 			 */
20162 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
20163 				if (class == BPF_LD &&
20164 				    BPF_MODE(code) == BPF_IMM)
20165 					i++;
20166 				continue;
20167 			}
20168 
20169 			/* ctx load could be transformed into wider load. */
20170 			if (class == BPF_LDX &&
20171 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
20172 				continue;
20173 
20174 			imm_rnd = get_random_u32();
20175 			rnd_hi32_patch[0] = insn;
20176 			rnd_hi32_patch[1].imm = imm_rnd;
20177 			rnd_hi32_patch[3].dst_reg = load_reg;
20178 			patch = rnd_hi32_patch;
20179 			patch_len = 4;
20180 			goto apply_patch_buffer;
20181 		}
20182 
20183 		/* Add in an zero-extend instruction if a) the JIT has requested
20184 		 * it or b) it's a CMPXCHG.
20185 		 *
20186 		 * The latter is because: BPF_CMPXCHG always loads a value into
20187 		 * R0, therefore always zero-extends. However some archs'
20188 		 * equivalent instruction only does this load when the
20189 		 * comparison is successful. This detail of CMPXCHG is
20190 		 * orthogonal to the general zero-extension behaviour of the
20191 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
20192 		 */
20193 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
20194 			continue;
20195 
20196 		/* Zero-extension is done by the caller. */
20197 		if (bpf_pseudo_kfunc_call(&insn))
20198 			continue;
20199 
20200 		if (WARN_ON(load_reg == -1)) {
20201 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
20202 			return -EFAULT;
20203 		}
20204 
20205 		zext_patch[0] = insn;
20206 		zext_patch[1].dst_reg = load_reg;
20207 		zext_patch[1].src_reg = load_reg;
20208 		patch = zext_patch;
20209 		patch_len = 2;
20210 apply_patch_buffer:
20211 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
20212 		if (!new_prog)
20213 			return -ENOMEM;
20214 		env->prog = new_prog;
20215 		insns = new_prog->insnsi;
20216 		aux = env->insn_aux_data;
20217 		delta += patch_len - 1;
20218 	}
20219 
20220 	return 0;
20221 }
20222 
20223 /* convert load instructions that access fields of a context type into a
20224  * sequence of instructions that access fields of the underlying structure:
20225  *     struct __sk_buff    -> struct sk_buff
20226  *     struct bpf_sock_ops -> struct sock
20227  */
20228 static int convert_ctx_accesses(struct bpf_verifier_env *env)
20229 {
20230 	struct bpf_subprog_info *subprogs = env->subprog_info;
20231 	const struct bpf_verifier_ops *ops = env->ops;
20232 	int i, cnt, size, ctx_field_size, delta = 0, epilogue_cnt = 0;
20233 	const int insn_cnt = env->prog->len;
20234 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
20235 	struct bpf_insn *insn_buf = env->insn_buf;
20236 	struct bpf_insn *insn;
20237 	u32 target_size, size_default, off;
20238 	struct bpf_prog *new_prog;
20239 	enum bpf_access_type type;
20240 	bool is_narrower_load;
20241 	int epilogue_idx = 0;
20242 
20243 	if (ops->gen_epilogue) {
20244 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
20245 						 -(subprogs[0].stack_depth + 8));
20246 		if (epilogue_cnt >= INSN_BUF_SIZE) {
20247 			verbose(env, "bpf verifier is misconfigured\n");
20248 			return -EINVAL;
20249 		} else if (epilogue_cnt) {
20250 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
20251 			cnt = 0;
20252 			subprogs[0].stack_depth += 8;
20253 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
20254 						      -subprogs[0].stack_depth);
20255 			insn_buf[cnt++] = env->prog->insnsi[0];
20256 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
20257 			if (!new_prog)
20258 				return -ENOMEM;
20259 			env->prog = new_prog;
20260 			delta += cnt - 1;
20261 		}
20262 	}
20263 
20264 	if (ops->gen_prologue || env->seen_direct_write) {
20265 		if (!ops->gen_prologue) {
20266 			verbose(env, "bpf verifier is misconfigured\n");
20267 			return -EINVAL;
20268 		}
20269 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
20270 					env->prog);
20271 		if (cnt >= INSN_BUF_SIZE) {
20272 			verbose(env, "bpf verifier is misconfigured\n");
20273 			return -EINVAL;
20274 		} else if (cnt) {
20275 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
20276 			if (!new_prog)
20277 				return -ENOMEM;
20278 
20279 			env->prog = new_prog;
20280 			delta += cnt - 1;
20281 		}
20282 	}
20283 
20284 	if (delta)
20285 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
20286 
20287 	if (bpf_prog_is_offloaded(env->prog->aux))
20288 		return 0;
20289 
20290 	insn = env->prog->insnsi + delta;
20291 
20292 	for (i = 0; i < insn_cnt; i++, insn++) {
20293 		bpf_convert_ctx_access_t convert_ctx_access;
20294 		u8 mode;
20295 
20296 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
20297 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
20298 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
20299 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
20300 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
20301 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
20302 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
20303 			type = BPF_READ;
20304 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
20305 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
20306 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
20307 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
20308 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
20309 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
20310 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
20311 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
20312 			type = BPF_WRITE;
20313 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
20314 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
20315 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
20316 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
20317 			env->prog->aux->num_exentries++;
20318 			continue;
20319 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
20320 			   epilogue_cnt &&
20321 			   i + delta < subprogs[1].start) {
20322 			/* Generate epilogue for the main prog */
20323 			if (epilogue_idx) {
20324 				/* jump back to the earlier generated epilogue */
20325 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
20326 				cnt = 1;
20327 			} else {
20328 				memcpy(insn_buf, epilogue_buf,
20329 				       epilogue_cnt * sizeof(*epilogue_buf));
20330 				cnt = epilogue_cnt;
20331 				/* epilogue_idx cannot be 0. It must have at
20332 				 * least one ctx ptr saving insn before the
20333 				 * epilogue.
20334 				 */
20335 				epilogue_idx = i + delta;
20336 			}
20337 			goto patch_insn_buf;
20338 		} else {
20339 			continue;
20340 		}
20341 
20342 		if (type == BPF_WRITE &&
20343 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
20344 			struct bpf_insn patch[] = {
20345 				*insn,
20346 				BPF_ST_NOSPEC(),
20347 			};
20348 
20349 			cnt = ARRAY_SIZE(patch);
20350 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
20351 			if (!new_prog)
20352 				return -ENOMEM;
20353 
20354 			delta    += cnt - 1;
20355 			env->prog = new_prog;
20356 			insn      = new_prog->insnsi + i + delta;
20357 			continue;
20358 		}
20359 
20360 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
20361 		case PTR_TO_CTX:
20362 			if (!ops->convert_ctx_access)
20363 				continue;
20364 			convert_ctx_access = ops->convert_ctx_access;
20365 			break;
20366 		case PTR_TO_SOCKET:
20367 		case PTR_TO_SOCK_COMMON:
20368 			convert_ctx_access = bpf_sock_convert_ctx_access;
20369 			break;
20370 		case PTR_TO_TCP_SOCK:
20371 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
20372 			break;
20373 		case PTR_TO_XDP_SOCK:
20374 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
20375 			break;
20376 		case PTR_TO_BTF_ID:
20377 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
20378 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
20379 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
20380 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
20381 		 * any faults for loads into such types. BPF_WRITE is disallowed
20382 		 * for this case.
20383 		 */
20384 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
20385 			if (type == BPF_READ) {
20386 				if (BPF_MODE(insn->code) == BPF_MEM)
20387 					insn->code = BPF_LDX | BPF_PROBE_MEM |
20388 						     BPF_SIZE((insn)->code);
20389 				else
20390 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
20391 						     BPF_SIZE((insn)->code);
20392 				env->prog->aux->num_exentries++;
20393 			}
20394 			continue;
20395 		case PTR_TO_ARENA:
20396 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
20397 				verbose(env, "sign extending loads from arena are not supported yet\n");
20398 				return -EOPNOTSUPP;
20399 			}
20400 			insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
20401 			env->prog->aux->num_exentries++;
20402 			continue;
20403 		default:
20404 			continue;
20405 		}
20406 
20407 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
20408 		size = BPF_LDST_BYTES(insn);
20409 		mode = BPF_MODE(insn->code);
20410 
20411 		/* If the read access is a narrower load of the field,
20412 		 * convert to a 4/8-byte load, to minimum program type specific
20413 		 * convert_ctx_access changes. If conversion is successful,
20414 		 * we will apply proper mask to the result.
20415 		 */
20416 		is_narrower_load = size < ctx_field_size;
20417 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
20418 		off = insn->off;
20419 		if (is_narrower_load) {
20420 			u8 size_code;
20421 
20422 			if (type == BPF_WRITE) {
20423 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
20424 				return -EINVAL;
20425 			}
20426 
20427 			size_code = BPF_H;
20428 			if (ctx_field_size == 4)
20429 				size_code = BPF_W;
20430 			else if (ctx_field_size == 8)
20431 				size_code = BPF_DW;
20432 
20433 			insn->off = off & ~(size_default - 1);
20434 			insn->code = BPF_LDX | BPF_MEM | size_code;
20435 		}
20436 
20437 		target_size = 0;
20438 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
20439 					 &target_size);
20440 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
20441 		    (ctx_field_size && !target_size)) {
20442 			verbose(env, "bpf verifier is misconfigured\n");
20443 			return -EINVAL;
20444 		}
20445 
20446 		if (is_narrower_load && size < target_size) {
20447 			u8 shift = bpf_ctx_narrow_access_offset(
20448 				off, size, size_default) * 8;
20449 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
20450 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
20451 				return -EINVAL;
20452 			}
20453 			if (ctx_field_size <= 4) {
20454 				if (shift)
20455 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
20456 									insn->dst_reg,
20457 									shift);
20458 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
20459 								(1 << size * 8) - 1);
20460 			} else {
20461 				if (shift)
20462 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
20463 									insn->dst_reg,
20464 									shift);
20465 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
20466 								(1ULL << size * 8) - 1);
20467 			}
20468 		}
20469 		if (mode == BPF_MEMSX)
20470 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
20471 						       insn->dst_reg, insn->dst_reg,
20472 						       size * 8, 0);
20473 
20474 patch_insn_buf:
20475 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20476 		if (!new_prog)
20477 			return -ENOMEM;
20478 
20479 		delta += cnt - 1;
20480 
20481 		/* keep walking new program and skip insns we just inserted */
20482 		env->prog = new_prog;
20483 		insn      = new_prog->insnsi + i + delta;
20484 	}
20485 
20486 	return 0;
20487 }
20488 
20489 static int jit_subprogs(struct bpf_verifier_env *env)
20490 {
20491 	struct bpf_prog *prog = env->prog, **func, *tmp;
20492 	int i, j, subprog_start, subprog_end = 0, len, subprog;
20493 	struct bpf_map *map_ptr;
20494 	struct bpf_insn *insn;
20495 	void *old_bpf_func;
20496 	int err, num_exentries;
20497 
20498 	if (env->subprog_cnt <= 1)
20499 		return 0;
20500 
20501 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
20502 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
20503 			continue;
20504 
20505 		/* Upon error here we cannot fall back to interpreter but
20506 		 * need a hard reject of the program. Thus -EFAULT is
20507 		 * propagated in any case.
20508 		 */
20509 		subprog = find_subprog(env, i + insn->imm + 1);
20510 		if (subprog < 0) {
20511 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
20512 				  i + insn->imm + 1);
20513 			return -EFAULT;
20514 		}
20515 		/* temporarily remember subprog id inside insn instead of
20516 		 * aux_data, since next loop will split up all insns into funcs
20517 		 */
20518 		insn->off = subprog;
20519 		/* remember original imm in case JIT fails and fallback
20520 		 * to interpreter will be needed
20521 		 */
20522 		env->insn_aux_data[i].call_imm = insn->imm;
20523 		/* point imm to __bpf_call_base+1 from JITs point of view */
20524 		insn->imm = 1;
20525 		if (bpf_pseudo_func(insn)) {
20526 #if defined(MODULES_VADDR)
20527 			u64 addr = MODULES_VADDR;
20528 #else
20529 			u64 addr = VMALLOC_START;
20530 #endif
20531 			/* jit (e.g. x86_64) may emit fewer instructions
20532 			 * if it learns a u32 imm is the same as a u64 imm.
20533 			 * Set close enough to possible prog address.
20534 			 */
20535 			insn[0].imm = (u32)addr;
20536 			insn[1].imm = addr >> 32;
20537 		}
20538 	}
20539 
20540 	err = bpf_prog_alloc_jited_linfo(prog);
20541 	if (err)
20542 		goto out_undo_insn;
20543 
20544 	err = -ENOMEM;
20545 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
20546 	if (!func)
20547 		goto out_undo_insn;
20548 
20549 	for (i = 0; i < env->subprog_cnt; i++) {
20550 		subprog_start = subprog_end;
20551 		subprog_end = env->subprog_info[i + 1].start;
20552 
20553 		len = subprog_end - subprog_start;
20554 		/* bpf_prog_run() doesn't call subprogs directly,
20555 		 * hence main prog stats include the runtime of subprogs.
20556 		 * subprogs don't have IDs and not reachable via prog_get_next_id
20557 		 * func[i]->stats will never be accessed and stays NULL
20558 		 */
20559 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
20560 		if (!func[i])
20561 			goto out_free;
20562 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
20563 		       len * sizeof(struct bpf_insn));
20564 		func[i]->type = prog->type;
20565 		func[i]->len = len;
20566 		if (bpf_prog_calc_tag(func[i]))
20567 			goto out_free;
20568 		func[i]->is_func = 1;
20569 		func[i]->sleepable = prog->sleepable;
20570 		func[i]->aux->func_idx = i;
20571 		/* Below members will be freed only at prog->aux */
20572 		func[i]->aux->btf = prog->aux->btf;
20573 		func[i]->aux->func_info = prog->aux->func_info;
20574 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
20575 		func[i]->aux->poke_tab = prog->aux->poke_tab;
20576 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
20577 
20578 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
20579 			struct bpf_jit_poke_descriptor *poke;
20580 
20581 			poke = &prog->aux->poke_tab[j];
20582 			if (poke->insn_idx < subprog_end &&
20583 			    poke->insn_idx >= subprog_start)
20584 				poke->aux = func[i]->aux;
20585 		}
20586 
20587 		func[i]->aux->name[0] = 'F';
20588 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
20589 		if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
20590 			func[i]->aux->jits_use_priv_stack = true;
20591 
20592 		func[i]->jit_requested = 1;
20593 		func[i]->blinding_requested = prog->blinding_requested;
20594 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
20595 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
20596 		func[i]->aux->linfo = prog->aux->linfo;
20597 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
20598 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
20599 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
20600 		func[i]->aux->arena = prog->aux->arena;
20601 		num_exentries = 0;
20602 		insn = func[i]->insnsi;
20603 		for (j = 0; j < func[i]->len; j++, insn++) {
20604 			if (BPF_CLASS(insn->code) == BPF_LDX &&
20605 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
20606 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
20607 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
20608 				num_exentries++;
20609 			if ((BPF_CLASS(insn->code) == BPF_STX ||
20610 			     BPF_CLASS(insn->code) == BPF_ST) &&
20611 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
20612 				num_exentries++;
20613 			if (BPF_CLASS(insn->code) == BPF_STX &&
20614 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
20615 				num_exentries++;
20616 		}
20617 		func[i]->aux->num_exentries = num_exentries;
20618 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
20619 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
20620 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
20621 		if (!i)
20622 			func[i]->aux->exception_boundary = env->seen_exception;
20623 		func[i] = bpf_int_jit_compile(func[i]);
20624 		if (!func[i]->jited) {
20625 			err = -ENOTSUPP;
20626 			goto out_free;
20627 		}
20628 		cond_resched();
20629 	}
20630 
20631 	/* at this point all bpf functions were successfully JITed
20632 	 * now populate all bpf_calls with correct addresses and
20633 	 * run last pass of JIT
20634 	 */
20635 	for (i = 0; i < env->subprog_cnt; i++) {
20636 		insn = func[i]->insnsi;
20637 		for (j = 0; j < func[i]->len; j++, insn++) {
20638 			if (bpf_pseudo_func(insn)) {
20639 				subprog = insn->off;
20640 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
20641 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
20642 				continue;
20643 			}
20644 			if (!bpf_pseudo_call(insn))
20645 				continue;
20646 			subprog = insn->off;
20647 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
20648 		}
20649 
20650 		/* we use the aux data to keep a list of the start addresses
20651 		 * of the JITed images for each function in the program
20652 		 *
20653 		 * for some architectures, such as powerpc64, the imm field
20654 		 * might not be large enough to hold the offset of the start
20655 		 * address of the callee's JITed image from __bpf_call_base
20656 		 *
20657 		 * in such cases, we can lookup the start address of a callee
20658 		 * by using its subprog id, available from the off field of
20659 		 * the call instruction, as an index for this list
20660 		 */
20661 		func[i]->aux->func = func;
20662 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
20663 		func[i]->aux->real_func_cnt = env->subprog_cnt;
20664 	}
20665 	for (i = 0; i < env->subprog_cnt; i++) {
20666 		old_bpf_func = func[i]->bpf_func;
20667 		tmp = bpf_int_jit_compile(func[i]);
20668 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
20669 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
20670 			err = -ENOTSUPP;
20671 			goto out_free;
20672 		}
20673 		cond_resched();
20674 	}
20675 
20676 	/* finally lock prog and jit images for all functions and
20677 	 * populate kallsysm. Begin at the first subprogram, since
20678 	 * bpf_prog_load will add the kallsyms for the main program.
20679 	 */
20680 	for (i = 1; i < env->subprog_cnt; i++) {
20681 		err = bpf_prog_lock_ro(func[i]);
20682 		if (err)
20683 			goto out_free;
20684 	}
20685 
20686 	for (i = 1; i < env->subprog_cnt; i++)
20687 		bpf_prog_kallsyms_add(func[i]);
20688 
20689 	/* Last step: make now unused interpreter insns from main
20690 	 * prog consistent for later dump requests, so they can
20691 	 * later look the same as if they were interpreted only.
20692 	 */
20693 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
20694 		if (bpf_pseudo_func(insn)) {
20695 			insn[0].imm = env->insn_aux_data[i].call_imm;
20696 			insn[1].imm = insn->off;
20697 			insn->off = 0;
20698 			continue;
20699 		}
20700 		if (!bpf_pseudo_call(insn))
20701 			continue;
20702 		insn->off = env->insn_aux_data[i].call_imm;
20703 		subprog = find_subprog(env, i + insn->off + 1);
20704 		insn->imm = subprog;
20705 	}
20706 
20707 	prog->jited = 1;
20708 	prog->bpf_func = func[0]->bpf_func;
20709 	prog->jited_len = func[0]->jited_len;
20710 	prog->aux->extable = func[0]->aux->extable;
20711 	prog->aux->num_exentries = func[0]->aux->num_exentries;
20712 	prog->aux->func = func;
20713 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
20714 	prog->aux->real_func_cnt = env->subprog_cnt;
20715 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
20716 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
20717 	bpf_prog_jit_attempt_done(prog);
20718 	return 0;
20719 out_free:
20720 	/* We failed JIT'ing, so at this point we need to unregister poke
20721 	 * descriptors from subprogs, so that kernel is not attempting to
20722 	 * patch it anymore as we're freeing the subprog JIT memory.
20723 	 */
20724 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
20725 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
20726 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
20727 	}
20728 	/* At this point we're guaranteed that poke descriptors are not
20729 	 * live anymore. We can just unlink its descriptor table as it's
20730 	 * released with the main prog.
20731 	 */
20732 	for (i = 0; i < env->subprog_cnt; i++) {
20733 		if (!func[i])
20734 			continue;
20735 		func[i]->aux->poke_tab = NULL;
20736 		bpf_jit_free(func[i]);
20737 	}
20738 	kfree(func);
20739 out_undo_insn:
20740 	/* cleanup main prog to be interpreted */
20741 	prog->jit_requested = 0;
20742 	prog->blinding_requested = 0;
20743 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
20744 		if (!bpf_pseudo_call(insn))
20745 			continue;
20746 		insn->off = 0;
20747 		insn->imm = env->insn_aux_data[i].call_imm;
20748 	}
20749 	bpf_prog_jit_attempt_done(prog);
20750 	return err;
20751 }
20752 
20753 static int fixup_call_args(struct bpf_verifier_env *env)
20754 {
20755 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
20756 	struct bpf_prog *prog = env->prog;
20757 	struct bpf_insn *insn = prog->insnsi;
20758 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
20759 	int i, depth;
20760 #endif
20761 	int err = 0;
20762 
20763 	if (env->prog->jit_requested &&
20764 	    !bpf_prog_is_offloaded(env->prog->aux)) {
20765 		err = jit_subprogs(env);
20766 		if (err == 0)
20767 			return 0;
20768 		if (err == -EFAULT)
20769 			return err;
20770 	}
20771 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
20772 	if (has_kfunc_call) {
20773 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
20774 		return -EINVAL;
20775 	}
20776 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
20777 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
20778 		 * have to be rejected, since interpreter doesn't support them yet.
20779 		 */
20780 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
20781 		return -EINVAL;
20782 	}
20783 	for (i = 0; i < prog->len; i++, insn++) {
20784 		if (bpf_pseudo_func(insn)) {
20785 			/* When JIT fails the progs with callback calls
20786 			 * have to be rejected, since interpreter doesn't support them yet.
20787 			 */
20788 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
20789 			return -EINVAL;
20790 		}
20791 
20792 		if (!bpf_pseudo_call(insn))
20793 			continue;
20794 		depth = get_callee_stack_depth(env, insn, i);
20795 		if (depth < 0)
20796 			return depth;
20797 		bpf_patch_call_args(insn, depth);
20798 	}
20799 	err = 0;
20800 #endif
20801 	return err;
20802 }
20803 
20804 /* replace a generic kfunc with a specialized version if necessary */
20805 static void specialize_kfunc(struct bpf_verifier_env *env,
20806 			     u32 func_id, u16 offset, unsigned long *addr)
20807 {
20808 	struct bpf_prog *prog = env->prog;
20809 	bool seen_direct_write;
20810 	void *xdp_kfunc;
20811 	bool is_rdonly;
20812 
20813 	if (bpf_dev_bound_kfunc_id(func_id)) {
20814 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
20815 		if (xdp_kfunc) {
20816 			*addr = (unsigned long)xdp_kfunc;
20817 			return;
20818 		}
20819 		/* fallback to default kfunc when not supported by netdev */
20820 	}
20821 
20822 	if (offset)
20823 		return;
20824 
20825 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
20826 		seen_direct_write = env->seen_direct_write;
20827 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
20828 
20829 		if (is_rdonly)
20830 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
20831 
20832 		/* restore env->seen_direct_write to its original value, since
20833 		 * may_access_direct_pkt_data mutates it
20834 		 */
20835 		env->seen_direct_write = seen_direct_write;
20836 	}
20837 }
20838 
20839 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
20840 					    u16 struct_meta_reg,
20841 					    u16 node_offset_reg,
20842 					    struct bpf_insn *insn,
20843 					    struct bpf_insn *insn_buf,
20844 					    int *cnt)
20845 {
20846 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
20847 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
20848 
20849 	insn_buf[0] = addr[0];
20850 	insn_buf[1] = addr[1];
20851 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
20852 	insn_buf[3] = *insn;
20853 	*cnt = 4;
20854 }
20855 
20856 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
20857 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
20858 {
20859 	const struct bpf_kfunc_desc *desc;
20860 
20861 	if (!insn->imm) {
20862 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
20863 		return -EINVAL;
20864 	}
20865 
20866 	*cnt = 0;
20867 
20868 	/* insn->imm has the btf func_id. Replace it with an offset relative to
20869 	 * __bpf_call_base, unless the JIT needs to call functions that are
20870 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
20871 	 */
20872 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
20873 	if (!desc) {
20874 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
20875 			insn->imm);
20876 		return -EFAULT;
20877 	}
20878 
20879 	if (!bpf_jit_supports_far_kfunc_call())
20880 		insn->imm = BPF_CALL_IMM(desc->addr);
20881 	if (insn->off)
20882 		return 0;
20883 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
20884 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
20885 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20886 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
20887 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
20888 
20889 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
20890 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
20891 				insn_idx);
20892 			return -EFAULT;
20893 		}
20894 
20895 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
20896 		insn_buf[1] = addr[0];
20897 		insn_buf[2] = addr[1];
20898 		insn_buf[3] = *insn;
20899 		*cnt = 4;
20900 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
20901 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
20902 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
20903 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20904 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
20905 
20906 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
20907 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
20908 				insn_idx);
20909 			return -EFAULT;
20910 		}
20911 
20912 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
20913 		    !kptr_struct_meta) {
20914 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
20915 				insn_idx);
20916 			return -EFAULT;
20917 		}
20918 
20919 		insn_buf[0] = addr[0];
20920 		insn_buf[1] = addr[1];
20921 		insn_buf[2] = *insn;
20922 		*cnt = 3;
20923 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
20924 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
20925 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
20926 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20927 		int struct_meta_reg = BPF_REG_3;
20928 		int node_offset_reg = BPF_REG_4;
20929 
20930 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
20931 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
20932 			struct_meta_reg = BPF_REG_4;
20933 			node_offset_reg = BPF_REG_5;
20934 		}
20935 
20936 		if (!kptr_struct_meta) {
20937 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
20938 				insn_idx);
20939 			return -EFAULT;
20940 		}
20941 
20942 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
20943 						node_offset_reg, insn, insn_buf, cnt);
20944 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
20945 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
20946 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
20947 		*cnt = 1;
20948 	} else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) {
20949 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) };
20950 
20951 		insn_buf[0] = ld_addrs[0];
20952 		insn_buf[1] = ld_addrs[1];
20953 		insn_buf[2] = *insn;
20954 		*cnt = 3;
20955 	}
20956 	return 0;
20957 }
20958 
20959 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
20960 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
20961 {
20962 	struct bpf_subprog_info *info = env->subprog_info;
20963 	int cnt = env->subprog_cnt;
20964 	struct bpf_prog *prog;
20965 
20966 	/* We only reserve one slot for hidden subprogs in subprog_info. */
20967 	if (env->hidden_subprog_cnt) {
20968 		verbose(env, "verifier internal error: only one hidden subprog supported\n");
20969 		return -EFAULT;
20970 	}
20971 	/* We're not patching any existing instruction, just appending the new
20972 	 * ones for the hidden subprog. Hence all of the adjustment operations
20973 	 * in bpf_patch_insn_data are no-ops.
20974 	 */
20975 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
20976 	if (!prog)
20977 		return -ENOMEM;
20978 	env->prog = prog;
20979 	info[cnt + 1].start = info[cnt].start;
20980 	info[cnt].start = prog->len - len + 1;
20981 	env->subprog_cnt++;
20982 	env->hidden_subprog_cnt++;
20983 	return 0;
20984 }
20985 
20986 /* Do various post-verification rewrites in a single program pass.
20987  * These rewrites simplify JIT and interpreter implementations.
20988  */
20989 static int do_misc_fixups(struct bpf_verifier_env *env)
20990 {
20991 	struct bpf_prog *prog = env->prog;
20992 	enum bpf_attach_type eatype = prog->expected_attach_type;
20993 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
20994 	struct bpf_insn *insn = prog->insnsi;
20995 	const struct bpf_func_proto *fn;
20996 	const int insn_cnt = prog->len;
20997 	const struct bpf_map_ops *ops;
20998 	struct bpf_insn_aux_data *aux;
20999 	struct bpf_insn *insn_buf = env->insn_buf;
21000 	struct bpf_prog *new_prog;
21001 	struct bpf_map *map_ptr;
21002 	int i, ret, cnt, delta = 0, cur_subprog = 0;
21003 	struct bpf_subprog_info *subprogs = env->subprog_info;
21004 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
21005 	u16 stack_depth_extra = 0;
21006 
21007 	if (env->seen_exception && !env->exception_callback_subprog) {
21008 		struct bpf_insn patch[] = {
21009 			env->prog->insnsi[insn_cnt - 1],
21010 			BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
21011 			BPF_EXIT_INSN(),
21012 		};
21013 
21014 		ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
21015 		if (ret < 0)
21016 			return ret;
21017 		prog = env->prog;
21018 		insn = prog->insnsi;
21019 
21020 		env->exception_callback_subprog = env->subprog_cnt - 1;
21021 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
21022 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
21023 	}
21024 
21025 	for (i = 0; i < insn_cnt;) {
21026 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
21027 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
21028 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
21029 				/* convert to 32-bit mov that clears upper 32-bit */
21030 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
21031 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
21032 				insn->off = 0;
21033 				insn->imm = 0;
21034 			} /* cast from as(0) to as(1) should be handled by JIT */
21035 			goto next_insn;
21036 		}
21037 
21038 		if (env->insn_aux_data[i + delta].needs_zext)
21039 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
21040 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
21041 
21042 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
21043 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
21044 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
21045 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
21046 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
21047 		    insn->off == 1 && insn->imm == -1) {
21048 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
21049 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
21050 			struct bpf_insn *patchlet;
21051 			struct bpf_insn chk_and_sdiv[] = {
21052 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21053 					     BPF_NEG | BPF_K, insn->dst_reg,
21054 					     0, 0, 0),
21055 			};
21056 			struct bpf_insn chk_and_smod[] = {
21057 				BPF_MOV32_IMM(insn->dst_reg, 0),
21058 			};
21059 
21060 			patchlet = isdiv ? chk_and_sdiv : chk_and_smod;
21061 			cnt = isdiv ? ARRAY_SIZE(chk_and_sdiv) : ARRAY_SIZE(chk_and_smod);
21062 
21063 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
21064 			if (!new_prog)
21065 				return -ENOMEM;
21066 
21067 			delta    += cnt - 1;
21068 			env->prog = prog = new_prog;
21069 			insn      = new_prog->insnsi + i + delta;
21070 			goto next_insn;
21071 		}
21072 
21073 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
21074 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
21075 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
21076 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
21077 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
21078 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
21079 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
21080 			bool is_sdiv = isdiv && insn->off == 1;
21081 			bool is_smod = !isdiv && insn->off == 1;
21082 			struct bpf_insn *patchlet;
21083 			struct bpf_insn chk_and_div[] = {
21084 				/* [R,W]x div 0 -> 0 */
21085 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21086 					     BPF_JNE | BPF_K, insn->src_reg,
21087 					     0, 2, 0),
21088 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
21089 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21090 				*insn,
21091 			};
21092 			struct bpf_insn chk_and_mod[] = {
21093 				/* [R,W]x mod 0 -> [R,W]x */
21094 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21095 					     BPF_JEQ | BPF_K, insn->src_reg,
21096 					     0, 1 + (is64 ? 0 : 1), 0),
21097 				*insn,
21098 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21099 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
21100 			};
21101 			struct bpf_insn chk_and_sdiv[] = {
21102 				/* [R,W]x sdiv 0 -> 0
21103 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
21104 				 * INT_MIN sdiv -1 -> INT_MIN
21105 				 */
21106 				BPF_MOV64_REG(BPF_REG_AX, insn->src_reg),
21107 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21108 					     BPF_ADD | BPF_K, BPF_REG_AX,
21109 					     0, 0, 1),
21110 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21111 					     BPF_JGT | BPF_K, BPF_REG_AX,
21112 					     0, 4, 1),
21113 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21114 					     BPF_JEQ | BPF_K, BPF_REG_AX,
21115 					     0, 1, 0),
21116 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21117 					     BPF_MOV | BPF_K, insn->dst_reg,
21118 					     0, 0, 0),
21119 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
21120 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21121 					     BPF_NEG | BPF_K, insn->dst_reg,
21122 					     0, 0, 0),
21123 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21124 				*insn,
21125 			};
21126 			struct bpf_insn chk_and_smod[] = {
21127 				/* [R,W]x mod 0 -> [R,W]x */
21128 				/* [R,W]x mod -1 -> 0 */
21129 				BPF_MOV64_REG(BPF_REG_AX, insn->src_reg),
21130 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
21131 					     BPF_ADD | BPF_K, BPF_REG_AX,
21132 					     0, 0, 1),
21133 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21134 					     BPF_JGT | BPF_K, BPF_REG_AX,
21135 					     0, 3, 1),
21136 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
21137 					     BPF_JEQ | BPF_K, BPF_REG_AX,
21138 					     0, 3 + (is64 ? 0 : 1), 1),
21139 				BPF_MOV32_IMM(insn->dst_reg, 0),
21140 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21141 				*insn,
21142 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
21143 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
21144 			};
21145 
21146 			if (is_sdiv) {
21147 				patchlet = chk_and_sdiv;
21148 				cnt = ARRAY_SIZE(chk_and_sdiv);
21149 			} else if (is_smod) {
21150 				patchlet = chk_and_smod;
21151 				cnt = ARRAY_SIZE(chk_and_smod) - (is64 ? 2 : 0);
21152 			} else {
21153 				patchlet = isdiv ? chk_and_div : chk_and_mod;
21154 				cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
21155 					      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
21156 			}
21157 
21158 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
21159 			if (!new_prog)
21160 				return -ENOMEM;
21161 
21162 			delta    += cnt - 1;
21163 			env->prog = prog = new_prog;
21164 			insn      = new_prog->insnsi + i + delta;
21165 			goto next_insn;
21166 		}
21167 
21168 		/* Make it impossible to de-reference a userspace address */
21169 		if (BPF_CLASS(insn->code) == BPF_LDX &&
21170 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
21171 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
21172 			struct bpf_insn *patch = &insn_buf[0];
21173 			u64 uaddress_limit = bpf_arch_uaddress_limit();
21174 
21175 			if (!uaddress_limit)
21176 				goto next_insn;
21177 
21178 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
21179 			if (insn->off)
21180 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
21181 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
21182 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
21183 			*patch++ = *insn;
21184 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
21185 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
21186 
21187 			cnt = patch - insn_buf;
21188 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21189 			if (!new_prog)
21190 				return -ENOMEM;
21191 
21192 			delta    += cnt - 1;
21193 			env->prog = prog = new_prog;
21194 			insn      = new_prog->insnsi + i + delta;
21195 			goto next_insn;
21196 		}
21197 
21198 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
21199 		if (BPF_CLASS(insn->code) == BPF_LD &&
21200 		    (BPF_MODE(insn->code) == BPF_ABS ||
21201 		     BPF_MODE(insn->code) == BPF_IND)) {
21202 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
21203 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
21204 				verbose(env, "bpf verifier is misconfigured\n");
21205 				return -EINVAL;
21206 			}
21207 
21208 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21209 			if (!new_prog)
21210 				return -ENOMEM;
21211 
21212 			delta    += cnt - 1;
21213 			env->prog = prog = new_prog;
21214 			insn      = new_prog->insnsi + i + delta;
21215 			goto next_insn;
21216 		}
21217 
21218 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
21219 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
21220 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
21221 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
21222 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
21223 			struct bpf_insn *patch = &insn_buf[0];
21224 			bool issrc, isneg, isimm;
21225 			u32 off_reg;
21226 
21227 			aux = &env->insn_aux_data[i + delta];
21228 			if (!aux->alu_state ||
21229 			    aux->alu_state == BPF_ALU_NON_POINTER)
21230 				goto next_insn;
21231 
21232 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
21233 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
21234 				BPF_ALU_SANITIZE_SRC;
21235 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
21236 
21237 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
21238 			if (isimm) {
21239 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
21240 			} else {
21241 				if (isneg)
21242 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
21243 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
21244 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
21245 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
21246 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
21247 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
21248 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
21249 			}
21250 			if (!issrc)
21251 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
21252 			insn->src_reg = BPF_REG_AX;
21253 			if (isneg)
21254 				insn->code = insn->code == code_add ?
21255 					     code_sub : code_add;
21256 			*patch++ = *insn;
21257 			if (issrc && isneg && !isimm)
21258 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
21259 			cnt = patch - insn_buf;
21260 
21261 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21262 			if (!new_prog)
21263 				return -ENOMEM;
21264 
21265 			delta    += cnt - 1;
21266 			env->prog = prog = new_prog;
21267 			insn      = new_prog->insnsi + i + delta;
21268 			goto next_insn;
21269 		}
21270 
21271 		if (is_may_goto_insn(insn)) {
21272 			int stack_off = -stack_depth - 8;
21273 
21274 			stack_depth_extra = 8;
21275 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
21276 			if (insn->off >= 0)
21277 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
21278 			else
21279 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
21280 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
21281 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
21282 			cnt = 4;
21283 
21284 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21285 			if (!new_prog)
21286 				return -ENOMEM;
21287 
21288 			delta += cnt - 1;
21289 			env->prog = prog = new_prog;
21290 			insn = new_prog->insnsi + i + delta;
21291 			goto next_insn;
21292 		}
21293 
21294 		if (insn->code != (BPF_JMP | BPF_CALL))
21295 			goto next_insn;
21296 		if (insn->src_reg == BPF_PSEUDO_CALL)
21297 			goto next_insn;
21298 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
21299 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
21300 			if (ret)
21301 				return ret;
21302 			if (cnt == 0)
21303 				goto next_insn;
21304 
21305 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21306 			if (!new_prog)
21307 				return -ENOMEM;
21308 
21309 			delta	 += cnt - 1;
21310 			env->prog = prog = new_prog;
21311 			insn	  = new_prog->insnsi + i + delta;
21312 			goto next_insn;
21313 		}
21314 
21315 		/* Skip inlining the helper call if the JIT does it. */
21316 		if (bpf_jit_inlines_helper_call(insn->imm))
21317 			goto next_insn;
21318 
21319 		if (insn->imm == BPF_FUNC_get_route_realm)
21320 			prog->dst_needed = 1;
21321 		if (insn->imm == BPF_FUNC_get_prandom_u32)
21322 			bpf_user_rnd_init_once();
21323 		if (insn->imm == BPF_FUNC_override_return)
21324 			prog->kprobe_override = 1;
21325 		if (insn->imm == BPF_FUNC_tail_call) {
21326 			/* If we tail call into other programs, we
21327 			 * cannot make any assumptions since they can
21328 			 * be replaced dynamically during runtime in
21329 			 * the program array.
21330 			 */
21331 			prog->cb_access = 1;
21332 			if (!allow_tail_call_in_subprogs(env))
21333 				prog->aux->stack_depth = MAX_BPF_STACK;
21334 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
21335 
21336 			/* mark bpf_tail_call as different opcode to avoid
21337 			 * conditional branch in the interpreter for every normal
21338 			 * call and to prevent accidental JITing by JIT compiler
21339 			 * that doesn't support bpf_tail_call yet
21340 			 */
21341 			insn->imm = 0;
21342 			insn->code = BPF_JMP | BPF_TAIL_CALL;
21343 
21344 			aux = &env->insn_aux_data[i + delta];
21345 			if (env->bpf_capable && !prog->blinding_requested &&
21346 			    prog->jit_requested &&
21347 			    !bpf_map_key_poisoned(aux) &&
21348 			    !bpf_map_ptr_poisoned(aux) &&
21349 			    !bpf_map_ptr_unpriv(aux)) {
21350 				struct bpf_jit_poke_descriptor desc = {
21351 					.reason = BPF_POKE_REASON_TAIL_CALL,
21352 					.tail_call.map = aux->map_ptr_state.map_ptr,
21353 					.tail_call.key = bpf_map_key_immediate(aux),
21354 					.insn_idx = i + delta,
21355 				};
21356 
21357 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
21358 				if (ret < 0) {
21359 					verbose(env, "adding tail call poke descriptor failed\n");
21360 					return ret;
21361 				}
21362 
21363 				insn->imm = ret + 1;
21364 				goto next_insn;
21365 			}
21366 
21367 			if (!bpf_map_ptr_unpriv(aux))
21368 				goto next_insn;
21369 
21370 			/* instead of changing every JIT dealing with tail_call
21371 			 * emit two extra insns:
21372 			 * if (index >= max_entries) goto out;
21373 			 * index &= array->index_mask;
21374 			 * to avoid out-of-bounds cpu speculation
21375 			 */
21376 			if (bpf_map_ptr_poisoned(aux)) {
21377 				verbose(env, "tail_call abusing map_ptr\n");
21378 				return -EINVAL;
21379 			}
21380 
21381 			map_ptr = aux->map_ptr_state.map_ptr;
21382 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
21383 						  map_ptr->max_entries, 2);
21384 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
21385 						    container_of(map_ptr,
21386 								 struct bpf_array,
21387 								 map)->index_mask);
21388 			insn_buf[2] = *insn;
21389 			cnt = 3;
21390 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21391 			if (!new_prog)
21392 				return -ENOMEM;
21393 
21394 			delta    += cnt - 1;
21395 			env->prog = prog = new_prog;
21396 			insn      = new_prog->insnsi + i + delta;
21397 			goto next_insn;
21398 		}
21399 
21400 		if (insn->imm == BPF_FUNC_timer_set_callback) {
21401 			/* The verifier will process callback_fn as many times as necessary
21402 			 * with different maps and the register states prepared by
21403 			 * set_timer_callback_state will be accurate.
21404 			 *
21405 			 * The following use case is valid:
21406 			 *   map1 is shared by prog1, prog2, prog3.
21407 			 *   prog1 calls bpf_timer_init for some map1 elements
21408 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
21409 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
21410 			 *   prog3 calls bpf_timer_start for some map1 elements.
21411 			 *     Those that were not both bpf_timer_init-ed and
21412 			 *     bpf_timer_set_callback-ed will return -EINVAL.
21413 			 */
21414 			struct bpf_insn ld_addrs[2] = {
21415 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
21416 			};
21417 
21418 			insn_buf[0] = ld_addrs[0];
21419 			insn_buf[1] = ld_addrs[1];
21420 			insn_buf[2] = *insn;
21421 			cnt = 3;
21422 
21423 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21424 			if (!new_prog)
21425 				return -ENOMEM;
21426 
21427 			delta    += cnt - 1;
21428 			env->prog = prog = new_prog;
21429 			insn      = new_prog->insnsi + i + delta;
21430 			goto patch_call_imm;
21431 		}
21432 
21433 		if (is_storage_get_function(insn->imm)) {
21434 			if (!in_sleepable(env) ||
21435 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
21436 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
21437 			else
21438 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
21439 			insn_buf[1] = *insn;
21440 			cnt = 2;
21441 
21442 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21443 			if (!new_prog)
21444 				return -ENOMEM;
21445 
21446 			delta += cnt - 1;
21447 			env->prog = prog = new_prog;
21448 			insn = new_prog->insnsi + i + delta;
21449 			goto patch_call_imm;
21450 		}
21451 
21452 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
21453 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
21454 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
21455 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
21456 			 */
21457 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
21458 			insn_buf[1] = *insn;
21459 			cnt = 2;
21460 
21461 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21462 			if (!new_prog)
21463 				return -ENOMEM;
21464 
21465 			delta += cnt - 1;
21466 			env->prog = prog = new_prog;
21467 			insn = new_prog->insnsi + i + delta;
21468 			goto patch_call_imm;
21469 		}
21470 
21471 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
21472 		 * and other inlining handlers are currently limited to 64 bit
21473 		 * only.
21474 		 */
21475 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
21476 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
21477 		     insn->imm == BPF_FUNC_map_update_elem ||
21478 		     insn->imm == BPF_FUNC_map_delete_elem ||
21479 		     insn->imm == BPF_FUNC_map_push_elem   ||
21480 		     insn->imm == BPF_FUNC_map_pop_elem    ||
21481 		     insn->imm == BPF_FUNC_map_peek_elem   ||
21482 		     insn->imm == BPF_FUNC_redirect_map    ||
21483 		     insn->imm == BPF_FUNC_for_each_map_elem ||
21484 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
21485 			aux = &env->insn_aux_data[i + delta];
21486 			if (bpf_map_ptr_poisoned(aux))
21487 				goto patch_call_imm;
21488 
21489 			map_ptr = aux->map_ptr_state.map_ptr;
21490 			ops = map_ptr->ops;
21491 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
21492 			    ops->map_gen_lookup) {
21493 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
21494 				if (cnt == -EOPNOTSUPP)
21495 					goto patch_map_ops_generic;
21496 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
21497 					verbose(env, "bpf verifier is misconfigured\n");
21498 					return -EINVAL;
21499 				}
21500 
21501 				new_prog = bpf_patch_insn_data(env, i + delta,
21502 							       insn_buf, cnt);
21503 				if (!new_prog)
21504 					return -ENOMEM;
21505 
21506 				delta    += cnt - 1;
21507 				env->prog = prog = new_prog;
21508 				insn      = new_prog->insnsi + i + delta;
21509 				goto next_insn;
21510 			}
21511 
21512 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
21513 				     (void *(*)(struct bpf_map *map, void *key))NULL));
21514 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
21515 				     (long (*)(struct bpf_map *map, void *key))NULL));
21516 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
21517 				     (long (*)(struct bpf_map *map, void *key, void *value,
21518 					      u64 flags))NULL));
21519 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
21520 				     (long (*)(struct bpf_map *map, void *value,
21521 					      u64 flags))NULL));
21522 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
21523 				     (long (*)(struct bpf_map *map, void *value))NULL));
21524 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
21525 				     (long (*)(struct bpf_map *map, void *value))NULL));
21526 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
21527 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
21528 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
21529 				     (long (*)(struct bpf_map *map,
21530 					      bpf_callback_t callback_fn,
21531 					      void *callback_ctx,
21532 					      u64 flags))NULL));
21533 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
21534 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
21535 
21536 patch_map_ops_generic:
21537 			switch (insn->imm) {
21538 			case BPF_FUNC_map_lookup_elem:
21539 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
21540 				goto next_insn;
21541 			case BPF_FUNC_map_update_elem:
21542 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
21543 				goto next_insn;
21544 			case BPF_FUNC_map_delete_elem:
21545 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
21546 				goto next_insn;
21547 			case BPF_FUNC_map_push_elem:
21548 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
21549 				goto next_insn;
21550 			case BPF_FUNC_map_pop_elem:
21551 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
21552 				goto next_insn;
21553 			case BPF_FUNC_map_peek_elem:
21554 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
21555 				goto next_insn;
21556 			case BPF_FUNC_redirect_map:
21557 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
21558 				goto next_insn;
21559 			case BPF_FUNC_for_each_map_elem:
21560 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
21561 				goto next_insn;
21562 			case BPF_FUNC_map_lookup_percpu_elem:
21563 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
21564 				goto next_insn;
21565 			}
21566 
21567 			goto patch_call_imm;
21568 		}
21569 
21570 		/* Implement bpf_jiffies64 inline. */
21571 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
21572 		    insn->imm == BPF_FUNC_jiffies64) {
21573 			struct bpf_insn ld_jiffies_addr[2] = {
21574 				BPF_LD_IMM64(BPF_REG_0,
21575 					     (unsigned long)&jiffies),
21576 			};
21577 
21578 			insn_buf[0] = ld_jiffies_addr[0];
21579 			insn_buf[1] = ld_jiffies_addr[1];
21580 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
21581 						  BPF_REG_0, 0);
21582 			cnt = 3;
21583 
21584 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
21585 						       cnt);
21586 			if (!new_prog)
21587 				return -ENOMEM;
21588 
21589 			delta    += cnt - 1;
21590 			env->prog = prog = new_prog;
21591 			insn      = new_prog->insnsi + i + delta;
21592 			goto next_insn;
21593 		}
21594 
21595 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
21596 		/* Implement bpf_get_smp_processor_id() inline. */
21597 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
21598 		    verifier_inlines_helper_call(env, insn->imm)) {
21599 			/* BPF_FUNC_get_smp_processor_id inlining is an
21600 			 * optimization, so if pcpu_hot.cpu_number is ever
21601 			 * changed in some incompatible and hard to support
21602 			 * way, it's fine to back out this inlining logic
21603 			 */
21604 			insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number);
21605 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
21606 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
21607 			cnt = 3;
21608 
21609 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21610 			if (!new_prog)
21611 				return -ENOMEM;
21612 
21613 			delta    += cnt - 1;
21614 			env->prog = prog = new_prog;
21615 			insn      = new_prog->insnsi + i + delta;
21616 			goto next_insn;
21617 		}
21618 #endif
21619 		/* Implement bpf_get_func_arg inline. */
21620 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21621 		    insn->imm == BPF_FUNC_get_func_arg) {
21622 			/* Load nr_args from ctx - 8 */
21623 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21624 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
21625 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
21626 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
21627 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
21628 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
21629 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
21630 			insn_buf[7] = BPF_JMP_A(1);
21631 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
21632 			cnt = 9;
21633 
21634 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21635 			if (!new_prog)
21636 				return -ENOMEM;
21637 
21638 			delta    += cnt - 1;
21639 			env->prog = prog = new_prog;
21640 			insn      = new_prog->insnsi + i + delta;
21641 			goto next_insn;
21642 		}
21643 
21644 		/* Implement bpf_get_func_ret inline. */
21645 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21646 		    insn->imm == BPF_FUNC_get_func_ret) {
21647 			if (eatype == BPF_TRACE_FEXIT ||
21648 			    eatype == BPF_MODIFY_RETURN) {
21649 				/* Load nr_args from ctx - 8 */
21650 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21651 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
21652 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
21653 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
21654 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
21655 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
21656 				cnt = 6;
21657 			} else {
21658 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
21659 				cnt = 1;
21660 			}
21661 
21662 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21663 			if (!new_prog)
21664 				return -ENOMEM;
21665 
21666 			delta    += cnt - 1;
21667 			env->prog = prog = new_prog;
21668 			insn      = new_prog->insnsi + i + delta;
21669 			goto next_insn;
21670 		}
21671 
21672 		/* Implement get_func_arg_cnt inline. */
21673 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21674 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
21675 			/* Load nr_args from ctx - 8 */
21676 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21677 
21678 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
21679 			if (!new_prog)
21680 				return -ENOMEM;
21681 
21682 			env->prog = prog = new_prog;
21683 			insn      = new_prog->insnsi + i + delta;
21684 			goto next_insn;
21685 		}
21686 
21687 		/* Implement bpf_get_func_ip inline. */
21688 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21689 		    insn->imm == BPF_FUNC_get_func_ip) {
21690 			/* Load IP address from ctx - 16 */
21691 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
21692 
21693 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
21694 			if (!new_prog)
21695 				return -ENOMEM;
21696 
21697 			env->prog = prog = new_prog;
21698 			insn      = new_prog->insnsi + i + delta;
21699 			goto next_insn;
21700 		}
21701 
21702 		/* Implement bpf_get_branch_snapshot inline. */
21703 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
21704 		    prog->jit_requested && BITS_PER_LONG == 64 &&
21705 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
21706 			/* We are dealing with the following func protos:
21707 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
21708 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
21709 			 */
21710 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
21711 
21712 			/* struct perf_branch_entry is part of UAPI and is
21713 			 * used as an array element, so extremely unlikely to
21714 			 * ever grow or shrink
21715 			 */
21716 			BUILD_BUG_ON(br_entry_size != 24);
21717 
21718 			/* if (unlikely(flags)) return -EINVAL */
21719 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
21720 
21721 			/* Transform size (bytes) into number of entries (cnt = size / 24).
21722 			 * But to avoid expensive division instruction, we implement
21723 			 * divide-by-3 through multiplication, followed by further
21724 			 * division by 8 through 3-bit right shift.
21725 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
21726 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
21727 			 *
21728 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
21729 			 */
21730 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
21731 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
21732 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
21733 
21734 			/* call perf_snapshot_branch_stack implementation */
21735 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
21736 			/* if (entry_cnt == 0) return -ENOENT */
21737 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
21738 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
21739 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
21740 			insn_buf[7] = BPF_JMP_A(3);
21741 			/* return -EINVAL; */
21742 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
21743 			insn_buf[9] = BPF_JMP_A(1);
21744 			/* return -ENOENT; */
21745 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
21746 			cnt = 11;
21747 
21748 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21749 			if (!new_prog)
21750 				return -ENOMEM;
21751 
21752 			delta    += cnt - 1;
21753 			env->prog = prog = new_prog;
21754 			insn      = new_prog->insnsi + i + delta;
21755 			goto next_insn;
21756 		}
21757 
21758 		/* Implement bpf_kptr_xchg inline */
21759 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
21760 		    insn->imm == BPF_FUNC_kptr_xchg &&
21761 		    bpf_jit_supports_ptr_xchg()) {
21762 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
21763 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
21764 			cnt = 2;
21765 
21766 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21767 			if (!new_prog)
21768 				return -ENOMEM;
21769 
21770 			delta    += cnt - 1;
21771 			env->prog = prog = new_prog;
21772 			insn      = new_prog->insnsi + i + delta;
21773 			goto next_insn;
21774 		}
21775 patch_call_imm:
21776 		fn = env->ops->get_func_proto(insn->imm, env->prog);
21777 		/* all functions that have prototype and verifier allowed
21778 		 * programs to call them, must be real in-kernel functions
21779 		 */
21780 		if (!fn->func) {
21781 			verbose(env,
21782 				"kernel subsystem misconfigured func %s#%d\n",
21783 				func_id_name(insn->imm), insn->imm);
21784 			return -EFAULT;
21785 		}
21786 		insn->imm = fn->func - __bpf_call_base;
21787 next_insn:
21788 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
21789 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
21790 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
21791 			cur_subprog++;
21792 			stack_depth = subprogs[cur_subprog].stack_depth;
21793 			stack_depth_extra = 0;
21794 		}
21795 		i++;
21796 		insn++;
21797 	}
21798 
21799 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
21800 	for (i = 0; i < env->subprog_cnt; i++) {
21801 		int subprog_start = subprogs[i].start;
21802 		int stack_slots = subprogs[i].stack_extra / 8;
21803 
21804 		if (!stack_slots)
21805 			continue;
21806 		if (stack_slots > 1) {
21807 			verbose(env, "verifier bug: stack_slots supports may_goto only\n");
21808 			return -EFAULT;
21809 		}
21810 
21811 		/* Add ST insn to subprog prologue to init extra stack */
21812 		insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP,
21813 					 -subprogs[i].stack_depth, BPF_MAX_LOOPS);
21814 		/* Copy first actual insn to preserve it */
21815 		insn_buf[1] = env->prog->insnsi[subprog_start];
21816 
21817 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2);
21818 		if (!new_prog)
21819 			return -ENOMEM;
21820 		env->prog = prog = new_prog;
21821 		/*
21822 		 * If may_goto is a first insn of a prog there could be a jmp
21823 		 * insn that points to it, hence adjust all such jmps to point
21824 		 * to insn after BPF_ST that inits may_goto count.
21825 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
21826 		 */
21827 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, 1));
21828 	}
21829 
21830 	/* Since poke tab is now finalized, publish aux to tracker. */
21831 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
21832 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
21833 		if (!map_ptr->ops->map_poke_track ||
21834 		    !map_ptr->ops->map_poke_untrack ||
21835 		    !map_ptr->ops->map_poke_run) {
21836 			verbose(env, "bpf verifier is misconfigured\n");
21837 			return -EINVAL;
21838 		}
21839 
21840 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
21841 		if (ret < 0) {
21842 			verbose(env, "tracking tail call prog failed\n");
21843 			return ret;
21844 		}
21845 	}
21846 
21847 	sort_kfunc_descs_by_imm_off(env->prog);
21848 
21849 	return 0;
21850 }
21851 
21852 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
21853 					int position,
21854 					s32 stack_base,
21855 					u32 callback_subprogno,
21856 					u32 *total_cnt)
21857 {
21858 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
21859 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
21860 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
21861 	int reg_loop_max = BPF_REG_6;
21862 	int reg_loop_cnt = BPF_REG_7;
21863 	int reg_loop_ctx = BPF_REG_8;
21864 
21865 	struct bpf_insn *insn_buf = env->insn_buf;
21866 	struct bpf_prog *new_prog;
21867 	u32 callback_start;
21868 	u32 call_insn_offset;
21869 	s32 callback_offset;
21870 	u32 cnt = 0;
21871 
21872 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
21873 	 * be careful to modify this code in sync.
21874 	 */
21875 
21876 	/* Return error and jump to the end of the patch if
21877 	 * expected number of iterations is too big.
21878 	 */
21879 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
21880 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
21881 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
21882 	/* spill R6, R7, R8 to use these as loop vars */
21883 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
21884 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
21885 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
21886 	/* initialize loop vars */
21887 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
21888 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
21889 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
21890 	/* loop header,
21891 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
21892 	 */
21893 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
21894 	/* callback call,
21895 	 * correct callback offset would be set after patching
21896 	 */
21897 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
21898 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
21899 	insn_buf[cnt++] = BPF_CALL_REL(0);
21900 	/* increment loop counter */
21901 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
21902 	/* jump to loop header if callback returned 0 */
21903 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
21904 	/* return value of bpf_loop,
21905 	 * set R0 to the number of iterations
21906 	 */
21907 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
21908 	/* restore original values of R6, R7, R8 */
21909 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
21910 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
21911 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
21912 
21913 	*total_cnt = cnt;
21914 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
21915 	if (!new_prog)
21916 		return new_prog;
21917 
21918 	/* callback start is known only after patching */
21919 	callback_start = env->subprog_info[callback_subprogno].start;
21920 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
21921 	call_insn_offset = position + 12;
21922 	callback_offset = callback_start - call_insn_offset - 1;
21923 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
21924 
21925 	return new_prog;
21926 }
21927 
21928 static bool is_bpf_loop_call(struct bpf_insn *insn)
21929 {
21930 	return insn->code == (BPF_JMP | BPF_CALL) &&
21931 		insn->src_reg == 0 &&
21932 		insn->imm == BPF_FUNC_loop;
21933 }
21934 
21935 /* For all sub-programs in the program (including main) check
21936  * insn_aux_data to see if there are bpf_loop calls that require
21937  * inlining. If such calls are found the calls are replaced with a
21938  * sequence of instructions produced by `inline_bpf_loop` function and
21939  * subprog stack_depth is increased by the size of 3 registers.
21940  * This stack space is used to spill values of the R6, R7, R8.  These
21941  * registers are used to store the loop bound, counter and context
21942  * variables.
21943  */
21944 static int optimize_bpf_loop(struct bpf_verifier_env *env)
21945 {
21946 	struct bpf_subprog_info *subprogs = env->subprog_info;
21947 	int i, cur_subprog = 0, cnt, delta = 0;
21948 	struct bpf_insn *insn = env->prog->insnsi;
21949 	int insn_cnt = env->prog->len;
21950 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
21951 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
21952 	u16 stack_depth_extra = 0;
21953 
21954 	for (i = 0; i < insn_cnt; i++, insn++) {
21955 		struct bpf_loop_inline_state *inline_state =
21956 			&env->insn_aux_data[i + delta].loop_inline_state;
21957 
21958 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
21959 			struct bpf_prog *new_prog;
21960 
21961 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
21962 			new_prog = inline_bpf_loop(env,
21963 						   i + delta,
21964 						   -(stack_depth + stack_depth_extra),
21965 						   inline_state->callback_subprogno,
21966 						   &cnt);
21967 			if (!new_prog)
21968 				return -ENOMEM;
21969 
21970 			delta     += cnt - 1;
21971 			env->prog  = new_prog;
21972 			insn       = new_prog->insnsi + i + delta;
21973 		}
21974 
21975 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
21976 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
21977 			cur_subprog++;
21978 			stack_depth = subprogs[cur_subprog].stack_depth;
21979 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
21980 			stack_depth_extra = 0;
21981 		}
21982 	}
21983 
21984 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
21985 
21986 	return 0;
21987 }
21988 
21989 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
21990  * adjust subprograms stack depth when possible.
21991  */
21992 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
21993 {
21994 	struct bpf_subprog_info *subprog = env->subprog_info;
21995 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
21996 	struct bpf_insn *insn = env->prog->insnsi;
21997 	int insn_cnt = env->prog->len;
21998 	u32 spills_num;
21999 	bool modified = false;
22000 	int i, j;
22001 
22002 	for (i = 0; i < insn_cnt; i++, insn++) {
22003 		if (aux[i].fastcall_spills_num > 0) {
22004 			spills_num = aux[i].fastcall_spills_num;
22005 			/* NOPs would be removed by opt_remove_nops() */
22006 			for (j = 1; j <= spills_num; ++j) {
22007 				*(insn - j) = NOP;
22008 				*(insn + j) = NOP;
22009 			}
22010 			modified = true;
22011 		}
22012 		if ((subprog + 1)->start == i + 1) {
22013 			if (modified && !subprog->keep_fastcall_stack)
22014 				subprog->stack_depth = -subprog->fastcall_stack_off;
22015 			subprog++;
22016 			modified = false;
22017 		}
22018 	}
22019 
22020 	return 0;
22021 }
22022 
22023 static void free_states(struct bpf_verifier_env *env)
22024 {
22025 	struct bpf_verifier_state_list *sl, *sln;
22026 	int i;
22027 
22028 	sl = env->free_list;
22029 	while (sl) {
22030 		sln = sl->next;
22031 		free_verifier_state(&sl->state, false);
22032 		kfree(sl);
22033 		sl = sln;
22034 	}
22035 	env->free_list = NULL;
22036 
22037 	if (!env->explored_states)
22038 		return;
22039 
22040 	for (i = 0; i < state_htab_size(env); i++) {
22041 		sl = env->explored_states[i];
22042 
22043 		while (sl) {
22044 			sln = sl->next;
22045 			free_verifier_state(&sl->state, false);
22046 			kfree(sl);
22047 			sl = sln;
22048 		}
22049 		env->explored_states[i] = NULL;
22050 	}
22051 }
22052 
22053 static int do_check_common(struct bpf_verifier_env *env, int subprog)
22054 {
22055 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
22056 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
22057 	struct bpf_verifier_state *state;
22058 	struct bpf_reg_state *regs;
22059 	int ret, i;
22060 
22061 	env->prev_linfo = NULL;
22062 	env->pass_cnt++;
22063 
22064 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
22065 	if (!state)
22066 		return -ENOMEM;
22067 	state->curframe = 0;
22068 	state->speculative = false;
22069 	state->branches = 1;
22070 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
22071 	if (!state->frame[0]) {
22072 		kfree(state);
22073 		return -ENOMEM;
22074 	}
22075 	env->cur_state = state;
22076 	init_func_state(env, state->frame[0],
22077 			BPF_MAIN_FUNC /* callsite */,
22078 			0 /* frameno */,
22079 			subprog);
22080 	state->first_insn_idx = env->subprog_info[subprog].start;
22081 	state->last_insn_idx = -1;
22082 
22083 	regs = state->frame[state->curframe]->regs;
22084 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
22085 		const char *sub_name = subprog_name(env, subprog);
22086 		struct bpf_subprog_arg_info *arg;
22087 		struct bpf_reg_state *reg;
22088 
22089 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
22090 		ret = btf_prepare_func_args(env, subprog);
22091 		if (ret)
22092 			goto out;
22093 
22094 		if (subprog_is_exc_cb(env, subprog)) {
22095 			state->frame[0]->in_exception_callback_fn = true;
22096 			/* We have already ensured that the callback returns an integer, just
22097 			 * like all global subprogs. We need to determine it only has a single
22098 			 * scalar argument.
22099 			 */
22100 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
22101 				verbose(env, "exception cb only supports single integer argument\n");
22102 				ret = -EINVAL;
22103 				goto out;
22104 			}
22105 		}
22106 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
22107 			arg = &sub->args[i - BPF_REG_1];
22108 			reg = &regs[i];
22109 
22110 			if (arg->arg_type == ARG_PTR_TO_CTX) {
22111 				reg->type = PTR_TO_CTX;
22112 				mark_reg_known_zero(env, regs, i);
22113 			} else if (arg->arg_type == ARG_ANYTHING) {
22114 				reg->type = SCALAR_VALUE;
22115 				mark_reg_unknown(env, regs, i);
22116 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
22117 				/* assume unspecial LOCAL dynptr type */
22118 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
22119 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
22120 				reg->type = PTR_TO_MEM;
22121 				if (arg->arg_type & PTR_MAYBE_NULL)
22122 					reg->type |= PTR_MAYBE_NULL;
22123 				mark_reg_known_zero(env, regs, i);
22124 				reg->mem_size = arg->mem_size;
22125 				reg->id = ++env->id_gen;
22126 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
22127 				reg->type = PTR_TO_BTF_ID;
22128 				if (arg->arg_type & PTR_MAYBE_NULL)
22129 					reg->type |= PTR_MAYBE_NULL;
22130 				if (arg->arg_type & PTR_UNTRUSTED)
22131 					reg->type |= PTR_UNTRUSTED;
22132 				if (arg->arg_type & PTR_TRUSTED)
22133 					reg->type |= PTR_TRUSTED;
22134 				mark_reg_known_zero(env, regs, i);
22135 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
22136 				reg->btf_id = arg->btf_id;
22137 				reg->id = ++env->id_gen;
22138 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
22139 				/* caller can pass either PTR_TO_ARENA or SCALAR */
22140 				mark_reg_unknown(env, regs, i);
22141 			} else {
22142 				WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
22143 					  i - BPF_REG_1, arg->arg_type);
22144 				ret = -EFAULT;
22145 				goto out;
22146 			}
22147 		}
22148 	} else {
22149 		/* if main BPF program has associated BTF info, validate that
22150 		 * it's matching expected signature, and otherwise mark BTF
22151 		 * info for main program as unreliable
22152 		 */
22153 		if (env->prog->aux->func_info_aux) {
22154 			ret = btf_prepare_func_args(env, 0);
22155 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
22156 				env->prog->aux->func_info_aux[0].unreliable = true;
22157 		}
22158 
22159 		/* 1st arg to a function */
22160 		regs[BPF_REG_1].type = PTR_TO_CTX;
22161 		mark_reg_known_zero(env, regs, BPF_REG_1);
22162 	}
22163 
22164 	ret = do_check(env);
22165 out:
22166 	/* check for NULL is necessary, since cur_state can be freed inside
22167 	 * do_check() under memory pressure.
22168 	 */
22169 	if (env->cur_state) {
22170 		free_verifier_state(env->cur_state, true);
22171 		env->cur_state = NULL;
22172 	}
22173 	while (!pop_stack(env, NULL, NULL, false));
22174 	if (!ret && pop_log)
22175 		bpf_vlog_reset(&env->log, 0);
22176 	free_states(env);
22177 	return ret;
22178 }
22179 
22180 /* Lazily verify all global functions based on their BTF, if they are called
22181  * from main BPF program or any of subprograms transitively.
22182  * BPF global subprogs called from dead code are not validated.
22183  * All callable global functions must pass verification.
22184  * Otherwise the whole program is rejected.
22185  * Consider:
22186  * int bar(int);
22187  * int foo(int f)
22188  * {
22189  *    return bar(f);
22190  * }
22191  * int bar(int b)
22192  * {
22193  *    ...
22194  * }
22195  * foo() will be verified first for R1=any_scalar_value. During verification it
22196  * will be assumed that bar() already verified successfully and call to bar()
22197  * from foo() will be checked for type match only. Later bar() will be verified
22198  * independently to check that it's safe for R1=any_scalar_value.
22199  */
22200 static int do_check_subprogs(struct bpf_verifier_env *env)
22201 {
22202 	struct bpf_prog_aux *aux = env->prog->aux;
22203 	struct bpf_func_info_aux *sub_aux;
22204 	int i, ret, new_cnt;
22205 
22206 	if (!aux->func_info)
22207 		return 0;
22208 
22209 	/* exception callback is presumed to be always called */
22210 	if (env->exception_callback_subprog)
22211 		subprog_aux(env, env->exception_callback_subprog)->called = true;
22212 
22213 again:
22214 	new_cnt = 0;
22215 	for (i = 1; i < env->subprog_cnt; i++) {
22216 		if (!subprog_is_global(env, i))
22217 			continue;
22218 
22219 		sub_aux = subprog_aux(env, i);
22220 		if (!sub_aux->called || sub_aux->verified)
22221 			continue;
22222 
22223 		env->insn_idx = env->subprog_info[i].start;
22224 		WARN_ON_ONCE(env->insn_idx == 0);
22225 		ret = do_check_common(env, i);
22226 		if (ret) {
22227 			return ret;
22228 		} else if (env->log.level & BPF_LOG_LEVEL) {
22229 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
22230 				i, subprog_name(env, i));
22231 		}
22232 
22233 		/* We verified new global subprog, it might have called some
22234 		 * more global subprogs that we haven't verified yet, so we
22235 		 * need to do another pass over subprogs to verify those.
22236 		 */
22237 		sub_aux->verified = true;
22238 		new_cnt++;
22239 	}
22240 
22241 	/* We can't loop forever as we verify at least one global subprog on
22242 	 * each pass.
22243 	 */
22244 	if (new_cnt)
22245 		goto again;
22246 
22247 	return 0;
22248 }
22249 
22250 static int do_check_main(struct bpf_verifier_env *env)
22251 {
22252 	int ret;
22253 
22254 	env->insn_idx = 0;
22255 	ret = do_check_common(env, 0);
22256 	if (!ret)
22257 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
22258 	return ret;
22259 }
22260 
22261 
22262 static void print_verification_stats(struct bpf_verifier_env *env)
22263 {
22264 	int i;
22265 
22266 	if (env->log.level & BPF_LOG_STATS) {
22267 		verbose(env, "verification time %lld usec\n",
22268 			div_u64(env->verification_time, 1000));
22269 		verbose(env, "stack depth ");
22270 		for (i = 0; i < env->subprog_cnt; i++) {
22271 			u32 depth = env->subprog_info[i].stack_depth;
22272 
22273 			verbose(env, "%d", depth);
22274 			if (i + 1 < env->subprog_cnt)
22275 				verbose(env, "+");
22276 		}
22277 		verbose(env, "\n");
22278 	}
22279 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
22280 		"total_states %d peak_states %d mark_read %d\n",
22281 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
22282 		env->max_states_per_insn, env->total_states,
22283 		env->peak_states, env->longest_mark_read_walk);
22284 }
22285 
22286 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
22287 {
22288 	const struct btf_type *t, *func_proto;
22289 	const struct bpf_struct_ops_desc *st_ops_desc;
22290 	const struct bpf_struct_ops *st_ops;
22291 	const struct btf_member *member;
22292 	struct bpf_prog *prog = env->prog;
22293 	u32 btf_id, member_idx;
22294 	struct btf *btf;
22295 	const char *mname;
22296 	int err;
22297 
22298 	if (!prog->gpl_compatible) {
22299 		verbose(env, "struct ops programs must have a GPL compatible license\n");
22300 		return -EINVAL;
22301 	}
22302 
22303 	if (!prog->aux->attach_btf_id)
22304 		return -ENOTSUPP;
22305 
22306 	btf = prog->aux->attach_btf;
22307 	if (btf_is_module(btf)) {
22308 		/* Make sure st_ops is valid through the lifetime of env */
22309 		env->attach_btf_mod = btf_try_get_module(btf);
22310 		if (!env->attach_btf_mod) {
22311 			verbose(env, "struct_ops module %s is not found\n",
22312 				btf_get_name(btf));
22313 			return -ENOTSUPP;
22314 		}
22315 	}
22316 
22317 	btf_id = prog->aux->attach_btf_id;
22318 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
22319 	if (!st_ops_desc) {
22320 		verbose(env, "attach_btf_id %u is not a supported struct\n",
22321 			btf_id);
22322 		return -ENOTSUPP;
22323 	}
22324 	st_ops = st_ops_desc->st_ops;
22325 
22326 	t = st_ops_desc->type;
22327 	member_idx = prog->expected_attach_type;
22328 	if (member_idx >= btf_type_vlen(t)) {
22329 		verbose(env, "attach to invalid member idx %u of struct %s\n",
22330 			member_idx, st_ops->name);
22331 		return -EINVAL;
22332 	}
22333 
22334 	member = &btf_type_member(t)[member_idx];
22335 	mname = btf_name_by_offset(btf, member->name_off);
22336 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
22337 					       NULL);
22338 	if (!func_proto) {
22339 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
22340 			mname, member_idx, st_ops->name);
22341 		return -EINVAL;
22342 	}
22343 
22344 	err = bpf_struct_ops_supported(st_ops, __btf_member_bit_offset(t, member) / 8);
22345 	if (err) {
22346 		verbose(env, "attach to unsupported member %s of struct %s\n",
22347 			mname, st_ops->name);
22348 		return err;
22349 	}
22350 
22351 	if (st_ops->check_member) {
22352 		err = st_ops->check_member(t, member, prog);
22353 
22354 		if (err) {
22355 			verbose(env, "attach to unsupported member %s of struct %s\n",
22356 				mname, st_ops->name);
22357 			return err;
22358 		}
22359 	}
22360 
22361 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
22362 		verbose(env, "Private stack not supported by jit\n");
22363 		return -EACCES;
22364 	}
22365 
22366 	/* btf_ctx_access() used this to provide argument type info */
22367 	prog->aux->ctx_arg_info =
22368 		st_ops_desc->arg_info[member_idx].info;
22369 	prog->aux->ctx_arg_info_size =
22370 		st_ops_desc->arg_info[member_idx].cnt;
22371 
22372 	prog->aux->attach_func_proto = func_proto;
22373 	prog->aux->attach_func_name = mname;
22374 	env->ops = st_ops->verifier_ops;
22375 
22376 	return 0;
22377 }
22378 #define SECURITY_PREFIX "security_"
22379 
22380 static int check_attach_modify_return(unsigned long addr, const char *func_name)
22381 {
22382 	if (within_error_injection_list(addr) ||
22383 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
22384 		return 0;
22385 
22386 	return -EINVAL;
22387 }
22388 
22389 /* list of non-sleepable functions that are otherwise on
22390  * ALLOW_ERROR_INJECTION list
22391  */
22392 BTF_SET_START(btf_non_sleepable_error_inject)
22393 /* Three functions below can be called from sleepable and non-sleepable context.
22394  * Assume non-sleepable from bpf safety point of view.
22395  */
22396 BTF_ID(func, __filemap_add_folio)
22397 #ifdef CONFIG_FAIL_PAGE_ALLOC
22398 BTF_ID(func, should_fail_alloc_page)
22399 #endif
22400 #ifdef CONFIG_FAILSLAB
22401 BTF_ID(func, should_failslab)
22402 #endif
22403 BTF_SET_END(btf_non_sleepable_error_inject)
22404 
22405 static int check_non_sleepable_error_inject(u32 btf_id)
22406 {
22407 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
22408 }
22409 
22410 int bpf_check_attach_target(struct bpf_verifier_log *log,
22411 			    const struct bpf_prog *prog,
22412 			    const struct bpf_prog *tgt_prog,
22413 			    u32 btf_id,
22414 			    struct bpf_attach_target_info *tgt_info)
22415 {
22416 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
22417 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
22418 	char trace_symbol[KSYM_SYMBOL_LEN];
22419 	const char prefix[] = "btf_trace_";
22420 	struct bpf_raw_event_map *btp;
22421 	int ret = 0, subprog = -1, i;
22422 	const struct btf_type *t;
22423 	bool conservative = true;
22424 	const char *tname, *fname;
22425 	struct btf *btf;
22426 	long addr = 0;
22427 	struct module *mod = NULL;
22428 
22429 	if (!btf_id) {
22430 		bpf_log(log, "Tracing programs must provide btf_id\n");
22431 		return -EINVAL;
22432 	}
22433 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
22434 	if (!btf) {
22435 		bpf_log(log,
22436 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
22437 		return -EINVAL;
22438 	}
22439 	t = btf_type_by_id(btf, btf_id);
22440 	if (!t) {
22441 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
22442 		return -EINVAL;
22443 	}
22444 	tname = btf_name_by_offset(btf, t->name_off);
22445 	if (!tname) {
22446 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
22447 		return -EINVAL;
22448 	}
22449 	if (tgt_prog) {
22450 		struct bpf_prog_aux *aux = tgt_prog->aux;
22451 		bool tgt_changes_pkt_data;
22452 
22453 		if (bpf_prog_is_dev_bound(prog->aux) &&
22454 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
22455 			bpf_log(log, "Target program bound device mismatch");
22456 			return -EINVAL;
22457 		}
22458 
22459 		for (i = 0; i < aux->func_info_cnt; i++)
22460 			if (aux->func_info[i].type_id == btf_id) {
22461 				subprog = i;
22462 				break;
22463 			}
22464 		if (subprog == -1) {
22465 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
22466 			return -EINVAL;
22467 		}
22468 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
22469 			bpf_log(log,
22470 				"%s programs cannot attach to exception callback\n",
22471 				prog_extension ? "Extension" : "FENTRY/FEXIT");
22472 			return -EINVAL;
22473 		}
22474 		conservative = aux->func_info_aux[subprog].unreliable;
22475 		if (prog_extension) {
22476 			if (conservative) {
22477 				bpf_log(log,
22478 					"Cannot replace static functions\n");
22479 				return -EINVAL;
22480 			}
22481 			if (!prog->jit_requested) {
22482 				bpf_log(log,
22483 					"Extension programs should be JITed\n");
22484 				return -EINVAL;
22485 			}
22486 			tgt_changes_pkt_data = aux->func
22487 					       ? aux->func[subprog]->aux->changes_pkt_data
22488 					       : aux->changes_pkt_data;
22489 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
22490 				bpf_log(log,
22491 					"Extension program changes packet data, while original does not\n");
22492 				return -EINVAL;
22493 			}
22494 		}
22495 		if (!tgt_prog->jited) {
22496 			bpf_log(log, "Can attach to only JITed progs\n");
22497 			return -EINVAL;
22498 		}
22499 		if (prog_tracing) {
22500 			if (aux->attach_tracing_prog) {
22501 				/*
22502 				 * Target program is an fentry/fexit which is already attached
22503 				 * to another tracing program. More levels of nesting
22504 				 * attachment are not allowed.
22505 				 */
22506 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
22507 				return -EINVAL;
22508 			}
22509 		} else if (tgt_prog->type == prog->type) {
22510 			/*
22511 			 * To avoid potential call chain cycles, prevent attaching of a
22512 			 * program extension to another extension. It's ok to attach
22513 			 * fentry/fexit to extension program.
22514 			 */
22515 			bpf_log(log, "Cannot recursively attach\n");
22516 			return -EINVAL;
22517 		}
22518 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
22519 		    prog_extension &&
22520 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
22521 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
22522 			/* Program extensions can extend all program types
22523 			 * except fentry/fexit. The reason is the following.
22524 			 * The fentry/fexit programs are used for performance
22525 			 * analysis, stats and can be attached to any program
22526 			 * type. When extension program is replacing XDP function
22527 			 * it is necessary to allow performance analysis of all
22528 			 * functions. Both original XDP program and its program
22529 			 * extension. Hence attaching fentry/fexit to
22530 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
22531 			 * fentry/fexit was allowed it would be possible to create
22532 			 * long call chain fentry->extension->fentry->extension
22533 			 * beyond reasonable stack size. Hence extending fentry
22534 			 * is not allowed.
22535 			 */
22536 			bpf_log(log, "Cannot extend fentry/fexit\n");
22537 			return -EINVAL;
22538 		}
22539 	} else {
22540 		if (prog_extension) {
22541 			bpf_log(log, "Cannot replace kernel functions\n");
22542 			return -EINVAL;
22543 		}
22544 	}
22545 
22546 	switch (prog->expected_attach_type) {
22547 	case BPF_TRACE_RAW_TP:
22548 		if (tgt_prog) {
22549 			bpf_log(log,
22550 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
22551 			return -EINVAL;
22552 		}
22553 		if (!btf_type_is_typedef(t)) {
22554 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
22555 				btf_id);
22556 			return -EINVAL;
22557 		}
22558 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
22559 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
22560 				btf_id, tname);
22561 			return -EINVAL;
22562 		}
22563 		tname += sizeof(prefix) - 1;
22564 
22565 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
22566 		 * names. Thus using bpf_raw_event_map to get argument names.
22567 		 */
22568 		btp = bpf_get_raw_tracepoint(tname);
22569 		if (!btp)
22570 			return -EINVAL;
22571 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
22572 					trace_symbol);
22573 		bpf_put_raw_tracepoint(btp);
22574 
22575 		if (fname)
22576 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
22577 
22578 		if (!fname || ret < 0) {
22579 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
22580 				prefix, tname);
22581 			t = btf_type_by_id(btf, t->type);
22582 			if (!btf_type_is_ptr(t))
22583 				/* should never happen in valid vmlinux build */
22584 				return -EINVAL;
22585 		} else {
22586 			t = btf_type_by_id(btf, ret);
22587 			if (!btf_type_is_func(t))
22588 				/* should never happen in valid vmlinux build */
22589 				return -EINVAL;
22590 		}
22591 
22592 		t = btf_type_by_id(btf, t->type);
22593 		if (!btf_type_is_func_proto(t))
22594 			/* should never happen in valid vmlinux build */
22595 			return -EINVAL;
22596 
22597 		break;
22598 	case BPF_TRACE_ITER:
22599 		if (!btf_type_is_func(t)) {
22600 			bpf_log(log, "attach_btf_id %u is not a function\n",
22601 				btf_id);
22602 			return -EINVAL;
22603 		}
22604 		t = btf_type_by_id(btf, t->type);
22605 		if (!btf_type_is_func_proto(t))
22606 			return -EINVAL;
22607 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22608 		if (ret)
22609 			return ret;
22610 		break;
22611 	default:
22612 		if (!prog_extension)
22613 			return -EINVAL;
22614 		fallthrough;
22615 	case BPF_MODIFY_RETURN:
22616 	case BPF_LSM_MAC:
22617 	case BPF_LSM_CGROUP:
22618 	case BPF_TRACE_FENTRY:
22619 	case BPF_TRACE_FEXIT:
22620 		if (!btf_type_is_func(t)) {
22621 			bpf_log(log, "attach_btf_id %u is not a function\n",
22622 				btf_id);
22623 			return -EINVAL;
22624 		}
22625 		if (prog_extension &&
22626 		    btf_check_type_match(log, prog, btf, t))
22627 			return -EINVAL;
22628 		t = btf_type_by_id(btf, t->type);
22629 		if (!btf_type_is_func_proto(t))
22630 			return -EINVAL;
22631 
22632 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
22633 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
22634 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
22635 			return -EINVAL;
22636 
22637 		if (tgt_prog && conservative)
22638 			t = NULL;
22639 
22640 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22641 		if (ret < 0)
22642 			return ret;
22643 
22644 		if (tgt_prog) {
22645 			if (subprog == 0)
22646 				addr = (long) tgt_prog->bpf_func;
22647 			else
22648 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
22649 		} else {
22650 			if (btf_is_module(btf)) {
22651 				mod = btf_try_get_module(btf);
22652 				if (mod)
22653 					addr = find_kallsyms_symbol_value(mod, tname);
22654 				else
22655 					addr = 0;
22656 			} else {
22657 				addr = kallsyms_lookup_name(tname);
22658 			}
22659 			if (!addr) {
22660 				module_put(mod);
22661 				bpf_log(log,
22662 					"The address of function %s cannot be found\n",
22663 					tname);
22664 				return -ENOENT;
22665 			}
22666 		}
22667 
22668 		if (prog->sleepable) {
22669 			ret = -EINVAL;
22670 			switch (prog->type) {
22671 			case BPF_PROG_TYPE_TRACING:
22672 
22673 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
22674 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
22675 				 */
22676 				if (!check_non_sleepable_error_inject(btf_id) &&
22677 				    within_error_injection_list(addr))
22678 					ret = 0;
22679 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
22680 				 * in the fmodret id set with the KF_SLEEPABLE flag.
22681 				 */
22682 				else {
22683 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
22684 										prog);
22685 
22686 					if (flags && (*flags & KF_SLEEPABLE))
22687 						ret = 0;
22688 				}
22689 				break;
22690 			case BPF_PROG_TYPE_LSM:
22691 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
22692 				 * Only some of them are sleepable.
22693 				 */
22694 				if (bpf_lsm_is_sleepable_hook(btf_id))
22695 					ret = 0;
22696 				break;
22697 			default:
22698 				break;
22699 			}
22700 			if (ret) {
22701 				module_put(mod);
22702 				bpf_log(log, "%s is not sleepable\n", tname);
22703 				return ret;
22704 			}
22705 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
22706 			if (tgt_prog) {
22707 				module_put(mod);
22708 				bpf_log(log, "can't modify return codes of BPF programs\n");
22709 				return -EINVAL;
22710 			}
22711 			ret = -EINVAL;
22712 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
22713 			    !check_attach_modify_return(addr, tname))
22714 				ret = 0;
22715 			if (ret) {
22716 				module_put(mod);
22717 				bpf_log(log, "%s() is not modifiable\n", tname);
22718 				return ret;
22719 			}
22720 		}
22721 
22722 		break;
22723 	}
22724 	tgt_info->tgt_addr = addr;
22725 	tgt_info->tgt_name = tname;
22726 	tgt_info->tgt_type = t;
22727 	tgt_info->tgt_mod = mod;
22728 	return 0;
22729 }
22730 
22731 BTF_SET_START(btf_id_deny)
22732 BTF_ID_UNUSED
22733 #ifdef CONFIG_SMP
22734 BTF_ID(func, migrate_disable)
22735 BTF_ID(func, migrate_enable)
22736 #endif
22737 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
22738 BTF_ID(func, rcu_read_unlock_strict)
22739 #endif
22740 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
22741 BTF_ID(func, preempt_count_add)
22742 BTF_ID(func, preempt_count_sub)
22743 #endif
22744 #ifdef CONFIG_PREEMPT_RCU
22745 BTF_ID(func, __rcu_read_lock)
22746 BTF_ID(func, __rcu_read_unlock)
22747 #endif
22748 BTF_SET_END(btf_id_deny)
22749 
22750 static bool can_be_sleepable(struct bpf_prog *prog)
22751 {
22752 	if (prog->type == BPF_PROG_TYPE_TRACING) {
22753 		switch (prog->expected_attach_type) {
22754 		case BPF_TRACE_FENTRY:
22755 		case BPF_TRACE_FEXIT:
22756 		case BPF_MODIFY_RETURN:
22757 		case BPF_TRACE_ITER:
22758 			return true;
22759 		default:
22760 			return false;
22761 		}
22762 	}
22763 	return prog->type == BPF_PROG_TYPE_LSM ||
22764 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
22765 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
22766 }
22767 
22768 static int check_attach_btf_id(struct bpf_verifier_env *env)
22769 {
22770 	struct bpf_prog *prog = env->prog;
22771 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
22772 	struct bpf_attach_target_info tgt_info = {};
22773 	u32 btf_id = prog->aux->attach_btf_id;
22774 	struct bpf_trampoline *tr;
22775 	int ret;
22776 	u64 key;
22777 
22778 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
22779 		if (prog->sleepable)
22780 			/* attach_btf_id checked to be zero already */
22781 			return 0;
22782 		verbose(env, "Syscall programs can only be sleepable\n");
22783 		return -EINVAL;
22784 	}
22785 
22786 	if (prog->sleepable && !can_be_sleepable(prog)) {
22787 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
22788 		return -EINVAL;
22789 	}
22790 
22791 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
22792 		return check_struct_ops_btf_id(env);
22793 
22794 	if (prog->type != BPF_PROG_TYPE_TRACING &&
22795 	    prog->type != BPF_PROG_TYPE_LSM &&
22796 	    prog->type != BPF_PROG_TYPE_EXT)
22797 		return 0;
22798 
22799 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
22800 	if (ret)
22801 		return ret;
22802 
22803 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
22804 		/* to make freplace equivalent to their targets, they need to
22805 		 * inherit env->ops and expected_attach_type for the rest of the
22806 		 * verification
22807 		 */
22808 		env->ops = bpf_verifier_ops[tgt_prog->type];
22809 		prog->expected_attach_type = tgt_prog->expected_attach_type;
22810 	}
22811 
22812 	/* store info about the attachment target that will be used later */
22813 	prog->aux->attach_func_proto = tgt_info.tgt_type;
22814 	prog->aux->attach_func_name = tgt_info.tgt_name;
22815 	prog->aux->mod = tgt_info.tgt_mod;
22816 
22817 	if (tgt_prog) {
22818 		prog->aux->saved_dst_prog_type = tgt_prog->type;
22819 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
22820 	}
22821 
22822 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
22823 		prog->aux->attach_btf_trace = true;
22824 		return 0;
22825 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
22826 		if (!bpf_iter_prog_supported(prog))
22827 			return -EINVAL;
22828 		return 0;
22829 	}
22830 
22831 	if (prog->type == BPF_PROG_TYPE_LSM) {
22832 		ret = bpf_lsm_verify_prog(&env->log, prog);
22833 		if (ret < 0)
22834 			return ret;
22835 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
22836 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
22837 		return -EINVAL;
22838 	}
22839 
22840 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
22841 	tr = bpf_trampoline_get(key, &tgt_info);
22842 	if (!tr)
22843 		return -ENOMEM;
22844 
22845 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
22846 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
22847 
22848 	prog->aux->dst_trampoline = tr;
22849 	return 0;
22850 }
22851 
22852 struct btf *bpf_get_btf_vmlinux(void)
22853 {
22854 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
22855 		mutex_lock(&bpf_verifier_lock);
22856 		if (!btf_vmlinux)
22857 			btf_vmlinux = btf_parse_vmlinux();
22858 		mutex_unlock(&bpf_verifier_lock);
22859 	}
22860 	return btf_vmlinux;
22861 }
22862 
22863 /*
22864  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
22865  * this case expect that every file descriptor in the array is either a map or
22866  * a BTF. Everything else is considered to be trash.
22867  */
22868 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
22869 {
22870 	struct bpf_map *map;
22871 	struct btf *btf;
22872 	CLASS(fd, f)(fd);
22873 	int err;
22874 
22875 	map = __bpf_map_get(f);
22876 	if (!IS_ERR(map)) {
22877 		err = __add_used_map(env, map);
22878 		if (err < 0)
22879 			return err;
22880 		return 0;
22881 	}
22882 
22883 	btf = __btf_get_by_fd(f);
22884 	if (!IS_ERR(btf)) {
22885 		err = __add_used_btf(env, btf);
22886 		if (err < 0)
22887 			return err;
22888 		return 0;
22889 	}
22890 
22891 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
22892 	return PTR_ERR(map);
22893 }
22894 
22895 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
22896 {
22897 	size_t size = sizeof(int);
22898 	int ret;
22899 	int fd;
22900 	u32 i;
22901 
22902 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
22903 
22904 	/*
22905 	 * The only difference between old (no fd_array_cnt is given) and new
22906 	 * APIs is that in the latter case the fd_array is expected to be
22907 	 * continuous and is scanned for map fds right away
22908 	 */
22909 	if (!attr->fd_array_cnt)
22910 		return 0;
22911 
22912 	/* Check for integer overflow */
22913 	if (attr->fd_array_cnt >= (U32_MAX / size)) {
22914 		verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
22915 		return -EINVAL;
22916 	}
22917 
22918 	for (i = 0; i < attr->fd_array_cnt; i++) {
22919 		if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
22920 			return -EFAULT;
22921 
22922 		ret = add_fd_from_fd_array(env, fd);
22923 		if (ret)
22924 			return ret;
22925 	}
22926 
22927 	return 0;
22928 }
22929 
22930 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
22931 {
22932 	u64 start_time = ktime_get_ns();
22933 	struct bpf_verifier_env *env;
22934 	int i, len, ret = -EINVAL, err;
22935 	u32 log_true_size;
22936 	bool is_priv;
22937 
22938 	/* no program is valid */
22939 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
22940 		return -EINVAL;
22941 
22942 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
22943 	 * allocate/free it every time bpf_check() is called
22944 	 */
22945 	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
22946 	if (!env)
22947 		return -ENOMEM;
22948 
22949 	env->bt.env = env;
22950 
22951 	len = (*prog)->len;
22952 	env->insn_aux_data =
22953 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
22954 	ret = -ENOMEM;
22955 	if (!env->insn_aux_data)
22956 		goto err_free_env;
22957 	for (i = 0; i < len; i++)
22958 		env->insn_aux_data[i].orig_idx = i;
22959 	env->prog = *prog;
22960 	env->ops = bpf_verifier_ops[env->prog->type];
22961 
22962 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
22963 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
22964 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
22965 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
22966 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
22967 
22968 	bpf_get_btf_vmlinux();
22969 
22970 	/* grab the mutex to protect few globals used by verifier */
22971 	if (!is_priv)
22972 		mutex_lock(&bpf_verifier_lock);
22973 
22974 	/* user could have requested verbose verifier output
22975 	 * and supplied buffer to store the verification trace
22976 	 */
22977 	ret = bpf_vlog_init(&env->log, attr->log_level,
22978 			    (char __user *) (unsigned long) attr->log_buf,
22979 			    attr->log_size);
22980 	if (ret)
22981 		goto err_unlock;
22982 
22983 	ret = process_fd_array(env, attr, uattr);
22984 	if (ret)
22985 		goto skip_full_check;
22986 
22987 	mark_verifier_state_clean(env);
22988 
22989 	if (IS_ERR(btf_vmlinux)) {
22990 		/* Either gcc or pahole or kernel are broken. */
22991 		verbose(env, "in-kernel BTF is malformed\n");
22992 		ret = PTR_ERR(btf_vmlinux);
22993 		goto skip_full_check;
22994 	}
22995 
22996 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
22997 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
22998 		env->strict_alignment = true;
22999 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
23000 		env->strict_alignment = false;
23001 
23002 	if (is_priv)
23003 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
23004 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
23005 
23006 	env->explored_states = kvcalloc(state_htab_size(env),
23007 				       sizeof(struct bpf_verifier_state_list *),
23008 				       GFP_USER);
23009 	ret = -ENOMEM;
23010 	if (!env->explored_states)
23011 		goto skip_full_check;
23012 
23013 	ret = check_btf_info_early(env, attr, uattr);
23014 	if (ret < 0)
23015 		goto skip_full_check;
23016 
23017 	ret = add_subprog_and_kfunc(env);
23018 	if (ret < 0)
23019 		goto skip_full_check;
23020 
23021 	ret = check_subprogs(env);
23022 	if (ret < 0)
23023 		goto skip_full_check;
23024 
23025 	ret = check_btf_info(env, attr, uattr);
23026 	if (ret < 0)
23027 		goto skip_full_check;
23028 
23029 	ret = resolve_pseudo_ldimm64(env);
23030 	if (ret < 0)
23031 		goto skip_full_check;
23032 
23033 	if (bpf_prog_is_offloaded(env->prog->aux)) {
23034 		ret = bpf_prog_offload_verifier_prep(env->prog);
23035 		if (ret)
23036 			goto skip_full_check;
23037 	}
23038 
23039 	ret = check_cfg(env);
23040 	if (ret < 0)
23041 		goto skip_full_check;
23042 
23043 	ret = check_attach_btf_id(env);
23044 	if (ret)
23045 		goto skip_full_check;
23046 
23047 	ret = mark_fastcall_patterns(env);
23048 	if (ret < 0)
23049 		goto skip_full_check;
23050 
23051 	ret = do_check_main(env);
23052 	ret = ret ?: do_check_subprogs(env);
23053 
23054 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
23055 		ret = bpf_prog_offload_finalize(env);
23056 
23057 skip_full_check:
23058 	kvfree(env->explored_states);
23059 
23060 	/* might decrease stack depth, keep it before passes that
23061 	 * allocate additional slots.
23062 	 */
23063 	if (ret == 0)
23064 		ret = remove_fastcall_spills_fills(env);
23065 
23066 	if (ret == 0)
23067 		ret = check_max_stack_depth(env);
23068 
23069 	/* instruction rewrites happen after this point */
23070 	if (ret == 0)
23071 		ret = optimize_bpf_loop(env);
23072 
23073 	if (is_priv) {
23074 		if (ret == 0)
23075 			opt_hard_wire_dead_code_branches(env);
23076 		if (ret == 0)
23077 			ret = opt_remove_dead_code(env);
23078 		if (ret == 0)
23079 			ret = opt_remove_nops(env);
23080 	} else {
23081 		if (ret == 0)
23082 			sanitize_dead_code(env);
23083 	}
23084 
23085 	if (ret == 0)
23086 		/* program is valid, convert *(u32*)(ctx + off) accesses */
23087 		ret = convert_ctx_accesses(env);
23088 
23089 	if (ret == 0)
23090 		ret = do_misc_fixups(env);
23091 
23092 	/* do 32-bit optimization after insn patching has done so those patched
23093 	 * insns could be handled correctly.
23094 	 */
23095 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
23096 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
23097 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
23098 								     : false;
23099 	}
23100 
23101 	if (ret == 0)
23102 		ret = fixup_call_args(env);
23103 
23104 	env->verification_time = ktime_get_ns() - start_time;
23105 	print_verification_stats(env);
23106 	env->prog->aux->verified_insns = env->insn_processed;
23107 
23108 	/* preserve original error even if log finalization is successful */
23109 	err = bpf_vlog_finalize(&env->log, &log_true_size);
23110 	if (err)
23111 		ret = err;
23112 
23113 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
23114 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
23115 				  &log_true_size, sizeof(log_true_size))) {
23116 		ret = -EFAULT;
23117 		goto err_release_maps;
23118 	}
23119 
23120 	if (ret)
23121 		goto err_release_maps;
23122 
23123 	if (env->used_map_cnt) {
23124 		/* if program passed verifier, update used_maps in bpf_prog_info */
23125 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
23126 							  sizeof(env->used_maps[0]),
23127 							  GFP_KERNEL);
23128 
23129 		if (!env->prog->aux->used_maps) {
23130 			ret = -ENOMEM;
23131 			goto err_release_maps;
23132 		}
23133 
23134 		memcpy(env->prog->aux->used_maps, env->used_maps,
23135 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
23136 		env->prog->aux->used_map_cnt = env->used_map_cnt;
23137 	}
23138 	if (env->used_btf_cnt) {
23139 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
23140 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
23141 							  sizeof(env->used_btfs[0]),
23142 							  GFP_KERNEL);
23143 		if (!env->prog->aux->used_btfs) {
23144 			ret = -ENOMEM;
23145 			goto err_release_maps;
23146 		}
23147 
23148 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
23149 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
23150 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
23151 	}
23152 	if (env->used_map_cnt || env->used_btf_cnt) {
23153 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
23154 		 * bpf_ld_imm64 instructions
23155 		 */
23156 		convert_pseudo_ld_imm64(env);
23157 	}
23158 
23159 	adjust_btf_func(env);
23160 
23161 err_release_maps:
23162 	if (!env->prog->aux->used_maps)
23163 		/* if we didn't copy map pointers into bpf_prog_info, release
23164 		 * them now. Otherwise free_used_maps() will release them.
23165 		 */
23166 		release_maps(env);
23167 	if (!env->prog->aux->used_btfs)
23168 		release_btfs(env);
23169 
23170 	/* extension progs temporarily inherit the attach_type of their targets
23171 	   for verification purposes, so set it back to zero before returning
23172 	 */
23173 	if (env->prog->type == BPF_PROG_TYPE_EXT)
23174 		env->prog->expected_attach_type = 0;
23175 
23176 	*prog = env->prog;
23177 
23178 	module_put(env->attach_btf_mod);
23179 err_unlock:
23180 	if (!is_priv)
23181 		mutex_unlock(&bpf_verifier_lock);
23182 	vfree(env->insn_aux_data);
23183 	kvfree(env->insn_hist);
23184 err_free_env:
23185 	kvfree(env);
23186 	return ret;
23187 }
23188