xref: /linux/kernel/bpf/verifier.c (revision 333f7de560e1196034b67db16916b10a0c529e1d)
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/cnum.h>
30 #include <linux/bpf_mem_alloc.h>
31 #include <net/xdp.h>
32 #include <linux/trace_events.h>
33 #include <linux/kallsyms.h>
34 
35 #include "disasm.h"
36 
37 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
38 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
39 	[_id] = & _name ## _verifier_ops,
40 #define BPF_MAP_TYPE(_id, _ops)
41 #define BPF_LINK_TYPE(_id, _name)
42 #include <linux/bpf_types.h>
43 #undef BPF_PROG_TYPE
44 #undef BPF_MAP_TYPE
45 #undef BPF_LINK_TYPE
46 };
47 
48 enum bpf_features {
49 	BPF_FEAT_RDONLY_CAST_TO_VOID = 0,
50 	BPF_FEAT_STREAMS	     = 1,
51 	__MAX_BPF_FEAT,
52 };
53 
54 struct bpf_mem_alloc bpf_global_percpu_ma;
55 static bool bpf_global_percpu_ma_set;
56 
57 /* bpf_check() is a static code analyzer that walks eBPF program
58  * instruction by instruction and updates register/stack state.
59  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
60  *
61  * The first pass is depth-first-search to check that the program is a DAG.
62  * It rejects the following programs:
63  * - larger than BPF_MAXINSNS insns
64  * - if loop is present (detected via back-edge)
65  * - unreachable insns exist (shouldn't be a forest. program = one function)
66  * - out of bounds or malformed jumps
67  * The second pass is all possible path descent from the 1st insn.
68  * Since it's analyzing all paths through the program, the length of the
69  * analysis is limited to 64k insn, which may be hit even if total number of
70  * insn is less then 4K, but there are too many branches that change stack/regs.
71  * Number of 'branches to be analyzed' is limited to 1k
72  *
73  * On entry to each instruction, each register has a type, and the instruction
74  * changes the types of the registers depending on instruction semantics.
75  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
76  * copied to R1.
77  *
78  * All registers are 64-bit.
79  * R0 - return register
80  * R1-R5 argument passing registers
81  * R6-R9 callee saved registers
82  * R10 - frame pointer read-only
83  *
84  * At the start of BPF program the register R1 contains a pointer to bpf_context
85  * and has type PTR_TO_CTX.
86  *
87  * Verifier tracks arithmetic operations on pointers in case:
88  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
89  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
90  * 1st insn copies R10 (which has FRAME_PTR) type into R1
91  * and 2nd arithmetic instruction is pattern matched to recognize
92  * that it wants to construct a pointer to some element within stack.
93  * So after 2nd insn, the register R1 has type PTR_TO_STACK
94  * (and -20 constant is saved for further stack bounds checking).
95  * Meaning that this reg is a pointer to stack plus known immediate constant.
96  *
97  * Most of the time the registers have SCALAR_VALUE type, which
98  * means the register has some value, but it's not a valid pointer.
99  * (like pointer plus pointer becomes SCALAR_VALUE type)
100  *
101  * When verifier sees load or store instructions the type of base register
102  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
103  * four pointer types recognized by check_mem_access() function.
104  *
105  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
106  * and the range of [ptr, ptr + map's value_size) is accessible.
107  *
108  * registers used to pass values to function calls are checked against
109  * function argument constraints.
110  *
111  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
112  * It means that the register type passed to this function must be
113  * PTR_TO_STACK and it will be used inside the function as
114  * 'pointer to map element key'
115  *
116  * For example the argument constraints for bpf_map_lookup_elem():
117  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
118  *   .arg1_type = ARG_CONST_MAP_PTR,
119  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
120  *
121  * ret_type says that this function returns 'pointer to map elem value or null'
122  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
123  * 2nd argument should be a pointer to stack, which will be used inside
124  * the helper function as a pointer to map element key.
125  *
126  * On the kernel side the helper function looks like:
127  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
128  * {
129  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
130  *    void *key = (void *) (unsigned long) r2;
131  *    void *value;
132  *
133  *    here kernel can access 'key' and 'map' pointers safely, knowing that
134  *    [key, key + map->key_size) bytes are valid and were initialized on
135  *    the stack of eBPF program.
136  * }
137  *
138  * Corresponding eBPF program may look like:
139  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
140  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
141  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
142  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
143  * here verifier looks at prototype of map_lookup_elem() and sees:
144  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
145  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
146  *
147  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
148  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
149  * and were initialized prior to this call.
150  * If it's ok, then verifier allows this BPF_CALL insn and looks at
151  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
152  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
153  * returns either pointer to map value or NULL.
154  *
155  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
156  * insn, the register holding that pointer in the true branch changes state to
157  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
158  * branch. See check_cond_jmp_op().
159  *
160  * After the call R0 is set to return type of the function and registers R1-R5
161  * are set to NOT_INIT to indicate that they are no longer readable.
162  *
163  * The following reference types represent a potential reference to a kernel
164  * resource which, after first being allocated, must be checked and freed by
165  * the BPF program:
166  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
167  *
168  * When the verifier sees a helper call return a reference type, it allocates a
169  * pointer id for the reference and stores it in the current function state.
170  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
171  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
172  * passes through a NULL-check conditional. For the branch wherein the state is
173  * changed to CONST_IMM, the verifier releases the reference.
174  *
175  * For each helper function that allocates a reference, such as
176  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
177  * bpf_sk_release(). When a reference type passes into the release function,
178  * the verifier also releases the reference. If any unchecked or unreleased
179  * reference remains at the end of the program, the verifier rejects it.
180  */
181 
182 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
183 struct bpf_verifier_stack_elem {
184 	/* verifier state is 'st'
185 	 * before processing instruction 'insn_idx'
186 	 * and after processing instruction 'prev_insn_idx'
187 	 */
188 	struct bpf_verifier_state st;
189 	int insn_idx;
190 	int prev_insn_idx;
191 	struct bpf_verifier_stack_elem *next;
192 	/* length of verifier log at the time this state was pushed on stack */
193 	u32 log_pos;
194 };
195 
196 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
197 #define BPF_COMPLEXITY_LIMIT_STATES	64
198 
199 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
200 
201 #define BPF_PRIV_STACK_MIN_SIZE		64
202 
203 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id);
204 static int release_reference_nomark(struct bpf_verifier_state *state, int id);
205 static int release_reference(struct bpf_verifier_env *env, int id);
206 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
207 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
208 static bool is_tracing_prog_type(enum bpf_prog_type type);
209 static int ref_set_non_owning(struct bpf_verifier_env *env,
210 			      struct bpf_reg_state *reg);
211 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg);
212 static inline bool in_sleepable_context(struct bpf_verifier_env *env);
213 static const char *non_sleepable_context_description(struct bpf_verifier_env *env);
214 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);
215 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);
216 
217 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
218 			      struct bpf_map *map,
219 			      bool unpriv, bool poison)
220 {
221 	unpriv |= bpf_map_ptr_unpriv(aux);
222 	aux->map_ptr_state.unpriv = unpriv;
223 	aux->map_ptr_state.poison = poison;
224 	aux->map_ptr_state.map_ptr = map;
225 }
226 
227 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
228 {
229 	bool poisoned = bpf_map_key_poisoned(aux);
230 
231 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
232 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
233 }
234 
235 static void update_ref_obj(struct ref_obj_desc *ref_obj, struct bpf_reg_state *reg)
236 {
237 	ref_obj->id = reg->id;
238 	ref_obj->parent_id = reg->parent_id;
239 	ref_obj->cnt++;
240 }
241 
242 static int validate_ref_obj(struct bpf_verifier_env *env, struct ref_obj_desc *ref_obj)
243 {
244 	if (ref_obj->cnt > 1) {
245 		verifier_bug(env, "function expects only one referenced object but got %d\n",
246 			     ref_obj->cnt);
247 		return -EFAULT;
248 	}
249 
250 	return 0;
251 }
252 
253 struct bpf_call_arg_meta {
254 	struct bpf_map_desc map;
255 	struct bpf_dynptr_desc dynptr;
256 	struct ref_obj_desc ref_obj;
257 	bool raw_mode;
258 	bool pkt_access;
259 	u8 release_regno;
260 	int regno;
261 	int access_size;
262 	int mem_size;
263 	u64 msize_max_value;
264 	int func_id;
265 	struct btf *btf;
266 	u32 btf_id;
267 	struct btf *ret_btf;
268 	u32 ret_btf_id;
269 	u32 subprogno;
270 	struct btf_field *kptr_field;
271 	s64 const_map_key;
272 };
273 
274 struct bpf_kfunc_meta {
275 	struct btf *btf;
276 	const struct btf_type *proto;
277 	const char *name;
278 	const u32 *flags;
279 	s32 id;
280 };
281 
282 struct btf *btf_vmlinux;
283 
284 typedef struct argno {
285 	int argno;
286 } argno_t;
287 
288 static argno_t argno_from_reg(u32 regno)
289 {
290 	return (argno_t){ .argno = regno };
291 }
292 
293 static argno_t argno_from_arg(u32 arg)
294 {
295 	return (argno_t){ .argno = -arg };
296 }
297 
298 static int reg_from_argno(argno_t a)
299 {
300 	if (a.argno >= 0)
301 		return a.argno;
302 	if (a.argno >= -MAX_BPF_FUNC_REG_ARGS)
303 		return -a.argno;
304 	return -1;
305 }
306 
307 static int arg_from_argno(argno_t a)
308 {
309 	if (a.argno < 0)
310 		return -a.argno;
311 	return -1;
312 }
313 
314 static int arg_idx_from_argno(argno_t a)
315 {
316 	return arg_from_argno(a) - 1;
317 }
318 
319 static const char *btf_type_name(const struct btf *btf, u32 id)
320 {
321 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
322 }
323 
324 static DEFINE_MUTEX(bpf_verifier_lock);
325 static DEFINE_MUTEX(bpf_percpu_ma_lock);
326 
327 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
328 {
329 	struct bpf_verifier_env *env = private_data;
330 	va_list args;
331 
332 	if (!bpf_verifier_log_needed(&env->log))
333 		return;
334 
335 	va_start(args, fmt);
336 	bpf_verifier_vlog(&env->log, fmt, args);
337 	va_end(args);
338 }
339 
340 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
341 				   struct bpf_reg_state *reg,
342 				   struct bpf_retval_range range, const char *ctx,
343 				   const char *reg_name)
344 {
345 	bool unknown = true;
346 
347 	verbose(env, "%s the register %s has", ctx, reg_name);
348 	if (reg_smin(reg) > S64_MIN) {
349 		verbose(env, " smin=%lld", reg_smin(reg));
350 		unknown = false;
351 	}
352 	if (reg_smax(reg) < S64_MAX) {
353 		verbose(env, " smax=%lld", reg_smax(reg));
354 		unknown = false;
355 	}
356 	if (unknown)
357 		verbose(env, " unknown scalar value");
358 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
359 }
360 
361 static bool reg_not_null(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
362 {
363 	enum bpf_reg_type type;
364 
365 	type = reg->type;
366 	if (type_may_be_null(type))
367 		return false;
368 
369 	type = base_type(type);
370 	return type == PTR_TO_SOCKET ||
371 		type == PTR_TO_TCP_SOCK ||
372 		type == PTR_TO_MAP_VALUE ||
373 		type == PTR_TO_MAP_KEY ||
374 		type == PTR_TO_SOCK_COMMON ||
375 		(type == PTR_TO_BTF_ID && is_trusted_reg(env, reg)) ||
376 		(type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) ||
377 		type == CONST_PTR_TO_MAP;
378 }
379 
380 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
381 {
382 	struct btf_record *rec = NULL;
383 	struct btf_struct_meta *meta;
384 
385 	if (reg->type == PTR_TO_MAP_VALUE) {
386 		rec = reg->map_ptr->record;
387 	} else if (type_is_ptr_alloc_obj(reg->type)) {
388 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
389 		if (meta)
390 			rec = meta->record;
391 	}
392 	return rec;
393 }
394 
395 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog)
396 {
397 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
398 
399 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
400 }
401 
402 static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog)
403 {
404 	const struct btf_type *type, *func, *func_proto;
405 	const struct btf *btf = env->prog->aux->btf;
406 	u32 btf_id;
407 
408 	btf_id = env->prog->aux->func_info[subprog].type_id;
409 
410 	func = btf_type_by_id(btf, btf_id);
411 	if (verifier_bug_if(!func, env, "btf_id %u not found", btf_id))
412 		return false;
413 
414 	func_proto = btf_type_by_id(btf, func->type);
415 	if (!func_proto)
416 		return false;
417 
418 	type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
419 	if (!type)
420 		return false;
421 
422 	return btf_type_is_void(type);
423 }
424 
425 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
426 {
427 	struct bpf_func_info *info;
428 
429 	if (!env->prog->aux->func_info)
430 		return "";
431 
432 	info = &env->prog->aux->func_info[subprog];
433 	return btf_type_name(env->prog->aux->btf, info->type_id);
434 }
435 
436 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
437 {
438 	struct bpf_subprog_info *info = subprog_info(env, subprog);
439 
440 	info->is_cb = true;
441 	info->is_async_cb = true;
442 	info->is_exception_cb = true;
443 }
444 
445 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
446 {
447 	return subprog_info(env, subprog)->is_exception_cb;
448 }
449 
450 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
451 {
452 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
453 }
454 
455 static bool type_is_rdonly_mem(u32 type)
456 {
457 	return type & MEM_RDONLY;
458 }
459 
460 static bool is_acquire_function(enum bpf_func_id func_id,
461 				const struct bpf_map *map)
462 {
463 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
464 
465 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
466 	    func_id == BPF_FUNC_sk_lookup_udp ||
467 	    func_id == BPF_FUNC_skc_lookup_tcp ||
468 	    func_id == BPF_FUNC_ringbuf_reserve ||
469 	    func_id == BPF_FUNC_kptr_xchg)
470 		return true;
471 
472 	if (func_id == BPF_FUNC_map_lookup_elem &&
473 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
474 	     map_type == BPF_MAP_TYPE_SOCKHASH))
475 		return true;
476 
477 	return false;
478 }
479 
480 static bool is_ptr_cast_function(enum bpf_func_id func_id)
481 {
482 	return func_id == BPF_FUNC_tcp_sock ||
483 		func_id == BPF_FUNC_sk_fullsock ||
484 		func_id == BPF_FUNC_skc_to_tcp_sock ||
485 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
486 		func_id == BPF_FUNC_skc_to_udp6_sock ||
487 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
488 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
489 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
490 }
491 
492 static bool is_sync_callback_calling_kfunc(u32 btf_id);
493 static bool is_async_callback_calling_kfunc(u32 btf_id);
494 static bool is_callback_calling_kfunc(u32 btf_id);
495 
496 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id);
497 static bool is_task_work_add_kfunc(u32 func_id);
498 
499 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
500 {
501 	return func_id == BPF_FUNC_for_each_map_elem ||
502 	       func_id == BPF_FUNC_find_vma ||
503 	       func_id == BPF_FUNC_loop ||
504 	       func_id == BPF_FUNC_user_ringbuf_drain;
505 }
506 
507 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
508 {
509 	return func_id == BPF_FUNC_timer_set_callback;
510 }
511 
512 static bool is_callback_calling_function(enum bpf_func_id func_id)
513 {
514 	return is_sync_callback_calling_function(func_id) ||
515 	       is_async_callback_calling_function(func_id);
516 }
517 
518 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn)
519 {
520 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
521 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
522 }
523 
524 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn)
525 {
526 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
527 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
528 }
529 
530 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn)
531 {
532 	/* bpf_timer callbacks are never sleepable. */
533 	if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback)
534 		return false;
535 
536 	/* bpf_wq and bpf_task_work callbacks are always sleepable. */
537 	if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
538 	    (is_bpf_wq_set_callback_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm)))
539 		return true;
540 
541 	verifier_bug(env, "unhandled async callback in is_async_cb_sleepable");
542 	return false;
543 }
544 
545 bool bpf_is_may_goto_insn(struct bpf_insn *insn)
546 {
547 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
548 }
549 
550 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
551 {
552        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
553 
554        /* We need to check that slots between [spi - nr_slots + 1, spi] are
555 	* within [0, allocated_stack).
556 	*
557 	* Please note that the spi grows downwards. For example, a dynptr
558 	* takes the size of two stack slots; the first slot will be at
559 	* spi and the second slot will be at spi - 1.
560 	*/
561        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
562 }
563 
564 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
565 			          const char *obj_kind, int nr_slots)
566 {
567 	int off, spi;
568 
569 	if (!tnum_is_const(reg->var_off)) {
570 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
571 		return -EINVAL;
572 	}
573 
574 	off = reg->var_off.value;
575 	if (off % BPF_REG_SIZE) {
576 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
577 		return -EINVAL;
578 	}
579 
580 	spi = bpf_get_spi(off);
581 	if (spi + 1 < nr_slots) {
582 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
583 		return -EINVAL;
584 	}
585 
586 	if (!is_spi_bounds_valid(bpf_func(env, reg), spi, nr_slots))
587 		return -ERANGE;
588 	return spi;
589 }
590 
591 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
592 {
593 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
594 }
595 
596 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
597 {
598 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
599 }
600 
601 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
602 {
603 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
604 }
605 
606 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
607 {
608 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
609 	case DYNPTR_TYPE_LOCAL:
610 		return BPF_DYNPTR_TYPE_LOCAL;
611 	case DYNPTR_TYPE_RINGBUF:
612 		return BPF_DYNPTR_TYPE_RINGBUF;
613 	case DYNPTR_TYPE_SKB:
614 		return BPF_DYNPTR_TYPE_SKB;
615 	case DYNPTR_TYPE_XDP:
616 		return BPF_DYNPTR_TYPE_XDP;
617 	case DYNPTR_TYPE_SKB_META:
618 		return BPF_DYNPTR_TYPE_SKB_META;
619 	case DYNPTR_TYPE_FILE:
620 		return BPF_DYNPTR_TYPE_FILE;
621 	default:
622 		return BPF_DYNPTR_TYPE_INVALID;
623 	}
624 }
625 
626 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
627 {
628 	switch (type) {
629 	case BPF_DYNPTR_TYPE_LOCAL:
630 		return DYNPTR_TYPE_LOCAL;
631 	case BPF_DYNPTR_TYPE_RINGBUF:
632 		return DYNPTR_TYPE_RINGBUF;
633 	case BPF_DYNPTR_TYPE_SKB:
634 		return DYNPTR_TYPE_SKB;
635 	case BPF_DYNPTR_TYPE_XDP:
636 		return DYNPTR_TYPE_XDP;
637 	case BPF_DYNPTR_TYPE_SKB_META:
638 		return DYNPTR_TYPE_SKB_META;
639 	case BPF_DYNPTR_TYPE_FILE:
640 		return DYNPTR_TYPE_FILE;
641 	default:
642 		return 0;
643 	}
644 }
645 
646 static bool dynptr_type_referenced(enum bpf_dynptr_type type)
647 {
648 	return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE;
649 }
650 
651 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
652 			      enum bpf_dynptr_type type,
653 			      bool first_slot, int id, int parent_id);
654 
655 
656 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
657 				   struct bpf_reg_state *sreg1,
658 				   struct bpf_reg_state *sreg2,
659 				   enum bpf_dynptr_type type, int parent_id)
660 {
661 	int id = ++env->id_gen;
662 
663 	__mark_dynptr_reg(sreg1, type, true, id, parent_id);
664 	__mark_dynptr_reg(sreg2, type, false, id, parent_id);
665 }
666 
667 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
668 			       struct bpf_reg_state *reg,
669 			       enum bpf_dynptr_type type)
670 {
671 	__mark_dynptr_reg(reg, type, true, ++env->id_gen, 0);
672 }
673 
674 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
675 				        struct bpf_func_state *state, int spi);
676 
677 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
678 				   enum bpf_arg_type arg_type, int insn_idx,
679 				   struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr)
680 {
681 	struct bpf_func_state *state = bpf_func(env, reg);
682 	int spi, i, err, parent_id = 0;
683 	enum bpf_dynptr_type type;
684 
685 	spi = dynptr_get_spi(env, reg);
686 	if (spi < 0)
687 		return spi;
688 
689 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
690 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
691 	 * to ensure that for the following example:
692 	 *	[d1][d1][d2][d2]
693 	 * spi    3   2   1   0
694 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
695 	 * case they do belong to same dynptr, second call won't see slot_type
696 	 * as STACK_DYNPTR and will simply skip destruction.
697 	 */
698 	err = destroy_if_dynptr_stack_slot(env, state, spi);
699 	if (err)
700 		return err;
701 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
702 	if (err)
703 		return err;
704 
705 	for (i = 0; i < BPF_REG_SIZE; i++) {
706 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
707 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
708 	}
709 
710 	type = arg_to_dynptr_type(arg_type);
711 	if (type == BPF_DYNPTR_TYPE_INVALID)
712 		return -EINVAL;
713 
714 	if (dynptr->type == BPF_DYNPTR_TYPE_INVALID) { /* dynptr constructors */
715 		err = validate_ref_obj(env, ref_obj);
716 		if (err)
717 			return err;
718 
719 		/* Track parent's id if the parent is a referenced object */
720 		parent_id = ref_obj->id;
721 
722 		if (dynptr_type_referenced(type)) {
723 			int id;
724 
725 			/*
726 			 * Create an intermediate reference that tracks the referenced
727 			 * object for the referenced dynptr. Freeing a referenced dynptr
728 			 * through helpers/kfuncs will invalidate all clones.
729 			 */
730 			id = acquire_reference(env, insn_idx, parent_id);
731 			if (id < 0)
732 				return id;
733 
734 			parent_id = id;
735 		}
736 	} else { /* bpf_dynptr_clone() */
737 		parent_id = dynptr->parent_id;
738 	}
739 
740 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
741 			       &state->stack[spi - 1].spilled_ptr, type, parent_id);
742 
743 	return 0;
744 }
745 
746 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_stack_state *stack)
747 {
748 	int i;
749 
750 	for (i = 0; i < BPF_REG_SIZE; i++) {
751 		stack[0].slot_type[i] = STACK_INVALID;
752 		stack[1].slot_type[i] = STACK_INVALID;
753 	}
754 
755 	bpf_mark_reg_not_init(env, &stack[0].spilled_ptr);
756 	bpf_mark_reg_not_init(env, &stack[1].spilled_ptr);
757 }
758 
759 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
760 {
761 	struct bpf_func_state *state = bpf_func(env, reg);
762 	int spi;
763 
764 	spi = dynptr_get_spi(env, reg);
765 	if (spi < 0)
766 		return spi;
767 
768 	/*
769 	 * For referenced dynptr, release the parent ref which cascades to
770 	 * all clones and derived slices. For non-referenced dynptr, only
771 	 * the dynptr and slices derived from it will be invalidated.
772 	 */
773 	reg = &state->stack[spi].spilled_ptr;
774 	return release_reference(env, dynptr_type_referenced(reg->dynptr.type)
775 				      ? reg->parent_id
776 				      : reg->id);
777 }
778 
779 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
780 			       struct bpf_reg_state *reg);
781 
782 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
783 {
784 	if (!env->allow_ptr_leaks)
785 		bpf_mark_reg_not_init(env, reg);
786 	else
787 		__mark_reg_unknown(env, reg);
788 }
789 
790 static int dynptr_ref_cnt(struct bpf_verifier_env *env, int v_parent_id)
791 {
792 	struct bpf_stack_state *stack;
793 	struct bpf_func_state *state;
794 	struct bpf_reg_state *reg;
795 	int ref_cnt = 0;
796 
797 	bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, 1 << STACK_DYNPTR, ({
798 		if (!stack || stack->slot_type[0] != STACK_DYNPTR)
799 			continue;
800 		if (!stack->spilled_ptr.dynptr.first_slot)
801 			continue;
802 		if (stack->spilled_ptr.parent_id == v_parent_id)
803 			ref_cnt++;
804 	}));
805 
806 	return ref_cnt;
807 }
808 
809 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
810 				        struct bpf_func_state *state, int spi)
811 {
812 	int err = 0;
813 
814 	/* We always ensure that STACK_DYNPTR is never set partially,
815 	 * hence just checking for slot_type[0] is enough. This is
816 	 * different for STACK_SPILL, where it may be only set for
817 	 * 1 byte, so code has to use is_spilled_reg.
818 	 */
819 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
820 		return 0;
821 
822 	/* Reposition spi to first slot */
823 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
824 		spi = spi + 1;
825 
826 	/*
827 	 * A referenced dynptr can be overwritten only if there is at
828 	 * least one other dynptr sharing the same virtual ref parent,
829 	 * ensuring the reference can still be properly released.
830 	 */
831 	if (dynptr_type_referenced(state->stack[spi].spilled_ptr.dynptr.type) &&
832 	    dynptr_ref_cnt(env, state->stack[spi].spilled_ptr.parent_id) <= 1) {
833 		verbose(env, "cannot overwrite referenced dynptr\n");
834 		return -EINVAL;
835 	}
836 
837 	/* Invalidate the dynptr and any derived slices */
838 	err = release_reference(env, state->stack[spi].spilled_ptr.id);
839 	if (!err) {
840 		mark_stack_slot_scratched(env, spi);
841 		mark_stack_slot_scratched(env, spi - 1);
842 	}
843 
844 	return err;
845 }
846 
847 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
848 {
849 	int spi;
850 
851 	if (reg->type == CONST_PTR_TO_DYNPTR)
852 		return false;
853 
854 	spi = dynptr_get_spi(env, reg);
855 
856 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
857 	 * error because this just means the stack state hasn't been updated yet.
858 	 * We will do check_mem_access to check and update stack bounds later.
859 	 */
860 	if (spi < 0 && spi != -ERANGE)
861 		return false;
862 
863 	/* We don't need to check if the stack slots are marked by previous
864 	 * dynptr initializations because we allow overwriting existing unreferenced
865 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
866 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
867 	 * touching are completely destructed before we reinitialize them for a new
868 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
869 	 * instead of delaying it until the end where the user will get "Unreleased
870 	 * reference" error.
871 	 */
872 	return true;
873 }
874 
875 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
876 {
877 	struct bpf_func_state *state = bpf_func(env, reg);
878 	int i, spi;
879 
880 	/* This already represents first slot of initialized bpf_dynptr.
881 	 *
882 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
883 	 * check_func_arg_reg_off's logic, so we don't need to check its
884 	 * offset and alignment.
885 	 */
886 	if (reg->type == CONST_PTR_TO_DYNPTR)
887 		return true;
888 
889 	spi = dynptr_get_spi(env, reg);
890 	if (spi < 0)
891 		return false;
892 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
893 		return false;
894 
895 	for (i = 0; i < BPF_REG_SIZE; i++) {
896 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
897 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
898 			return false;
899 	}
900 
901 	return true;
902 }
903 
904 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
905 				    enum bpf_arg_type arg_type)
906 {
907 	struct bpf_func_state *state = bpf_func(env, reg);
908 	enum bpf_dynptr_type dynptr_type;
909 	int spi;
910 
911 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
912 	if (arg_type == ARG_PTR_TO_DYNPTR)
913 		return true;
914 
915 	dynptr_type = arg_to_dynptr_type(arg_type);
916 	if (reg->type == CONST_PTR_TO_DYNPTR) {
917 		return reg->dynptr.type == dynptr_type;
918 	} else {
919 		spi = dynptr_get_spi(env, reg);
920 		if (spi < 0)
921 			return false;
922 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
923 	}
924 }
925 
926 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
927 
928 static bool in_rcu_cs(struct bpf_verifier_env *env);
929 
930 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
931 
932 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
933 				 struct bpf_kfunc_call_arg_meta *meta,
934 				 struct bpf_reg_state *reg, int insn_idx,
935 				 struct btf *btf, u32 btf_id, int nr_slots)
936 {
937 	struct bpf_func_state *state = bpf_func(env, reg);
938 	int spi, i, j, id;
939 
940 	spi = iter_get_spi(env, reg, nr_slots);
941 	if (spi < 0)
942 		return spi;
943 
944 	id = acquire_reference(env, insn_idx, 0);
945 	if (id < 0)
946 		return id;
947 
948 	for (i = 0; i < nr_slots; i++) {
949 		struct bpf_stack_state *slot = &state->stack[spi - i];
950 		struct bpf_reg_state *st = &slot->spilled_ptr;
951 
952 		__mark_reg_known_zero(st);
953 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
954 		if (is_kfunc_rcu_protected(meta)) {
955 			if (in_rcu_cs(env))
956 				st->type |= MEM_RCU;
957 			else
958 				st->type |= PTR_UNTRUSTED;
959 		}
960 		st->id = i == 0 ? id : 0;
961 		st->iter.btf = btf;
962 		st->iter.btf_id = btf_id;
963 		st->iter.state = BPF_ITER_STATE_ACTIVE;
964 		st->iter.depth = 0;
965 
966 		for (j = 0; j < BPF_REG_SIZE; j++)
967 			slot->slot_type[j] = STACK_ITER;
968 
969 		mark_stack_slot_scratched(env, spi - i);
970 	}
971 
972 	return 0;
973 }
974 
975 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
976 				   struct bpf_reg_state *reg, int nr_slots)
977 {
978 	struct bpf_func_state *state = bpf_func(env, reg);
979 	int spi, i, j;
980 
981 	spi = iter_get_spi(env, reg, nr_slots);
982 	if (spi < 0)
983 		return spi;
984 
985 	for (i = 0; i < nr_slots; i++) {
986 		struct bpf_stack_state *slot = &state->stack[spi - i];
987 		struct bpf_reg_state *st = &slot->spilled_ptr;
988 
989 		if (i == 0)
990 			WARN_ON_ONCE(release_reference(env, st->id));
991 
992 		bpf_mark_reg_not_init(env, st);
993 
994 		for (j = 0; j < BPF_REG_SIZE; j++)
995 			slot->slot_type[j] = STACK_INVALID;
996 
997 		mark_stack_slot_scratched(env, spi - i);
998 	}
999 
1000 	return 0;
1001 }
1002 
1003 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1004 				     struct bpf_reg_state *reg, int nr_slots)
1005 {
1006 	struct bpf_func_state *state = bpf_func(env, reg);
1007 	int spi, i, j;
1008 
1009 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1010 	 * will do check_mem_access to check and update stack bounds later, so
1011 	 * return true for that case.
1012 	 */
1013 	spi = iter_get_spi(env, reg, nr_slots);
1014 	if (spi == -ERANGE)
1015 		return true;
1016 	if (spi < 0)
1017 		return false;
1018 
1019 	for (i = 0; i < nr_slots; i++) {
1020 		struct bpf_stack_state *slot = &state->stack[spi - i];
1021 
1022 		for (j = 0; j < BPF_REG_SIZE; j++)
1023 			if (slot->slot_type[j] == STACK_ITER)
1024 				return false;
1025 	}
1026 
1027 	return true;
1028 }
1029 
1030 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1031 				   struct btf *btf, u32 btf_id, int nr_slots)
1032 {
1033 	struct bpf_func_state *state = bpf_func(env, reg);
1034 	int spi, i, j;
1035 
1036 	spi = iter_get_spi(env, reg, nr_slots);
1037 	if (spi < 0)
1038 		return -EINVAL;
1039 
1040 	for (i = 0; i < nr_slots; i++) {
1041 		struct bpf_stack_state *slot = &state->stack[spi - i];
1042 		struct bpf_reg_state *st = &slot->spilled_ptr;
1043 
1044 		if (st->type & PTR_UNTRUSTED)
1045 			return -EPROTO;
1046 		/* only main (first) slot has id set */
1047 		if (i == 0 && !st->id)
1048 			return -EINVAL;
1049 		if (i != 0 && st->id)
1050 			return -EINVAL;
1051 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1052 			return -EINVAL;
1053 
1054 		for (j = 0; j < BPF_REG_SIZE; j++)
1055 			if (slot->slot_type[j] != STACK_ITER)
1056 				return -EINVAL;
1057 	}
1058 
1059 	return 0;
1060 }
1061 
1062 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1063 static int release_irq_state(struct bpf_verifier_state *state, int id);
1064 
1065 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1066 				     struct bpf_kfunc_call_arg_meta *meta,
1067 				     struct bpf_reg_state *reg, int insn_idx,
1068 				     int kfunc_class)
1069 {
1070 	struct bpf_func_state *state = bpf_func(env, reg);
1071 	struct bpf_stack_state *slot;
1072 	struct bpf_reg_state *st;
1073 	int spi, i, id;
1074 
1075 	spi = irq_flag_get_spi(env, reg);
1076 	if (spi < 0)
1077 		return spi;
1078 
1079 	id = acquire_irq_state(env, insn_idx);
1080 	if (id < 0)
1081 		return id;
1082 
1083 	slot = &state->stack[spi];
1084 	st = &slot->spilled_ptr;
1085 
1086 	__mark_reg_known_zero(st);
1087 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1088 	st->id = id;
1089 	st->irq.kfunc_class = kfunc_class;
1090 
1091 	for (i = 0; i < BPF_REG_SIZE; i++)
1092 		slot->slot_type[i] = STACK_IRQ_FLAG;
1093 
1094 	mark_stack_slot_scratched(env, spi);
1095 	return 0;
1096 }
1097 
1098 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1099 				      int kfunc_class)
1100 {
1101 	struct bpf_func_state *state = bpf_func(env, reg);
1102 	struct bpf_stack_state *slot;
1103 	struct bpf_reg_state *st;
1104 	int spi, i, err;
1105 
1106 	spi = irq_flag_get_spi(env, reg);
1107 	if (spi < 0)
1108 		return spi;
1109 
1110 	slot = &state->stack[spi];
1111 	st = &slot->spilled_ptr;
1112 
1113 	if (st->irq.kfunc_class != kfunc_class) {
1114 		const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1115 		const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1116 
1117 		verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1118 			flag_kfunc, used_kfunc);
1119 		return -EINVAL;
1120 	}
1121 
1122 	err = release_irq_state(env->cur_state, st->id);
1123 	WARN_ON_ONCE(err && err != -EACCES);
1124 	if (err) {
1125 		int insn_idx = 0;
1126 
1127 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1128 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1129 				insn_idx = env->cur_state->refs[i].insn_idx;
1130 				break;
1131 			}
1132 		}
1133 
1134 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1135 			env->cur_state->active_irq_id, insn_idx);
1136 		return err;
1137 	}
1138 
1139 	bpf_mark_reg_not_init(env, st);
1140 
1141 	for (i = 0; i < BPF_REG_SIZE; i++)
1142 		slot->slot_type[i] = STACK_INVALID;
1143 
1144 	mark_stack_slot_scratched(env, spi);
1145 	return 0;
1146 }
1147 
1148 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1149 {
1150 	struct bpf_func_state *state = bpf_func(env, reg);
1151 	struct bpf_stack_state *slot;
1152 	int spi, i;
1153 
1154 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1155 	 * will do check_mem_access to check and update stack bounds later, so
1156 	 * return true for that case.
1157 	 */
1158 	spi = irq_flag_get_spi(env, reg);
1159 	if (spi == -ERANGE)
1160 		return true;
1161 	if (spi < 0)
1162 		return false;
1163 
1164 	slot = &state->stack[spi];
1165 
1166 	for (i = 0; i < BPF_REG_SIZE; i++)
1167 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1168 			return false;
1169 	return true;
1170 }
1171 
1172 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1173 {
1174 	struct bpf_func_state *state = bpf_func(env, reg);
1175 	struct bpf_stack_state *slot;
1176 	struct bpf_reg_state *st;
1177 	int spi, i;
1178 
1179 	spi = irq_flag_get_spi(env, reg);
1180 	if (spi < 0)
1181 		return -EINVAL;
1182 
1183 	slot = &state->stack[spi];
1184 	st = &slot->spilled_ptr;
1185 
1186 	if (!st->id)
1187 		return -EINVAL;
1188 
1189 	for (i = 0; i < BPF_REG_SIZE; i++)
1190 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1191 			return -EINVAL;
1192 	return 0;
1193 }
1194 
1195 /* Check if given stack slot is "special":
1196  *   - spilled register state (STACK_SPILL);
1197  *   - dynptr state (STACK_DYNPTR);
1198  *   - iter state (STACK_ITER).
1199  *   - irq flag state (STACK_IRQ_FLAG)
1200  */
1201 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1202 {
1203 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1204 
1205 	switch (type) {
1206 	case STACK_SPILL:
1207 	case STACK_DYNPTR:
1208 	case STACK_ITER:
1209 	case STACK_IRQ_FLAG:
1210 		return true;
1211 	case STACK_INVALID:
1212 	case STACK_POISON:
1213 	case STACK_MISC:
1214 	case STACK_ZERO:
1215 		return false;
1216 	default:
1217 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1218 		return true;
1219 	}
1220 }
1221 
1222 /* The reg state of a pointer or a bounded scalar was saved when
1223  * it was spilled to the stack.
1224  */
1225 
1226 /*
1227  * Mark stack slot as STACK_MISC, unless it is already:
1228  * - STACK_INVALID, in which case they are equivalent.
1229  * - STACK_ZERO, in which case we preserve more precise STACK_ZERO.
1230  * - STACK_POISON, which truly forbids access to the slot.
1231  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1232  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1233  * unnecessary as both are considered equivalent when loading data and pruning,
1234  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1235  * slots.
1236  */
1237 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1238 {
1239 	if (*stype == STACK_ZERO)
1240 		return;
1241 	if (*stype == STACK_INVALID || *stype == STACK_POISON)
1242 		return;
1243 	*stype = STACK_MISC;
1244 }
1245 
1246 static void scrub_spilled_slot(u8 *stype)
1247 {
1248 	if (*stype != STACK_INVALID && *stype != STACK_POISON)
1249 		*stype = STACK_MISC;
1250 }
1251 
1252 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1253  * small to hold src. This is different from krealloc since we don't want to preserve
1254  * the contents of dst.
1255  *
1256  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1257  * not be allocated.
1258  */
1259 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1260 {
1261 	size_t alloc_bytes;
1262 	void *orig = dst;
1263 	size_t bytes;
1264 
1265 	if (ZERO_OR_NULL_PTR(src))
1266 		goto out;
1267 
1268 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1269 		return NULL;
1270 
1271 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1272 	dst = krealloc(orig, alloc_bytes, flags);
1273 	if (!dst) {
1274 		kfree(orig);
1275 		return NULL;
1276 	}
1277 
1278 	memcpy(dst, src, bytes);
1279 out:
1280 	return dst ? dst : ZERO_SIZE_PTR;
1281 }
1282 
1283 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1284  * small to hold new_n items. new items are zeroed out if the array grows.
1285  *
1286  * Contrary to krealloc_array, does not free arr if new_n is zero.
1287  */
1288 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1289 {
1290 	size_t alloc_size;
1291 	void *new_arr;
1292 
1293 	if (!new_n || old_n == new_n)
1294 		goto out;
1295 
1296 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1297 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1298 	if (!new_arr) {
1299 		kfree(arr);
1300 		return NULL;
1301 	}
1302 	arr = new_arr;
1303 
1304 	if (new_n > old_n)
1305 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1306 
1307 out:
1308 	return arr ? arr : ZERO_SIZE_PTR;
1309 }
1310 
1311 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1312 {
1313 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1314 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1315 	if (!dst->refs)
1316 		return -ENOMEM;
1317 
1318 	dst->acquired_refs = src->acquired_refs;
1319 	dst->active_locks = src->active_locks;
1320 	dst->active_preempt_locks = src->active_preempt_locks;
1321 	dst->active_rcu_locks = src->active_rcu_locks;
1322 	dst->active_irq_id = src->active_irq_id;
1323 	dst->active_lock_id = src->active_lock_id;
1324 	dst->active_lock_ptr = src->active_lock_ptr;
1325 	return 0;
1326 }
1327 
1328 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1329 {
1330 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1331 
1332 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1333 				GFP_KERNEL_ACCOUNT);
1334 	if (!dst->stack)
1335 		return -ENOMEM;
1336 
1337 	dst->allocated_stack = src->allocated_stack;
1338 
1339 	/* copy stack args state */
1340 	n = src->out_stack_arg_cnt;
1341 	if (n) {
1342 		dst->stack_arg_regs = copy_array(dst->stack_arg_regs, src->stack_arg_regs, n,
1343 						 sizeof(struct bpf_reg_state),
1344 						 GFP_KERNEL_ACCOUNT);
1345 		if (!dst->stack_arg_regs)
1346 			return -ENOMEM;
1347 	}
1348 
1349 	dst->out_stack_arg_cnt = src->out_stack_arg_cnt;
1350 	return 0;
1351 }
1352 
1353 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1354 {
1355 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1356 				    sizeof(struct bpf_reference_state));
1357 	if (!state->refs)
1358 		return -ENOMEM;
1359 
1360 	state->acquired_refs = n;
1361 	return 0;
1362 }
1363 
1364 /* Possibly update state->allocated_stack to be at least size bytes. Also
1365  * possibly update the function's high-water mark in its bpf_subprog_info.
1366  */
1367 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1368 {
1369 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1370 
1371 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1372 	size = round_up(size, BPF_REG_SIZE);
1373 	n = size / BPF_REG_SIZE;
1374 
1375 	if (old_n >= n)
1376 		return 0;
1377 
1378 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1379 	if (!state->stack)
1380 		return -ENOMEM;
1381 
1382 	state->allocated_stack = size;
1383 
1384 	/* update known max for given subprogram */
1385 	if (env->subprog_info[state->subprogno].stack_depth < size)
1386 		env->subprog_info[state->subprogno].stack_depth = size;
1387 
1388 	return 0;
1389 }
1390 
1391 static int grow_stack_arg_slots(struct bpf_verifier_env *env,
1392 				struct bpf_func_state *state, int cnt)
1393 {
1394 	size_t old_n = state->out_stack_arg_cnt;
1395 
1396 	if (old_n >= cnt)
1397 		return 0;
1398 
1399 	state->stack_arg_regs = realloc_array(state->stack_arg_regs, old_n, cnt,
1400 					      sizeof(struct bpf_reg_state));
1401 	if (!state->stack_arg_regs)
1402 		return -ENOMEM;
1403 
1404 	state->out_stack_arg_cnt = cnt;
1405 	return 0;
1406 }
1407 
1408 /* Acquire a pointer id from the env and update the state->refs to include
1409  * this new pointer reference.
1410  * On success, returns a valid pointer id to associate with the register
1411  * On failure, returns a negative errno.
1412  */
1413 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1414 {
1415 	struct bpf_verifier_state *state = env->cur_state;
1416 	int new_ofs = state->acquired_refs;
1417 	int err;
1418 
1419 	err = resize_reference_state(state, state->acquired_refs + 1);
1420 	if (err)
1421 		return NULL;
1422 	state->refs[new_ofs].insn_idx = insn_idx;
1423 
1424 	return &state->refs[new_ofs];
1425 }
1426 
1427 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id)
1428 {
1429 	struct bpf_reference_state *s;
1430 
1431 	s = acquire_reference_state(env, insn_idx);
1432 	if (!s)
1433 		return -ENOMEM;
1434 	s->type = REF_TYPE_PTR;
1435 	s->id = ++env->id_gen;
1436 	s->parent_id = parent_id;
1437 	return s->id;
1438 }
1439 
1440 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1441 			      int id, void *ptr)
1442 {
1443 	struct bpf_verifier_state *state = env->cur_state;
1444 	struct bpf_reference_state *s;
1445 
1446 	s = acquire_reference_state(env, insn_idx);
1447 	if (!s)
1448 		return -ENOMEM;
1449 	s->type = type;
1450 	s->id = id;
1451 	s->ptr = ptr;
1452 
1453 	state->active_locks++;
1454 	state->active_lock_id = id;
1455 	state->active_lock_ptr = ptr;
1456 	return 0;
1457 }
1458 
1459 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1460 {
1461 	struct bpf_verifier_state *state = env->cur_state;
1462 	struct bpf_reference_state *s;
1463 
1464 	s = acquire_reference_state(env, insn_idx);
1465 	if (!s)
1466 		return -ENOMEM;
1467 	s->type = REF_TYPE_IRQ;
1468 	s->id = ++env->id_gen;
1469 
1470 	state->active_irq_id = s->id;
1471 	return s->id;
1472 }
1473 
1474 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1475 {
1476 	int last_idx;
1477 	size_t rem;
1478 
1479 	/* IRQ state requires the relative ordering of elements remaining the
1480 	 * same, since it relies on the refs array to behave as a stack, so that
1481 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1482 	 * the array instead of swapping the final element into the deleted idx.
1483 	 */
1484 	last_idx = state->acquired_refs - 1;
1485 	rem = state->acquired_refs - idx - 1;
1486 	if (last_idx && idx != last_idx)
1487 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1488 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1489 	state->acquired_refs--;
1490 	return;
1491 }
1492 
1493 static bool find_reference_state(struct bpf_verifier_state *state, int id)
1494 {
1495 	int i;
1496 
1497 	for (i = 0; i < state->acquired_refs; i++) {
1498 		if (state->refs[i].type != REF_TYPE_PTR)
1499 			continue;
1500 		if (state->refs[i].id == id)
1501 			return true;
1502 	}
1503 
1504 	return false;
1505 }
1506 
1507 static bool reg_is_referenced(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
1508 {
1509 	return find_reference_state(env->cur_state, reg->id);
1510 }
1511 
1512 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
1513 {
1514 	void *prev_ptr = NULL;
1515 	u32 prev_id = 0;
1516 	int i;
1517 
1518 	for (i = 0; i < state->acquired_refs; i++) {
1519 		if (state->refs[i].type == type && state->refs[i].id == id &&
1520 		    state->refs[i].ptr == ptr) {
1521 			release_reference_state(state, i);
1522 			state->active_locks--;
1523 			/* Reassign active lock (id, ptr). */
1524 			state->active_lock_id = prev_id;
1525 			state->active_lock_ptr = prev_ptr;
1526 			return 0;
1527 		}
1528 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1529 			prev_id = state->refs[i].id;
1530 			prev_ptr = state->refs[i].ptr;
1531 		}
1532 	}
1533 	return -EINVAL;
1534 }
1535 
1536 static int release_irq_state(struct bpf_verifier_state *state, int id)
1537 {
1538 	u32 prev_id = 0;
1539 	int i;
1540 
1541 	if (id != state->active_irq_id)
1542 		return -EACCES;
1543 
1544 	for (i = 0; i < state->acquired_refs; i++) {
1545 		if (state->refs[i].type != REF_TYPE_IRQ)
1546 			continue;
1547 		if (state->refs[i].id == id) {
1548 			release_reference_state(state, i);
1549 			state->active_irq_id = prev_id;
1550 			return 0;
1551 		} else {
1552 			prev_id = state->refs[i].id;
1553 		}
1554 	}
1555 	return -EINVAL;
1556 }
1557 
1558 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1559 						   int id, void *ptr)
1560 {
1561 	int i;
1562 
1563 	for (i = 0; i < state->acquired_refs; i++) {
1564 		struct bpf_reference_state *s = &state->refs[i];
1565 
1566 		if (!(s->type & type))
1567 			continue;
1568 
1569 		if (s->id == id && s->ptr == ptr)
1570 			return s;
1571 	}
1572 	return NULL;
1573 }
1574 
1575 static void free_func_state(struct bpf_func_state *state)
1576 {
1577 	if (!state)
1578 		return;
1579 	kfree(state->stack_arg_regs);
1580 	kfree(state->stack);
1581 	kfree(state);
1582 }
1583 
1584 void bpf_clear_jmp_history(struct bpf_verifier_state *state)
1585 {
1586 	kfree(state->jmp_history);
1587 	state->jmp_history = NULL;
1588 	state->jmp_history_cnt = 0;
1589 }
1590 
1591 void bpf_free_verifier_state(struct bpf_verifier_state *state,
1592 			    bool free_self)
1593 {
1594 	int i;
1595 
1596 	for (i = 0; i <= state->curframe; i++) {
1597 		free_func_state(state->frame[i]);
1598 		state->frame[i] = NULL;
1599 	}
1600 	kfree(state->refs);
1601 	bpf_clear_jmp_history(state);
1602 	if (free_self)
1603 		kfree(state);
1604 }
1605 
1606 /* copy verifier state from src to dst growing dst stack space
1607  * when necessary to accommodate larger src stack
1608  */
1609 static int copy_func_state(struct bpf_func_state *dst,
1610 			   const struct bpf_func_state *src)
1611 {
1612 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1613 	return copy_stack_state(dst, src);
1614 }
1615 
1616 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,
1617 			   const struct bpf_verifier_state *src)
1618 {
1619 	struct bpf_func_state *dst;
1620 	int i, err;
1621 
1622 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1623 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1624 					  GFP_KERNEL_ACCOUNT);
1625 	if (!dst_state->jmp_history)
1626 		return -ENOMEM;
1627 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1628 
1629 	/* if dst has more stack frames then src frame, free them, this is also
1630 	 * necessary in case of exceptional exits using bpf_throw.
1631 	 */
1632 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1633 		free_func_state(dst_state->frame[i]);
1634 		dst_state->frame[i] = NULL;
1635 	}
1636 	err = copy_reference_state(dst_state, src);
1637 	if (err)
1638 		return err;
1639 	dst_state->speculative = src->speculative;
1640 	dst_state->in_sleepable = src->in_sleepable;
1641 	dst_state->curframe = src->curframe;
1642 	dst_state->branches = src->branches;
1643 	dst_state->parent = src->parent;
1644 	dst_state->first_insn_idx = src->first_insn_idx;
1645 	dst_state->last_insn_idx = src->last_insn_idx;
1646 	dst_state->dfs_depth = src->dfs_depth;
1647 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1648 	dst_state->may_goto_depth = src->may_goto_depth;
1649 	dst_state->equal_state = src->equal_state;
1650 	for (i = 0; i <= src->curframe; i++) {
1651 		dst = dst_state->frame[i];
1652 		if (!dst) {
1653 			dst = kzalloc_obj(*dst, GFP_KERNEL_ACCOUNT);
1654 			if (!dst)
1655 				return -ENOMEM;
1656 			dst_state->frame[i] = dst;
1657 		}
1658 		err = copy_func_state(dst, src->frame[i]);
1659 		if (err)
1660 			return err;
1661 	}
1662 	return 0;
1663 }
1664 
1665 static u32 state_htab_size(struct bpf_verifier_env *env)
1666 {
1667 	return env->prog->len;
1668 }
1669 
1670 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx)
1671 {
1672 	struct bpf_verifier_state *cur = env->cur_state;
1673 	struct bpf_func_state *state = cur->frame[cur->curframe];
1674 
1675 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1676 }
1677 
1678 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1679 {
1680 	int fr;
1681 
1682 	if (a->curframe != b->curframe)
1683 		return false;
1684 
1685 	for (fr = a->curframe; fr >= 0; fr--)
1686 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1687 			return false;
1688 
1689 	return true;
1690 }
1691 
1692 
1693 void bpf_free_backedges(struct bpf_scc_visit *visit)
1694 {
1695 	struct bpf_scc_backedge *backedge, *next;
1696 
1697 	for (backedge = visit->backedges; backedge; backedge = next) {
1698 		bpf_free_verifier_state(&backedge->state, false);
1699 		next = backedge->next;
1700 		kfree(backedge);
1701 	}
1702 	visit->backedges = NULL;
1703 }
1704 
1705 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1706 		     int *insn_idx, bool pop_log)
1707 {
1708 	struct bpf_verifier_state *cur = env->cur_state;
1709 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1710 	int err;
1711 
1712 	if (env->head == NULL)
1713 		return -ENOENT;
1714 
1715 	if (cur) {
1716 		err = bpf_copy_verifier_state(cur, &head->st);
1717 		if (err)
1718 			return err;
1719 	}
1720 	if (pop_log)
1721 		bpf_vlog_reset(&env->log, head->log_pos);
1722 	if (insn_idx)
1723 		*insn_idx = head->insn_idx;
1724 	if (prev_insn_idx)
1725 		*prev_insn_idx = head->prev_insn_idx;
1726 	elem = head->next;
1727 	bpf_free_verifier_state(&head->st, false);
1728 	kfree(head);
1729 	env->head = elem;
1730 	env->stack_size--;
1731 	return 0;
1732 }
1733 
1734 static bool error_recoverable_with_nospec(int err)
1735 {
1736 	/* Should only return true for non-fatal errors that are allowed to
1737 	 * occur during speculative verification. For these we can insert a
1738 	 * nospec and the program might still be accepted. Do not include
1739 	 * something like ENOMEM because it is likely to re-occur for the next
1740 	 * architectural path once it has been recovered-from in all speculative
1741 	 * paths.
1742 	 */
1743 	return err == -EPERM || err == -EACCES || err == -EINVAL;
1744 }
1745 
1746 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1747 					     int insn_idx, int prev_insn_idx,
1748 					     bool speculative)
1749 {
1750 	struct bpf_verifier_state *cur = env->cur_state;
1751 	struct bpf_verifier_stack_elem *elem;
1752 	int err;
1753 
1754 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
1755 	if (!elem)
1756 		return ERR_PTR(-ENOMEM);
1757 
1758 	elem->insn_idx = insn_idx;
1759 	elem->prev_insn_idx = prev_insn_idx;
1760 	elem->next = env->head;
1761 	elem->log_pos = env->log.end_pos;
1762 	env->head = elem;
1763 	env->stack_size++;
1764 	err = bpf_copy_verifier_state(&elem->st, cur);
1765 	if (err)
1766 		return ERR_PTR(-ENOMEM);
1767 	elem->st.speculative |= speculative;
1768 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1769 		verbose(env, "The sequence of %d jumps is too complex.\n",
1770 			env->stack_size);
1771 		return ERR_PTR(-E2BIG);
1772 	}
1773 	if (elem->st.parent) {
1774 		++elem->st.parent->branches;
1775 		/* WARN_ON(branches > 2) technically makes sense here,
1776 		 * but
1777 		 * 1. speculative states will bump 'branches' for non-branch
1778 		 * instructions
1779 		 * 2. is_state_visited() heuristics may decide not to create
1780 		 * a new state for a sequence of branches and all such current
1781 		 * and cloned states will be pointing to a single parent state
1782 		 * which might have large 'branches' count.
1783 		 */
1784 	}
1785 	return &elem->st;
1786 }
1787 
1788 static const char *reg_arg_name(struct bpf_verifier_env *env, argno_t argno)
1789 {
1790 	char *buf = env->tmp_arg_name;
1791 	int len = sizeof(env->tmp_arg_name);
1792 	int arg, regno = reg_from_argno(argno);
1793 
1794 	if (regno >= 0) {
1795 		snprintf(buf, len, "R%d", regno);
1796 	} else {
1797 		arg = arg_from_argno(argno);
1798 		snprintf(buf, len, "*(R11-%u)", (arg - MAX_BPF_FUNC_REG_ARGS) * BPF_REG_SIZE);
1799 	}
1800 
1801 	return buf;
1802 }
1803 
1804 static const int caller_saved[CALLER_SAVED_REGS] = {
1805 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1806 };
1807 
1808 /* This helper doesn't clear reg->id */
1809 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1810 {
1811 	reg->var_off = tnum_const(imm);
1812 	reg->r64 = cnum64_from_urange(imm, imm);
1813 	reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
1814 }
1815 
1816 /* Mark the unknown part of a register (variable offset or scalar value) as
1817  * known to have the value @imm.
1818  */
1819 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1820 {
1821 	/* Clear off and union(map_ptr, range) */
1822 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1823 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1824 	reg->id = 0;
1825 	reg->parent_id = 0;
1826 	___mark_reg_known(reg, imm);
1827 }
1828 
1829 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1830 {
1831 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1832 	reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
1833 }
1834 
1835 /* Mark the 'variable offset' part of a register as zero.  This should be
1836  * used only on registers holding a pointer type.
1837  */
1838 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1839 {
1840 	__mark_reg_known(reg, 0);
1841 }
1842 
1843 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1844 {
1845 	__mark_reg_known(reg, 0);
1846 	reg->type = SCALAR_VALUE;
1847 	/* all scalars are assumed imprecise initially (unless unprivileged,
1848 	 * in which case everything is forced to be precise)
1849 	 */
1850 	reg->precise = !env->bpf_capable;
1851 }
1852 
1853 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1854 				struct bpf_reg_state *regs, u32 regno)
1855 {
1856 	__mark_reg_known_zero(regs + regno);
1857 }
1858 
1859 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1860 			      bool first_slot, int id, int parent_id)
1861 {
1862 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1863 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1864 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1865 	 */
1866 	__mark_reg_known_zero(reg);
1867 	reg->type = CONST_PTR_TO_DYNPTR;
1868 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1869 	reg->id = id;
1870 	reg->parent_id = parent_id;
1871 	reg->dynptr.type = type;
1872 	reg->dynptr.first_slot = first_slot;
1873 }
1874 
1875 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1876 {
1877 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1878 		const struct bpf_map *map = reg->map_ptr;
1879 
1880 		if (map->inner_map_meta) {
1881 			reg->type = CONST_PTR_TO_MAP;
1882 			reg->map_ptr = map->inner_map_meta;
1883 			/* transfer reg's id which is unique for every map_lookup_elem
1884 			 * as UID of the inner map.
1885 			 */
1886 			if (btf_record_has_field(map->inner_map_meta->record,
1887 						 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) {
1888 				reg->map_uid = reg->id;
1889 			}
1890 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1891 			reg->type = PTR_TO_XDP_SOCK;
1892 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1893 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1894 			reg->type = PTR_TO_SOCKET;
1895 		} else {
1896 			reg->type = PTR_TO_MAP_VALUE;
1897 		}
1898 		return;
1899 	}
1900 
1901 	reg->type &= ~PTR_MAYBE_NULL;
1902 }
1903 
1904 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1905 				struct btf_field_graph_root *ds_head)
1906 {
1907 	__mark_reg_known(&regs[regno], ds_head->node_offset);
1908 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1909 	regs[regno].btf = ds_head->btf;
1910 	regs[regno].btf_id = ds_head->value_btf_id;
1911 }
1912 
1913 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1914 {
1915 	return type_is_pkt_pointer(reg->type);
1916 }
1917 
1918 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1919 {
1920 	return reg_is_pkt_pointer(reg) ||
1921 	       reg->type == PTR_TO_PACKET_END;
1922 }
1923 
1924 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1925 {
1926 	return base_type(reg->type) == PTR_TO_MEM &&
1927 	       (reg->type &
1928 		(DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META));
1929 }
1930 
1931 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1932 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1933 				    enum bpf_reg_type which)
1934 {
1935 	/* The register can already have a range from prior markings.
1936 	 * This is fine as long as it hasn't been advanced from its
1937 	 * origin.
1938 	 */
1939 	return reg->type == which &&
1940 	       reg->id == 0 &&
1941 	       tnum_equals_const(reg->var_off, 0);
1942 }
1943 
1944 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1945 {
1946 	reg->r32 = CNUM32_UNBOUNDED;
1947 }
1948 
1949 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1950 {
1951 	reg->r64 = CNUM64_UNBOUNDED;
1952 }
1953 
1954 /* Reset the min/max bounds of a register */
1955 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1956 {
1957 	__mark_reg64_unbounded(reg);
1958 	__mark_reg32_unbounded(reg);
1959 }
1960 
1961 static void reset_reg64_and_tnum(struct bpf_reg_state *reg)
1962 {
1963 	__mark_reg64_unbounded(reg);
1964 	reg->var_off = tnum_unknown;
1965 }
1966 
1967 static void reset_reg32_and_tnum(struct bpf_reg_state *reg)
1968 {
1969 	__mark_reg32_unbounded(reg);
1970 	reg->var_off = tnum_unknown;
1971 }
1972 
1973 static struct cnum32 cnum32_from_tnum(struct tnum tnum)
1974 {
1975 	tnum = tnum_subreg(tnum);
1976 	if ((tnum.mask & S32_MIN) || (tnum.value & S32_MIN))
1977 		/* min signed is max(sign bit) | min(other bits) */
1978 		/* max signed is min(sign bit) | max(other bits) */
1979 		return cnum32_from_srange(tnum.value | (tnum.mask & S32_MIN),
1980 					  tnum.value | (tnum.mask & S32_MAX));
1981 	else
1982 		return cnum32_from_urange(tnum.value, (tnum.value | tnum.mask));
1983 }
1984 
1985 static struct cnum64 cnum64_from_tnum(struct tnum tnum)
1986 {
1987 	if ((tnum.mask & S64_MIN) || (tnum.value & S64_MIN))
1988 		/* min signed is max(sign bit) | min(other bits) */
1989 		/* max signed is min(sign bit) | max(other bits) */
1990 		return cnum64_from_srange(tnum.value | (tnum.mask & S64_MIN),
1991 					  tnum.value | (tnum.mask & S64_MAX));
1992 	else
1993 		return cnum64_from_urange(tnum.value, (tnum.value | tnum.mask));
1994 }
1995 
1996 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1997 {
1998 	cnum32_intersect_with(&reg->r32, cnum32_from_tnum(reg->var_off));
1999 }
2000 
2001 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2002 {
2003 	u64 tnum_next, tmax;
2004 	bool umin_in_tnum;
2005 
2006 	cnum64_intersect_with(&reg->r64, cnum64_from_tnum(reg->var_off));
2007 
2008 	/* Check if u64 and tnum overlap in a single value */
2009 	tnum_next = tnum_step(reg->var_off, reg_umin(reg));
2010 	umin_in_tnum = (reg_umin(reg) & ~reg->var_off.mask) == reg->var_off.value;
2011 	tmax = reg->var_off.value | reg->var_off.mask;
2012 	if (umin_in_tnum && tnum_next > reg_umax(reg)) {
2013 		/* The u64 range and the tnum only overlap in umin.
2014 		 * u64:  ---[xxxxxx]-----
2015 		 * tnum: --xx----------x-
2016 		 */
2017 		___mark_reg_known(reg, reg_umin(reg));
2018 	} else if (!umin_in_tnum && tnum_next == tmax) {
2019 		/* The u64 range and the tnum only overlap in the maximum value
2020 		 * represented by the tnum, called tmax.
2021 		 * u64:  ---[xxxxxx]-----
2022 		 * tnum: xx-----x--------
2023 		 */
2024 		___mark_reg_known(reg, tmax);
2025 	} else if (!umin_in_tnum && tnum_next <= reg_umax(reg) &&
2026 		   tnum_step(reg->var_off, tnum_next) > reg_umax(reg)) {
2027 		/* The u64 range and the tnum only overlap in between umin
2028 		 * (excluded) and umax.
2029 		 * u64:  ---[xxxxxx]-----
2030 		 * tnum: xx----x-------x-
2031 		 */
2032 		___mark_reg_known(reg, tnum_next);
2033 	}
2034 }
2035 
2036 static void __update_reg_bounds(struct bpf_reg_state *reg)
2037 {
2038 	__update_reg32_bounds(reg);
2039 	__update_reg64_bounds(reg);
2040 }
2041 
2042 static void deduce_bounds_32_from_64(struct bpf_reg_state *reg)
2043 {
2044 	cnum32_intersect_with(&reg->r32, cnum32_from_cnum64(reg->r64));
2045 }
2046 
2047 static void deduce_bounds_64_from_32(struct bpf_reg_state *reg)
2048 {
2049 	reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32);
2050 }
2051 
2052 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2053 {
2054 	deduce_bounds_32_from_64(reg);
2055 	deduce_bounds_64_from_32(reg);
2056 }
2057 
2058 /* Attempts to improve var_off based on unsigned min/max information */
2059 static void __reg_bound_offset(struct bpf_reg_state *reg)
2060 {
2061 	struct tnum var64_off = tnum_intersect(reg->var_off,
2062 					       tnum_range(reg_umin(reg),
2063 							  reg_umax(reg)));
2064 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2065 					       tnum_range(reg_u32_min(reg),
2066 							  reg_u32_max(reg)));
2067 
2068 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2069 }
2070 
2071 static bool range_bounds_violation(struct bpf_reg_state *reg);
2072 
2073 static void reg_bounds_sync(struct bpf_reg_state *reg)
2074 {
2075 	/* If the input reg_state is invalid, we can exit early */
2076 	if (range_bounds_violation(reg))
2077 		return;
2078 	/* We might have learned new bounds from the var_off. */
2079 	__update_reg_bounds(reg);
2080 	/* We might have learned something about the sign bit. */
2081 	__reg_deduce_bounds(reg);
2082 	__reg_deduce_bounds(reg);
2083 	/* We might have learned some bits from the bounds. */
2084 	__reg_bound_offset(reg);
2085 	/* Intersecting with the old var_off might have improved our bounds
2086 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2087 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2088 	 */
2089 	__update_reg_bounds(reg);
2090 }
2091 
2092 static bool const_tnum_range_mismatch(struct bpf_reg_state *reg)
2093 {
2094 	if (!tnum_is_const(reg->var_off))
2095 		return false;
2096 
2097 	return !cnum64_is_const(reg->r64) || reg->r64.base != reg->var_off.value;
2098 }
2099 
2100 static bool const_tnum_range_mismatch_32(struct bpf_reg_state *reg)
2101 {
2102 	if (!tnum_subreg_is_const(reg->var_off))
2103 		return false;
2104 
2105 	return !cnum32_is_const(reg->r32) || reg->r32.base != tnum_subreg(reg->var_off).value;
2106 }
2107 
2108 static bool range_bounds_violation(struct bpf_reg_state *reg)
2109 {
2110 	return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64);
2111 }
2112 
2113 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2114 				   struct bpf_reg_state *reg, const char *ctx)
2115 {
2116 	const char *msg;
2117 
2118 	if (range_bounds_violation(reg)) {
2119 		msg = "range bounds violation";
2120 		goto out;
2121 	}
2122 
2123 	if (const_tnum_range_mismatch(reg)) {
2124 		msg = "const tnum out of sync with range bounds";
2125 		goto out;
2126 	}
2127 
2128 	if (const_tnum_range_mismatch_32(reg)) {
2129 		msg = "const subreg tnum out of sync with range bounds";
2130 		goto out;
2131 	}
2132 
2133 	return 0;
2134 out:
2135 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s r64={.base=%#llx, .size=%#llx} "
2136 		     "r32={.base=%#x, .size=%#x} var_off=(%#llx, %#llx)",
2137 		     ctx, msg,
2138 		     reg->r64.base, reg->r64.size,
2139 		     reg->r32.base, reg->r32.size,
2140 		     reg->var_off.value, reg->var_off.mask);
2141 	if (env->test_reg_invariants)
2142 		return -EFAULT;
2143 	__mark_reg_unbounded(reg);
2144 	return 0;
2145 }
2146 
2147 /* Mark a register as having a completely unknown (scalar) value. */
2148 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2149 {
2150 	s32 subreg_def = reg->subreg_def;
2151 
2152 	memset(reg, 0, sizeof(*reg));
2153 	reg->type = SCALAR_VALUE;
2154 	reg->var_off = tnum_unknown;
2155 	reg->subreg_def = subreg_def;
2156 	__mark_reg_unbounded(reg);
2157 }
2158 
2159 /* Mark a register as having a completely unknown (scalar) value,
2160  * initialize .precise as true when not bpf capable.
2161  */
2162 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2163 			       struct bpf_reg_state *reg)
2164 {
2165 	bpf_mark_reg_unknown_imprecise(reg);
2166 	reg->precise = !env->bpf_capable;
2167 }
2168 
2169 static void mark_reg_unknown(struct bpf_verifier_env *env,
2170 			     struct bpf_reg_state *regs, u32 regno)
2171 {
2172 	__mark_reg_unknown(env, regs + regno);
2173 }
2174 
2175 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2176 				struct bpf_reg_state *regs,
2177 				u32 regno,
2178 				s32 s32_min,
2179 				s32 s32_max)
2180 {
2181 	struct bpf_reg_state *reg = regs + regno;
2182 
2183 	reg_set_srange32(reg,
2184 			 max_t(s32, reg_s32_min(reg), s32_min),
2185 			 min_t(s32, reg_s32_max(reg), s32_max));
2186 	reg_set_srange64(reg,
2187 			 max_t(s64, reg_smin(reg), s32_min),
2188 			 min_t(s64, reg_smax(reg), s32_max));
2189 
2190 	reg_bounds_sync(reg);
2191 
2192 	return reg_bounds_sanity_check(env, reg, "s32_range");
2193 }
2194 
2195 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,
2196 			   struct bpf_reg_state *reg)
2197 {
2198 	__mark_reg_unknown(env, reg);
2199 	reg->type = NOT_INIT;
2200 }
2201 
2202 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2203 			   struct bpf_reg_state *regs, u32 regno,
2204 			   enum bpf_reg_type reg_type,
2205 			   struct btf *btf, u32 btf_id,
2206 			   enum bpf_type_flag flag)
2207 {
2208 	switch (reg_type) {
2209 	case SCALAR_VALUE:
2210 		mark_reg_unknown(env, regs, regno);
2211 		return 0;
2212 	case PTR_TO_BTF_ID:
2213 		mark_reg_known_zero(env, regs, regno);
2214 		regs[regno].type = PTR_TO_BTF_ID | flag;
2215 		regs[regno].btf = btf;
2216 		regs[regno].btf_id = btf_id;
2217 		if (type_may_be_null(flag))
2218 			regs[regno].id = ++env->id_gen;
2219 		return 0;
2220 	case PTR_TO_MEM:
2221 		mark_reg_known_zero(env, regs, regno);
2222 		regs[regno].type = PTR_TO_MEM | flag;
2223 		regs[regno].mem_size = 0;
2224 		return 0;
2225 	default:
2226 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2227 		return -EFAULT;
2228 	}
2229 }
2230 
2231 #define DEF_NOT_SUBREG	(0)
2232 static void init_reg_state(struct bpf_verifier_env *env,
2233 			   struct bpf_func_state *state)
2234 {
2235 	struct bpf_reg_state *regs = state->regs;
2236 	int i;
2237 
2238 	for (i = 0; i < MAX_BPF_REG; i++) {
2239 		bpf_mark_reg_not_init(env, &regs[i]);
2240 		regs[i].subreg_def = DEF_NOT_SUBREG;
2241 	}
2242 
2243 	/* frame pointer */
2244 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2245 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2246 	regs[BPF_REG_FP].frameno = state->frameno;
2247 }
2248 
2249 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2250 {
2251 	/*
2252 	 * return_32bit is set to false by default and set explicitly
2253 	 * by the caller when necessary.
2254 	 */
2255 	return (struct bpf_retval_range){ minval, maxval, false };
2256 }
2257 
2258 static void init_func_state(struct bpf_verifier_env *env,
2259 			    struct bpf_func_state *state,
2260 			    int callsite, int frameno, int subprogno)
2261 {
2262 	state->callsite = callsite;
2263 	state->frameno = frameno;
2264 	state->subprogno = subprogno;
2265 	state->callback_ret_range = retval_range(0, 0);
2266 	init_reg_state(env, state);
2267 	mark_verifier_state_scratched(env);
2268 }
2269 
2270 /* Similar to push_stack(), but for async callbacks */
2271 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2272 						int insn_idx, int prev_insn_idx,
2273 						int subprog, bool is_sleepable)
2274 {
2275 	struct bpf_verifier_stack_elem *elem;
2276 	struct bpf_func_state *frame;
2277 
2278 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
2279 	if (!elem)
2280 		return ERR_PTR(-ENOMEM);
2281 
2282 	elem->insn_idx = insn_idx;
2283 	elem->prev_insn_idx = prev_insn_idx;
2284 	elem->next = env->head;
2285 	elem->log_pos = env->log.end_pos;
2286 	env->head = elem;
2287 	env->stack_size++;
2288 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2289 		verbose(env,
2290 			"The sequence of %d jumps is too complex for async cb.\n",
2291 			env->stack_size);
2292 		return ERR_PTR(-E2BIG);
2293 	}
2294 	/* Unlike push_stack() do not bpf_copy_verifier_state().
2295 	 * The caller state doesn't matter.
2296 	 * This is async callback. It starts in a fresh stack.
2297 	 * Initialize it similar to do_check_common().
2298 	 */
2299 	elem->st.branches = 1;
2300 	elem->st.in_sleepable = is_sleepable;
2301 	frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT);
2302 	if (!frame)
2303 		return ERR_PTR(-ENOMEM);
2304 	init_func_state(env, frame,
2305 			BPF_MAIN_FUNC /* callsite */,
2306 			0 /* frameno within this callchain */,
2307 			subprog /* subprog number within this prog */);
2308 	elem->st.frame[0] = frame;
2309 	return &elem->st;
2310 }
2311 
2312 
2313 static int cmp_subprogs(const void *a, const void *b)
2314 {
2315 	return ((struct bpf_subprog_info *)a)->start -
2316 	       ((struct bpf_subprog_info *)b)->start;
2317 }
2318 
2319 /* Find subprogram that contains instruction at 'off' */
2320 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)
2321 {
2322 	struct bpf_subprog_info *vals = env->subprog_info;
2323 	int l, r, m;
2324 
2325 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2326 		return NULL;
2327 
2328 	l = 0;
2329 	r = env->subprog_cnt - 1;
2330 	while (l < r) {
2331 		m = l + (r - l + 1) / 2;
2332 		if (vals[m].start <= off)
2333 			l = m;
2334 		else
2335 			r = m - 1;
2336 	}
2337 	return &vals[l];
2338 }
2339 
2340 /* Find subprogram that starts exactly at 'off' */
2341 int bpf_find_subprog(struct bpf_verifier_env *env, int off)
2342 {
2343 	struct bpf_subprog_info *p;
2344 
2345 	p = bpf_find_containing_subprog(env, off);
2346 	if (!p || p->start != off)
2347 		return -ENOENT;
2348 	return p - env->subprog_info;
2349 }
2350 
2351 static int add_subprog(struct bpf_verifier_env *env, int off)
2352 {
2353 	int insn_cnt = env->prog->len;
2354 	int ret;
2355 
2356 	if (off >= insn_cnt || off < 0) {
2357 		verbose(env, "call to invalid destination\n");
2358 		return -EINVAL;
2359 	}
2360 	ret = bpf_find_subprog(env, off);
2361 	if (ret >= 0)
2362 		return ret;
2363 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2364 		verbose(env, "too many subprograms\n");
2365 		return -E2BIG;
2366 	}
2367 	/* determine subprog starts. The end is one before the next starts */
2368 	env->subprog_info[env->subprog_cnt++].start = off;
2369 	sort(env->subprog_info, env->subprog_cnt,
2370 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2371 	return env->subprog_cnt - 1;
2372 }
2373 
2374 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2375 {
2376 	struct bpf_prog_aux *aux = env->prog->aux;
2377 	struct btf *btf = aux->btf;
2378 	const struct btf_type *t;
2379 	u32 main_btf_id, id;
2380 	const char *name;
2381 	int ret, i;
2382 
2383 	/* Non-zero func_info_cnt implies valid btf */
2384 	if (!aux->func_info_cnt)
2385 		return 0;
2386 	main_btf_id = aux->func_info[0].type_id;
2387 
2388 	t = btf_type_by_id(btf, main_btf_id);
2389 	if (!t) {
2390 		verbose(env, "invalid btf id for main subprog in func_info\n");
2391 		return -EINVAL;
2392 	}
2393 
2394 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2395 	if (IS_ERR(name)) {
2396 		ret = PTR_ERR(name);
2397 		/* If there is no tag present, there is no exception callback */
2398 		if (ret == -ENOENT)
2399 			ret = 0;
2400 		else if (ret == -EEXIST)
2401 			verbose(env, "multiple exception callback tags for main subprog\n");
2402 		return ret;
2403 	}
2404 
2405 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2406 	if (ret < 0) {
2407 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2408 		return ret;
2409 	}
2410 	id = ret;
2411 	t = btf_type_by_id(btf, id);
2412 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2413 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2414 		return -EINVAL;
2415 	}
2416 	ret = 0;
2417 	for (i = 0; i < aux->func_info_cnt; i++) {
2418 		if (aux->func_info[i].type_id != id)
2419 			continue;
2420 		ret = aux->func_info[i].insn_off;
2421 		/* Further func_info and subprog checks will also happen
2422 		 * later, so assume this is the right insn_off for now.
2423 		 */
2424 		if (!ret) {
2425 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2426 			ret = -EINVAL;
2427 		}
2428 	}
2429 	if (!ret) {
2430 		verbose(env, "exception callback type id not found in func_info\n");
2431 		ret = -EINVAL;
2432 	}
2433 	return ret;
2434 }
2435 
2436 #define MAX_KFUNC_BTFS	256
2437 
2438 struct bpf_kfunc_btf {
2439 	struct btf *btf;
2440 	struct module *module;
2441 	u16 offset;
2442 };
2443 
2444 struct bpf_kfunc_btf_tab {
2445 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2446 	u32 nr_descs;
2447 };
2448 
2449 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2450 {
2451 	const struct bpf_kfunc_desc *d0 = a;
2452 	const struct bpf_kfunc_desc *d1 = b;
2453 
2454 	/* func_id is not greater than BTF_MAX_TYPE */
2455 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2456 }
2457 
2458 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2459 {
2460 	const struct bpf_kfunc_btf *d0 = a;
2461 	const struct bpf_kfunc_btf *d1 = b;
2462 
2463 	return d0->offset - d1->offset;
2464 }
2465 
2466 static struct bpf_kfunc_desc *
2467 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2468 {
2469 	struct bpf_kfunc_desc desc = {
2470 		.func_id = func_id,
2471 		.offset = offset,
2472 	};
2473 	struct bpf_kfunc_desc_tab *tab;
2474 
2475 	tab = prog->aux->kfunc_tab;
2476 	return bsearch(&desc, tab->descs, tab->nr_descs,
2477 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2478 }
2479 
2480 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2481 		       u16 btf_fd_idx, u8 **func_addr)
2482 {
2483 	const struct bpf_kfunc_desc *desc;
2484 
2485 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2486 	if (!desc)
2487 		return -EFAULT;
2488 
2489 	*func_addr = (u8 *)desc->addr;
2490 	return 0;
2491 }
2492 
2493 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2494 					 s16 offset)
2495 {
2496 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2497 	struct bpf_kfunc_btf_tab *tab;
2498 	struct bpf_kfunc_btf *b;
2499 	struct module *mod;
2500 	struct btf *btf;
2501 	int btf_fd;
2502 
2503 	tab = env->prog->aux->kfunc_btf_tab;
2504 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2505 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2506 	if (!b) {
2507 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2508 			verbose(env, "too many different module BTFs\n");
2509 			return ERR_PTR(-E2BIG);
2510 		}
2511 
2512 		if (bpfptr_is_null(env->fd_array)) {
2513 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2514 			return ERR_PTR(-EPROTO);
2515 		}
2516 
2517 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2518 					    offset * sizeof(btf_fd),
2519 					    sizeof(btf_fd)))
2520 			return ERR_PTR(-EFAULT);
2521 
2522 		btf = btf_get_by_fd(btf_fd);
2523 		if (IS_ERR(btf)) {
2524 			verbose(env, "invalid module BTF fd specified\n");
2525 			return btf;
2526 		}
2527 
2528 		if (!btf_is_module(btf)) {
2529 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2530 			btf_put(btf);
2531 			return ERR_PTR(-EINVAL);
2532 		}
2533 
2534 		mod = btf_try_get_module(btf);
2535 		if (!mod) {
2536 			btf_put(btf);
2537 			return ERR_PTR(-ENXIO);
2538 		}
2539 
2540 		b = &tab->descs[tab->nr_descs++];
2541 		b->btf = btf;
2542 		b->module = mod;
2543 		b->offset = offset;
2544 
2545 		/* sort() reorders entries by value, so b may no longer point
2546 		 * to the right entry after this
2547 		 */
2548 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2549 		     kfunc_btf_cmp_by_off, NULL);
2550 	} else {
2551 		btf = b->btf;
2552 	}
2553 
2554 	return btf;
2555 }
2556 
2557 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2558 {
2559 	if (!tab)
2560 		return;
2561 
2562 	while (tab->nr_descs--) {
2563 		module_put(tab->descs[tab->nr_descs].module);
2564 		btf_put(tab->descs[tab->nr_descs].btf);
2565 	}
2566 	kfree(tab);
2567 }
2568 
2569 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2570 {
2571 	if (offset) {
2572 		if (offset < 0) {
2573 			/* In the future, this can be allowed to increase limit
2574 			 * of fd index into fd_array, interpreted as u16.
2575 			 */
2576 			verbose(env, "negative offset disallowed for kernel module function call\n");
2577 			return ERR_PTR(-EINVAL);
2578 		}
2579 
2580 		return __find_kfunc_desc_btf(env, offset);
2581 	}
2582 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2583 }
2584 
2585 #define KF_IMPL_SUFFIX "_impl"
2586 
2587 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_log *log,
2588 						    struct btf *btf,
2589 						    const char *func_name)
2590 {
2591 	const struct btf_type *func;
2592 	char buf[KSYM_NAME_LEN];
2593 	s32 impl_id;
2594 	int len;
2595 
2596 	len = snprintf(buf, sizeof(buf), "%s%s", func_name, KF_IMPL_SUFFIX);
2597 	if (len < 0 || len >= sizeof(buf)) {
2598 		bpf_log(log, "function name %s%s is too long\n",
2599 			func_name, KF_IMPL_SUFFIX);
2600 		return NULL;
2601 	}
2602 
2603 	impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC);
2604 	if (impl_id <= 0) {
2605 		bpf_log(log, "cannot find function %s in BTF\n", buf);
2606 		return NULL;
2607 	}
2608 
2609 	func = btf_type_by_id(btf, impl_id);
2610 
2611 	return btf_type_by_id(btf, func->type);
2612 }
2613 
2614 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
2615 			    s32 func_id,
2616 			    s16 offset,
2617 			    struct bpf_kfunc_meta *kfunc)
2618 {
2619 	const struct btf_type *func, *func_proto;
2620 	const char *func_name;
2621 	u32 *kfunc_flags;
2622 	struct btf *btf;
2623 
2624 	if (func_id <= 0) {
2625 		verbose(env, "invalid kernel function btf_id %d\n", func_id);
2626 		return -EINVAL;
2627 	}
2628 
2629 	btf = find_kfunc_desc_btf(env, offset);
2630 	if (IS_ERR(btf)) {
2631 		verbose(env, "failed to find BTF for kernel function\n");
2632 		return PTR_ERR(btf);
2633 	}
2634 
2635 	/*
2636 	 * Note that kfunc_flags may be NULL at this point, which
2637 	 * means that we couldn't find func_id in any relevant
2638 	 * kfunc_id_set. This most likely indicates an invalid kfunc
2639 	 * call.  However we don't fail with an error here,
2640 	 * and let the caller decide what to do with NULL kfunc->flags.
2641 	 */
2642 	kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog);
2643 
2644 	func = btf_type_by_id(btf, func_id);
2645 	if (!func || !btf_type_is_func(func)) {
2646 		verbose(env, "kernel btf_id %d is not a function\n", func_id);
2647 		return -EINVAL;
2648 	}
2649 
2650 	func_name = btf_name_by_offset(btf, func->name_off);
2651 
2652 	/*
2653 	 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag
2654 	 * can be found through the counterpart _impl kfunc.
2655 	 */
2656 	if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS))
2657 		func_proto = find_kfunc_impl_proto(&env->log, btf, func_name);
2658 	else
2659 		func_proto = btf_type_by_id(btf, func->type);
2660 
2661 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2662 		verbose(env, "kernel function btf_id %d does not have a valid func_proto\n",
2663 			func_id);
2664 		return -EINVAL;
2665 	}
2666 
2667 	memset(kfunc, 0, sizeof(*kfunc));
2668 	kfunc->btf = btf;
2669 	kfunc->id = func_id;
2670 	kfunc->name = func_name;
2671 	kfunc->proto = func_proto;
2672 	kfunc->flags = kfunc_flags;
2673 
2674 	return 0;
2675 }
2676 
2677 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
2678 {
2679 	struct bpf_kfunc_btf_tab *btf_tab;
2680 	struct btf_func_model func_model;
2681 	struct bpf_kfunc_desc_tab *tab;
2682 	struct bpf_prog_aux *prog_aux;
2683 	struct bpf_kfunc_meta kfunc;
2684 	struct bpf_kfunc_desc *desc;
2685 	unsigned long addr;
2686 	int err;
2687 
2688 	prog_aux = env->prog->aux;
2689 	tab = prog_aux->kfunc_tab;
2690 	btf_tab = prog_aux->kfunc_btf_tab;
2691 	if (!tab) {
2692 		if (!btf_vmlinux) {
2693 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2694 			return -ENOTSUPP;
2695 		}
2696 
2697 		if (!env->prog->jit_requested) {
2698 			verbose(env, "JIT is required for calling kernel function\n");
2699 			return -ENOTSUPP;
2700 		}
2701 
2702 		if (!bpf_jit_supports_kfunc_call()) {
2703 			verbose(env, "JIT does not support calling kernel function\n");
2704 			return -ENOTSUPP;
2705 		}
2706 
2707 		if (!env->prog->gpl_compatible) {
2708 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2709 			return -EINVAL;
2710 		}
2711 
2712 		tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT);
2713 		if (!tab)
2714 			return -ENOMEM;
2715 		prog_aux->kfunc_tab = tab;
2716 	}
2717 
2718 	/* func_id == 0 is always invalid, but instead of returning an error, be
2719 	 * conservative and wait until the code elimination pass before returning
2720 	 * error, so that invalid calls that get pruned out can be in BPF programs
2721 	 * loaded from userspace.  It is also required that offset be untouched
2722 	 * for such calls.
2723 	 */
2724 	if (!func_id && !offset)
2725 		return 0;
2726 
2727 	if (!btf_tab && offset) {
2728 		btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT);
2729 		if (!btf_tab)
2730 			return -ENOMEM;
2731 		prog_aux->kfunc_btf_tab = btf_tab;
2732 	}
2733 
2734 	if (find_kfunc_desc(env->prog, func_id, offset))
2735 		return 0;
2736 
2737 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2738 		verbose(env, "too many different kernel function calls\n");
2739 		return -E2BIG;
2740 	}
2741 
2742 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
2743 	if (err)
2744 		return err;
2745 
2746 	addr = kallsyms_lookup_name(kfunc.name);
2747 	if (!addr) {
2748 		verbose(env, "cannot find address for kernel function %s\n", kfunc.name);
2749 		return -EINVAL;
2750 	}
2751 
2752 	if (bpf_dev_bound_kfunc_id(func_id)) {
2753 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2754 		if (err)
2755 			return err;
2756 	}
2757 
2758 	err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model);
2759 	if (err)
2760 		return err;
2761 
2762 	desc = &tab->descs[tab->nr_descs++];
2763 	desc->func_id = func_id;
2764 	desc->offset = offset;
2765 	desc->addr = addr;
2766 	desc->func_model = func_model;
2767 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2768 	     kfunc_desc_cmp_by_id_off, NULL);
2769 	return 0;
2770 }
2771 
2772 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2773 {
2774 	return !!prog->aux->kfunc_tab;
2775 }
2776 
2777 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2778 {
2779 	struct bpf_subprog_info *subprog = env->subprog_info;
2780 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2781 	struct bpf_insn *insn = env->prog->insnsi;
2782 
2783 	/* Add entry function. */
2784 	ret = add_subprog(env, 0);
2785 	if (ret)
2786 		return ret;
2787 
2788 	for (i = 0; i < insn_cnt; i++, insn++) {
2789 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2790 		    !bpf_pseudo_kfunc_call(insn))
2791 			continue;
2792 
2793 		if (!env->bpf_capable) {
2794 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2795 			return -EPERM;
2796 		}
2797 
2798 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2799 			ret = add_subprog(env, i + insn->imm + 1);
2800 		else
2801 			ret = bpf_add_kfunc_call(env, insn->imm, insn->off);
2802 
2803 		if (ret < 0)
2804 			return ret;
2805 	}
2806 
2807 	ret = bpf_find_exception_callback_insn_off(env);
2808 	if (ret < 0)
2809 		return ret;
2810 	ex_cb_insn = ret;
2811 
2812 	/* If ex_cb_insn > 0, this means that the main program has a subprog
2813 	 * marked using BTF decl tag to serve as the exception callback.
2814 	 */
2815 	if (ex_cb_insn) {
2816 		ret = add_subprog(env, ex_cb_insn);
2817 		if (ret < 0)
2818 			return ret;
2819 		for (i = 1; i < env->subprog_cnt; i++) {
2820 			if (env->subprog_info[i].start != ex_cb_insn)
2821 				continue;
2822 			env->exception_callback_subprog = i;
2823 			bpf_mark_subprog_exc_cb(env, i);
2824 			break;
2825 		}
2826 	}
2827 
2828 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2829 	 * logic. 'subprog_cnt' should not be increased.
2830 	 */
2831 	subprog[env->subprog_cnt].start = insn_cnt;
2832 
2833 	if (env->log.level & BPF_LOG_LEVEL2)
2834 		for (i = 0; i < env->subprog_cnt; i++)
2835 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2836 
2837 	return 0;
2838 }
2839 
2840 static int check_subprogs(struct bpf_verifier_env *env)
2841 {
2842 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2843 	struct bpf_subprog_info *subprog = env->subprog_info;
2844 	struct bpf_insn *insn = env->prog->insnsi;
2845 	int insn_cnt = env->prog->len;
2846 
2847 	/* now check that all jumps are within the same subprog */
2848 	subprog_start = subprog[cur_subprog].start;
2849 	subprog_end = subprog[cur_subprog + 1].start;
2850 	for (i = 0; i < insn_cnt; i++) {
2851 		u8 code = insn[i].code;
2852 
2853 		if (code == (BPF_JMP | BPF_CALL) &&
2854 		    insn[i].src_reg == 0 &&
2855 		    insn[i].imm == BPF_FUNC_tail_call) {
2856 			subprog[cur_subprog].has_tail_call = true;
2857 			subprog[cur_subprog].tail_call_reachable = true;
2858 		}
2859 		if (BPF_CLASS(code) == BPF_LD &&
2860 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2861 			subprog[cur_subprog].has_ld_abs = true;
2862 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2863 			goto next;
2864 		if (BPF_OP(code) == BPF_CALL)
2865 			goto next;
2866 		if (BPF_OP(code) == BPF_EXIT) {
2867 			subprog[cur_subprog].exit_idx = i;
2868 			goto next;
2869 		}
2870 		off = i + bpf_jmp_offset(&insn[i]) + 1;
2871 		if (off < subprog_start || off >= subprog_end) {
2872 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2873 			return -EINVAL;
2874 		}
2875 next:
2876 		if (i == subprog_end - 1) {
2877 			/* to avoid fall-through from one subprog into another
2878 			 * the last insn of the subprog should be either exit
2879 			 * or unconditional jump back or bpf_throw call
2880 			 */
2881 			if (code != (BPF_JMP | BPF_EXIT) &&
2882 			    code != (BPF_JMP32 | BPF_JA) &&
2883 			    code != (BPF_JMP | BPF_JA)) {
2884 				verbose(env, "last insn is not an exit or jmp\n");
2885 				return -EINVAL;
2886 			}
2887 			subprog_start = subprog_end;
2888 			cur_subprog++;
2889 			if (cur_subprog < env->subprog_cnt)
2890 				subprog_end = subprog[cur_subprog + 1].start;
2891 		}
2892 	}
2893 	return 0;
2894 }
2895 
2896 /*
2897  * Sort subprogs in topological order so that leaf subprogs come first and
2898  * their callers come later. This is a DFS post-order traversal of the call
2899  * graph. Scan only reachable instructions (those in the computed postorder) of
2900  * the current subprog to discover callees (direct subprogs and sync
2901  * callbacks).
2902  */
2903 static int sort_subprogs_topo(struct bpf_verifier_env *env)
2904 {
2905 	struct bpf_subprog_info *si = env->subprog_info;
2906 	int *insn_postorder = env->cfg.insn_postorder;
2907 	struct bpf_insn *insn = env->prog->insnsi;
2908 	int cnt = env->subprog_cnt;
2909 	int *dfs_stack = NULL;
2910 	int top = 0, order = 0;
2911 	int i, ret = 0;
2912 	u8 *color = NULL;
2913 
2914 	color = kvzalloc_objs(*color, cnt, GFP_KERNEL_ACCOUNT);
2915 	dfs_stack = kvmalloc_objs(*dfs_stack, cnt, GFP_KERNEL_ACCOUNT);
2916 	if (!color || !dfs_stack) {
2917 		ret = -ENOMEM;
2918 		goto out;
2919 	}
2920 
2921 	/*
2922 	 * DFS post-order traversal.
2923 	 * Color values: 0 = unvisited, 1 = on stack, 2 = done.
2924 	 */
2925 	for (i = 0; i < cnt; i++) {
2926 		if (color[i])
2927 			continue;
2928 		color[i] = 1;
2929 		dfs_stack[top++] = i;
2930 
2931 		while (top > 0) {
2932 			int cur = dfs_stack[top - 1];
2933 			int po_start = si[cur].postorder_start;
2934 			int po_end = si[cur + 1].postorder_start;
2935 			bool pushed = false;
2936 			int j;
2937 
2938 			for (j = po_start; j < po_end; j++) {
2939 				int idx = insn_postorder[j];
2940 				int callee;
2941 
2942 				if (!bpf_pseudo_call(&insn[idx]) && !bpf_pseudo_func(&insn[idx]))
2943 					continue;
2944 				callee = bpf_find_subprog(env, idx + insn[idx].imm + 1);
2945 				if (callee < 0) {
2946 					ret = -EFAULT;
2947 					goto out;
2948 				}
2949 				if (color[callee] == 2)
2950 					continue;
2951 				if (color[callee] == 1) {
2952 					if (bpf_pseudo_func(&insn[idx]))
2953 						continue;
2954 					verbose(env, "recursive call from %s() to %s()\n",
2955 						subprog_name(env, cur),
2956 						subprog_name(env, callee));
2957 					ret = -EINVAL;
2958 					goto out;
2959 				}
2960 				color[callee] = 1;
2961 				dfs_stack[top++] = callee;
2962 				pushed = true;
2963 				break;
2964 			}
2965 
2966 			if (!pushed) {
2967 				color[cur] = 2;
2968 				env->subprog_topo_order[order++] = cur;
2969 				top--;
2970 			}
2971 		}
2972 	}
2973 
2974 	if (env->log.level & BPF_LOG_LEVEL2)
2975 		for (i = 0; i < cnt; i++)
2976 			verbose(env, "topo_order[%d] = %s\n",
2977 				i, subprog_name(env, env->subprog_topo_order[i]));
2978 out:
2979 	kvfree(dfs_stack);
2980 	kvfree(color);
2981 	return ret;
2982 }
2983 
2984 static void mark_stack_slots_scratched(struct bpf_verifier_env *env,
2985 				       int spi, int nr_slots)
2986 {
2987 	int i;
2988 
2989 	for (i = 0; i < nr_slots; i++)
2990 		mark_stack_slot_scratched(env, spi - i);
2991 }
2992 
2993 /* This function is supposed to be used by the following 32-bit optimization
2994  * code only. It returns TRUE if the source or destination register operates
2995  * on 64-bit, otherwise return FALSE.
2996  */
2997 bool bpf_is_reg64(struct bpf_insn *insn,
2998 	      u32 regno, struct bpf_reg_state *reg, enum bpf_reg_arg_type t)
2999 {
3000 	u8 code, class, op;
3001 
3002 	code = insn->code;
3003 	class = BPF_CLASS(code);
3004 	op = BPF_OP(code);
3005 	if (class == BPF_JMP) {
3006 		/* BPF_EXIT for "main" will reach here. Return TRUE
3007 		 * conservatively.
3008 		 */
3009 		if (op == BPF_EXIT)
3010 			return true;
3011 		if (op == BPF_CALL) {
3012 			/* BPF to BPF call will reach here because of marking
3013 			 * caller saved clobber with DST_OP_NO_MARK for which we
3014 			 * don't care the register def because they are anyway
3015 			 * marked as NOT_INIT already.
3016 			 */
3017 			if (insn->src_reg == BPF_PSEUDO_CALL)
3018 				return false;
3019 			/* Helper call will reach here because of arg type
3020 			 * check, conservatively return TRUE.
3021 			 */
3022 			if (t == SRC_OP)
3023 				return true;
3024 
3025 			return false;
3026 		}
3027 	}
3028 
3029 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3030 		return false;
3031 
3032 	if (class == BPF_ALU64 || class == BPF_JMP ||
3033 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3034 		return true;
3035 
3036 	if (class == BPF_ALU || class == BPF_JMP32)
3037 		return false;
3038 
3039 	if (class == BPF_LDX) {
3040 		if (t != SRC_OP)
3041 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3042 		/* LDX source must be ptr. */
3043 		return true;
3044 	}
3045 
3046 	if (class == BPF_STX) {
3047 		/* BPF_STX (including atomic variants) has one or more source
3048 		 * operands, one of which is a ptr. Check whether the caller is
3049 		 * asking about it.
3050 		 */
3051 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3052 			return true;
3053 		return BPF_SIZE(code) == BPF_DW;
3054 	}
3055 
3056 	if (class == BPF_LD) {
3057 		u8 mode = BPF_MODE(code);
3058 
3059 		/* LD_IMM64 */
3060 		if (mode == BPF_IMM)
3061 			return true;
3062 
3063 		/* Both LD_IND and LD_ABS return 32-bit data. */
3064 		if (t != SRC_OP)
3065 			return  false;
3066 
3067 		/* Implicit ctx ptr. */
3068 		if (regno == BPF_REG_6)
3069 			return true;
3070 
3071 		/* Explicit source could be any width. */
3072 		return true;
3073 	}
3074 
3075 	if (class == BPF_ST)
3076 		/* The only source register for BPF_ST is a ptr. */
3077 		return true;
3078 
3079 	/* Conservatively return true at default. */
3080 	return true;
3081 }
3082 
3083 static void mark_insn_zext(struct bpf_verifier_env *env,
3084 			   struct bpf_reg_state *reg)
3085 {
3086 	s32 def_idx = reg->subreg_def;
3087 
3088 	if (def_idx == DEF_NOT_SUBREG)
3089 		return;
3090 
3091 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3092 	/* The dst will be zero extended, so won't be sub-register anymore. */
3093 	reg->subreg_def = DEF_NOT_SUBREG;
3094 }
3095 
3096 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3097 			   enum bpf_reg_arg_type t)
3098 {
3099 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3100 	struct bpf_reg_state *reg;
3101 	bool rw64;
3102 
3103 	mark_reg_scratched(env, regno);
3104 
3105 	reg = &regs[regno];
3106 	rw64 = bpf_is_reg64(insn, regno, reg, t);
3107 	if (t == SRC_OP) {
3108 		/* check whether register used as source operand can be read */
3109 		if (reg->type == NOT_INIT) {
3110 			verbose(env, "R%d !read_ok\n", regno);
3111 			return -EACCES;
3112 		}
3113 		/* We don't need to worry about FP liveness because it's read-only */
3114 		if (regno == BPF_REG_FP)
3115 			return 0;
3116 
3117 		if (rw64)
3118 			mark_insn_zext(env, reg);
3119 
3120 		return 0;
3121 	} else {
3122 		/* check whether register used as dest operand can be written to */
3123 		if (regno == BPF_REG_FP) {
3124 			verbose(env, "frame pointer is read only\n");
3125 			return -EACCES;
3126 		}
3127 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3128 		if (t == DST_OP)
3129 			mark_reg_unknown(env, regs, regno);
3130 	}
3131 	return 0;
3132 }
3133 
3134 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3135 			 enum bpf_reg_arg_type t)
3136 {
3137 	struct bpf_verifier_state *vstate = env->cur_state;
3138 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3139 
3140 	return __check_reg_arg(env, state->regs, regno, t);
3141 }
3142 
3143 static void mark_indirect_target(struct bpf_verifier_env *env, int idx)
3144 {
3145 	env->insn_aux_data[idx].indirect_target = true;
3146 }
3147 
3148 #define LR_FRAMENO_BITS	4
3149 #define LR_SPI_BITS	6
3150 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3151 #define LR_SIZE_BITS	4
3152 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3153 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3154 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3155 #define LR_SPI_OFF	LR_FRAMENO_BITS
3156 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3157 #define LINKED_REGS_MAX	5
3158 
3159 static_assert(MAX_CALL_FRAMES <= (1 << LR_FRAMENO_BITS));
3160 static_assert(LINKED_REGS_MAX < (1 << LR_SIZE_BITS));
3161 static_assert(LINKED_REGS_MAX * LR_ENTRY_BITS + LR_SIZE_BITS <= 64);
3162 
3163 struct linked_reg {
3164 	u8 frameno;
3165 	union {
3166 		u8 spi;
3167 		u8 regno;
3168 	};
3169 	bool is_reg;
3170 };
3171 
3172 struct linked_regs {
3173 	int cnt;
3174 	struct linked_reg entries[LINKED_REGS_MAX];
3175 };
3176 
3177 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3178 {
3179 	if (s->cnt < LINKED_REGS_MAX)
3180 		return &s->entries[s->cnt++];
3181 
3182 	return NULL;
3183 }
3184 
3185 /*
3186  * Use u64 as a vector of 5 11-bit values, use first 4-bits to track
3187  * number of elements currently in stack.
3188  * Pack one history entry for linked registers as 11 bits in the following format:
3189  * - 4-bits frameno
3190  * - 6-bits spi_or_reg
3191  * - 1-bit  is_reg
3192  */
3193 static u64 linked_regs_pack(struct linked_regs *s)
3194 {
3195 	u64 val = 0;
3196 	int i;
3197 
3198 	for (i = 0; i < s->cnt; ++i) {
3199 		struct linked_reg *e = &s->entries[i];
3200 		u64 tmp = 0;
3201 
3202 		tmp |= e->frameno;
3203 		tmp |= e->spi << LR_SPI_OFF;
3204 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3205 
3206 		val <<= LR_ENTRY_BITS;
3207 		val |= tmp;
3208 	}
3209 	val <<= LR_SIZE_BITS;
3210 	val |= s->cnt;
3211 	return val;
3212 }
3213 
3214 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3215 {
3216 	int i;
3217 
3218 	s->cnt = val & LR_SIZE_MASK;
3219 	val >>= LR_SIZE_BITS;
3220 
3221 	for (i = 0; i < s->cnt; ++i) {
3222 		struct linked_reg *e = &s->entries[i];
3223 
3224 		e->frameno =  val & LR_FRAMENO_MASK;
3225 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3226 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3227 		val >>= LR_ENTRY_BITS;
3228 	}
3229 }
3230 
3231 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3232 {
3233 	const struct btf_type *func;
3234 	struct btf *desc_btf;
3235 
3236 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3237 		return NULL;
3238 
3239 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3240 	if (IS_ERR(desc_btf))
3241 		return "<error>";
3242 
3243 	func = btf_type_by_id(desc_btf, insn->imm);
3244 	return btf_name_by_offset(desc_btf, func->name_off);
3245 }
3246 
3247 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
3248 {
3249 	const struct bpf_insn_cbs cbs = {
3250 		.cb_call	= disasm_kfunc_name,
3251 		.cb_print	= verbose,
3252 		.private_data	= env,
3253 	};
3254 
3255 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3256 }
3257 
3258 /* If any register R in hist->linked_regs is marked as precise in bt,
3259  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
3260  */
3261 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
3262 {
3263 	struct linked_regs linked_regs;
3264 	bool some_precise = false;
3265 	int i;
3266 
3267 	if (!hist || hist->linked_regs == 0)
3268 		return;
3269 
3270 	linked_regs_unpack(hist->linked_regs, &linked_regs);
3271 	for (i = 0; i < linked_regs.cnt; ++i) {
3272 		struct linked_reg *e = &linked_regs.entries[i];
3273 
3274 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
3275 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
3276 			some_precise = true;
3277 			break;
3278 		}
3279 	}
3280 
3281 	if (!some_precise)
3282 		return;
3283 
3284 	for (i = 0; i < linked_regs.cnt; ++i) {
3285 		struct linked_reg *e = &linked_regs.entries[i];
3286 
3287 		if (e->is_reg)
3288 			bpf_bt_set_frame_reg(bt, e->frameno, e->regno);
3289 		else
3290 			bpf_bt_set_frame_slot(bt, e->frameno, e->spi);
3291 	}
3292 }
3293 
3294 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3295 {
3296 	return bpf_mark_chain_precision(env, env->cur_state, regno, NULL);
3297 }
3298 
3299 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
3300  * desired reg and stack masks across all relevant frames
3301  */
3302 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
3303 				      struct bpf_verifier_state *starting_state)
3304 {
3305 	return bpf_mark_chain_precision(env, starting_state, -1, NULL);
3306 }
3307 
3308 static bool is_spillable_regtype(enum bpf_reg_type type)
3309 {
3310 	switch (base_type(type)) {
3311 	case PTR_TO_MAP_VALUE:
3312 	case PTR_TO_STACK:
3313 	case PTR_TO_CTX:
3314 	case PTR_TO_PACKET:
3315 	case PTR_TO_PACKET_META:
3316 	case PTR_TO_PACKET_END:
3317 	case PTR_TO_FLOW_KEYS:
3318 	case CONST_PTR_TO_MAP:
3319 	case PTR_TO_SOCKET:
3320 	case PTR_TO_SOCK_COMMON:
3321 	case PTR_TO_TCP_SOCK:
3322 	case PTR_TO_XDP_SOCK:
3323 	case PTR_TO_BTF_ID:
3324 	case PTR_TO_BUF:
3325 	case PTR_TO_MEM:
3326 	case PTR_TO_FUNC:
3327 	case PTR_TO_MAP_KEY:
3328 	case PTR_TO_ARENA:
3329 		return true;
3330 	default:
3331 		return false;
3332 	}
3333 }
3334 
3335 
3336 /* check if register is a constant scalar value */
3337 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
3338 {
3339 	return reg->type == SCALAR_VALUE &&
3340 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
3341 }
3342 
3343 /* assuming is_reg_const() is true, return constant value of a register */
3344 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
3345 {
3346 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
3347 }
3348 
3349 static bool __is_pointer_value(bool allow_ptr_leaks,
3350 			       const struct bpf_reg_state *reg)
3351 {
3352 	if (allow_ptr_leaks)
3353 		return false;
3354 
3355 	return reg->type != SCALAR_VALUE;
3356 }
3357 
3358 static void clear_scalar_id(struct bpf_reg_state *reg)
3359 {
3360 	reg->id = 0;
3361 	reg->delta = 0;
3362 }
3363 
3364 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
3365 					struct bpf_reg_state *src_reg)
3366 {
3367 	if (src_reg->type != SCALAR_VALUE)
3368 		return;
3369 	/*
3370 	 * The verifier is processing rX = rY insn and
3371 	 * rY->id has special linked register already.
3372 	 * Cleared it, since multiple rX += const are not supported.
3373 	 */
3374 	if (src_reg->id & BPF_ADD_CONST)
3375 		clear_scalar_id(src_reg);
3376 	/*
3377 	 * Ensure that src_reg has a valid ID that will be copied to
3378 	 * dst_reg and then will be used by sync_linked_regs() to
3379 	 * propagate min/max range.
3380 	 */
3381 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
3382 		src_reg->id = ++env->id_gen;
3383 }
3384 
3385 static void save_register_state(struct bpf_verifier_env *env,
3386 				struct bpf_func_state *state,
3387 				int spi, struct bpf_reg_state *reg,
3388 				int size)
3389 {
3390 	int i;
3391 
3392 	state->stack[spi].spilled_ptr = *reg;
3393 
3394 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3395 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3396 
3397 	/* size < 8 bytes spill */
3398 	for (; i; i--)
3399 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
3400 }
3401 
3402 static bool is_bpf_st_mem(struct bpf_insn *insn)
3403 {
3404 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3405 }
3406 
3407 static int get_reg_width(struct bpf_reg_state *reg)
3408 {
3409 	return fls64(reg_umax(reg));
3410 }
3411 
3412 /* See comment for mark_fastcall_pattern_for_call() */
3413 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
3414 					  struct bpf_func_state *state, int insn_idx, int off)
3415 {
3416 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
3417 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
3418 	int i;
3419 
3420 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
3421 		return;
3422 	/* access to the region [max_stack_depth .. fastcall_stack_off)
3423 	 * from something that is not a part of the fastcall pattern,
3424 	 * disable fastcall rewrites for current subprogram by setting
3425 	 * fastcall_stack_off to a value smaller than any possible offset.
3426 	 */
3427 	subprog->fastcall_stack_off = S16_MIN;
3428 	/* reset fastcall aux flags within subprogram,
3429 	 * happens at most once per subprogram
3430 	 */
3431 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
3432 		aux[i].fastcall_spills_num = 0;
3433 		aux[i].fastcall_pattern = 0;
3434 	}
3435 }
3436 
3437 static void scrub_special_slot(struct bpf_func_state *state, int spi)
3438 {
3439 	int i;
3440 
3441 	/* regular write of data into stack destroys any spilled ptr */
3442 	state->stack[spi].spilled_ptr.type = NOT_INIT;
3443 	/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
3444 	if (is_stack_slot_special(&state->stack[spi]))
3445 		for (i = 0; i < BPF_REG_SIZE; i++)
3446 			scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3447 }
3448 
3449 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3450  * stack boundary and alignment are checked in check_mem_access()
3451  */
3452 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3453 				       /* stack frame we're writing to */
3454 				       struct bpf_func_state *state,
3455 				       int off, int size, int value_regno,
3456 				       int insn_idx)
3457 {
3458 	struct bpf_func_state *cur; /* state of the current function */
3459 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3460 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3461 	struct bpf_reg_state *reg = NULL;
3462 	int insn_flags = INSN_F_STACK_ACCESS;
3463 	int hist_spi = spi, hist_frame = state->frameno;
3464 
3465 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3466 	 * so it's aligned access and [off, off + size) are within stack limits
3467 	 */
3468 	if (!env->allow_ptr_leaks &&
3469 	    bpf_is_spilled_reg(&state->stack[spi]) &&
3470 	    !bpf_is_spilled_scalar_reg(&state->stack[spi]) &&
3471 	    size != BPF_REG_SIZE) {
3472 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3473 		return -EACCES;
3474 	}
3475 
3476 	cur = env->cur_state->frame[env->cur_state->curframe];
3477 	if (value_regno >= 0)
3478 		reg = &cur->regs[value_regno];
3479 	if (!env->bypass_spec_v4) {
3480 		bool sanitize = reg && is_spillable_regtype(reg->type);
3481 
3482 		for (i = 0; i < size; i++) {
3483 			u8 type = state->stack[spi].slot_type[(slot - i) %
3484 							      BPF_REG_SIZE];
3485 
3486 			if (type != STACK_MISC && type != STACK_ZERO) {
3487 				sanitize = true;
3488 				break;
3489 			}
3490 		}
3491 
3492 		if (sanitize)
3493 			env->insn_aux_data[insn_idx].nospec_result = true;
3494 	}
3495 
3496 	err = destroy_if_dynptr_stack_slot(env, state, spi);
3497 	if (err)
3498 		return err;
3499 
3500 	check_fastcall_stack_contract(env, state, insn_idx, off);
3501 	mark_stack_slot_scratched(env, spi);
3502 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
3503 		bool reg_value_fits;
3504 
3505 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
3506 		/* Make sure that reg had an ID to build a relation on spill. */
3507 		if (reg_value_fits)
3508 			assign_scalar_id_before_mov(env, reg);
3509 		save_register_state(env, state, spi, reg, size);
3510 		/* Break the relation on a narrowing spill. */
3511 		if (!reg_value_fits)
3512 			state->stack[spi].spilled_ptr.id = 0;
3513 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3514 		   env->bpf_capable) {
3515 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
3516 
3517 		memset(tmp_reg, 0, sizeof(*tmp_reg));
3518 		__mark_reg_known(tmp_reg, insn->imm);
3519 		tmp_reg->type = SCALAR_VALUE;
3520 		save_register_state(env, state, spi, tmp_reg, size);
3521 	} else if (reg && is_spillable_regtype(reg->type)) {
3522 		/* register containing pointer is being spilled into stack */
3523 		if (size != BPF_REG_SIZE) {
3524 			verbose_linfo(env, insn_idx, "; ");
3525 			verbose(env, "invalid size of register spill\n");
3526 			return -EACCES;
3527 		}
3528 		if (state != cur && reg->type == PTR_TO_STACK) {
3529 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3530 			return -EINVAL;
3531 		}
3532 		save_register_state(env, state, spi, reg, size);
3533 	} else {
3534 		u8 type = STACK_MISC;
3535 
3536 		scrub_special_slot(state, spi);
3537 
3538 		/* when we zero initialize stack slots mark them as such */
3539 		if ((reg && bpf_register_is_null(reg)) ||
3540 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3541 			/* STACK_ZERO case happened because register spill
3542 			 * wasn't properly aligned at the stack slot boundary,
3543 			 * so it's not a register spill anymore; force
3544 			 * originating register to be precise to make
3545 			 * STACK_ZERO correct for subsequent states
3546 			 */
3547 			err = mark_chain_precision(env, value_regno);
3548 			if (err)
3549 				return err;
3550 			type = STACK_ZERO;
3551 		}
3552 
3553 		/* Mark slots affected by this stack write. */
3554 		for (i = 0; i < size; i++)
3555 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
3556 		insn_flags = 0; /* not a register spill */
3557 	}
3558 
3559 	if (insn_flags)
3560 		return bpf_push_jmp_history(env, env->cur_state, insn_flags,
3561 					    hist_spi, hist_frame, 0);
3562 	return 0;
3563 }
3564 
3565 /* Write the stack: 'stack[ptr_reg + off] = value_regno'. 'ptr_reg' is
3566  * known to contain a variable offset.
3567  * This function checks whether the write is permitted and conservatively
3568  * tracks the effects of the write, considering that each stack slot in the
3569  * dynamic range is potentially written to.
3570  *
3571  * 'value_regno' can be -1, meaning that an unknown value is being written to
3572  * the stack.
3573  *
3574  * Spilled pointers in range are not marked as written because we don't know
3575  * what's going to be actually written. This means that read propagation for
3576  * future reads cannot be terminated by this write.
3577  *
3578  * For privileged programs, uninitialized stack slots are considered
3579  * initialized by this write (even though we don't know exactly what offsets
3580  * are going to be written to). The idea is that we don't want the verifier to
3581  * reject future reads that access slots written to through variable offsets.
3582  */
3583 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3584 				     /* func where register points to */
3585 				     struct bpf_func_state *state,
3586 				     struct bpf_reg_state *ptr_reg, int off, int size,
3587 				     int value_regno, int insn_idx)
3588 {
3589 	struct bpf_func_state *cur; /* state of the current function */
3590 	int min_off, max_off;
3591 	int i, err;
3592 	struct bpf_reg_state *value_reg = NULL;
3593 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3594 	bool writing_zero = false;
3595 	/* set if the fact that we're writing a zero is used to let any
3596 	 * stack slots remain STACK_ZERO
3597 	 */
3598 	bool zero_used = false;
3599 
3600 	cur = env->cur_state->frame[env->cur_state->curframe];
3601 	min_off = reg_smin(ptr_reg) + off;
3602 	max_off = reg_smax(ptr_reg) + off + size;
3603 	if (value_regno >= 0)
3604 		value_reg = &cur->regs[value_regno];
3605 	if ((value_reg && bpf_register_is_null(value_reg)) ||
3606 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
3607 		writing_zero = true;
3608 
3609 	for (i = min_off; i < max_off; i++) {
3610 		int spi;
3611 
3612 		spi = bpf_get_spi(i);
3613 		err = destroy_if_dynptr_stack_slot(env, state, spi);
3614 		if (err)
3615 			return err;
3616 	}
3617 
3618 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
3619 	/* Variable offset writes destroy any spilled pointers in range. */
3620 	for (i = min_off; i < max_off; i++) {
3621 		u8 new_type, *stype;
3622 		int slot, spi;
3623 
3624 		slot = -i - 1;
3625 		spi = slot / BPF_REG_SIZE;
3626 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3627 		mark_stack_slot_scratched(env, spi);
3628 
3629 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3630 			/* Reject the write if range we may write to has not
3631 			 * been initialized beforehand. If we didn't reject
3632 			 * here, the ptr status would be erased below (even
3633 			 * though not all slots are actually overwritten),
3634 			 * possibly opening the door to leaks.
3635 			 *
3636 			 * We do however catch STACK_INVALID case below, and
3637 			 * only allow reading possibly uninitialized memory
3638 			 * later for CAP_PERFMON, as the write may not happen to
3639 			 * that slot.
3640 			 */
3641 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3642 				insn_idx, i);
3643 			return -EINVAL;
3644 		}
3645 
3646 		/* If writing_zero and the spi slot contains a spill of value 0,
3647 		 * maintain the spill type.
3648 		 */
3649 		if (writing_zero && *stype == STACK_SPILL &&
3650 		    bpf_is_spilled_scalar_reg(&state->stack[spi])) {
3651 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
3652 
3653 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
3654 				zero_used = true;
3655 				continue;
3656 			}
3657 		}
3658 
3659 		/*
3660 		 * Scrub slots if variable-offset stack write goes over spilled pointers.
3661 		 * Otherwise bpf_is_spilled_reg() may == true && spilled_ptr.type == NOT_INIT
3662 		 * and valid program is rejected by check_stack_read_fixed_off()
3663 		 * with obscure "invalid size of register fill" message.
3664 		 */
3665 		scrub_special_slot(state, spi);
3666 
3667 		/* Update the slot type. */
3668 		new_type = STACK_MISC;
3669 		if (writing_zero && *stype == STACK_ZERO) {
3670 			new_type = STACK_ZERO;
3671 			zero_used = true;
3672 		}
3673 		/* If the slot is STACK_INVALID, we check whether it's OK to
3674 		 * pretend that it will be initialized by this write. The slot
3675 		 * might not actually be written to, and so if we mark it as
3676 		 * initialized future reads might leak uninitialized memory.
3677 		 * For privileged programs, we will accept such reads to slots
3678 		 * that may or may not be written because, if we're reject
3679 		 * them, the error would be too confusing.
3680 		 * Conservatively, treat STACK_POISON in a similar way.
3681 		 */
3682 		if ((*stype == STACK_INVALID || *stype == STACK_POISON) &&
3683 		    !env->allow_uninit_stack) {
3684 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3685 					insn_idx, i);
3686 			return -EINVAL;
3687 		}
3688 		*stype = new_type;
3689 	}
3690 	if (zero_used) {
3691 		/* backtracking doesn't work for STACK_ZERO yet. */
3692 		err = mark_chain_precision(env, value_regno);
3693 		if (err)
3694 			return err;
3695 	}
3696 	return 0;
3697 }
3698 
3699 /* When register 'dst_regno' is assigned some values from stack[min_off,
3700  * max_off), we set the register's type according to the types of the
3701  * respective stack slots. If all the stack values are known to be zeros, then
3702  * so is the destination reg. Otherwise, the register is considered to be
3703  * SCALAR. This function does not deal with register filling; the caller must
3704  * ensure that all spilled registers in the stack range have been marked as
3705  * read.
3706  */
3707 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3708 				/* func where src register points to */
3709 				struct bpf_func_state *ptr_state,
3710 				int min_off, int max_off, int dst_regno)
3711 {
3712 	struct bpf_verifier_state *vstate = env->cur_state;
3713 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3714 	int i, slot, spi;
3715 	u8 *stype;
3716 	int zeros = 0;
3717 
3718 	for (i = min_off; i < max_off; i++) {
3719 		slot = -i - 1;
3720 		spi = slot / BPF_REG_SIZE;
3721 		mark_stack_slot_scratched(env, spi);
3722 		stype = ptr_state->stack[spi].slot_type;
3723 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3724 			break;
3725 		zeros++;
3726 	}
3727 	if (zeros == max_off - min_off) {
3728 		/* Any access_size read into register is zero extended,
3729 		 * so the whole register == const_zero.
3730 		 */
3731 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
3732 	} else {
3733 		/* have read misc data from the stack */
3734 		mark_reg_unknown(env, state->regs, dst_regno);
3735 	}
3736 }
3737 
3738 /* Read the stack at 'off' and put the results into the register indicated by
3739  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3740  * spilled reg.
3741  *
3742  * 'dst_regno' can be -1, meaning that the read value is not going to a
3743  * register.
3744  *
3745  * The access is assumed to be within the current stack bounds.
3746  */
3747 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3748 				      /* func where src register points to */
3749 				      struct bpf_func_state *reg_state,
3750 				      int off, int size, int dst_regno)
3751 {
3752 	struct bpf_verifier_state *vstate = env->cur_state;
3753 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3754 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3755 	struct bpf_reg_state *reg;
3756 	u8 *stype, type;
3757 	int insn_flags = INSN_F_STACK_ACCESS;
3758 	int hist_spi = spi, hist_frame = reg_state->frameno;
3759 
3760 	stype = reg_state->stack[spi].slot_type;
3761 	reg = &reg_state->stack[spi].spilled_ptr;
3762 
3763 	mark_stack_slot_scratched(env, spi);
3764 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
3765 
3766 	if (bpf_is_spilled_reg(&reg_state->stack[spi])) {
3767 		u8 spill_size = 1;
3768 
3769 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3770 			spill_size++;
3771 
3772 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3773 			if (reg->type != SCALAR_VALUE) {
3774 				verbose_linfo(env, env->insn_idx, "; ");
3775 				verbose(env, "invalid size of register fill\n");
3776 				return -EACCES;
3777 			}
3778 
3779 			if (dst_regno < 0)
3780 				return 0;
3781 
3782 			if (size <= spill_size &&
3783 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
3784 				/* The earlier check_reg_arg() has decided the
3785 				 * subreg_def for this insn.  Save it first.
3786 				 */
3787 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3788 
3789 				if (env->bpf_capable && size == 4 && spill_size == 4 &&
3790 				    get_reg_width(reg) <= 32)
3791 					/* Ensure stack slot has an ID to build a relation
3792 					 * with the destination register on fill.
3793 					 */
3794 					assign_scalar_id_before_mov(env, reg);
3795 				state->regs[dst_regno] = *reg;
3796 				state->regs[dst_regno].subreg_def = subreg_def;
3797 
3798 				/* Break the relation on a narrowing fill.
3799 				 * coerce_reg_to_size will adjust the boundaries.
3800 				 */
3801 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
3802 					clear_scalar_id(&state->regs[dst_regno]);
3803 			} else {
3804 				int spill_cnt = 0, zero_cnt = 0;
3805 
3806 				for (i = 0; i < size; i++) {
3807 					type = stype[(slot - i) % BPF_REG_SIZE];
3808 					if (type == STACK_SPILL) {
3809 						spill_cnt++;
3810 						continue;
3811 					}
3812 					if (type == STACK_MISC)
3813 						continue;
3814 					if (type == STACK_ZERO) {
3815 						zero_cnt++;
3816 						continue;
3817 					}
3818 					if (type == STACK_INVALID && env->allow_uninit_stack)
3819 						continue;
3820 					if (type == STACK_POISON) {
3821 						verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n",
3822 							off, i, size);
3823 					} else {
3824 						verbose(env, "invalid read from stack off %d+%d size %d\n",
3825 							off, i, size);
3826 					}
3827 					return -EACCES;
3828 				}
3829 
3830 				if (spill_cnt == size &&
3831 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
3832 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
3833 					/* this IS register fill, so keep insn_flags */
3834 				} else if (zero_cnt == size) {
3835 					/* similarly to mark_reg_stack_read(), preserve zeroes */
3836 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
3837 					insn_flags = 0; /* not restoring original register state */
3838 				} else {
3839 					mark_reg_unknown(env, state->regs, dst_regno);
3840 					insn_flags = 0; /* not restoring original register state */
3841 				}
3842 			}
3843 		} else if (dst_regno >= 0) {
3844 			/* restore register state from stack */
3845 			if (env->bpf_capable)
3846 				/* Ensure stack slot has an ID to build a relation
3847 				 * with the destination register on fill.
3848 				 */
3849 				assign_scalar_id_before_mov(env, reg);
3850 			state->regs[dst_regno] = *reg;
3851 			/* mark reg as written since spilled pointer state likely
3852 			 * has its liveness marks cleared by is_state_visited()
3853 			 * which resets stack/reg liveness for state transitions
3854 			 */
3855 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3856 			/* If dst_regno==-1, the caller is asking us whether
3857 			 * it is acceptable to use this value as a SCALAR_VALUE
3858 			 * (e.g. for XADD).
3859 			 * We must not allow unprivileged callers to do that
3860 			 * with spilled pointers.
3861 			 */
3862 			verbose(env, "leaking pointer from stack off %d\n",
3863 				off);
3864 			return -EACCES;
3865 		}
3866 	} else {
3867 		for (i = 0; i < size; i++) {
3868 			type = stype[(slot - i) % BPF_REG_SIZE];
3869 			if (type == STACK_MISC)
3870 				continue;
3871 			if (type == STACK_ZERO)
3872 				continue;
3873 			if (type == STACK_INVALID && env->allow_uninit_stack)
3874 				continue;
3875 			if (type == STACK_POISON) {
3876 				verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n",
3877 					off, i, size);
3878 			} else {
3879 				verbose(env, "invalid read from stack off %d+%d size %d\n",
3880 					off, i, size);
3881 			}
3882 			return -EACCES;
3883 		}
3884 		if (dst_regno >= 0)
3885 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3886 		insn_flags = 0; /* we are not restoring spilled register */
3887 	}
3888 	if (insn_flags)
3889 		return bpf_push_jmp_history(env, env->cur_state, insn_flags,
3890 					    hist_spi, hist_frame, 0);
3891 	return 0;
3892 }
3893 
3894 enum bpf_access_src {
3895 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3896 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3897 };
3898 
3899 static int check_stack_range_initialized(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3900 					 argno_t argno, int off, int access_size,
3901 					 bool zero_size_allowed,
3902 					 enum bpf_access_type type,
3903 					 struct bpf_call_arg_meta *meta);
3904 
3905 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3906 {
3907 	return cur_regs(env) + regno;
3908 }
3909 
3910 /* Read the stack at 'reg + off' and put the result into the register
3911  * 'dst_regno'.
3912  * 'off' includes the pointer register's fixed offset(i.e. 'reg->off'),
3913  * but not its variable offset.
3914  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3915  *
3916  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3917  * filling registers (i.e. reads of spilled register cannot be detected when
3918  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3919  * SCALAR_VALUE. That's why we assert that the 'reg' has a variable
3920  * offset; for a fixed offset check_stack_read_fixed_off should be used
3921  * instead.
3922  */
3923 static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3924 				    argno_t ptr_argno, int off, int size, int dst_regno)
3925 {
3926 	struct bpf_func_state *ptr_state = bpf_func(env, reg);
3927 	int err;
3928 	int min_off, max_off;
3929 
3930 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3931 	 */
3932 	err = check_stack_range_initialized(env, reg, ptr_argno, off, size,
3933 					    false, BPF_READ, NULL);
3934 	if (err)
3935 		return err;
3936 
3937 	min_off = reg_smin(reg) + off;
3938 	max_off = reg_smax(reg) + off;
3939 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3940 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
3941 	return 0;
3942 }
3943 
3944 /* check_stack_read dispatches to check_stack_read_fixed_off or
3945  * check_stack_read_var_off.
3946  *
3947  * The caller must ensure that the offset falls within the allocated stack
3948  * bounds.
3949  *
3950  * 'dst_regno' is a register which will receive the value from the stack. It
3951  * can be -1, meaning that the read value is not going to a register.
3952  */
3953 static int check_stack_read(struct bpf_verifier_env *env,
3954 			    struct bpf_reg_state *reg, argno_t ptr_argno, int off, int size,
3955 			    int dst_regno)
3956 {
3957 	struct bpf_func_state *state = bpf_func(env, reg);
3958 	int err;
3959 	/* Some accesses are only permitted with a static offset. */
3960 	bool var_off = !tnum_is_const(reg->var_off);
3961 
3962 	/* The offset is required to be static when reads don't go to a
3963 	 * register, in order to not leak pointers (see
3964 	 * check_stack_read_fixed_off).
3965 	 */
3966 	if (dst_regno < 0 && var_off) {
3967 		char tn_buf[48];
3968 
3969 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3970 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3971 			tn_buf, off, size);
3972 		return -EACCES;
3973 	}
3974 	/* Variable offset is prohibited for unprivileged mode for simplicity
3975 	 * since it requires corresponding support in Spectre masking for stack
3976 	 * ALU. See also retrieve_ptr_limit(). The check in
3977 	 * check_stack_access_for_ptr_arithmetic() called by
3978 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
3979 	 * with variable offsets, therefore no check is required here. Further,
3980 	 * just checking it here would be insufficient as speculative stack
3981 	 * writes could still lead to unsafe speculative behaviour.
3982 	 */
3983 	if (!var_off) {
3984 		off += reg->var_off.value;
3985 		err = check_stack_read_fixed_off(env, state, off, size,
3986 						 dst_regno);
3987 	} else {
3988 		/* Variable offset stack reads need more conservative handling
3989 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3990 		 * branch.
3991 		 */
3992 		err = check_stack_read_var_off(env, reg, ptr_argno, off, size,
3993 					       dst_regno);
3994 	}
3995 	return err;
3996 }
3997 
3998 
3999 /* check_stack_write dispatches to check_stack_write_fixed_off or
4000  * check_stack_write_var_off.
4001  *
4002  * 'reg' is the register used as a pointer into the stack.
4003  * 'value_regno' is the register whose value we're writing to the stack. It can
4004  * be -1, meaning that we're not writing from a register.
4005  *
4006  * The caller must ensure that the offset falls within the maximum stack size.
4007  */
4008 static int check_stack_write(struct bpf_verifier_env *env,
4009 			     struct bpf_reg_state *reg, int off, int size,
4010 			     int value_regno, int insn_idx)
4011 {
4012 	struct bpf_func_state *state = bpf_func(env, reg);
4013 	int err;
4014 
4015 	if (tnum_is_const(reg->var_off)) {
4016 		off += reg->var_off.value;
4017 		err = check_stack_write_fixed_off(env, state, off, size,
4018 						  value_regno, insn_idx);
4019 	} else {
4020 		/* Variable offset stack reads need more conservative handling
4021 		 * than fixed offset ones.
4022 		 */
4023 		err = check_stack_write_var_off(env, state,
4024 						reg, off, size,
4025 						value_regno, insn_idx);
4026 	}
4027 	return err;
4028 }
4029 
4030 /*
4031  * Write a value to the outgoing stack arg area.
4032  * off is a negative offset from r11 (e.g. -8 for arg6, -16 for arg7).
4033  */
4034 static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state,
4035 				 int off, struct bpf_reg_state *value_reg)
4036 {
4037 	int max_stack_arg_regs = MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS;
4038 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4039 	int spi = -off / BPF_REG_SIZE - 1;
4040 	struct bpf_reg_state *arg;
4041 	int err;
4042 
4043 	if (spi >= max_stack_arg_regs) {
4044 		verbose(env, "stack arg write offset %d exceeds max %d stack args\n",
4045 			off, max_stack_arg_regs);
4046 		return -EINVAL;
4047 	}
4048 
4049 	err = grow_stack_arg_slots(env, state, spi + 1);
4050 	if (err)
4051 		return err;
4052 
4053 	/* Track the max outgoing stack arg slot count. */
4054 	if (spi + 1 > subprog->max_out_stack_arg_cnt)
4055 		subprog->max_out_stack_arg_cnt = spi + 1;
4056 
4057 	if (value_reg) {
4058 		state->stack_arg_regs[spi] = *value_reg;
4059 	} else {
4060 		/* BPF_ST: store immediate, treat as scalar */
4061 		arg = &state->stack_arg_regs[spi];
4062 		arg->type = SCALAR_VALUE;
4063 		__mark_reg_known(arg, env->prog->insnsi[env->insn_idx].imm);
4064 	}
4065 	state->no_stack_arg_load = true;
4066 	return bpf_push_jmp_history(env, env->cur_state,
4067 				    INSN_F_STACK_ARG_ACCESS, spi, 0, 0);
4068 }
4069 
4070 /*
4071  * Read a value from the incoming stack arg area.
4072  * off is a positive offset from r11 (e.g. +8 for arg6, +16 for arg7).
4073  */
4074 static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_state *state,
4075 				int off, int dst_regno)
4076 {
4077 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4078 	struct bpf_verifier_state *vstate = env->cur_state;
4079 	int spi = off / BPF_REG_SIZE - 1;
4080 	struct bpf_func_state *caller, *cur;
4081 	struct bpf_reg_state *arg;
4082 
4083 	if (state->no_stack_arg_load) {
4084 		verbose(env, "r11 load must be before any r11 store or call insn\n");
4085 		return -EINVAL;
4086 	}
4087 
4088 	if (spi + 1 > bpf_in_stack_arg_cnt(subprog)) {
4089 		verbose(env, "invalid read from stack arg off %d depth %d\n",
4090 			off, bpf_in_stack_arg_cnt(subprog) * BPF_REG_SIZE);
4091 		return -EACCES;
4092 	}
4093 
4094 	caller = vstate->frame[vstate->curframe - 1];
4095 	arg = &caller->stack_arg_regs[spi];
4096 	cur = vstate->frame[vstate->curframe];
4097 	cur->regs[dst_regno] = *arg;
4098 	return bpf_push_jmp_history(env, env->cur_state,
4099 				    INSN_F_STACK_ARG_ACCESS, spi, 0, 0);
4100 }
4101 
4102 static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx)
4103 {
4104 	struct bpf_func_state *caller = cur_func(env);
4105 	int spi = arg_idx - MAX_BPF_FUNC_REG_ARGS;
4106 
4107 	bt_set_frame_stack_arg_slot(&env->bt, caller->frameno, spi);
4108 	return mark_chain_precision_batch(env, env->cur_state);
4109 }
4110 
4111 static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller,
4112 				     int nargs)
4113 {
4114 	int i, spi;
4115 
4116 	for (i = MAX_BPF_FUNC_REG_ARGS; i < nargs; i++) {
4117 		spi = i - MAX_BPF_FUNC_REG_ARGS;
4118 		if (spi >= caller->out_stack_arg_cnt ||
4119 		    caller->stack_arg_regs[spi].type == NOT_INIT) {
4120 			verbose(env, "callee expects %d args, stack arg%d is not initialized\n",
4121 				nargs, spi + 1);
4122 			return -EFAULT;
4123 		}
4124 	}
4125 
4126 	return 0;
4127 }
4128 
4129 static struct bpf_reg_state *get_func_arg_reg(struct bpf_func_state *caller,
4130 					      struct bpf_reg_state *regs, int arg)
4131 {
4132 	if (arg < MAX_BPF_FUNC_REG_ARGS)
4133 		return &regs[arg + 1];
4134 
4135 	return &caller->stack_arg_regs[arg - MAX_BPF_FUNC_REG_ARGS];
4136 }
4137 
4138 static int check_map_access_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4139 				 int off, int size, enum bpf_access_type type)
4140 {
4141 	struct bpf_map *map = reg->map_ptr;
4142 	u32 cap = bpf_map_flags_to_cap(map);
4143 
4144 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4145 		verbose(env, "write into map forbidden, value_size=%d off=%lld size=%d\n",
4146 			map->value_size, reg_smin(reg) + off, size);
4147 		return -EACCES;
4148 	}
4149 
4150 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4151 		verbose(env, "read from map forbidden, value_size=%d off=%lld size=%d\n",
4152 			map->value_size, reg_smin(reg) + off, size);
4153 		return -EACCES;
4154 	}
4155 
4156 	return 0;
4157 }
4158 
4159 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4160 static int __check_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4161 			      int off, int size, u32 mem_size,
4162 			      bool zero_size_allowed)
4163 {
4164 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4165 
4166 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4167 		return 0;
4168 
4169 	switch (reg->type) {
4170 	case PTR_TO_MAP_KEY:
4171 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4172 			mem_size, off, size);
4173 		break;
4174 	case PTR_TO_MAP_VALUE:
4175 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4176 			mem_size, off, size);
4177 		break;
4178 	case PTR_TO_PACKET:
4179 	case PTR_TO_PACKET_META:
4180 	case PTR_TO_PACKET_END:
4181 		verbose(env, "invalid access to packet, off=%d size=%d, %s(id=%d,off=%d,r=%d)\n",
4182 			off, size, reg_arg_name(env, argno), reg->id, off, mem_size);
4183 		break;
4184 	case PTR_TO_CTX:
4185 		verbose(env, "invalid access to context, ctx_size=%d off=%d size=%d\n",
4186 			mem_size, off, size);
4187 		break;
4188 	case PTR_TO_MEM:
4189 	default:
4190 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4191 			mem_size, off, size);
4192 	}
4193 
4194 	return -EACCES;
4195 }
4196 
4197 /* check read/write into a memory region with possible variable offset */
4198 static int check_mem_region_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4199 				   int off, int size, u32 mem_size,
4200 				   bool zero_size_allowed)
4201 {
4202 	int err;
4203 
4204 	/* We may have adjusted the register pointing to memory region, so we
4205 	 * need to try adding each of min_value and max_value to off
4206 	 * to make sure our theoretical access will be safe.
4207 	 *
4208 	 * The minimum value is only important with signed
4209 	 * comparisons where we can't assume the floor of a
4210 	 * value is 0.  If we are using signed variables for our
4211 	 * index'es we need to make sure that whatever we use
4212 	 * will have a set floor within our range.
4213 	 */
4214 	if (reg_smin(reg) < 0 &&
4215 	    (reg_smin(reg) == S64_MIN ||
4216 	     (off + reg_smin(reg) != (s64)(s32)(off + reg_smin(reg))) ||
4217 	      reg_smin(reg) + off < 0)) {
4218 		verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4219 			reg_arg_name(env, argno));
4220 		return -EACCES;
4221 	}
4222 	err = __check_mem_access(env, reg, argno, reg_smin(reg) + off, size,
4223 				 mem_size, zero_size_allowed);
4224 	if (err) {
4225 		verbose(env, "%s min value is outside of the allowed memory range\n",
4226 			reg_arg_name(env, argno));
4227 		return err;
4228 	}
4229 
4230 	/* If we haven't set a max value then we need to bail since we can't be
4231 	 * sure we won't do bad things.
4232 	 * If reg_umax(reg) + off could overflow, treat that as unbounded too.
4233 	 */
4234 	if (reg_umax(reg) >= BPF_MAX_VAR_OFF) {
4235 		verbose(env, "%s unbounded memory access, make sure to bounds check any such access\n",
4236 			reg_arg_name(env, argno));
4237 		return -EACCES;
4238 	}
4239 	err = __check_mem_access(env, reg, argno, reg_umax(reg) + off, size,
4240 				 mem_size, zero_size_allowed);
4241 	if (err) {
4242 		verbose(env, "%s max value is outside of the allowed memory range\n",
4243 			reg_arg_name(env, argno));
4244 		return err;
4245 	}
4246 
4247 	return 0;
4248 }
4249 
4250 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4251 			       const struct bpf_reg_state *reg, argno_t argno,
4252 			       bool fixed_off_ok)
4253 {
4254 	/* Access to this pointer-typed register or passing it to a helper
4255 	 * is only allowed in its original, unmodified form.
4256 	 */
4257 
4258 	if (!tnum_is_const(reg->var_off)) {
4259 		char tn_buf[48];
4260 
4261 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4262 		verbose(env, "variable %s access var_off=%s disallowed\n",
4263 			reg_type_str(env, reg->type), tn_buf);
4264 		return -EACCES;
4265 	}
4266 
4267 	if (reg_smin(reg) < 0) {
4268 		verbose(env, "negative offset %s ptr %s off=%lld disallowed\n",
4269 			reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value);
4270 		return -EACCES;
4271 	}
4272 
4273 	if (!fixed_off_ok && reg->var_off.value != 0) {
4274 		verbose(env, "dereference of modified %s ptr %s off=%lld disallowed\n",
4275 			reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value);
4276 		return -EACCES;
4277 	}
4278 
4279 	return 0;
4280 }
4281 
4282 static int check_ptr_off_reg(struct bpf_verifier_env *env,
4283 		             const struct bpf_reg_state *reg, int regno)
4284 {
4285 	return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false);
4286 }
4287 
4288 static int map_kptr_match_type(struct bpf_verifier_env *env,
4289 			       struct btf_field *kptr_field,
4290 			       struct bpf_reg_state *reg, u32 regno)
4291 {
4292 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4293 	int perm_flags;
4294 	const char *reg_name = "";
4295 
4296 	if (base_type(reg->type) != PTR_TO_BTF_ID)
4297 		goto bad_type;
4298 
4299 	if (btf_is_kernel(reg->btf)) {
4300 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4301 
4302 		/* Only unreferenced case accepts untrusted pointers */
4303 		if (kptr_field->type == BPF_KPTR_UNREF)
4304 			perm_flags |= PTR_UNTRUSTED;
4305 	} else {
4306 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
4307 		if (kptr_field->type == BPF_KPTR_PERCPU)
4308 			perm_flags |= MEM_PERCPU;
4309 	}
4310 
4311 	if (type_flag(reg->type) & ~perm_flags)
4312 		goto bad_type;
4313 
4314 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4315 	reg_name = btf_type_name(reg->btf, reg->btf_id);
4316 
4317 	/* For ref_ptr case, release function check should ensure we get one
4318 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4319 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
4320 	 * Since ref_ptr cannot be accessed directly by BPF insns, check for
4321 	 * reg->id is not needed here.
4322 	 */
4323 	if (__check_ptr_off_reg(env, reg, argno_from_reg(regno), true))
4324 		return -EACCES;
4325 
4326 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
4327 	 * we also need to take into account the reg->var_off.
4328 	 *
4329 	 * We want to support cases like:
4330 	 *
4331 	 * struct foo {
4332 	 *         struct bar br;
4333 	 *         struct baz bz;
4334 	 * };
4335 	 *
4336 	 * struct foo *v;
4337 	 * v = func();	      // PTR_TO_BTF_ID
4338 	 * val->foo = v;      // reg->var_off is zero, btf and btf_id match type
4339 	 * val->bar = &v->br; // reg->var_off is still zero, but we need to retry with
4340 	 *                    // first member type of struct after comparison fails
4341 	 * val->baz = &v->bz; // reg->var_off is non-zero, so struct needs to be walked
4342 	 *                    // to match type
4343 	 *
4344 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->var_off
4345 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
4346 	 * the struct to match type against first member of struct, i.e. reject
4347 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4348 	 * strict mode to true for type match.
4349 	 */
4350 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->var_off.value,
4351 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4352 				  kptr_field->type != BPF_KPTR_UNREF))
4353 		goto bad_type;
4354 	return 0;
4355 bad_type:
4356 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4357 		reg_type_str(env, reg->type), reg_name);
4358 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4359 	if (kptr_field->type == BPF_KPTR_UNREF)
4360 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4361 			targ_name);
4362 	else
4363 		verbose(env, "\n");
4364 	return -EINVAL;
4365 }
4366 
4367 static bool in_sleepable(struct bpf_verifier_env *env)
4368 {
4369 	return env->cur_state->in_sleepable;
4370 }
4371 
4372 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
4373  * can dereference RCU protected pointers and result is PTR_TRUSTED.
4374  */
4375 static bool in_rcu_cs(struct bpf_verifier_env *env)
4376 {
4377 	return env->cur_state->active_rcu_locks ||
4378 	       env->cur_state->active_locks ||
4379 	       !in_sleepable(env);
4380 }
4381 
4382 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
4383 BTF_SET_START(rcu_protected_types)
4384 #ifdef CONFIG_NET
4385 BTF_ID(struct, prog_test_ref_kfunc)
4386 #endif
4387 #ifdef CONFIG_CGROUPS
4388 BTF_ID(struct, cgroup)
4389 #endif
4390 #ifdef CONFIG_BPF_JIT
4391 BTF_ID(struct, bpf_cpumask)
4392 #endif
4393 BTF_ID(struct, task_struct)
4394 #ifdef CONFIG_CRYPTO
4395 BTF_ID(struct, bpf_crypto_ctx)
4396 #endif
4397 BTF_SET_END(rcu_protected_types)
4398 
4399 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
4400 {
4401 	if (!btf_is_kernel(btf))
4402 		return true;
4403 	return btf_id_set_contains(&rcu_protected_types, btf_id);
4404 }
4405 
4406 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
4407 {
4408 	struct btf_struct_meta *meta;
4409 
4410 	if (btf_is_kernel(kptr_field->kptr.btf))
4411 		return NULL;
4412 
4413 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
4414 				    kptr_field->kptr.btf_id);
4415 
4416 	return meta ? meta->record : NULL;
4417 }
4418 
4419 static bool rcu_safe_kptr(const struct btf_field *field)
4420 {
4421 	const struct btf_field_kptr *kptr = &field->kptr;
4422 
4423 	return field->type == BPF_KPTR_PERCPU ||
4424 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
4425 }
4426 
4427 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
4428 {
4429 	struct btf_record *rec;
4430 	u32 ret;
4431 
4432 	ret = PTR_MAYBE_NULL;
4433 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
4434 		ret |= MEM_RCU;
4435 		if (kptr_field->type == BPF_KPTR_PERCPU)
4436 			ret |= MEM_PERCPU;
4437 		else if (!btf_is_kernel(kptr_field->kptr.btf))
4438 			ret |= MEM_ALLOC;
4439 
4440 		rec = kptr_pointee_btf_record(kptr_field);
4441 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
4442 			ret |= NON_OWN_REF;
4443 	} else {
4444 		ret |= PTR_UNTRUSTED;
4445 	}
4446 
4447 	return ret;
4448 }
4449 
4450 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
4451 			    struct btf_field *field)
4452 {
4453 	struct bpf_reg_state *reg;
4454 	const struct btf_type *t;
4455 
4456 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
4457 	mark_reg_known_zero(env, cur_regs(env), regno);
4458 	reg = reg_state(env, regno);
4459 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
4460 	reg->mem_size = t->size;
4461 	reg->id = ++env->id_gen;
4462 
4463 	return 0;
4464 }
4465 
4466 static int check_map_kptr_access(struct bpf_verifier_env *env,
4467 				 int value_regno, int insn_idx,
4468 				 struct btf_field *kptr_field)
4469 {
4470 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4471 	int class = BPF_CLASS(insn->code);
4472 	struct bpf_reg_state *val_reg;
4473 	int ret;
4474 
4475 	/* Things we already checked for in check_map_access and caller:
4476 	 *  - Reject cases where variable offset may touch kptr
4477 	 *  - size of access (must be BPF_DW)
4478 	 *  - tnum_is_const(reg->var_off)
4479 	 *  - kptr_field->offset == off + reg->var_off.value
4480 	 */
4481 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4482 	if (BPF_MODE(insn->code) != BPF_MEM) {
4483 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4484 		return -EACCES;
4485 	}
4486 
4487 	/* We only allow loading referenced kptr, since it will be marked as
4488 	 * untrusted, similar to unreferenced kptr.
4489 	 */
4490 	if (class != BPF_LDX &&
4491 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
4492 		verbose(env, "store to referenced kptr disallowed\n");
4493 		return -EACCES;
4494 	}
4495 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
4496 		verbose(env, "store to uptr disallowed\n");
4497 		return -EACCES;
4498 	}
4499 
4500 	if (class == BPF_LDX) {
4501 		if (kptr_field->type == BPF_UPTR)
4502 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
4503 
4504 		/* We can simply mark the value_regno receiving the pointer
4505 		 * value from map as PTR_TO_BTF_ID, with the correct type.
4506 		 */
4507 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
4508 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4509 				      btf_ld_kptr_type(env, kptr_field));
4510 		if (ret < 0)
4511 			return ret;
4512 	} else if (class == BPF_STX) {
4513 		val_reg = reg_state(env, value_regno);
4514 		if (!bpf_register_is_null(val_reg) &&
4515 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4516 			return -EACCES;
4517 	} else if (class == BPF_ST) {
4518 		if (insn->imm) {
4519 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4520 				kptr_field->offset);
4521 			return -EACCES;
4522 		}
4523 	} else {
4524 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4525 		return -EACCES;
4526 	}
4527 	return 0;
4528 }
4529 
4530 /*
4531  * Return the size of the memory region accessible from a pointer to map value.
4532  * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible.
4533  */
4534 static u32 map_mem_size(const struct bpf_map *map)
4535 {
4536 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY)
4537 		return map->max_entries * sizeof(long);
4538 
4539 	return map->value_size;
4540 }
4541 
4542 /* check read/write into a map element with possible variable offset */
4543 static int check_map_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4544 			    int off, int size, bool zero_size_allowed,
4545 			    enum bpf_access_src src)
4546 {
4547 	struct bpf_map *map = reg->map_ptr;
4548 	u32 mem_size = map_mem_size(map);
4549 	struct btf_record *rec;
4550 	int err, i;
4551 
4552 	err = check_mem_region_access(env, reg, argno, off, size, mem_size, zero_size_allowed);
4553 	if (err)
4554 		return err;
4555 
4556 	if (IS_ERR_OR_NULL(map->record))
4557 		return 0;
4558 	rec = map->record;
4559 	for (i = 0; i < rec->cnt; i++) {
4560 		struct btf_field *field = &rec->fields[i];
4561 		u32 p = field->offset;
4562 
4563 		/* If any part of a field  can be touched by load/store, reject
4564 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
4565 		 * it is sufficient to check x1 < y2 && y1 < x2.
4566 		 */
4567 		if (reg_smin(reg) + off < p + field->size &&
4568 		    p < reg_umax(reg) + off + size) {
4569 			switch (field->type) {
4570 			case BPF_KPTR_UNREF:
4571 			case BPF_KPTR_REF:
4572 			case BPF_KPTR_PERCPU:
4573 			case BPF_UPTR:
4574 				if (src != ACCESS_DIRECT) {
4575 					verbose(env, "%s cannot be accessed indirectly by helper\n",
4576 						btf_field_type_name(field->type));
4577 					return -EACCES;
4578 				}
4579 				if (!tnum_is_const(reg->var_off)) {
4580 					verbose(env, "%s access cannot have variable offset\n",
4581 						btf_field_type_name(field->type));
4582 					return -EACCES;
4583 				}
4584 				if (p != off + reg->var_off.value) {
4585 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
4586 						btf_field_type_name(field->type),
4587 						p, off + reg->var_off.value);
4588 					return -EACCES;
4589 				}
4590 				if (size != bpf_size_to_bytes(BPF_DW)) {
4591 					verbose(env, "%s access size must be BPF_DW\n",
4592 						btf_field_type_name(field->type));
4593 					return -EACCES;
4594 				}
4595 				break;
4596 			default:
4597 				verbose(env, "%s cannot be accessed directly by load/store\n",
4598 					btf_field_type_name(field->type));
4599 				return -EACCES;
4600 			}
4601 		}
4602 	}
4603 	return 0;
4604 }
4605 
4606 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4607 			       const struct bpf_call_arg_meta *meta,
4608 			       enum bpf_access_type t)
4609 {
4610 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4611 
4612 	switch (prog_type) {
4613 	/* Program types only with direct read access go here! */
4614 	case BPF_PROG_TYPE_LWT_IN:
4615 	case BPF_PROG_TYPE_LWT_OUT:
4616 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4617 	case BPF_PROG_TYPE_SK_REUSEPORT:
4618 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4619 	case BPF_PROG_TYPE_CGROUP_SKB:
4620 		if (t == BPF_WRITE)
4621 			return false;
4622 		fallthrough;
4623 
4624 	/* Program types with direct read + write access go here! */
4625 	case BPF_PROG_TYPE_SCHED_CLS:
4626 	case BPF_PROG_TYPE_SCHED_ACT:
4627 	case BPF_PROG_TYPE_XDP:
4628 	case BPF_PROG_TYPE_LWT_XMIT:
4629 	case BPF_PROG_TYPE_SK_SKB:
4630 	case BPF_PROG_TYPE_SK_MSG:
4631 		if (meta)
4632 			return meta->pkt_access;
4633 
4634 		env->seen_direct_write = true;
4635 		return true;
4636 
4637 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4638 		if (t == BPF_WRITE)
4639 			env->seen_direct_write = true;
4640 
4641 		return true;
4642 
4643 	default:
4644 		return false;
4645 	}
4646 }
4647 
4648 static int check_packet_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off,
4649 			       int size, bool zero_size_allowed)
4650 {
4651 	int err;
4652 
4653 	if (reg->range < 0) {
4654 		verbose(env, "%s offset is outside of the packet\n", reg_arg_name(env, argno));
4655 		return -EINVAL;
4656 	}
4657 
4658 	err = check_mem_region_access(env, reg, argno, off, size, reg->range, zero_size_allowed);
4659 	if (err)
4660 		return err;
4661 
4662 	/* __check_mem_access has made sure "off + size - 1" is within u16.
4663 	 * reg_umax(reg) can't be bigger than MAX_PACKET_OFF which is 0xffff,
4664 	 * otherwise find_good_pkt_pointers would have refused to set range info
4665 	 * that __check_mem_access would have rejected this pkt access.
4666 	 * Therefore, "off + reg_umax(reg) + size - 1" won't overflow u32.
4667 	 */
4668 	env->prog->aux->max_pkt_offset =
4669 		max_t(u32, env->prog->aux->max_pkt_offset,
4670 		      off + reg_umax(reg) + size - 1);
4671 
4672 	return 0;
4673 }
4674 
4675 static bool is_var_ctx_off_allowed(struct bpf_prog *prog)
4676 {
4677 	return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL;
4678 }
4679 
4680 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4681 static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4682 			      enum bpf_access_type t, struct bpf_insn_access_aux *info)
4683 {
4684 	if (env->ops->is_valid_access &&
4685 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
4686 		/* A non zero info.ctx_field_size indicates that this field is a
4687 		 * candidate for later verifier transformation to load the whole
4688 		 * field and then apply a mask when accessed with a narrower
4689 		 * access than actual ctx access size. A zero info.ctx_field_size
4690 		 * will only allow for whole field access and rejects any other
4691 		 * type of narrower access.
4692 		 */
4693 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
4694 			if (info->ref_id &&
4695 			    !find_reference_state(env->cur_state, info->ref_id)) {
4696 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
4697 					off);
4698 				return -EACCES;
4699 			}
4700 		} else {
4701 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
4702 		}
4703 		/* remember the offset of last byte accessed in ctx */
4704 		if (env->prog->aux->max_ctx_offset < off + size)
4705 			env->prog->aux->max_ctx_offset = off + size;
4706 		return 0;
4707 	}
4708 
4709 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4710 	return -EACCES;
4711 }
4712 
4713 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno,
4714 			    int off, int access_size, enum bpf_access_type t,
4715 			    struct bpf_insn_access_aux *info)
4716 {
4717 	/*
4718 	 * Program types that don't rewrite ctx accesses can safely
4719 	 * dereference ctx pointers with fixed offsets.
4720 	 */
4721 	bool var_off_ok = is_var_ctx_off_allowed(env->prog);
4722 	bool fixed_off_ok = !env->ops->convert_ctx_access;
4723 	int err;
4724 
4725 	if (var_off_ok)
4726 		err = check_mem_region_access(env, reg, argno, off, access_size, U16_MAX, false);
4727 	else
4728 		err = __check_ptr_off_reg(env, reg, argno, fixed_off_ok);
4729 	if (err)
4730 		return err;
4731 	off += reg_umax(reg);
4732 
4733 	err = __check_ctx_access(env, insn_idx, off, access_size, t, info);
4734 	if (err)
4735 		verbose_linfo(env, insn_idx, "; ");
4736 	return err;
4737 }
4738 
4739 static int check_flow_keys_access(struct bpf_verifier_env *env,
4740 				  struct bpf_reg_state *reg, argno_t argno,
4741 				  int off, int size)
4742 {
4743 	/* Only a constant offset is allowed here; fold it into off. */
4744 	if (!tnum_is_const(reg->var_off)) {
4745 		char tn_buf[48];
4746 
4747 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4748 		verbose(env, "%s invalid variable offset to flow keys: off=%d, var_off=%s\n",
4749 			reg_arg_name(env, argno), off, tn_buf);
4750 		return -EACCES;
4751 	}
4752 	off += reg->var_off.value;
4753 
4754 	if (size < 0 || off < 0 ||
4755 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
4756 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
4757 			off, size);
4758 		return -EACCES;
4759 	}
4760 	return 0;
4761 }
4762 
4763 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4764 			     struct bpf_reg_state *reg, argno_t argno, int off, int size,
4765 			     enum bpf_access_type t)
4766 {
4767 	struct bpf_insn_access_aux info = {};
4768 	bool valid;
4769 
4770 	if (reg_smin(reg) < 0) {
4771 		verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4772 			reg_arg_name(env, argno));
4773 		return -EACCES;
4774 	}
4775 
4776 	switch (reg->type) {
4777 	case PTR_TO_SOCK_COMMON:
4778 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4779 		break;
4780 	case PTR_TO_SOCKET:
4781 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4782 		break;
4783 	case PTR_TO_TCP_SOCK:
4784 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4785 		break;
4786 	case PTR_TO_XDP_SOCK:
4787 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4788 		break;
4789 	default:
4790 		valid = false;
4791 	}
4792 
4793 
4794 	if (valid) {
4795 		env->insn_aux_data[insn_idx].ctx_field_size =
4796 			info.ctx_field_size;
4797 		return 0;
4798 	}
4799 
4800 	verbose(env, "%s invalid %s access off=%d size=%d\n",
4801 		reg_arg_name(env, argno), reg_type_str(env, reg->type), off, size);
4802 
4803 	return -EACCES;
4804 }
4805 
4806 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4807 {
4808 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4809 }
4810 
4811 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4812 {
4813 	const struct bpf_reg_state *reg = reg_state(env, regno);
4814 
4815 	return reg->type == PTR_TO_CTX;
4816 }
4817 
4818 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4819 {
4820 	const struct bpf_reg_state *reg = reg_state(env, regno);
4821 
4822 	return type_is_sk_pointer(reg->type);
4823 }
4824 
4825 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4826 {
4827 	const struct bpf_reg_state *reg = reg_state(env, regno);
4828 
4829 	return type_is_pkt_pointer(reg->type);
4830 }
4831 
4832 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4833 {
4834 	const struct bpf_reg_state *reg = reg_state(env, regno);
4835 
4836 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4837 	return reg->type == PTR_TO_FLOW_KEYS;
4838 }
4839 
4840 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
4841 {
4842 	const struct bpf_reg_state *reg = reg_state(env, regno);
4843 
4844 	return reg->type == PTR_TO_ARENA;
4845 }
4846 
4847 /* Return false if @regno contains a pointer whose type isn't supported for
4848  * atomic instruction @insn.
4849  */
4850 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
4851 			       struct bpf_insn *insn)
4852 {
4853 	if (is_ctx_reg(env, regno))
4854 		return false;
4855 	if (is_pkt_reg(env, regno))
4856 		return false;
4857 	if (is_flow_key_reg(env, regno))
4858 		return false;
4859 	if (is_sk_reg(env, regno))
4860 		return false;
4861 	if (is_arena_reg(env, regno))
4862 		return bpf_jit_supports_insn(insn, true);
4863 
4864 	return true;
4865 }
4866 
4867 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
4868 #ifdef CONFIG_NET
4869 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
4870 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4871 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
4872 #endif
4873 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
4874 };
4875 
4876 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
4877 {
4878 	/* A referenced register is always trusted. */
4879 	if (reg_is_referenced(env, reg))
4880 		return true;
4881 
4882 	/* Types listed in the reg2btf_ids are always trusted */
4883 	if (reg2btf_ids[base_type(reg->type)] &&
4884 	    !bpf_type_has_unsafe_modifiers(reg->type))
4885 		return true;
4886 
4887 	/* If a register is not referenced, it is trusted if it has the
4888 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4889 	 * other type modifiers may be safe, but we elect to take an opt-in
4890 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4891 	 * not.
4892 	 *
4893 	 * Eventually, we should make PTR_TRUSTED the single source of truth
4894 	 * for whether a register is trusted.
4895 	 */
4896 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4897 	       !bpf_type_has_unsafe_modifiers(reg->type);
4898 }
4899 
4900 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4901 {
4902 	return reg->type & MEM_RCU;
4903 }
4904 
4905 static void clear_trusted_flags(enum bpf_type_flag *flag)
4906 {
4907 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
4908 }
4909 
4910 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4911 				   const struct bpf_reg_state *reg,
4912 				   int off, int size, bool strict)
4913 {
4914 	struct tnum reg_off;
4915 	int ip_align;
4916 
4917 	/* Byte size accesses are always allowed. */
4918 	if (!strict || size == 1)
4919 		return 0;
4920 
4921 	/* For platforms that do not have a Kconfig enabling
4922 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4923 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4924 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4925 	 * to this code only in strict mode where we want to emulate
4926 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4927 	 * unconditional IP align value of '2'.
4928 	 */
4929 	ip_align = 2;
4930 
4931 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + off));
4932 	if (!tnum_is_aligned(reg_off, size)) {
4933 		char tn_buf[48];
4934 
4935 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4936 		verbose(env,
4937 			"misaligned packet access off %d+%s+%d size %d\n",
4938 			ip_align, tn_buf, off, size);
4939 		return -EACCES;
4940 	}
4941 
4942 	return 0;
4943 }
4944 
4945 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4946 				       const struct bpf_reg_state *reg,
4947 				       const char *pointer_desc,
4948 				       int off, int size, bool strict)
4949 {
4950 	struct tnum reg_off;
4951 
4952 	/* Byte size accesses are always allowed. */
4953 	if (!strict || size == 1)
4954 		return 0;
4955 
4956 	reg_off = tnum_add(reg->var_off, tnum_const(off));
4957 	if (!tnum_is_aligned(reg_off, size)) {
4958 		char tn_buf[48];
4959 
4960 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4961 		verbose(env, "misaligned %saccess off %s+%d size %d\n",
4962 			pointer_desc, tn_buf, off, size);
4963 		return -EACCES;
4964 	}
4965 
4966 	return 0;
4967 }
4968 
4969 static int check_ptr_alignment(struct bpf_verifier_env *env,
4970 			       const struct bpf_reg_state *reg, int off,
4971 			       int size, bool strict_alignment_once)
4972 {
4973 	bool strict = env->strict_alignment || strict_alignment_once;
4974 	const char *pointer_desc = "";
4975 
4976 	switch (reg->type) {
4977 	case PTR_TO_PACKET:
4978 	case PTR_TO_PACKET_META:
4979 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4980 		 * right in front, treat it the very same way.
4981 		 */
4982 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4983 	case PTR_TO_FLOW_KEYS:
4984 		pointer_desc = "flow keys ";
4985 		break;
4986 	case PTR_TO_MAP_KEY:
4987 		pointer_desc = "key ";
4988 		break;
4989 	case PTR_TO_MAP_VALUE:
4990 		pointer_desc = "value ";
4991 		if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY)
4992 			strict = true;
4993 		break;
4994 	case PTR_TO_CTX:
4995 		pointer_desc = "context ";
4996 		break;
4997 	case PTR_TO_STACK:
4998 		pointer_desc = "stack ";
4999 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5000 		 * and check_stack_read_fixed_off() relies on stack accesses being
5001 		 * aligned.
5002 		 */
5003 		strict = true;
5004 		break;
5005 	case PTR_TO_SOCKET:
5006 		pointer_desc = "sock ";
5007 		break;
5008 	case PTR_TO_SOCK_COMMON:
5009 		pointer_desc = "sock_common ";
5010 		break;
5011 	case PTR_TO_TCP_SOCK:
5012 		pointer_desc = "tcp_sock ";
5013 		break;
5014 	case PTR_TO_XDP_SOCK:
5015 		pointer_desc = "xdp_sock ";
5016 		break;
5017 	case PTR_TO_ARENA:
5018 		return 0;
5019 	default:
5020 		break;
5021 	}
5022 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5023 					   strict);
5024 }
5025 
5026 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
5027 {
5028 	if (!bpf_jit_supports_private_stack())
5029 		return NO_PRIV_STACK;
5030 
5031 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
5032 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
5033 	 * explicitly.
5034 	 */
5035 	switch (prog->type) {
5036 	case BPF_PROG_TYPE_KPROBE:
5037 	case BPF_PROG_TYPE_TRACEPOINT:
5038 	case BPF_PROG_TYPE_PERF_EVENT:
5039 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
5040 		return PRIV_STACK_ADAPTIVE;
5041 	case BPF_PROG_TYPE_TRACING:
5042 	case BPF_PROG_TYPE_LSM:
5043 	case BPF_PROG_TYPE_STRUCT_OPS:
5044 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
5045 			return PRIV_STACK_ADAPTIVE;
5046 		fallthrough;
5047 	default:
5048 		break;
5049 	}
5050 
5051 	return NO_PRIV_STACK;
5052 }
5053 
5054 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5055 {
5056 	if (env->prog->jit_requested)
5057 		return round_up(stack_depth, 16);
5058 
5059 	/* round up to 32-bytes, since this is granularity
5060 	 * of interpreter stack size
5061 	 */
5062 	return round_up(max_t(u32, stack_depth, 1), 32);
5063 }
5064 
5065 /* temporary state used for call frame depth calculation */
5066 struct bpf_subprog_call_depth_info {
5067 	int ret_insn; /* caller instruction where we return to. */
5068 	int caller; /* caller subprogram idx */
5069 	int frame; /* # of consecutive static call stack frames on top of stack */
5070 };
5071 
5072 /* starting from main bpf function walk all instructions of the function
5073  * and recursively walk all callees that given function can call.
5074  * Ignore jump and exit insns.
5075  */
5076 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
5077 					 struct bpf_subprog_call_depth_info *dinfo,
5078 					 bool priv_stack_supported)
5079 {
5080 	struct bpf_subprog_info *subprog = env->subprog_info;
5081 	struct bpf_insn *insn = env->prog->insnsi;
5082 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
5083 	bool tail_call_reachable = false;
5084 	int total;
5085 	int tmp;
5086 
5087 	/* no caller idx */
5088 	dinfo[idx].caller = -1;
5089 
5090 	i = subprog[idx].start;
5091 	if (!priv_stack_supported)
5092 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5093 process_func:
5094 	/* protect against potential stack overflow that might happen when
5095 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5096 	 * depth for such case down to 256 so that the worst case scenario
5097 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5098 	 * 8k).
5099 	 *
5100 	 * To get the idea what might happen, see an example:
5101 	 * func1 -> sub rsp, 128
5102 	 *  subfunc1 -> sub rsp, 256
5103 	 *  tailcall1 -> add rsp, 256
5104 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5105 	 *   subfunc2 -> sub rsp, 64
5106 	 *   subfunc22 -> sub rsp, 128
5107 	 *   tailcall2 -> add rsp, 128
5108 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5109 	 *
5110 	 * tailcall will unwind the current stack frame but it will not get rid
5111 	 * of caller's stack as shown on the example above.
5112 	 */
5113 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5114 		verbose(env,
5115 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5116 			depth);
5117 		return -EACCES;
5118 	}
5119 
5120 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
5121 	if (IS_ENABLED(CONFIG_X86_64) && subprog[idx].stack_arg_cnt) {
5122 		/* x86-64 uses R9 for both private stack frame pointer and arg6. */
5123 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5124 	} else if (priv_stack_supported) {
5125 		/* Request private stack support only if the subprog stack
5126 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
5127 		 * avoid jit penalty if the stack usage is small.
5128 		 */
5129 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
5130 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
5131 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
5132 	}
5133 
5134 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
5135 		if (subprog_depth > env->max_stack_depth)
5136 			env->max_stack_depth = subprog_depth;
5137 		if (subprog_depth > MAX_BPF_STACK) {
5138 			verbose(env, "stack size of subprog %d is %d. Too large\n",
5139 				idx, subprog_depth);
5140 			return -EACCES;
5141 		}
5142 	} else {
5143 		depth += subprog_depth;
5144 		if (depth > env->max_stack_depth)
5145 			env->max_stack_depth = depth;
5146 		if (depth > MAX_BPF_STACK) {
5147 			total = 0;
5148 			for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller)
5149 				total++;
5150 
5151 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
5152 				total, depth);
5153 			return -EACCES;
5154 		}
5155 	}
5156 continue_func:
5157 	subprog_end = subprog[idx + 1].start;
5158 	for (; i < subprog_end; i++) {
5159 		int next_insn, sidx;
5160 
5161 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5162 			bool err = false;
5163 
5164 			if (!bpf_is_throw_kfunc(insn + i))
5165 				continue;
5166 			for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) {
5167 				if (subprog[tmp].is_cb) {
5168 					err = true;
5169 					break;
5170 				}
5171 			}
5172 			if (!err)
5173 				continue;
5174 			verbose(env,
5175 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5176 				i, idx);
5177 			return -EINVAL;
5178 		}
5179 
5180 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5181 			continue;
5182 		/* remember insn and function to return to */
5183 
5184 		/* find the callee */
5185 		next_insn = i + insn[i].imm + 1;
5186 		sidx = bpf_find_subprog(env, next_insn);
5187 		if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
5188 			return -EFAULT;
5189 		if (subprog[sidx].is_async_cb) {
5190 			if (subprog[sidx].has_tail_call) {
5191 				verifier_bug(env, "subprog has tail_call and async cb");
5192 				return -EFAULT;
5193 			}
5194 			/* async callbacks don't increase bpf prog stack size unless called directly */
5195 			if (!bpf_pseudo_call(insn + i))
5196 				continue;
5197 			if (subprog[sidx].is_exception_cb) {
5198 				verbose(env, "insn %d cannot call exception cb directly", i);
5199 				return -EINVAL;
5200 			}
5201 		}
5202 
5203 		/* store caller info for after we return from callee */
5204 		dinfo[idx].frame = frame;
5205 		dinfo[idx].ret_insn = i + 1;
5206 
5207 		/* push caller idx into callee's dinfo */
5208 		dinfo[sidx].caller = idx;
5209 
5210 		i = next_insn;
5211 
5212 		idx = sidx;
5213 		if (!priv_stack_supported)
5214 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5215 
5216 		if (subprog[idx].has_tail_call)
5217 			tail_call_reachable = true;
5218 
5219 		frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1;
5220 		if (frame >= MAX_CALL_FRAMES) {
5221 			verbose(env, "the call stack of %d frames is too deep !\n",
5222 				frame);
5223 			return -E2BIG;
5224 		}
5225 		goto process_func;
5226 	}
5227 	/* if tail call got detected across bpf2bpf calls then mark each of the
5228 	 * currently present subprog frames as tail call reachable subprogs;
5229 	 * this info will be utilized by JIT so that we will be preserving the
5230 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5231 	 */
5232 	if (tail_call_reachable) {
5233 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
5234 			if (subprog[tmp].is_exception_cb) {
5235 				verbose(env, "cannot tail call within exception cb\n");
5236 				return -EINVAL;
5237 			}
5238 			if (subprog[tmp].stack_arg_cnt) {
5239 				verbose(env, "tail_calls are not allowed in programs with stack args\n");
5240 				return -EINVAL;
5241 			}
5242 			subprog[tmp].tail_call_reachable = true;
5243 		}
5244 	} else if (!idx && subprog[0].has_tail_call && subprog[0].stack_arg_cnt) {
5245 		verbose(env, "tail_calls are not allowed in programs with stack args\n");
5246 		return -EINVAL;
5247 	}
5248 
5249 	if (subprog[0].tail_call_reachable)
5250 		env->prog->aux->tail_call_reachable = true;
5251 
5252 	/* end of for() loop means the last insn of the 'subprog'
5253 	 * was reached. Doesn't matter whether it was JA or EXIT
5254 	 */
5255 	if (frame == 0 && dinfo[idx].caller < 0)
5256 		return 0;
5257 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
5258 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
5259 
5260 	/* pop caller idx from callee */
5261 	idx = dinfo[idx].caller;
5262 
5263 	/* retrieve caller state from its frame */
5264 	frame = dinfo[idx].frame;
5265 	i = dinfo[idx].ret_insn;
5266 
5267 	/* reset tail_call_reachable to the parent's actual state */
5268 	tail_call_reachable = subprog[idx].tail_call_reachable;
5269 
5270 	goto continue_func;
5271 }
5272 
5273 static int check_max_stack_depth(struct bpf_verifier_env *env)
5274 {
5275 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
5276 	struct bpf_subprog_call_depth_info *dinfo;
5277 	struct bpf_subprog_info *si = env->subprog_info;
5278 	bool priv_stack_supported;
5279 	int ret;
5280 
5281 	dinfo = kvcalloc(env->subprog_cnt, sizeof(*dinfo), GFP_KERNEL_ACCOUNT);
5282 	if (!dinfo)
5283 		return -ENOMEM;
5284 
5285 	for (int i = 0; i < env->subprog_cnt; i++) {
5286 		if (si[i].has_tail_call) {
5287 			priv_stack_mode = NO_PRIV_STACK;
5288 			break;
5289 		}
5290 	}
5291 
5292 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
5293 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
5294 
5295 	/* All async_cb subprogs use normal kernel stack. If a particular
5296 	 * subprog appears in both main prog and async_cb subtree, that
5297 	 * subprog will use normal kernel stack to avoid potential nesting.
5298 	 * The reverse subprog traversal ensures when main prog subtree is
5299 	 * checked, the subprogs appearing in async_cb subtrees are already
5300 	 * marked as using normal kernel stack, so stack size checking can
5301 	 * be done properly.
5302 	 */
5303 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
5304 		if (!i || si[i].is_async_cb) {
5305 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
5306 			ret = check_max_stack_depth_subprog(env, i, dinfo,
5307 					priv_stack_supported);
5308 			if (ret < 0) {
5309 				kvfree(dinfo);
5310 				return ret;
5311 			}
5312 		}
5313 	}
5314 
5315 	for (int i = 0; i < env->subprog_cnt; i++) {
5316 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
5317 			env->prog->aux->jits_use_priv_stack = true;
5318 			break;
5319 		}
5320 	}
5321 
5322 	kvfree(dinfo);
5323 
5324 	return 0;
5325 }
5326 
5327 static int __check_buffer_access(struct bpf_verifier_env *env,
5328 				 const char *buf_info,
5329 				 const struct bpf_reg_state *reg,
5330 				 argno_t argno, int off, int size,
5331 				 u32 *access_end)
5332 {
5333 	s64 start;
5334 
5335 	if (!tnum_is_const(reg->var_off)) {
5336 		char tn_buf[48];
5337 
5338 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5339 		verbose(env,
5340 			"%s invalid variable buffer offset: off=%d, var_off=%s\n",
5341 			reg_arg_name(env, argno), off, tn_buf);
5342 		return -EACCES;
5343 	}
5344 
5345 	start = (s64)reg->var_off.value + off;
5346 	if (start < 0) {
5347 		verbose(env,
5348 			"%s invalid negative %s buffer offset: off=%d, var_off=%lld\n",
5349 			reg_arg_name(env, argno), buf_info, off, (s64)reg->var_off.value);
5350 		return -EACCES;
5351 	}
5352 
5353 	*access_end = start + size;
5354 	return 0;
5355 }
5356 
5357 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5358 				  const struct bpf_reg_state *reg,
5359 				  argno_t argno, int off, int size)
5360 {
5361 	u32 access_end;
5362 	int err;
5363 
5364 	err = __check_buffer_access(env, "tracepoint", reg, argno, off, size, &access_end);
5365 	if (err)
5366 		return err;
5367 
5368 	env->prog->aux->max_tp_access = max(access_end, env->prog->aux->max_tp_access);
5369 
5370 	return 0;
5371 }
5372 
5373 static int check_buffer_access(struct bpf_verifier_env *env,
5374 			       const struct bpf_reg_state *reg,
5375 			       argno_t argno, int off, int size,
5376 			       bool zero_size_allowed,
5377 			       u32 *max_access)
5378 {
5379 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5380 	u32 access_end;
5381 	int err;
5382 
5383 	err = __check_buffer_access(env, buf_info, reg, argno, off, size, &access_end);
5384 	if (err)
5385 		return err;
5386 
5387 	*max_access = max(access_end, *max_access);
5388 
5389 	return 0;
5390 }
5391 
5392 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5393 static void zext_32_to_64(struct bpf_reg_state *reg)
5394 {
5395 	reg->var_off = tnum_subreg(reg->var_off);
5396 	reg_set_urange64(reg, reg_u32_min(reg), reg_u32_max(reg));
5397 }
5398 
5399 /* truncate register to smaller size (in bytes)
5400  * must be called with size < BPF_REG_SIZE
5401  */
5402 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5403 {
5404 	u64 mask;
5405 
5406 	/* clear high bits in bit representation */
5407 	reg->var_off = tnum_cast(reg->var_off, size);
5408 
5409 	/* fix arithmetic bounds */
5410 	mask = ((u64)1 << (size * 8)) - 1;
5411 	if ((reg_umin(reg) & ~mask) == (reg_umax(reg) & ~mask))
5412 		reg_set_urange64(reg, reg_umin(reg) & mask, reg_umax(reg) & mask);
5413 	else
5414 		reg_set_urange64(reg, 0, mask);
5415 
5416 	/* If size is smaller than 32bit register the 32bit register
5417 	 * values are also truncated so we push 64-bit bounds into
5418 	 * 32-bit bounds. Above were truncated < 32-bits already.
5419 	 */
5420 	if (size < 4)
5421 		__mark_reg32_unbounded(reg);
5422 
5423 	reg_bounds_sync(reg);
5424 }
5425 
5426 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5427 {
5428 	if (size == 1) {
5429 		reg_set_srange64(reg, S8_MIN, S8_MAX);
5430 		reg_set_srange32(reg, S8_MIN, S8_MAX);
5431 	} else if (size == 2) {
5432 		reg_set_srange64(reg, S16_MIN, S16_MAX);
5433 		reg_set_srange32(reg, S16_MIN, S16_MAX);
5434 	} else {
5435 		/* size == 4 */
5436 		reg_set_srange64(reg, S32_MIN, S32_MAX);
5437 		reg_set_srange32(reg, S32_MIN, S32_MAX);
5438 	}
5439 	reg->var_off = tnum_unknown;
5440 }
5441 
5442 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
5443 {
5444 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
5445 	u64 top_smax_value, top_smin_value;
5446 	u64 num_bits = size * 8;
5447 
5448 	if (tnum_is_const(reg->var_off)) {
5449 		u64_cval = reg->var_off.value;
5450 		if (size == 1)
5451 			reg->var_off = tnum_const((s8)u64_cval);
5452 		else if (size == 2)
5453 			reg->var_off = tnum_const((s16)u64_cval);
5454 		else
5455 			/* size == 4 */
5456 			reg->var_off = tnum_const((s32)u64_cval);
5457 
5458 		u64_cval = reg->var_off.value;
5459 		reg->r64 = cnum64_from_urange(u64_cval, u64_cval);
5460 		reg->r32 = cnum32_from_urange((u32)u64_cval, (u32)u64_cval);
5461 		return;
5462 	}
5463 
5464 	top_smax_value = ((u64)reg_smax(reg) >> num_bits) << num_bits;
5465 	top_smin_value = ((u64)reg_smin(reg) >> num_bits) << num_bits;
5466 
5467 	if (top_smax_value != top_smin_value)
5468 		goto out;
5469 
5470 	/* find the s64_min and s64_min after sign extension */
5471 	if (size == 1) {
5472 		init_s64_max = (s8)reg_smax(reg);
5473 		init_s64_min = (s8)reg_smin(reg);
5474 	} else if (size == 2) {
5475 		init_s64_max = (s16)reg_smax(reg);
5476 		init_s64_min = (s16)reg_smin(reg);
5477 	} else {
5478 		init_s64_max = (s32)reg_smax(reg);
5479 		init_s64_min = (s32)reg_smin(reg);
5480 	}
5481 
5482 	s64_max = max(init_s64_max, init_s64_min);
5483 	s64_min = min(init_s64_max, init_s64_min);
5484 
5485 	/* both of s64_max/s64_min positive or negative */
5486 	if ((s64_max >= 0) == (s64_min >= 0)) {
5487 		reg_set_srange64(reg, s64_min, s64_max);
5488 		reg_set_srange32(reg, s64_min, s64_max);
5489 		reg->var_off = tnum_range(s64_min, s64_max);
5490 		return;
5491 	}
5492 
5493 out:
5494 	set_sext64_default_val(reg, size);
5495 }
5496 
5497 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
5498 {
5499 	if (size == 1)
5500 		reg_set_srange32(reg, S8_MIN, S8_MAX);
5501 	else
5502 		/* size == 2 */
5503 		reg_set_srange32(reg, S16_MIN, S16_MAX);
5504 	reg->var_off = tnum_subreg(tnum_unknown);
5505 }
5506 
5507 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
5508 {
5509 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
5510 	u32 top_smax_value, top_smin_value;
5511 	u32 num_bits = size * 8;
5512 
5513 	if (tnum_is_const(reg->var_off)) {
5514 		u32_val = reg->var_off.value;
5515 		if (size == 1)
5516 			reg->var_off = tnum_const((s8)u32_val);
5517 		else
5518 			reg->var_off = tnum_const((s16)u32_val);
5519 
5520 		u32_val = reg->var_off.value;
5521 		reg_set_srange32(reg, u32_val, u32_val);
5522 		return;
5523 	}
5524 
5525 	top_smax_value = ((u32)reg_s32_max(reg) >> num_bits) << num_bits;
5526 	top_smin_value = ((u32)reg_s32_min(reg) >> num_bits) << num_bits;
5527 
5528 	if (top_smax_value != top_smin_value)
5529 		goto out;
5530 
5531 	/* find the s32_min and s32_min after sign extension */
5532 	if (size == 1) {
5533 		init_s32_max = (s8)reg_s32_max(reg);
5534 		init_s32_min = (s8)reg_s32_min(reg);
5535 	} else {
5536 		/* size == 2 */
5537 		init_s32_max = (s16)reg_s32_max(reg);
5538 		init_s32_min = (s16)reg_s32_min(reg);
5539 	}
5540 	s32_max = max(init_s32_max, init_s32_min);
5541 	s32_min = min(init_s32_max, init_s32_min);
5542 
5543 	if ((s32_min >= 0) == (s32_max >= 0)) {
5544 		reg_set_srange32(reg, s32_min, s32_max);
5545 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
5546 		return;
5547 	}
5548 
5549 out:
5550 	set_sext32_default_val(reg, size);
5551 }
5552 
5553 bool bpf_map_is_rdonly(const struct bpf_map *map)
5554 {
5555 	/* A map is considered read-only if the following condition are true:
5556 	 *
5557 	 * 1) BPF program side cannot change any of the map content. The
5558 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5559 	 *    and was set at map creation time.
5560 	 * 2) The map value(s) have been initialized from user space by a
5561 	 *    loader and then "frozen", such that no new map update/delete
5562 	 *    operations from syscall side are possible for the rest of
5563 	 *    the map's lifetime from that point onwards.
5564 	 * 3) Any parallel/pending map update/delete operations from syscall
5565 	 *    side have been completed. Only after that point, it's safe to
5566 	 *    assume that map value(s) are immutable.
5567 	 */
5568 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
5569 	       READ_ONCE(map->frozen) &&
5570 	       !bpf_map_write_active(map);
5571 }
5572 
5573 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
5574 			bool is_ldsx)
5575 {
5576 	void *ptr;
5577 	u64 addr;
5578 	int err;
5579 
5580 	err = map->ops->map_direct_value_addr(map, &addr, off);
5581 	if (err)
5582 		return err;
5583 	ptr = (void *)(long)addr + off;
5584 
5585 	switch (size) {
5586 	case sizeof(u8):
5587 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
5588 		break;
5589 	case sizeof(u16):
5590 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
5591 		break;
5592 	case sizeof(u32):
5593 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
5594 		break;
5595 	case sizeof(u64):
5596 		*val = *(u64 *)ptr;
5597 		break;
5598 	default:
5599 		return -EINVAL;
5600 	}
5601 	return 0;
5602 }
5603 
5604 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
5605 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
5606 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
5607 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
5608 
5609 /*
5610  * Allow list few fields as RCU trusted or full trusted.
5611  * This logic doesn't allow mix tagging and will be removed once GCC supports
5612  * btf_type_tag.
5613  */
5614 
5615 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5616 BTF_TYPE_SAFE_RCU(struct task_struct) {
5617 	const cpumask_t *cpus_ptr;
5618 	struct css_set __rcu *cgroups;
5619 	struct task_struct __rcu *real_parent;
5620 	struct task_struct *group_leader;
5621 };
5622 
5623 BTF_TYPE_SAFE_RCU(struct cgroup) {
5624 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5625 	struct kernfs_node *kn;
5626 };
5627 
5628 BTF_TYPE_SAFE_RCU(struct css_set) {
5629 	struct cgroup *dfl_cgrp;
5630 };
5631 
5632 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
5633 	struct cgroup *cgroup;
5634 };
5635 
5636 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5637 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5638 	struct file __rcu *exe_file;
5639 #ifdef CONFIG_MEMCG
5640 	struct task_struct __rcu *owner;
5641 #endif
5642 };
5643 
5644 /* skb->sk, req->sk are not RCU protected, but we mark them as such
5645  * because bpf prog accessible sockets are SOCK_RCU_FREE.
5646  */
5647 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5648 	struct sock *sk;
5649 };
5650 
5651 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5652 	struct sock *sk;
5653 };
5654 
5655 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5656 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5657 	struct seq_file *seq;
5658 };
5659 
5660 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5661 	struct bpf_iter_meta *meta;
5662 	struct task_struct *task;
5663 };
5664 
5665 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5666 	struct file *file;
5667 };
5668 
5669 BTF_TYPE_SAFE_TRUSTED(struct file) {
5670 	struct inode *f_inode;
5671 };
5672 
5673 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
5674 	struct inode *d_inode;
5675 };
5676 
5677 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
5678 	struct sock *sk;
5679 };
5680 
5681 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) {
5682 	struct mm_struct *vm_mm;
5683 	struct file *vm_file;
5684 };
5685 
5686 static bool type_is_rcu(struct bpf_verifier_env *env,
5687 			struct bpf_reg_state *reg,
5688 			const char *field_name, u32 btf_id)
5689 {
5690 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5691 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
5692 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5693 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
5694 
5695 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5696 }
5697 
5698 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
5699 				struct bpf_reg_state *reg,
5700 				const char *field_name, u32 btf_id)
5701 {
5702 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
5703 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
5704 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
5705 
5706 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
5707 }
5708 
5709 static bool type_is_trusted(struct bpf_verifier_env *env,
5710 			    struct bpf_reg_state *reg,
5711 			    const char *field_name, u32 btf_id)
5712 {
5713 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5714 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5715 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5716 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5717 
5718 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5719 }
5720 
5721 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
5722 				    struct bpf_reg_state *reg,
5723 				    const char *field_name, u32 btf_id)
5724 {
5725 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
5726 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
5727 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
5728 
5729 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
5730 					  "__safe_trusted_or_null");
5731 }
5732 
5733 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5734 				   struct bpf_reg_state *regs, struct bpf_reg_state *reg,
5735 				   argno_t argno, int off, int size,
5736 				   enum bpf_access_type atype,
5737 				   int value_regno)
5738 {
5739 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5740 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5741 	const char *field_name = NULL;
5742 	enum bpf_type_flag flag = 0;
5743 	u32 btf_id = 0;
5744 	int ret;
5745 
5746 	if (!env->allow_ptr_leaks) {
5747 		verbose(env,
5748 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5749 			tname);
5750 		return -EPERM;
5751 	}
5752 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5753 		verbose(env,
5754 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5755 			tname);
5756 		return -EINVAL;
5757 	}
5758 
5759 	if (!tnum_is_const(reg->var_off)) {
5760 		char tn_buf[48];
5761 
5762 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5763 		verbose(env,
5764 			"%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5765 			reg_arg_name(env, argno), tname, off, tn_buf);
5766 		return -EACCES;
5767 	}
5768 
5769 	off += reg->var_off.value;
5770 
5771 	if (off < 0) {
5772 		verbose(env,
5773 			"%s is ptr_%s invalid negative access: off=%d\n",
5774 			reg_arg_name(env, argno), tname, off);
5775 		return -EACCES;
5776 	}
5777 
5778 	if (reg->type & MEM_USER) {
5779 		verbose(env,
5780 			"%s is ptr_%s access user memory: off=%d\n",
5781 			reg_arg_name(env, argno), tname, off);
5782 		return -EACCES;
5783 	}
5784 
5785 	if (reg->type & MEM_PERCPU) {
5786 		verbose(env,
5787 			"%s is ptr_%s access percpu memory: off=%d\n",
5788 			reg_arg_name(env, argno), tname, off);
5789 		return -EACCES;
5790 	}
5791 
5792 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
5793 		if (!btf_is_kernel(reg->btf)) {
5794 			verifier_bug(env, "reg->btf must be kernel btf");
5795 			return -EFAULT;
5796 		}
5797 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
5798 		if (ret < 0)
5799 			verbose(env,
5800 				"%s cannot write into ptr_%s at off=%d size=%d\n",
5801 				reg_arg_name(env, argno), tname, off, size);
5802 	} else {
5803 		/* Writes are permitted with default btf_struct_access for
5804 		 * program allocated objects (which always have id > 0),
5805 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5806 		 */
5807 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
5808 			verbose(env, "only read is supported\n");
5809 			return -EACCES;
5810 		}
5811 
5812 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5813 		    !(reg->type & MEM_RCU) && !reg_is_referenced(env, reg)) {
5814 			verifier_bug(env, "allocated object must have a referenced id");
5815 			return -EFAULT;
5816 		}
5817 
5818 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
5819 	}
5820 
5821 	if (ret < 0)
5822 		return ret;
5823 
5824 	if (ret != PTR_TO_BTF_ID) {
5825 		/* just mark; */
5826 
5827 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
5828 		/* If this is an untrusted pointer, all pointers formed by walking it
5829 		 * also inherit the untrusted flag.
5830 		 */
5831 		flag = PTR_UNTRUSTED;
5832 
5833 	} else if (is_trusted_reg(env, reg) || is_rcu_reg(reg)) {
5834 		/* By default any pointer obtained from walking a trusted pointer is no
5835 		 * longer trusted, unless the field being accessed has explicitly been
5836 		 * marked as inheriting its parent's state of trust (either full or RCU).
5837 		 * For example:
5838 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
5839 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
5840 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
5841 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
5842 		 *
5843 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
5844 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
5845 		 */
5846 		if (type_is_trusted(env, reg, field_name, btf_id)) {
5847 			flag |= PTR_TRUSTED;
5848 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
5849 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
5850 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
5851 			if (type_is_rcu(env, reg, field_name, btf_id)) {
5852 				/* ignore __rcu tag and mark it MEM_RCU */
5853 				flag |= MEM_RCU;
5854 			} else if (flag & MEM_RCU ||
5855 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
5856 				/* __rcu tagged pointers can be NULL */
5857 				flag |= MEM_RCU | PTR_MAYBE_NULL;
5858 
5859 				/* We always trust them */
5860 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
5861 				    flag & PTR_UNTRUSTED)
5862 					flag &= ~PTR_UNTRUSTED;
5863 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
5864 				/* keep as-is */
5865 			} else {
5866 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
5867 				clear_trusted_flags(&flag);
5868 			}
5869 		} else {
5870 			/*
5871 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
5872 			 * aggressively mark as untrusted otherwise such
5873 			 * pointers will be plain PTR_TO_BTF_ID without flags
5874 			 * and will be allowed to be passed into helpers for
5875 			 * compat reasons.
5876 			 */
5877 			flag = PTR_UNTRUSTED;
5878 		}
5879 	} else {
5880 		/* Old compat. Deprecated */
5881 		clear_trusted_flags(&flag);
5882 	}
5883 
5884 	if (atype == BPF_READ && value_regno >= 0) {
5885 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5886 		if (ret < 0)
5887 			return ret;
5888 	}
5889 
5890 	return 0;
5891 }
5892 
5893 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5894 				   struct bpf_reg_state *regs, struct bpf_reg_state *reg,
5895 				   argno_t argno, int off, int size,
5896 				   enum bpf_access_type atype,
5897 				   int value_regno)
5898 {
5899 	struct bpf_map *map = reg->map_ptr;
5900 	struct bpf_reg_state map_reg;
5901 	enum bpf_type_flag flag = 0;
5902 	const struct btf_type *t;
5903 	const char *tname;
5904 	u32 btf_id;
5905 	int ret;
5906 
5907 	if (!btf_vmlinux) {
5908 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5909 		return -ENOTSUPP;
5910 	}
5911 
5912 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5913 		verbose(env, "map_ptr access not supported for map type %d\n",
5914 			map->map_type);
5915 		return -ENOTSUPP;
5916 	}
5917 
5918 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5919 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5920 
5921 	if (!env->allow_ptr_leaks) {
5922 		verbose(env,
5923 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5924 			tname);
5925 		return -EPERM;
5926 	}
5927 
5928 	if (off < 0) {
5929 		verbose(env, "%s is %s invalid negative access: off=%d\n",
5930 			reg_arg_name(env, argno), tname, off);
5931 		return -EACCES;
5932 	}
5933 
5934 	if (atype != BPF_READ) {
5935 		verbose(env, "only read from %s is supported\n", tname);
5936 		return -EACCES;
5937 	}
5938 
5939 	/* Simulate access to a PTR_TO_BTF_ID */
5940 	memset(&map_reg, 0, sizeof(map_reg));
5941 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
5942 			      btf_vmlinux, *map->ops->map_btf_id, 0);
5943 	if (ret < 0)
5944 		return ret;
5945 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
5946 	if (ret < 0)
5947 		return ret;
5948 
5949 	if (value_regno >= 0) {
5950 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
5951 		if (ret < 0)
5952 			return ret;
5953 	}
5954 
5955 	return 0;
5956 }
5957 
5958 /* Check that the stack access at the given offset is within bounds. The
5959  * maximum valid offset is -1.
5960  *
5961  * The minimum valid offset is -MAX_BPF_STACK for writes, and
5962  * -state->allocated_stack for reads.
5963  */
5964 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
5965                                           s64 off,
5966                                           struct bpf_func_state *state,
5967                                           enum bpf_access_type t)
5968 {
5969 	int min_valid_off;
5970 
5971 	if (t == BPF_WRITE || env->allow_uninit_stack)
5972 		min_valid_off = -MAX_BPF_STACK;
5973 	else
5974 		min_valid_off = -state->allocated_stack;
5975 
5976 	if (off < min_valid_off || off > -1)
5977 		return -EACCES;
5978 	return 0;
5979 }
5980 
5981 /* Check that the stack access at 'regno + off' falls within the maximum stack
5982  * bounds.
5983  *
5984  * 'off' includes `regno->offset`, but not its dynamic part (if any).
5985  */
5986 static int check_stack_access_within_bounds(
5987 		struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5988 		argno_t argno, int off, int access_size,
5989 		enum bpf_access_type type)
5990 {
5991 	struct bpf_func_state *state = bpf_func(env, reg);
5992 	s64 min_off, max_off;
5993 	int err;
5994 	char *err_extra;
5995 
5996 	if (type == BPF_READ)
5997 		err_extra = " read from";
5998 	else
5999 		err_extra = " write to";
6000 
6001 	if (tnum_is_const(reg->var_off)) {
6002 		min_off = (s64)reg->var_off.value + off;
6003 		max_off = min_off + access_size;
6004 	} else {
6005 		if (reg_smax(reg) >= BPF_MAX_VAR_OFF ||
6006 		    reg_smin(reg) <= -BPF_MAX_VAR_OFF) {
6007 			verbose(env, "invalid unbounded variable-offset%s stack %s\n",
6008 				err_extra, reg_arg_name(env, argno));
6009 			return -EACCES;
6010 		}
6011 		min_off = reg_smin(reg) + off;
6012 		max_off = reg_smax(reg) + off + access_size;
6013 	}
6014 
6015 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6016 	if (!err && max_off > 0)
6017 		err = -EINVAL; /* out of stack access into non-negative offsets */
6018 	if (!err && access_size < 0)
6019 		/* access_size should not be negative (or overflow an int); others checks
6020 		 * along the way should have prevented such an access.
6021 		 */
6022 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6023 
6024 	if (err) {
6025 		if (tnum_is_const(reg->var_off)) {
6026 			verbose(env, "invalid%s stack %s off=%lld size=%d\n",
6027 				err_extra, reg_arg_name(env, argno), min_off, access_size);
6028 		} else {
6029 			char tn_buf[48];
6030 
6031 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6032 			verbose(env, "invalid variable-offset%s stack %s var_off=%s off=%d size=%d\n",
6033 				err_extra, reg_arg_name(env, argno), tn_buf, off, access_size);
6034 		}
6035 		return err;
6036 	}
6037 
6038 	/* Note that there is no stack access with offset zero, so the needed stack
6039 	 * size is -min_off, not -min_off+1.
6040 	 */
6041 	return grow_stack_state(env, state, -min_off /* size */);
6042 }
6043 
6044 static bool get_func_retval_range(struct bpf_prog *prog,
6045 				  struct bpf_retval_range *range)
6046 {
6047 	if (prog->type == BPF_PROG_TYPE_LSM &&
6048 		prog->expected_attach_type == BPF_LSM_MAC &&
6049 		!bpf_lsm_get_retval_range(prog, range)) {
6050 		return true;
6051 	}
6052 	return false;
6053 }
6054 
6055 static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val)
6056 {
6057 	struct bpf_reg_state fake_reg;
6058 
6059 	if (!val)
6060 		return;
6061 
6062 	fake_reg.type = SCALAR_VALUE;
6063 	__mark_reg_known(&fake_reg, val);
6064 
6065 	scalar32_min_max_add(dst_reg, &fake_reg);
6066 	scalar_min_max_add(dst_reg, &fake_reg);
6067 	dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off);
6068 
6069 	reg_bounds_sync(dst_reg);
6070 }
6071 
6072 /* check whether memory at (regno + off) is accessible for t = (read | write)
6073  * if t==write, value_regno is a register which value is stored into memory
6074  * if t==read, value_regno is a register which will receive the value from memory
6075  * if t==write && value_regno==-1, some unknown value is stored into memory
6076  * if t==read && value_regno==-1, don't care what we read from memory
6077  */
6078 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno,
6079 			    int off, int bpf_size, enum bpf_access_type t,
6080 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6081 {
6082 	struct bpf_reg_state *regs = cur_regs(env);
6083 	int size, err = 0;
6084 
6085 	size = bpf_size_to_bytes(bpf_size);
6086 	if (size < 0)
6087 		return size;
6088 
6089 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6090 	if (err)
6091 		return err;
6092 
6093 	if (reg->type == PTR_TO_MAP_KEY) {
6094 		if (t == BPF_WRITE) {
6095 			verbose(env, "write to change key %s not allowed\n",
6096 				reg_arg_name(env, argno));
6097 			return -EACCES;
6098 		}
6099 
6100 		err = check_mem_region_access(env, reg, argno, off, size,
6101 					      reg->map_ptr->key_size, false);
6102 		if (err)
6103 			return err;
6104 		if (value_regno >= 0)
6105 			mark_reg_unknown(env, regs, value_regno);
6106 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6107 		struct btf_field *kptr_field = NULL;
6108 
6109 		if (t == BPF_WRITE && value_regno >= 0 &&
6110 		    is_pointer_value(env, value_regno)) {
6111 			verbose(env, "R%d leaks addr into map\n", value_regno);
6112 			return -EACCES;
6113 		}
6114 		err = check_map_access_type(env, reg, off, size, t);
6115 		if (err)
6116 			return err;
6117 		err = check_map_access(env, reg, argno, off, size, false, ACCESS_DIRECT);
6118 		if (err)
6119 			return err;
6120 		if (tnum_is_const(reg->var_off))
6121 			kptr_field = btf_record_find(reg->map_ptr->record,
6122 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
6123 		if (kptr_field) {
6124 			err = check_map_kptr_access(env, value_regno, insn_idx, kptr_field);
6125 		} else if (t == BPF_READ && value_regno >= 0) {
6126 			struct bpf_map *map = reg->map_ptr;
6127 
6128 			/*
6129 			 * If map is read-only, track its contents as scalars,
6130 			 * unless it is an insn array (see the special case below)
6131 			 */
6132 			if (tnum_is_const(reg->var_off) &&
6133 			    bpf_map_is_rdonly(map) &&
6134 			    map->ops->map_direct_value_addr &&
6135 			    map->map_type != BPF_MAP_TYPE_INSN_ARRAY) {
6136 				int map_off = off + reg->var_off.value;
6137 				u64 val = 0;
6138 
6139 				err = bpf_map_direct_read(map, map_off, size,
6140 							  &val, is_ldsx);
6141 				if (err)
6142 					return err;
6143 
6144 				regs[value_regno].type = SCALAR_VALUE;
6145 				__mark_reg_known(&regs[value_regno], val);
6146 			} else if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
6147 				if (bpf_size != BPF_DW) {
6148 					verbose(env, "Invalid read of %d bytes from insn_array\n",
6149 						     size);
6150 					return -EACCES;
6151 				}
6152 				regs[value_regno] = *reg;
6153 				add_scalar_to_reg(&regs[value_regno], off);
6154 				regs[value_regno].type = PTR_TO_INSN;
6155 			} else {
6156 				mark_reg_unknown(env, regs, value_regno);
6157 			}
6158 		}
6159 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6160 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6161 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
6162 
6163 		if (type_may_be_null(reg->type)) {
6164 			verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno),
6165 				reg_type_str(env, reg->type));
6166 			return -EACCES;
6167 		}
6168 
6169 		if (t == BPF_WRITE && rdonly_mem) {
6170 			verbose(env, "%s cannot write into %s\n",
6171 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
6172 			return -EACCES;
6173 		}
6174 
6175 		if (t == BPF_WRITE && value_regno >= 0 &&
6176 		    is_pointer_value(env, value_regno)) {
6177 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6178 			return -EACCES;
6179 		}
6180 
6181 		/*
6182 		 * Accesses to untrusted PTR_TO_MEM are done through probe
6183 		 * instructions, hence no need to check bounds in that case.
6184 		 */
6185 		if (!rdonly_untrusted)
6186 			err = check_mem_region_access(env, reg, argno, off, size,
6187 						      reg->mem_size, false);
6188 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6189 			mark_reg_unknown(env, regs, value_regno);
6190 	} else if (reg->type == PTR_TO_CTX) {
6191 		struct bpf_insn_access_aux info = {
6192 			.reg_type = SCALAR_VALUE,
6193 			.is_ldsx = is_ldsx,
6194 			.log = &env->log,
6195 		};
6196 		struct bpf_retval_range range;
6197 
6198 		if (t == BPF_WRITE && value_regno >= 0 &&
6199 		    is_pointer_value(env, value_regno)) {
6200 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6201 			return -EACCES;
6202 		}
6203 
6204 		err = check_ctx_access(env, insn_idx, reg, argno, off, size, t, &info);
6205 		if (!err && t == BPF_READ && value_regno >= 0) {
6206 			/* ctx access returns either a scalar, or a
6207 			 * PTR_TO_PACKET[_META,_END]. In the latter
6208 			 * case, we know the offset is zero.
6209 			 */
6210 			if (info.reg_type == SCALAR_VALUE) {
6211 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
6212 					mark_reg_unknown(env, regs, value_regno);
6213 					err = __mark_reg_s32_range(env, regs, value_regno,
6214 								   range.minval, range.maxval);
6215 					if (err)
6216 						return err;
6217 				} else {
6218 					mark_reg_unknown(env, regs, value_regno);
6219 				}
6220 			} else {
6221 				mark_reg_known_zero(env, regs,
6222 						    value_regno);
6223 				/* A load of ctx field could have different
6224 				 * actual load size with the one encoded in the
6225 				 * insn. When the dst is PTR, it is for sure not
6226 				 * a sub-register.
6227 				 */
6228 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6229 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
6230 					regs[value_regno].btf = info.btf;
6231 					regs[value_regno].btf_id = info.btf_id;
6232 					regs[value_regno].id = info.ref_id;
6233 				}
6234 				if (type_may_be_null(info.reg_type) && !regs[value_regno].id)
6235 					regs[value_regno].id = ++env->id_gen;
6236 			}
6237 			regs[value_regno].type = info.reg_type;
6238 		}
6239 
6240 	} else if (reg->type == PTR_TO_STACK) {
6241 		/* Basic bounds checks. */
6242 		err = check_stack_access_within_bounds(env, reg, argno, off, size, t);
6243 		if (err)
6244 			return err;
6245 
6246 		if (t == BPF_READ)
6247 			err = check_stack_read(env, reg, argno, off, size,
6248 					       value_regno);
6249 		else
6250 			err = check_stack_write(env, reg, off, size,
6251 						value_regno, insn_idx);
6252 	} else if (reg_is_pkt_pointer(reg)) {
6253 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6254 			verbose(env, "cannot write into packet\n");
6255 			return -EACCES;
6256 		}
6257 		if (t == BPF_WRITE && value_regno >= 0 &&
6258 		    is_pointer_value(env, value_regno)) {
6259 			verbose(env, "R%d leaks addr into packet\n",
6260 				value_regno);
6261 			return -EACCES;
6262 		}
6263 		err = check_packet_access(env, reg, argno, off, size, false);
6264 		if (!err && t == BPF_READ && value_regno >= 0)
6265 			mark_reg_unknown(env, regs, value_regno);
6266 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6267 		if (t == BPF_WRITE && value_regno >= 0 &&
6268 		    is_pointer_value(env, value_regno)) {
6269 			verbose(env, "R%d leaks addr into flow keys\n",
6270 				value_regno);
6271 			return -EACCES;
6272 		}
6273 
6274 		err = check_flow_keys_access(env, reg, argno, off, size);
6275 		if (!err && t == BPF_READ && value_regno >= 0)
6276 			mark_reg_unknown(env, regs, value_regno);
6277 	} else if (type_is_sk_pointer(reg->type)) {
6278 		if (t == BPF_WRITE) {
6279 			verbose(env, "%s cannot write into %s\n",
6280 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
6281 			return -EACCES;
6282 		}
6283 		err = check_sock_access(env, insn_idx, reg, argno, off, size, t);
6284 		if (!err && value_regno >= 0)
6285 			mark_reg_unknown(env, regs, value_regno);
6286 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6287 		err = check_tp_buffer_access(env, reg, argno, off, size);
6288 		if (!err && t == BPF_READ && value_regno >= 0)
6289 			mark_reg_unknown(env, regs, value_regno);
6290 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6291 		   !type_may_be_null(reg->type)) {
6292 		err = check_ptr_to_btf_access(env, regs, reg, argno, off, size, t,
6293 					      value_regno);
6294 	} else if (reg->type == CONST_PTR_TO_MAP) {
6295 		err = check_ptr_to_map_access(env, regs, reg, argno, off, size, t,
6296 					      value_regno);
6297 	} else if (base_type(reg->type) == PTR_TO_BUF &&
6298 		   !type_may_be_null(reg->type)) {
6299 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6300 		u32 *max_access;
6301 
6302 		if (rdonly_mem) {
6303 			if (t == BPF_WRITE) {
6304 				verbose(env, "%s cannot write into %s\n",
6305 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
6306 				return -EACCES;
6307 			}
6308 			max_access = &env->prog->aux->max_rdonly_access;
6309 		} else {
6310 			max_access = &env->prog->aux->max_rdwr_access;
6311 		}
6312 
6313 		err = check_buffer_access(env, reg, argno, off, size, false,
6314 					  max_access);
6315 
6316 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6317 			mark_reg_unknown(env, regs, value_regno);
6318 	} else if (reg->type == PTR_TO_ARENA) {
6319 		if (t == BPF_READ && value_regno >= 0)
6320 			mark_reg_unknown(env, regs, value_regno);
6321 	} else {
6322 		verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno),
6323 			reg_type_str(env, reg->type));
6324 		return -EACCES;
6325 	}
6326 
6327 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6328 	    regs[value_regno].type == SCALAR_VALUE) {
6329 		if (!is_ldsx)
6330 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6331 			coerce_reg_to_size(&regs[value_regno], size);
6332 		else
6333 			coerce_reg_to_size_sx(&regs[value_regno], size);
6334 	}
6335 	return err;
6336 }
6337 
6338 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
6339 			     bool allow_trust_mismatch);
6340 
6341 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
6342 			  bool strict_alignment_once, bool is_ldsx,
6343 			  bool allow_trust_mismatch, const char *ctx)
6344 {
6345 	struct bpf_verifier_state *vstate = env->cur_state;
6346 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6347 	struct bpf_reg_state *regs = cur_regs(env);
6348 	enum bpf_reg_type src_reg_type;
6349 	int err;
6350 
6351 	/* Handle stack arg read */
6352 	if (is_stack_arg_ldx(insn)) {
6353 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
6354 		if (err)
6355 			return err;
6356 		return check_stack_arg_read(env, state, insn->off, insn->dst_reg);
6357 	}
6358 
6359 	/* check src operand */
6360 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6361 	if (err)
6362 		return err;
6363 
6364 	/* check dst operand */
6365 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
6366 	if (err)
6367 		return err;
6368 
6369 	src_reg_type = regs[insn->src_reg].type;
6370 
6371 	/* Check if (src_reg + off) is readable. The state of dst_reg will be
6372 	 * updated by this call.
6373 	 */
6374 	err = check_mem_access(env, env->insn_idx, regs + insn->src_reg, argno_from_reg(insn->src_reg), insn->off,
6375 			       BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
6376 			       strict_alignment_once, is_ldsx);
6377 	err = err ?: save_aux_ptr_type(env, src_reg_type,
6378 				       allow_trust_mismatch);
6379 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
6380 
6381 	return err;
6382 }
6383 
6384 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
6385 			   bool strict_alignment_once)
6386 {
6387 	struct bpf_verifier_state *vstate = env->cur_state;
6388 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6389 	struct bpf_reg_state *regs = cur_regs(env);
6390 	enum bpf_reg_type dst_reg_type;
6391 	int err;
6392 
6393 	/* Handle stack arg write */
6394 	if (is_stack_arg_stx(insn)) {
6395 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
6396 		if (err)
6397 			return err;
6398 		return check_stack_arg_write(env, state, insn->off, regs + insn->src_reg);
6399 	}
6400 
6401 	/* check src1 operand */
6402 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6403 	if (err)
6404 		return err;
6405 
6406 	/* check src2 operand */
6407 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6408 	if (err)
6409 		return err;
6410 
6411 	dst_reg_type = regs[insn->dst_reg].type;
6412 
6413 	/* Check if (dst_reg + off) is writeable. */
6414 	err = check_mem_access(env, env->insn_idx, regs + insn->dst_reg, argno_from_reg(insn->dst_reg), insn->off,
6415 			       BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
6416 			       strict_alignment_once, false);
6417 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
6418 
6419 	return err;
6420 }
6421 
6422 static int check_atomic_rmw(struct bpf_verifier_env *env,
6423 			    struct bpf_insn *insn)
6424 {
6425 	struct bpf_reg_state *dst_reg;
6426 	int load_reg;
6427 	int err;
6428 
6429 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6430 		verbose(env, "invalid atomic operand size\n");
6431 		return -EINVAL;
6432 	}
6433 
6434 	/* check src1 operand */
6435 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6436 	if (err)
6437 		return err;
6438 
6439 	/* check src2 operand */
6440 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6441 	if (err)
6442 		return err;
6443 
6444 	if (insn->imm == BPF_CMPXCHG) {
6445 		/* Check comparison of R0 with memory location */
6446 		const u32 aux_reg = BPF_REG_0;
6447 
6448 		err = check_reg_arg(env, aux_reg, SRC_OP);
6449 		if (err)
6450 			return err;
6451 
6452 		if (is_pointer_value(env, aux_reg)) {
6453 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6454 			return -EACCES;
6455 		}
6456 	}
6457 
6458 	if (is_pointer_value(env, insn->src_reg)) {
6459 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6460 		return -EACCES;
6461 	}
6462 
6463 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
6464 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6465 			insn->dst_reg,
6466 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6467 		return -EACCES;
6468 	}
6469 
6470 	if (insn->imm & BPF_FETCH) {
6471 		if (insn->imm == BPF_CMPXCHG)
6472 			load_reg = BPF_REG_0;
6473 		else
6474 			load_reg = insn->src_reg;
6475 
6476 		/* check and record load of old value */
6477 		err = check_reg_arg(env, load_reg, DST_OP);
6478 		if (err)
6479 			return err;
6480 	} else {
6481 		/* This instruction accesses a memory location but doesn't
6482 		 * actually load it into a register.
6483 		 */
6484 		load_reg = -1;
6485 	}
6486 
6487 	dst_reg = cur_regs(env) + insn->dst_reg;
6488 
6489 	/* Check whether we can read the memory, with second call for fetch
6490 	 * case to simulate the register fill.
6491 	 */
6492 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off,
6493 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6494 	if (!err && load_reg >= 0)
6495 		err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg),
6496 				       insn->off, BPF_SIZE(insn->code),
6497 				       BPF_READ, load_reg, true, false);
6498 	if (err)
6499 		return err;
6500 
6501 	if (is_arena_reg(env, insn->dst_reg)) {
6502 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
6503 		if (err)
6504 			return err;
6505 	}
6506 	/* Check whether we can write into the same memory. */
6507 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off,
6508 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6509 	if (err)
6510 		return err;
6511 	return 0;
6512 }
6513 
6514 static int check_atomic_load(struct bpf_verifier_env *env,
6515 			     struct bpf_insn *insn)
6516 {
6517 	int err;
6518 
6519 	err = check_load_mem(env, insn, true, false, false, "atomic_load");
6520 	if (err)
6521 		return err;
6522 
6523 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
6524 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
6525 			insn->src_reg,
6526 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
6527 		return -EACCES;
6528 	}
6529 
6530 	return 0;
6531 }
6532 
6533 static int check_atomic_store(struct bpf_verifier_env *env,
6534 			      struct bpf_insn *insn)
6535 {
6536 	int err;
6537 
6538 	err = check_store_reg(env, insn, true);
6539 	if (err)
6540 		return err;
6541 
6542 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
6543 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6544 			insn->dst_reg,
6545 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6546 		return -EACCES;
6547 	}
6548 
6549 	return 0;
6550 }
6551 
6552 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
6553 {
6554 	switch (insn->imm) {
6555 	case BPF_ADD:
6556 	case BPF_ADD | BPF_FETCH:
6557 	case BPF_AND:
6558 	case BPF_AND | BPF_FETCH:
6559 	case BPF_OR:
6560 	case BPF_OR | BPF_FETCH:
6561 	case BPF_XOR:
6562 	case BPF_XOR | BPF_FETCH:
6563 	case BPF_XCHG:
6564 	case BPF_CMPXCHG:
6565 		return check_atomic_rmw(env, insn);
6566 	case BPF_LOAD_ACQ:
6567 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
6568 			verbose(env,
6569 				"64-bit load-acquires are only supported on 64-bit arches\n");
6570 			return -EOPNOTSUPP;
6571 		}
6572 		return check_atomic_load(env, insn);
6573 	case BPF_STORE_REL:
6574 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
6575 			verbose(env,
6576 				"64-bit store-releases are only supported on 64-bit arches\n");
6577 			return -EOPNOTSUPP;
6578 		}
6579 		return check_atomic_store(env, insn);
6580 	default:
6581 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
6582 			insn->imm);
6583 		return -EINVAL;
6584 	}
6585 }
6586 
6587 /* When register 'regno' is used to read the stack (either directly or through
6588  * a helper function) make sure that it's within stack boundary and, depending
6589  * on the access type and privileges, that all elements of the stack are
6590  * initialized.
6591  *
6592  * All registers that have been spilled on the stack in the slots within the
6593  * read offsets are marked as read.
6594  */
6595 static int check_stack_range_initialized(
6596 		struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off,
6597 		int access_size, bool zero_size_allowed,
6598 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
6599 {
6600 	struct bpf_func_state *state = bpf_func(env, reg);
6601 	int err, min_off, max_off, i, j, slot, spi;
6602 	/* Some accesses can write anything into the stack, others are
6603 	 * read-only.
6604 	 */
6605 	bool clobber = type == BPF_WRITE;
6606 	/*
6607 	 * Negative access_size signals global subprog/kfunc arg check where
6608 	 * STACK_POISON slots are acceptable. static stack liveness
6609 	 * might have determined that subprog doesn't read them,
6610 	 * but BTF based global subprog validation isn't accurate enough.
6611 	 */
6612 	bool allow_poison = access_size < 0 || clobber;
6613 
6614 	access_size = abs(access_size);
6615 
6616 	if (access_size == 0 && !zero_size_allowed) {
6617 		verbose(env, "invalid zero-sized read\n");
6618 		return -EACCES;
6619 	}
6620 
6621 	err = check_stack_access_within_bounds(env, reg, argno, off, access_size, type);
6622 	if (err)
6623 		return err;
6624 
6625 
6626 	if (tnum_is_const(reg->var_off)) {
6627 		min_off = max_off = reg->var_off.value + off;
6628 	} else {
6629 		/* Variable offset is prohibited for unprivileged mode for
6630 		 * simplicity since it requires corresponding support in
6631 		 * Spectre masking for stack ALU.
6632 		 * See also retrieve_ptr_limit().
6633 		 */
6634 		if (!env->bypass_spec_v1) {
6635 			char tn_buf[48];
6636 
6637 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6638 			verbose(env, "%s variable offset stack access prohibited for !root, var_off=%s\n",
6639 				reg_arg_name(env, argno), tn_buf);
6640 			return -EACCES;
6641 		}
6642 		/* Only initialized buffer on stack is allowed to be accessed
6643 		 * with variable offset. With uninitialized buffer it's hard to
6644 		 * guarantee that whole memory is marked as initialized on
6645 		 * helper return since specific bounds are unknown what may
6646 		 * cause uninitialized stack leaking.
6647 		 */
6648 		if (meta && meta->raw_mode)
6649 			meta = NULL;
6650 
6651 		min_off = reg_smin(reg) + off;
6652 		max_off = reg_smax(reg) + off;
6653 	}
6654 
6655 	if (meta && meta->raw_mode) {
6656 		/* Ensure we won't be overwriting dynptrs when simulating byte
6657 		 * by byte access in check_helper_call using meta.access_size.
6658 		 * This would be a problem if we have a helper in the future
6659 		 * which takes:
6660 		 *
6661 		 *	helper(uninit_mem, len, dynptr)
6662 		 *
6663 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6664 		 * may end up writing to dynptr itself when touching memory from
6665 		 * arg 1. This can be relaxed on a case by case basis for known
6666 		 * safe cases, but reject due to the possibilitiy of aliasing by
6667 		 * default.
6668 		 */
6669 		for (i = min_off; i < max_off + access_size; i++) {
6670 			int stack_off = -i - 1;
6671 
6672 			spi = bpf_get_spi(i);
6673 			/* raw_mode may write past allocated_stack */
6674 			if (state->allocated_stack <= stack_off)
6675 				continue;
6676 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6677 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6678 				return -EACCES;
6679 			}
6680 		}
6681 		meta->access_size = access_size;
6682 		meta->regno = reg_from_argno(argno);
6683 		return 0;
6684 	}
6685 
6686 	for (i = min_off; i < max_off + access_size; i++) {
6687 		u8 *stype;
6688 
6689 		slot = -i - 1;
6690 		spi = slot / BPF_REG_SIZE;
6691 		if (state->allocated_stack <= slot) {
6692 			verbose(env, "allocated_stack too small\n");
6693 			return -EFAULT;
6694 		}
6695 
6696 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6697 		if (*stype == STACK_MISC)
6698 			goto mark;
6699 		if ((*stype == STACK_ZERO) ||
6700 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6701 			if (clobber) {
6702 				/* helper can write anything into the stack */
6703 				*stype = STACK_MISC;
6704 			}
6705 			goto mark;
6706 		}
6707 
6708 		if (bpf_is_spilled_reg(&state->stack[spi]) &&
6709 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6710 		     env->allow_ptr_leaks)) {
6711 			if (clobber) {
6712 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6713 				for (j = 0; j < BPF_REG_SIZE; j++)
6714 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6715 			}
6716 			goto mark;
6717 		}
6718 
6719 		if (*stype == STACK_POISON) {
6720 			if (allow_poison)
6721 				goto mark;
6722 			verbose(env, "reading from stack %s off %d+%d size %d, slot poisoned by dead code elimination\n",
6723 				reg_arg_name(env, argno), min_off, i - min_off, access_size);
6724 		} else if (tnum_is_const(reg->var_off)) {
6725 			verbose(env, "invalid read from stack %s off %d+%d size %d\n",
6726 				reg_arg_name(env, argno), min_off, i - min_off, access_size);
6727 		} else {
6728 			char tn_buf[48];
6729 
6730 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6731 			verbose(env, "invalid read from stack %s var_off %s+%d size %d\n",
6732 				reg_arg_name(env, argno), tn_buf, i - min_off, access_size);
6733 		}
6734 		return -EACCES;
6735 mark:
6736 		;
6737 	}
6738 	return 0;
6739 }
6740 
6741 static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
6742 				   int access_size, enum bpf_access_type access_type,
6743 				   bool zero_size_allowed,
6744 				   struct bpf_call_arg_meta *meta)
6745 {
6746 	struct bpf_reg_state *regs = cur_regs(env);
6747 	u32 *max_access;
6748 
6749 	switch (base_type(reg->type)) {
6750 	case PTR_TO_PACKET:
6751 	case PTR_TO_PACKET_META:
6752 		return check_packet_access(env, reg, argno, 0, access_size,
6753 					   zero_size_allowed);
6754 	case PTR_TO_MAP_KEY:
6755 		if (access_type == BPF_WRITE) {
6756 			verbose(env, "%s cannot write into %s\n",
6757 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
6758 			return -EACCES;
6759 		}
6760 		return check_mem_region_access(env, reg, argno, 0, access_size,
6761 					       reg->map_ptr->key_size, false);
6762 	case PTR_TO_MAP_VALUE:
6763 		if (check_map_access_type(env, reg, 0, access_size, access_type))
6764 			return -EACCES;
6765 		return check_map_access(env, reg, argno, 0, access_size,
6766 					zero_size_allowed, ACCESS_HELPER);
6767 	case PTR_TO_MEM:
6768 		if (type_is_rdonly_mem(reg->type)) {
6769 			if (access_type == BPF_WRITE) {
6770 				verbose(env, "%s cannot write into %s\n",
6771 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
6772 				return -EACCES;
6773 			}
6774 		}
6775 		return check_mem_region_access(env, reg, argno, 0,
6776 					       access_size, reg->mem_size,
6777 					       zero_size_allowed);
6778 	case PTR_TO_BUF:
6779 		if (type_is_rdonly_mem(reg->type)) {
6780 			if (access_type == BPF_WRITE) {
6781 				verbose(env, "%s cannot write into %s\n",
6782 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
6783 				return -EACCES;
6784 			}
6785 
6786 			max_access = &env->prog->aux->max_rdonly_access;
6787 		} else {
6788 			max_access = &env->prog->aux->max_rdwr_access;
6789 		}
6790 		return check_buffer_access(env, reg, argno, 0,
6791 					   access_size, zero_size_allowed,
6792 					   max_access);
6793 	case PTR_TO_STACK:
6794 		return check_stack_range_initialized(
6795 				env, reg,
6796 				argno, 0, access_size,
6797 				zero_size_allowed, access_type, meta);
6798 	case PTR_TO_BTF_ID:
6799 		return check_ptr_to_btf_access(env, regs, reg, argno, 0,
6800 					       access_size, access_type, -1);
6801 	case PTR_TO_CTX:
6802 		/* Only permit reading or writing syscall context using helper calls. */
6803 		if (is_var_ctx_off_allowed(env->prog)) {
6804 			int err = check_mem_region_access(env, reg, argno, 0, access_size, U16_MAX,
6805 							  zero_size_allowed);
6806 			if (err)
6807 				return err;
6808 			if (env->prog->aux->max_ctx_offset < reg_umax(reg) + access_size)
6809 				env->prog->aux->max_ctx_offset = reg_umax(reg) + access_size;
6810 			return 0;
6811 		}
6812 		fallthrough;
6813 	default: /* scalar_value or invalid ptr */
6814 		/* Allow zero-byte read from NULL, regardless of pointer type */
6815 		if (zero_size_allowed && access_size == 0 &&
6816 		    bpf_register_is_null(reg))
6817 			return 0;
6818 
6819 		verbose(env, "%s type=%s ", reg_arg_name(env, argno),
6820 			reg_type_str(env, reg->type));
6821 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6822 		return -EACCES;
6823 	}
6824 }
6825 
6826 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
6827  * size.
6828  *
6829  * @mem_reg contains the pointer, @size_reg contains the access size.
6830  */
6831 static int check_mem_size_reg(struct bpf_verifier_env *env,
6832 			      struct bpf_reg_state *mem_reg,
6833 			      struct bpf_reg_state *size_reg, argno_t mem_argno,
6834 			      argno_t size_argno, enum bpf_access_type access_type,
6835 			      bool zero_size_allowed,
6836 			      struct bpf_call_arg_meta *meta)
6837 {
6838 	int err;
6839 
6840 	/* This is used to refine r0 return value bounds for helpers
6841 	 * that enforce this value as an upper bound on return values.
6842 	 * See do_refine_retval_range() for helpers that can refine
6843 	 * the return value. C type of helper is u32 so we pull register
6844 	 * bound from umax_value however, if negative verifier errors
6845 	 * out. Only upper bounds can be learned because retval is an
6846 	 * int type and negative retvals are allowed.
6847 	 */
6848 	meta->msize_max_value = reg_umax(size_reg);
6849 
6850 	/* The register is SCALAR_VALUE; the access check happens using
6851 	 * its boundaries. For unprivileged variable accesses, disable
6852 	 * raw mode so that the program is required to initialize all
6853 	 * the memory that the helper could just partially fill up.
6854 	 */
6855 	if (!tnum_is_const(size_reg->var_off))
6856 		meta = NULL;
6857 
6858 	if (reg_smin(size_reg) < 0) {
6859 		verbose(env, "%s min value is negative, either use unsigned or 'var &= const'\n",
6860 			reg_arg_name(env, size_argno));
6861 		return -EACCES;
6862 	}
6863 
6864 	if (reg_umin(size_reg) == 0 && !zero_size_allowed) {
6865 		verbose(env, "%s invalid zero-sized read: u64=[%lld,%lld]\n",
6866 			reg_arg_name(env, size_argno), reg_umin(size_reg), reg_umax(size_reg));
6867 		return -EACCES;
6868 	}
6869 
6870 	if (reg_umax(size_reg) >= BPF_MAX_VAR_SIZ) {
6871 		verbose(env, "%s unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6872 			reg_arg_name(env, size_argno));
6873 		return -EACCES;
6874 	}
6875 	err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),
6876 				      access_type, zero_size_allowed, meta);
6877 	if (!err) {
6878 		int regno = reg_from_argno(size_argno);
6879 
6880 		if (regno >= 0)
6881 			err = mark_chain_precision(env, regno);
6882 		else
6883 			err = mark_stack_arg_precision(env, arg_idx_from_argno(size_argno));
6884 	}
6885 	return err;
6886 }
6887 
6888 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6889 			 argno_t argno, u32 mem_size)
6890 {
6891 	bool may_be_null = type_may_be_null(reg->type);
6892 	struct bpf_reg_state saved_reg;
6893 	int err;
6894 
6895 	if (bpf_register_is_null(reg))
6896 		return 0;
6897 
6898 	if (mem_size > S32_MAX) {
6899 		verbose(env, "%s memory size %u is too large\n",
6900 			reg_arg_name(env, argno), mem_size);
6901 		return -EACCES;
6902 	}
6903 
6904 	/* Assuming that the register contains a value check if the memory
6905 	 * access is safe. Temporarily save and restore the register's state as
6906 	 * the conversion shouldn't be visible to a caller.
6907 	 */
6908 	if (may_be_null) {
6909 		saved_reg = *reg;
6910 		mark_ptr_not_null_reg(reg);
6911 	}
6912 
6913 	int size = base_type(reg->type) == PTR_TO_STACK ? -(int)mem_size : mem_size;
6914 
6915 	err = check_helper_mem_access(env, reg, argno, size, BPF_READ, true, NULL);
6916 	err = err ?: check_helper_mem_access(env, reg, argno, size, BPF_WRITE, true, NULL);
6917 
6918 	if (may_be_null)
6919 		*reg = saved_reg;
6920 
6921 	return err;
6922 }
6923 
6924 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *mem_reg,
6925 				    struct bpf_reg_state *size_reg, argno_t mem_argno, argno_t size_argno)
6926 {
6927 	bool may_be_null = type_may_be_null(mem_reg->type);
6928 	struct bpf_reg_state saved_reg;
6929 	struct bpf_call_arg_meta meta;
6930 	int err;
6931 
6932 	memset(&meta, 0, sizeof(meta));
6933 
6934 	if (may_be_null) {
6935 		saved_reg = *mem_reg;
6936 		mark_ptr_not_null_reg(mem_reg);
6937 	}
6938 
6939 	err = check_mem_size_reg(env, mem_reg, size_reg, mem_argno, size_argno, BPF_READ, true, &meta);
6940 	err = err ?: check_mem_size_reg(env, mem_reg, size_reg, mem_argno, size_argno, BPF_WRITE, true, &meta);
6941 
6942 	if (may_be_null)
6943 		*mem_reg = saved_reg;
6944 
6945 	return err;
6946 }
6947 
6948 enum {
6949 	PROCESS_SPIN_LOCK = (1 << 0),
6950 	PROCESS_RES_LOCK  = (1 << 1),
6951 	PROCESS_LOCK_IRQ  = (1 << 2),
6952 };
6953 
6954 /* Implementation details:
6955  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6956  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6957  * Two bpf_map_lookups (even with the same key) will have different reg->id.
6958  * Two separate bpf_obj_new will also have different reg->id.
6959  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6960  * clears reg->id after value_or_null->value transition, since the verifier only
6961  * cares about the range of access to valid map value pointer and doesn't care
6962  * about actual address of the map element.
6963  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6964  * reg->id > 0 after value_or_null->value transition. By doing so
6965  * two bpf_map_lookups will be considered two different pointers that
6966  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6967  * returned from bpf_obj_new.
6968  * The verifier allows taking only one bpf_spin_lock at a time to avoid
6969  * dead-locks.
6970  * Since only one bpf_spin_lock is allowed the checks are simpler than
6971  * reg_is_refcounted() logic. The verifier needs to remember only
6972  * one spin_lock instead of array of acquired_refs.
6973  * env->cur_state->active_locks remembers which map value element or allocated
6974  * object got locked and clears it after bpf_spin_unlock.
6975  */
6976 static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int flags)
6977 {
6978 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
6979 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
6980 	struct bpf_verifier_state *cur = env->cur_state;
6981 	bool is_const = tnum_is_const(reg->var_off);
6982 	bool is_irq = flags & PROCESS_LOCK_IRQ;
6983 	u64 val = reg->var_off.value;
6984 	struct bpf_map *map = NULL;
6985 	struct btf *btf = NULL;
6986 	struct btf_record *rec;
6987 	u32 spin_lock_off;
6988 	int err;
6989 
6990 	if (!is_const) {
6991 		verbose(env,
6992 			"%s doesn't have constant offset. %s_lock has to be at the constant offset\n",
6993 			reg_arg_name(env, argno), lock_str);
6994 		return -EINVAL;
6995 	}
6996 	if (reg->type == PTR_TO_MAP_VALUE) {
6997 		map = reg->map_ptr;
6998 		if (!map->btf) {
6999 			verbose(env,
7000 				"map '%s' has to have BTF in order to use %s_lock\n",
7001 				map->name, lock_str);
7002 			return -EINVAL;
7003 		}
7004 	} else {
7005 		btf = reg->btf;
7006 	}
7007 
7008 	rec = reg_btf_record(reg);
7009 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
7010 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
7011 			map ? map->name : "kptr", lock_str);
7012 		return -EINVAL;
7013 	}
7014 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
7015 	if (spin_lock_off != val) {
7016 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
7017 			val, lock_str, spin_lock_off);
7018 		return -EINVAL;
7019 	}
7020 	if (is_lock) {
7021 		void *ptr;
7022 		int type;
7023 
7024 		if (map)
7025 			ptr = map;
7026 		else
7027 			ptr = btf;
7028 
7029 		if (!is_res_lock && cur->active_locks) {
7030 			if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) {
7031 				verbose(env,
7032 					"Locking two bpf_spin_locks are not allowed\n");
7033 				return -EINVAL;
7034 			}
7035 		} else if (is_res_lock && cur->active_locks) {
7036 			if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) {
7037 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
7038 				return -EINVAL;
7039 			}
7040 		}
7041 
7042 		if (is_res_lock && is_irq)
7043 			type = REF_TYPE_RES_LOCK_IRQ;
7044 		else if (is_res_lock)
7045 			type = REF_TYPE_RES_LOCK;
7046 		else
7047 			type = REF_TYPE_LOCK;
7048 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
7049 		if (err < 0) {
7050 			verbose(env, "Failed to acquire lock state\n");
7051 			return err;
7052 		}
7053 	} else {
7054 		void *ptr;
7055 		int type;
7056 
7057 		if (map)
7058 			ptr = map;
7059 		else
7060 			ptr = btf;
7061 
7062 		if (!cur->active_locks) {
7063 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
7064 			return -EINVAL;
7065 		}
7066 
7067 		if (is_res_lock && is_irq)
7068 			type = REF_TYPE_RES_LOCK_IRQ;
7069 		else if (is_res_lock)
7070 			type = REF_TYPE_RES_LOCK;
7071 		else
7072 			type = REF_TYPE_LOCK;
7073 		if (!find_lock_state(cur, type, reg->id, ptr)) {
7074 			verbose(env, "%s_unlock of different lock\n", lock_str);
7075 			return -EINVAL;
7076 		}
7077 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
7078 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
7079 			return -EINVAL;
7080 		}
7081 		if (release_lock_state(cur, type, reg->id, ptr)) {
7082 			verbose(env, "%s_unlock of different lock\n", lock_str);
7083 			return -EINVAL;
7084 		}
7085 
7086 		invalidate_non_owning_refs(env);
7087 	}
7088 	return 0;
7089 }
7090 
7091 /* Check if @regno is a pointer to a specific field in a map value */
7092 static int check_map_field_pointer(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
7093 				   enum btf_field_type field_type,
7094 				   struct bpf_map_desc *map_desc)
7095 {
7096 	bool is_const = tnum_is_const(reg->var_off);
7097 	struct bpf_map *map = reg->map_ptr;
7098 	u64 val = reg->var_off.value;
7099 	const char *struct_name = btf_field_type_name(field_type);
7100 	int field_off = -1;
7101 
7102 	if (!is_const) {
7103 		verbose(env,
7104 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
7105 			reg_arg_name(env, argno), struct_name);
7106 		return -EINVAL;
7107 	}
7108 	if (!map->btf) {
7109 		verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name,
7110 			struct_name);
7111 		return -EINVAL;
7112 	}
7113 	if (!btf_record_has_field(map->record, field_type)) {
7114 		verbose(env, "map '%s' has no valid %s\n", map->name, struct_name);
7115 		return -EINVAL;
7116 	}
7117 	switch (field_type) {
7118 	case BPF_TIMER:
7119 		field_off = map->record->timer_off;
7120 		break;
7121 	case BPF_TASK_WORK:
7122 		field_off = map->record->task_work_off;
7123 		break;
7124 	case BPF_WORKQUEUE:
7125 		field_off = map->record->wq_off;
7126 		break;
7127 	default:
7128 		verifier_bug(env, "unsupported BTF field type: %s\n", struct_name);
7129 		return -EINVAL;
7130 	}
7131 	if (field_off != val) {
7132 		verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n",
7133 			val, struct_name, field_off);
7134 		return -EINVAL;
7135 	}
7136 	if (map_desc->ptr) {
7137 		verifier_bug(env, "Two map pointers in a %s helper", struct_name);
7138 		return -EFAULT;
7139 	}
7140 	map_desc->uid = reg->map_uid;
7141 	map_desc->ptr = map;
7142 	return 0;
7143 }
7144 
7145 static int process_timer_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
7146 			      struct bpf_map_desc *map)
7147 {
7148 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
7149 		verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
7150 		return -EOPNOTSUPP;
7151 	}
7152 	return check_map_field_pointer(env, reg, argno, BPF_TIMER, map);
7153 }
7154 
7155 static int process_timer_helper(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
7156 				struct bpf_call_arg_meta *meta)
7157 {
7158 	return process_timer_func(env, reg, argno, &meta->map);
7159 }
7160 
7161 static int process_timer_kfunc(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
7162 			       struct bpf_kfunc_call_arg_meta *meta)
7163 {
7164 	return process_timer_func(env, reg, argno, &meta->map);
7165 }
7166 
7167 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7168 			     struct bpf_call_arg_meta *meta)
7169 {
7170 	struct bpf_reg_state *reg = reg_state(env, regno);
7171 	struct btf_field *kptr_field;
7172 	struct bpf_map *map_ptr;
7173 	struct btf_record *rec;
7174 	u32 kptr_off;
7175 
7176 	if (type_is_ptr_alloc_obj(reg->type)) {
7177 		rec = reg_btf_record(reg);
7178 	} else { /* PTR_TO_MAP_VALUE */
7179 		map_ptr = reg->map_ptr;
7180 		if (!map_ptr->btf) {
7181 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7182 				map_ptr->name);
7183 			return -EINVAL;
7184 		}
7185 		rec = map_ptr->record;
7186 		meta->map.ptr = map_ptr;
7187 	}
7188 
7189 	if (!tnum_is_const(reg->var_off)) {
7190 		verbose(env,
7191 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7192 			regno);
7193 		return -EINVAL;
7194 	}
7195 
7196 	if (!btf_record_has_field(rec, BPF_KPTR)) {
7197 		verbose(env, "R%d has no valid kptr\n", regno);
7198 		return -EINVAL;
7199 	}
7200 
7201 	kptr_off = reg->var_off.value;
7202 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
7203 	if (!kptr_field) {
7204 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7205 		return -EACCES;
7206 	}
7207 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7208 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7209 		return -EACCES;
7210 	}
7211 	meta->kptr_field = kptr_field;
7212 	return 0;
7213 }
7214 
7215 /*
7216  * Validate dynptr arguments for helper, kfunc and subprog.
7217  *
7218  * @dynptr is both input and output. It is populated when the argument is
7219  * tagged with MEM_UNINIT (i.e., the dynptr argument that will be constructed)
7220  * and consumed when the argument is expecting to be an initialized dynptr.
7221  * @parent_id is used to track the referenced parent object (e.g., file or skb in
7222  * qdisc program) when constructing a dynptr.
7223  *
7224  * There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7225  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7226  *
7227  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7228  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7229  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7230  *
7231  * Mutability of bpf_dynptr is at two levels: the dynptr and the memory the
7232  * dynptr points to. At the first level, the verifier will make sure a
7233  * CONST_PTR_TO_DYNPTR cannot be reinitialized or destroyed. The mutability of
7234  * a dynptr's view (i.e., start and offset) is not tracked as there is not such
7235  * use case. The second level is tracked using the upper bit of bpf_dynptr->size
7236  * and checked dynamically during runtime.
7237  */
7238 static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7239 			       argno_t argno, int insn_idx, enum bpf_arg_type arg_type,
7240 			       struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr)
7241 {
7242 	int spi, err = 0;
7243 
7244 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
7245 		verbose(env,
7246 			"%s expected pointer to stack or const struct bpf_dynptr\n",
7247 			reg_arg_name(env, argno));
7248 		return -EINVAL;
7249 	}
7250 
7251 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7252 	 *		 constructing a mutable bpf_dynptr object.
7253 	 *
7254 	 *		 Currently, this is only possible with PTR_TO_STACK
7255 	 *		 pointing to a region of at least 16 bytes which doesn't
7256 	 *		 contain an existing bpf_dynptr.
7257 	 *
7258 	 *  OBJ_RELEASE - Points to a initialized bpf_dynptr that will be
7259 	 *		  destroyed.
7260 	 *
7261 	 *  None       - Points to a initialized dynptr that cannot be
7262 	 *		 reinitialized or destroyed. However, the view of the
7263 	 *		 dynptr and the memory it points to may be mutated.
7264 	 */
7265 	if (arg_type & MEM_UNINIT) {
7266 		int i;
7267 
7268 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7269 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7270 			return -EINVAL;
7271 		}
7272 
7273 		/* we write BPF_DW bits (8 bytes) at a time */
7274 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7275 			err = check_mem_access(env, insn_idx, reg, argno,
7276 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7277 			if (err)
7278 				return err;
7279 		}
7280 
7281 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, ref_obj, dynptr);
7282 	} else /* OBJ_RELEASE and None case from above */ {
7283 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7284 		if (reg->type == CONST_PTR_TO_DYNPTR && (arg_type & OBJ_RELEASE)) {
7285 			verbose(env, "CONST_PTR_TO_DYNPTR cannot be released\n");
7286 			return -EINVAL;
7287 		}
7288 
7289 		if (!is_dynptr_reg_valid_init(env, reg)) {
7290 			verbose(env, "Expected an initialized dynptr as %s\n",
7291 				reg_arg_name(env, argno));
7292 			return -EINVAL;
7293 		}
7294 
7295 		/* Fold modifiers (in this case, OBJ_RELEASE) when checking expected type */
7296 		if (!is_dynptr_type_expected(env, reg, arg_type & ~OBJ_RELEASE)) {
7297 			verbose(env,
7298 				"Expected a dynptr of type %s as %s\n",
7299 				dynptr_type_str(arg_to_dynptr_type(arg_type)),
7300 				reg_arg_name(env, argno));
7301 			return -EINVAL;
7302 		}
7303 
7304 		if (reg->type != CONST_PTR_TO_DYNPTR) {
7305 			struct bpf_func_state *state = bpf_func(env, reg);
7306 
7307 			spi = dynptr_get_spi(env, reg);
7308 			if (spi < 0)
7309 				return spi;
7310 
7311 			/*
7312 			 * For CONST_PTR_TO_DYNPTR, reg is already scratched by check_reg_arg
7313 			 * in check_helper_call and mark_btf_func_reg_size in check_kfunc_call.
7314 			 */
7315 			mark_stack_slots_scratched(env, spi, BPF_DYNPTR_NR_SLOTS);
7316 
7317 			reg = &state->stack[spi].spilled_ptr;
7318 		}
7319 
7320 		if (dynptr) {
7321 			dynptr->type = reg->dynptr.type;
7322 			dynptr->id = reg->id;
7323 			dynptr->parent_id = reg->parent_id;
7324 		}
7325 	}
7326 	return err;
7327 }
7328 
7329 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7330 {
7331 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7332 }
7333 
7334 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7335 {
7336 	return meta->kfunc_flags & KF_ITER_NEW;
7337 }
7338 
7339 
7340 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7341 {
7342 	return meta->kfunc_flags & KF_ITER_DESTROY;
7343 }
7344 
7345 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
7346 			      const struct btf_param *arg)
7347 {
7348 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7349 	 * kfunc is iter state pointer
7350 	 */
7351 	if (is_iter_kfunc(meta))
7352 		return arg_idx == 0;
7353 
7354 	/* iter passed as an argument to a generic kfunc */
7355 	return btf_param_match_suffix(meta->btf, arg, "__iter");
7356 }
7357 
7358 static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int insn_idx,
7359 			    struct bpf_kfunc_call_arg_meta *meta)
7360 {
7361 	struct bpf_func_state *state = bpf_func(env, reg);
7362 	const struct btf_type *t;
7363 	u32 arg_idx = arg_idx_from_argno(argno);
7364 	int spi, err, i, nr_slots, btf_id;
7365 
7366 	if (reg->type != PTR_TO_STACK) {
7367 		verbose(env, "%s expected pointer to an iterator on stack\n",
7368 			reg_arg_name(env, argno));
7369 		return -EINVAL;
7370 	}
7371 
7372 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
7373 	 * ensures struct convention, so we wouldn't need to do any BTF
7374 	 * validation here. But given iter state can be passed as a parameter
7375 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
7376 	 * conservative here.
7377 	 */
7378 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, arg_idx);
7379 	if (btf_id < 0) {
7380 		verbose(env, "expected valid iter pointer as %s\n",
7381 			reg_arg_name(env, argno));
7382 		return -EINVAL;
7383 	}
7384 	t = btf_type_by_id(meta->btf, btf_id);
7385 	nr_slots = t->size / BPF_REG_SIZE;
7386 
7387 	if (is_iter_new_kfunc(meta)) {
7388 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7389 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7390 			verbose(env, "expected uninitialized iter_%s as %s\n",
7391 				iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno));
7392 			return -EINVAL;
7393 		}
7394 
7395 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7396 			err = check_mem_access(env, insn_idx, reg, argno,
7397 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7398 			if (err)
7399 				return err;
7400 		}
7401 
7402 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7403 		if (err)
7404 			return err;
7405 	} else {
7406 		/* iter_next() or iter_destroy(), as well as any kfunc
7407 		 * accepting iter argument, expect initialized iter state
7408 		 */
7409 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7410 		switch (err) {
7411 		case 0:
7412 			break;
7413 		case -EINVAL:
7414 			verbose(env, "expected an initialized iter_%s as %s\n",
7415 				iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno));
7416 			return err;
7417 		case -EPROTO:
7418 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7419 			return err;
7420 		default:
7421 			return err;
7422 		}
7423 
7424 		spi = iter_get_spi(env, reg, nr_slots);
7425 		if (spi < 0)
7426 			return spi;
7427 
7428 		mark_stack_slots_scratched(env, spi, nr_slots);
7429 
7430 		/* remember meta->iter info for process_iter_next_call() */
7431 		meta->iter.spi = spi;
7432 		meta->iter.frameno = reg->frameno;
7433 		update_ref_obj(&meta->ref_obj, &state->stack[spi].spilled_ptr);
7434 
7435 		if (is_iter_destroy_kfunc(meta)) {
7436 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7437 			if (err)
7438 				return err;
7439 		}
7440 	}
7441 
7442 	return 0;
7443 }
7444 
7445 /* Look for a previous loop entry at insn_idx: nearest parent state
7446  * stopped at insn_idx with callsites matching those in cur->frame.
7447  */
7448 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7449 						  struct bpf_verifier_state *cur,
7450 						  int insn_idx)
7451 {
7452 	struct bpf_verifier_state_list *sl;
7453 	struct bpf_verifier_state *st;
7454 	struct list_head *pos, *head;
7455 
7456 	/* Explored states are pushed in stack order, most recent states come first */
7457 	head = bpf_explored_state(env, insn_idx);
7458 	list_for_each(pos, head) {
7459 		sl = container_of(pos, struct bpf_verifier_state_list, node);
7460 		/* If st->branches != 0 state is a part of current DFS verification path,
7461 		 * hence cur & st for a loop.
7462 		 */
7463 		st = &sl->state;
7464 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7465 		    st->dfs_depth < cur->dfs_depth)
7466 			return st;
7467 	}
7468 
7469 	return NULL;
7470 }
7471 
7472 /*
7473  * Check if scalar registers are exact for the purpose of not widening.
7474  * More lenient than regs_exact()
7475  */
7476 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold,
7477 				    const struct bpf_reg_state *rcur)
7478 {
7479 	return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id));
7480 }
7481 
7482 static void maybe_widen_reg(struct bpf_verifier_env *env,
7483 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur)
7484 {
7485 	if (rold->type != SCALAR_VALUE)
7486 		return;
7487 	if (rold->type != rcur->type)
7488 		return;
7489 	if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur))
7490 		return;
7491 	__mark_reg_unknown(env, rcur);
7492 }
7493 
7494 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7495 				   struct bpf_verifier_state *old,
7496 				   struct bpf_verifier_state *cur)
7497 {
7498 	struct bpf_func_state *fold, *fcur;
7499 	int i, fr, num_slots;
7500 
7501 	for (fr = old->curframe; fr >= 0; fr--) {
7502 		fold = old->frame[fr];
7503 		fcur = cur->frame[fr];
7504 
7505 		for (i = 0; i < MAX_BPF_REG; i++)
7506 			maybe_widen_reg(env,
7507 					&fold->regs[i],
7508 					&fcur->regs[i]);
7509 
7510 		num_slots = min(fold->allocated_stack / BPF_REG_SIZE,
7511 				fcur->allocated_stack / BPF_REG_SIZE);
7512 		for (i = 0; i < num_slots; i++) {
7513 			if (!bpf_is_spilled_reg(&fold->stack[i]) ||
7514 			    !bpf_is_spilled_reg(&fcur->stack[i]))
7515 				continue;
7516 
7517 			maybe_widen_reg(env,
7518 					&fold->stack[i].spilled_ptr,
7519 					&fcur->stack[i].spilled_ptr);
7520 		}
7521 	}
7522 	return 0;
7523 }
7524 
7525 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
7526 						 struct bpf_kfunc_call_arg_meta *meta)
7527 {
7528 	int iter_frameno = meta->iter.frameno;
7529 	int iter_spi = meta->iter.spi;
7530 
7531 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7532 }
7533 
7534 /* process_iter_next_call() is called when verifier gets to iterator's next
7535  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7536  * to it as just "iter_next()" in comments below.
7537  *
7538  * BPF verifier relies on a crucial contract for any iter_next()
7539  * implementation: it should *eventually* return NULL, and once that happens
7540  * it should keep returning NULL. That is, once iterator exhausts elements to
7541  * iterate, it should never reset or spuriously return new elements.
7542  *
7543  * With the assumption of such contract, process_iter_next_call() simulates
7544  * a fork in the verifier state to validate loop logic correctness and safety
7545  * without having to simulate infinite amount of iterations.
7546  *
7547  * In current state, we first assume that iter_next() returned NULL and
7548  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7549  * conditions we should not form an infinite loop and should eventually reach
7550  * exit.
7551  *
7552  * Besides that, we also fork current state and enqueue it for later
7553  * verification. In a forked state we keep iterator state as ACTIVE
7554  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7555  * also bump iteration depth to prevent erroneous infinite loop detection
7556  * later on (see iter_active_depths_differ() comment for details). In this
7557  * state we assume that we'll eventually loop back to another iter_next()
7558  * calls (it could be in exactly same location or in some other instruction,
7559  * it doesn't matter, we don't make any unnecessary assumptions about this,
7560  * everything revolves around iterator state in a stack slot, not which
7561  * instruction is calling iter_next()). When that happens, we either will come
7562  * to iter_next() with equivalent state and can conclude that next iteration
7563  * will proceed in exactly the same way as we just verified, so it's safe to
7564  * assume that loop converges. If not, we'll go on another iteration
7565  * simulation with a different input state, until all possible starting states
7566  * are validated or we reach maximum number of instructions limit.
7567  *
7568  * This way, we will either exhaustively discover all possible input states
7569  * that iterator loop can start with and eventually will converge, or we'll
7570  * effectively regress into bounded loop simulation logic and either reach
7571  * maximum number of instructions if loop is not provably convergent, or there
7572  * is some statically known limit on number of iterations (e.g., if there is
7573  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7574  *
7575  * Iteration convergence logic in is_state_visited() relies on exact
7576  * states comparison, which ignores read and precision marks.
7577  * This is necessary because read and precision marks are not finalized
7578  * while in the loop. Exact comparison might preclude convergence for
7579  * simple programs like below:
7580  *
7581  *     i = 0;
7582  *     while(iter_next(&it))
7583  *       i++;
7584  *
7585  * At each iteration step i++ would produce a new distinct state and
7586  * eventually instruction processing limit would be reached.
7587  *
7588  * To avoid such behavior speculatively forget (widen) range for
7589  * imprecise scalar registers, if those registers were not precise at the
7590  * end of the previous iteration and do not match exactly.
7591  *
7592  * This is a conservative heuristic that allows to verify wide range of programs,
7593  * however it precludes verification of programs that conjure an
7594  * imprecise value on the first loop iteration and use it as precise on a second.
7595  * For example, the following safe program would fail to verify:
7596  *
7597  *     struct bpf_num_iter it;
7598  *     int arr[10];
7599  *     int i = 0, a = 0;
7600  *     bpf_iter_num_new(&it, 0, 10);
7601  *     while (bpf_iter_num_next(&it)) {
7602  *       if (a == 0) {
7603  *         a = 1;
7604  *         i = 7; // Because i changed verifier would forget
7605  *                // it's range on second loop entry.
7606  *       } else {
7607  *         arr[i] = 42; // This would fail to verify.
7608  *       }
7609  *     }
7610  *     bpf_iter_num_destroy(&it);
7611  */
7612 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7613 				  struct bpf_kfunc_call_arg_meta *meta)
7614 {
7615 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7616 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7617 	struct bpf_reg_state *cur_iter, *queued_iter;
7618 
7619 	BTF_TYPE_EMIT(struct bpf_iter);
7620 
7621 	cur_iter = get_iter_from_state(cur_st, meta);
7622 
7623 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7624 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7625 		verifier_bug(env, "unexpected iterator state %d (%s)",
7626 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7627 		return -EFAULT;
7628 	}
7629 
7630 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7631 		/* Because iter_next() call is a checkpoint is_state_visitied()
7632 		 * should guarantee parent state with same call sites and insn_idx.
7633 		 */
7634 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7635 		    !same_callsites(cur_st->parent, cur_st)) {
7636 			verifier_bug(env, "bad parent state for iter next call");
7637 			return -EFAULT;
7638 		}
7639 		/* Note cur_st->parent in the call below, it is necessary to skip
7640 		 * checkpoint created for cur_st by is_state_visited()
7641 		 * right at this instruction.
7642 		 */
7643 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7644 		/* branch out active iter state */
7645 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7646 		if (IS_ERR(queued_st))
7647 			return PTR_ERR(queued_st);
7648 
7649 		queued_iter = get_iter_from_state(queued_st, meta);
7650 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7651 		queued_iter->iter.depth++;
7652 		if (prev_st)
7653 			widen_imprecise_scalars(env, prev_st, queued_st);
7654 
7655 		queued_fr = queued_st->frame[queued_st->curframe];
7656 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7657 	}
7658 
7659 	/* switch to DRAINED state, but keep the depth unchanged */
7660 	/* mark current iter state as drained and assume returned NULL */
7661 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7662 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
7663 
7664 	return 0;
7665 }
7666 
7667 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7668 {
7669 	return type == ARG_CONST_SIZE ||
7670 	       type == ARG_CONST_SIZE_OR_ZERO;
7671 }
7672 
7673 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
7674 {
7675 	return base_type(type) == ARG_PTR_TO_MEM &&
7676 	       type & MEM_UNINIT;
7677 }
7678 
7679 static bool arg_type_is_release(enum bpf_arg_type type)
7680 {
7681 	return type & OBJ_RELEASE;
7682 }
7683 
7684 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7685 {
7686 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7687 }
7688 
7689 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7690 				 const struct bpf_call_arg_meta *meta,
7691 				 enum bpf_arg_type *arg_type)
7692 {
7693 	if (!meta->map.ptr) {
7694 		/* kernel subsystem misconfigured verifier */
7695 		verifier_bug(env, "invalid map_ptr to access map->type");
7696 		return -EFAULT;
7697 	}
7698 
7699 	switch (meta->map.ptr->map_type) {
7700 	case BPF_MAP_TYPE_SOCKMAP:
7701 	case BPF_MAP_TYPE_SOCKHASH:
7702 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7703 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7704 		} else {
7705 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
7706 			return -EINVAL;
7707 		}
7708 		break;
7709 	case BPF_MAP_TYPE_BLOOM_FILTER:
7710 		if (meta->func_id == BPF_FUNC_map_peek_elem)
7711 			*arg_type = ARG_PTR_TO_MAP_VALUE;
7712 		break;
7713 	default:
7714 		break;
7715 	}
7716 	return 0;
7717 }
7718 
7719 struct bpf_reg_types {
7720 	const enum bpf_reg_type types[10];
7721 	u32 *btf_id;
7722 };
7723 
7724 static const struct bpf_reg_types sock_types = {
7725 	.types = {
7726 		PTR_TO_SOCK_COMMON,
7727 		PTR_TO_SOCKET,
7728 		PTR_TO_TCP_SOCK,
7729 		PTR_TO_XDP_SOCK,
7730 	},
7731 };
7732 
7733 #ifdef CONFIG_NET
7734 static const struct bpf_reg_types btf_id_sock_common_types = {
7735 	.types = {
7736 		PTR_TO_SOCK_COMMON,
7737 		PTR_TO_SOCKET,
7738 		PTR_TO_TCP_SOCK,
7739 		PTR_TO_XDP_SOCK,
7740 		PTR_TO_BTF_ID,
7741 		PTR_TO_BTF_ID | PTR_TRUSTED,
7742 	},
7743 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7744 };
7745 #endif
7746 
7747 static const struct bpf_reg_types mem_types = {
7748 	.types = {
7749 		PTR_TO_STACK,
7750 		PTR_TO_PACKET,
7751 		PTR_TO_PACKET_META,
7752 		PTR_TO_MAP_KEY,
7753 		PTR_TO_MAP_VALUE,
7754 		PTR_TO_MEM,
7755 		PTR_TO_MEM | MEM_RINGBUF,
7756 		PTR_TO_BUF,
7757 		PTR_TO_BTF_ID | PTR_TRUSTED,
7758 		PTR_TO_CTX,
7759 	},
7760 };
7761 
7762 static const struct bpf_reg_types spin_lock_types = {
7763 	.types = {
7764 		PTR_TO_MAP_VALUE,
7765 		PTR_TO_BTF_ID | MEM_ALLOC,
7766 	}
7767 };
7768 
7769 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7770 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7771 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7772 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7773 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7774 static const struct bpf_reg_types btf_ptr_types = {
7775 	.types = {
7776 		PTR_TO_BTF_ID,
7777 		PTR_TO_BTF_ID | PTR_TRUSTED,
7778 		PTR_TO_BTF_ID | MEM_RCU,
7779 	},
7780 };
7781 static const struct bpf_reg_types percpu_btf_ptr_types = {
7782 	.types = {
7783 		PTR_TO_BTF_ID | MEM_PERCPU,
7784 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
7785 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7786 	}
7787 };
7788 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7789 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7790 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7791 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7792 static const struct bpf_reg_types kptr_xchg_dest_types = {
7793 	.types = {
7794 		PTR_TO_MAP_VALUE,
7795 		PTR_TO_BTF_ID | MEM_ALLOC,
7796 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF,
7797 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU,
7798 	}
7799 };
7800 static const struct bpf_reg_types dynptr_types = {
7801 	.types = {
7802 		PTR_TO_STACK,
7803 		CONST_PTR_TO_DYNPTR,
7804 	}
7805 };
7806 
7807 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7808 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
7809 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
7810 	[ARG_CONST_SIZE]		= &scalar_types,
7811 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
7812 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
7813 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
7814 	[ARG_PTR_TO_CTX]		= &context_types,
7815 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
7816 #ifdef CONFIG_NET
7817 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
7818 #endif
7819 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
7820 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
7821 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
7822 	[ARG_PTR_TO_MEM]		= &mem_types,
7823 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
7824 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
7825 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
7826 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
7827 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
7828 	[ARG_PTR_TO_TIMER]		= &timer_types,
7829 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
7830 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
7831 };
7832 
7833 static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
7834 			  enum bpf_arg_type arg_type,
7835 			  const u32 *arg_btf_id,
7836 			  struct bpf_call_arg_meta *meta)
7837 {
7838 	enum bpf_reg_type expected, type = reg->type;
7839 	const struct bpf_reg_types *compatible;
7840 	int i, j, err;
7841 
7842 	compatible = compatible_reg_types[base_type(arg_type)];
7843 	if (!compatible) {
7844 		verifier_bug(env, "unsupported arg type %d", arg_type);
7845 		return -EFAULT;
7846 	}
7847 
7848 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7849 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7850 	 *
7851 	 * Same for MAYBE_NULL:
7852 	 *
7853 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7854 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7855 	 *
7856 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7857 	 *
7858 	 * Therefore we fold these flags depending on the arg_type before comparison.
7859 	 */
7860 	if (arg_type & MEM_RDONLY)
7861 		type &= ~MEM_RDONLY;
7862 	if (arg_type & PTR_MAYBE_NULL)
7863 		type &= ~PTR_MAYBE_NULL;
7864 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
7865 		type &= ~DYNPTR_TYPE_FLAG_MASK;
7866 
7867 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
7868 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && reg_from_argno(argno) == BPF_REG_2) {
7869 		type &= ~MEM_ALLOC;
7870 		type &= ~MEM_PERCPU;
7871 	}
7872 
7873 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7874 		expected = compatible->types[i];
7875 		if (expected == NOT_INIT)
7876 			break;
7877 
7878 		if (type == expected)
7879 			goto found;
7880 	}
7881 
7882 	verbose(env, "%s type=%s expected=", reg_arg_name(env, argno), reg_type_str(env, reg->type));
7883 	for (j = 0; j + 1 < i; j++)
7884 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7885 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7886 	return -EACCES;
7887 
7888 found:
7889 	if (base_type(reg->type) != PTR_TO_BTF_ID)
7890 		return 0;
7891 
7892 	if (compatible == &mem_types) {
7893 		if (!(arg_type & MEM_RDONLY)) {
7894 			verbose(env,
7895 				"%s() may write into memory pointed by %s type=%s\n",
7896 				func_id_name(meta->func_id),
7897 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
7898 			return -EACCES;
7899 		}
7900 		return 0;
7901 	}
7902 
7903 	switch ((int)reg->type) {
7904 	case PTR_TO_BTF_ID:
7905 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7906 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
7907 	case PTR_TO_BTF_ID | MEM_RCU:
7908 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7909 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7910 	{
7911 		/* For bpf_sk_release, it needs to match against first member
7912 		 * 'struct sock_common', hence make an exception for it. This
7913 		 * allows bpf_sk_release to work for multiple socket types.
7914 		 */
7915 		bool strict_type_match = arg_type_is_release(arg_type) &&
7916 					 meta->func_id != BPF_FUNC_sk_release;
7917 
7918 		if (type_may_be_null(reg->type) &&
7919 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7920 			verbose(env, "Possibly NULL pointer passed to helper %s\n",
7921 				reg_arg_name(env, argno));
7922 			return -EACCES;
7923 		}
7924 
7925 		if (!arg_btf_id) {
7926 			if (!compatible->btf_id) {
7927 				verifier_bug(env, "missing arg compatible BTF ID");
7928 				return -EFAULT;
7929 			}
7930 			arg_btf_id = compatible->btf_id;
7931 		}
7932 
7933 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
7934 			if (map_kptr_match_type(env, meta->kptr_field, reg, reg_from_argno(argno)))
7935 				return -EACCES;
7936 		} else {
7937 			if (arg_btf_id == BPF_PTR_POISON) {
7938 				verbose(env, "verifier internal error:");
7939 				verbose(env, "%s has non-overwritten BPF_PTR_POISON type\n",
7940 					reg_arg_name(env, argno));
7941 				return -EACCES;
7942 			}
7943 
7944 			err = __check_ptr_off_reg(env, reg, argno, true);
7945 			if (err)
7946 				return err;
7947 
7948 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id,
7949 						  reg->var_off.value, btf_vmlinux, *arg_btf_id,
7950 						  strict_type_match)) {
7951 				verbose(env, "%s is of type %s but %s is expected\n",
7952 					reg_arg_name(env, argno),
7953 					btf_type_name(reg->btf, reg->btf_id),
7954 					btf_type_name(btf_vmlinux, *arg_btf_id));
7955 				return -EACCES;
7956 			}
7957 		}
7958 		break;
7959 	}
7960 	case PTR_TO_BTF_ID | MEM_ALLOC:
7961 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
7962 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
7963 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
7964 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7965 		    meta->func_id != BPF_FUNC_kptr_xchg) {
7966 			verifier_bug(env, "unimplemented handling of MEM_ALLOC");
7967 			return -EFAULT;
7968 		}
7969 		/* Check if local kptr in src arg matches kptr in dst arg */
7970 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
7971 			int regno = reg_from_argno(argno);
7972 
7973 			if (regno == BPF_REG_2 &&
7974 			    map_kptr_match_type(env, meta->kptr_field, reg, regno))
7975 				return -EACCES;
7976 		}
7977 		break;
7978 	case PTR_TO_BTF_ID | MEM_PERCPU:
7979 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
7980 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7981 		/* Handled by helper specific checks */
7982 		break;
7983 	default:
7984 		verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match");
7985 		return -EFAULT;
7986 	}
7987 	return 0;
7988 }
7989 
7990 static struct btf_field *
7991 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7992 {
7993 	struct btf_field *field;
7994 	struct btf_record *rec;
7995 
7996 	rec = reg_btf_record(reg);
7997 	if (!rec)
7998 		return NULL;
7999 
8000 	field = btf_record_find(rec, off, fields);
8001 	if (!field)
8002 		return NULL;
8003 
8004 	return field;
8005 }
8006 
8007 static int __check_func_arg_reg_off(struct bpf_verifier_env *env,
8008 				    const struct bpf_reg_state *reg, argno_t argno,
8009 				    enum bpf_arg_type arg_type,
8010 				    bool btf_id_fixed_off_ok)
8011 {
8012 	u32 type = reg->type;
8013 
8014 	/* When referenced register is passed to release function, its fixed
8015 	 * offset must be 0.
8016 	 *
8017 	 * We will check arg_type_is_release reg has id when storing
8018 	 * meta->release_regno.
8019 	 */
8020 	if (arg_type_is_release(arg_type)) {
8021 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8022 		 * may not directly point to the object being released, but to
8023 		 * dynptr pointing to such object, which might be at some offset
8024 		 * on the stack. In that case, we simply to fallback to the
8025 		 * default handling.
8026 		 */
8027 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8028 			return 0;
8029 
8030 		/* Doing check_ptr_off_reg check for the offset will catch this
8031 		 * because fixed_off_ok is false, but checking here allows us
8032 		 * to give the user a better error message.
8033 		 */
8034 		if (!tnum_is_const(reg->var_off) || reg->var_off.value != 0) {
8035 			verbose(env, "%s must have zero offset when passed to release func or trusted arg to kfunc\n",
8036 				reg_arg_name(env, argno));
8037 			return -EINVAL;
8038 		}
8039 	}
8040 
8041 	switch (type) {
8042 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8043 	case PTR_TO_STACK:
8044 	case PTR_TO_PACKET:
8045 	case PTR_TO_PACKET_META:
8046 	case PTR_TO_MAP_KEY:
8047 	case PTR_TO_MAP_VALUE:
8048 	case PTR_TO_MEM:
8049 	case PTR_TO_MEM | MEM_RDONLY:
8050 	case PTR_TO_MEM | MEM_RINGBUF:
8051 	case PTR_TO_BUF:
8052 	case PTR_TO_BUF | MEM_RDONLY:
8053 	case PTR_TO_ARENA:
8054 	case SCALAR_VALUE:
8055 		return 0;
8056 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8057 	 * fixed offset.
8058 	 */
8059 	case PTR_TO_BTF_ID:
8060 	case PTR_TO_BTF_ID | MEM_ALLOC:
8061 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8062 	case PTR_TO_BTF_ID | MEM_RCU:
8063 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8064 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8065 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8066 		 * its fixed offset must be 0. In the other cases, fixed offset
8067 		 * can be non-zero unless the caller requires otherwise.
8068 		 * var_off always must be 0 for PTR_TO_BTF_ID, hence we still
8069 		 * need to do checks instead of returning.
8070 		 */
8071 		return __check_ptr_off_reg(env, reg, argno, btf_id_fixed_off_ok);
8072 	case PTR_TO_CTX:
8073 		/*
8074 		 * Allow fixed and variable offsets for syscall context, but
8075 		 * only when the argument is passed as memory, not ctx,
8076 		 * otherwise we may get modified ctx in tail called programs and
8077 		 * global subprogs (that may act as extension prog hooks).
8078 		 */
8079 		if (arg_type != ARG_PTR_TO_CTX && is_var_ctx_off_allowed(env->prog))
8080 			return 0;
8081 		fallthrough;
8082 	default:
8083 		return __check_ptr_off_reg(env, reg, argno, false);
8084 	}
8085 }
8086 
8087 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8088 				  const struct bpf_reg_state *reg, argno_t argno,
8089 				  enum bpf_arg_type arg_type)
8090 {
8091 	return __check_func_arg_reg_off(env, reg, argno, arg_type, true);
8092 }
8093 
8094 static int check_arg_const_str(struct bpf_verifier_env *env,
8095 			       struct bpf_reg_state *reg, argno_t argno)
8096 {
8097 	struct bpf_map *map = reg->map_ptr;
8098 	int err;
8099 	int map_off;
8100 	u64 map_addr;
8101 	char *str_ptr;
8102 
8103 	if (reg->type != PTR_TO_MAP_VALUE)
8104 		return -EINVAL;
8105 
8106 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
8107 		verbose(env, "%s points to insn_array map which cannot be used as const string\n",
8108 			reg_arg_name(env, argno));
8109 		return -EACCES;
8110 	}
8111 
8112 	if (!bpf_map_is_rdonly(map)) {
8113 		verbose(env, "%s does not point to a readonly map'\n", reg_arg_name(env, argno));
8114 		return -EACCES;
8115 	}
8116 
8117 	if (!tnum_is_const(reg->var_off)) {
8118 		verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno));
8119 		return -EACCES;
8120 	}
8121 
8122 	if (!map->ops->map_direct_value_addr) {
8123 		verbose(env, "no direct value access support for this map type\n");
8124 		return -EACCES;
8125 	}
8126 
8127 	err = check_map_access(env, reg, argno, 0,
8128 			       map->value_size - reg->var_off.value, false,
8129 			       ACCESS_HELPER);
8130 	if (err)
8131 		return err;
8132 
8133 	map_off = reg->var_off.value;
8134 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8135 	if (err) {
8136 		verbose(env, "direct value access on string failed\n");
8137 		return err;
8138 	}
8139 
8140 	str_ptr = (char *)(long)(map_addr);
8141 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8142 		verbose(env, "string is not zero-terminated\n");
8143 		return -EINVAL;
8144 	}
8145 	return 0;
8146 }
8147 
8148 /* Returns constant key value in `value` if possible, else negative error */
8149 static int get_constant_map_key(struct bpf_verifier_env *env,
8150 				struct bpf_reg_state *key,
8151 				u32 key_size,
8152 				s64 *value)
8153 {
8154 	struct bpf_func_state *state = bpf_func(env, key);
8155 	struct bpf_reg_state *reg;
8156 	int slot, spi, off;
8157 	int spill_size = 0;
8158 	int zero_size = 0;
8159 	int stack_off;
8160 	int i, err;
8161 	u8 *stype;
8162 
8163 	if (!env->bpf_capable)
8164 		return -EOPNOTSUPP;
8165 	if (key->type != PTR_TO_STACK)
8166 		return -EOPNOTSUPP;
8167 	if (!tnum_is_const(key->var_off))
8168 		return -EOPNOTSUPP;
8169 
8170 	stack_off = key->var_off.value;
8171 	slot = -stack_off - 1;
8172 	spi = slot / BPF_REG_SIZE;
8173 	off = slot % BPF_REG_SIZE;
8174 	stype = state->stack[spi].slot_type;
8175 
8176 	/* First handle precisely tracked STACK_ZERO */
8177 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
8178 		zero_size++;
8179 	if (zero_size >= key_size) {
8180 		*value = 0;
8181 		return 0;
8182 	}
8183 
8184 	/* Check that stack contains a scalar spill of expected size */
8185 	if (!bpf_is_spilled_scalar_reg(&state->stack[spi]))
8186 		return -EOPNOTSUPP;
8187 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
8188 		spill_size++;
8189 	if (spill_size != key_size)
8190 		return -EOPNOTSUPP;
8191 
8192 	reg = &state->stack[spi].spilled_ptr;
8193 	if (!tnum_is_const(reg->var_off))
8194 		/* Stack value not statically known */
8195 		return -EOPNOTSUPP;
8196 
8197 	/* We are relying on a constant value. So mark as precise
8198 	 * to prevent pruning on it.
8199 	 */
8200 	bpf_bt_set_frame_slot(&env->bt, key->frameno, spi);
8201 	err = mark_chain_precision_batch(env, env->cur_state);
8202 	if (err < 0)
8203 		return err;
8204 
8205 	*value = reg->var_off.value;
8206 	return 0;
8207 }
8208 
8209 static bool can_elide_value_nullness(const struct bpf_map *map);
8210 
8211 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8212 			  struct bpf_call_arg_meta *meta,
8213 			  const struct bpf_func_proto *fn,
8214 			  int insn_idx)
8215 {
8216 	u32 regno = BPF_REG_1 + arg;
8217 	struct bpf_reg_state *reg = reg_state(env, regno);
8218 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8219 	argno_t argno = argno_from_arg(arg + 1);
8220 	enum bpf_reg_type type = reg->type;
8221 	u32 *arg_btf_id = NULL;
8222 	u32 key_size;
8223 	int err = 0;
8224 
8225 	if (arg_type == ARG_DONTCARE)
8226 		return 0;
8227 
8228 	err = check_reg_arg(env, regno, SRC_OP);
8229 	if (err)
8230 		return err;
8231 
8232 	if (arg_type == ARG_ANYTHING) {
8233 		if (is_pointer_value(env, regno)) {
8234 			verbose(env, "R%d leaks addr into helper function\n",
8235 				regno);
8236 			return -EACCES;
8237 		}
8238 		return 0;
8239 	}
8240 
8241 	if (type_is_pkt_pointer(type) &&
8242 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8243 		verbose(env, "helper access to the packet is not allowed\n");
8244 		return -EACCES;
8245 	}
8246 
8247 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8248 		err = resolve_map_arg_type(env, meta, &arg_type);
8249 		if (err)
8250 			return err;
8251 	}
8252 
8253 	if (bpf_register_is_null(reg) && type_may_be_null(arg_type))
8254 		/* A NULL register has a SCALAR_VALUE type, so skip
8255 		 * type checking.
8256 		 */
8257 		goto skip_type_check;
8258 
8259 	/* arg_btf_id and arg_size are in a union. */
8260 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8261 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8262 		arg_btf_id = fn->arg_btf_id[arg];
8263 
8264 	err = check_reg_type(env, reg, argno_from_reg(regno), arg_type, arg_btf_id, meta);
8265 	if (err)
8266 		return err;
8267 
8268 	err = check_func_arg_reg_off(env, reg, argno_from_reg(regno), arg_type);
8269 	if (err)
8270 		return err;
8271 
8272 skip_type_check:
8273 	if (arg_type_is_release(arg_type) && !arg_type_is_dynptr(arg_type) &&
8274 	    !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) {
8275 		verbose(env, "release helper %s expects referenced PTR_TO_BTF_ID passed to %s\n",
8276 			func_id_name(meta->func_id), reg_arg_name(env, argno));
8277 		return -EINVAL;
8278 	}
8279 
8280 	if (reg_is_referenced(env, reg))
8281 		update_ref_obj(&meta->ref_obj, reg);
8282 
8283 	switch (base_type(arg_type)) {
8284 	case ARG_CONST_MAP_PTR:
8285 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8286 		if (meta->map.ptr) {
8287 			/* Use map_uid (which is unique id of inner map) to reject:
8288 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8289 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8290 			 * if (inner_map1 && inner_map2) {
8291 			 *     timer = bpf_map_lookup_elem(inner_map1);
8292 			 *     if (timer)
8293 			 *         // mismatch would have been allowed
8294 			 *         bpf_timer_init(timer, inner_map2);
8295 			 * }
8296 			 *
8297 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8298 			 */
8299 			if (meta->map.ptr != reg->map_ptr ||
8300 			    meta->map.uid != reg->map_uid) {
8301 				verbose(env,
8302 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8303 					meta->map.uid, reg->map_uid);
8304 				return -EINVAL;
8305 			}
8306 		}
8307 		meta->map.ptr = reg->map_ptr;
8308 		meta->map.uid = reg->map_uid;
8309 		break;
8310 	case ARG_PTR_TO_MAP_KEY:
8311 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8312 		 * check that [key, key + map->key_size) are within
8313 		 * stack limits and initialized
8314 		 */
8315 		if (!meta->map.ptr) {
8316 			/* in function declaration map_ptr must come before
8317 			 * map_key, so that it's verified and known before
8318 			 * we have to check map_key here. Otherwise it means
8319 			 * that kernel subsystem misconfigured verifier
8320 			 */
8321 			verifier_bug(env, "invalid map_ptr to access map->key");
8322 			return -EFAULT;
8323 		}
8324 		key_size = meta->map.ptr->key_size;
8325 		err = check_helper_mem_access(env, reg, argno_from_reg(regno), key_size, BPF_READ, false, NULL);
8326 		if (err)
8327 			return err;
8328 		if (can_elide_value_nullness(meta->map.ptr)) {
8329 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
8330 			if (err < 0) {
8331 				meta->const_map_key = -1;
8332 				if (err == -EOPNOTSUPP)
8333 					err = 0;
8334 				else
8335 					return err;
8336 			}
8337 		}
8338 		break;
8339 	case ARG_PTR_TO_MAP_VALUE:
8340 		if (type_may_be_null(arg_type) && bpf_register_is_null(reg))
8341 			return 0;
8342 
8343 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8344 		 * check [value, value + map->value_size) validity
8345 		 */
8346 		if (!meta->map.ptr) {
8347 			/* kernel subsystem misconfigured verifier */
8348 			verifier_bug(env, "invalid map_ptr to access map->value");
8349 			return -EFAULT;
8350 		}
8351 		meta->raw_mode = arg_type & MEM_UNINIT;
8352 		err = check_helper_mem_access(env, reg, argno_from_reg(regno), meta->map.ptr->value_size,
8353 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
8354 					      false, meta);
8355 		break;
8356 	case ARG_PTR_TO_PERCPU_BTF_ID:
8357 		if (!reg->btf_id) {
8358 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8359 			return -EACCES;
8360 		}
8361 		meta->ret_btf = reg->btf;
8362 		meta->ret_btf_id = reg->btf_id;
8363 		break;
8364 	case ARG_PTR_TO_SPIN_LOCK:
8365 		if (in_rbtree_lock_required_cb(env)) {
8366 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8367 			return -EACCES;
8368 		}
8369 		if (meta->func_id == BPF_FUNC_spin_lock) {
8370 			err = process_spin_lock(env, reg, argno_from_reg(regno), PROCESS_SPIN_LOCK);
8371 			if (err)
8372 				return err;
8373 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8374 			err = process_spin_lock(env, reg, argno_from_reg(regno), 0);
8375 			if (err)
8376 				return err;
8377 		} else {
8378 			verifier_bug(env, "spin lock arg on unexpected helper");
8379 			return -EFAULT;
8380 		}
8381 		break;
8382 	case ARG_PTR_TO_TIMER:
8383 		err = process_timer_helper(env, reg, argno_from_reg(regno), meta);
8384 		if (err)
8385 			return err;
8386 		break;
8387 	case ARG_PTR_TO_FUNC:
8388 		meta->subprogno = reg->subprogno;
8389 		break;
8390 	case ARG_PTR_TO_MEM:
8391 		/* The access to this pointer is only checked when we hit the
8392 		 * next is_mem_size argument below.
8393 		 */
8394 		meta->raw_mode = arg_type & MEM_UNINIT;
8395 		if (arg_type & MEM_FIXED_SIZE) {
8396 			err = check_helper_mem_access(env, reg, argno_from_reg(regno), fn->arg_size[arg],
8397 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
8398 						      false, meta);
8399 			if (err)
8400 				return err;
8401 			if (arg_type & MEM_ALIGNED)
8402 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
8403 		}
8404 		break;
8405 	case ARG_CONST_SIZE:
8406 		err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, argno_from_reg(regno - 1),
8407 					 argno_from_reg(regno),
8408 					 fn->arg_type[arg - 1] & MEM_WRITE ?
8409 					 BPF_WRITE : BPF_READ,
8410 					 false, meta);
8411 		break;
8412 	case ARG_CONST_SIZE_OR_ZERO:
8413 		err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, argno_from_reg(regno - 1),
8414 					 argno_from_reg(regno),
8415 					 fn->arg_type[arg - 1] & MEM_WRITE ?
8416 					 BPF_WRITE : BPF_READ,
8417 					 true, meta);
8418 		break;
8419 	case ARG_PTR_TO_DYNPTR:
8420 		err = process_dynptr_func(env, reg, argno_from_reg(regno), insn_idx, arg_type, &meta->ref_obj,
8421 					  &meta->dynptr);
8422 		if (err)
8423 			return err;
8424 		break;
8425 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8426 		if (!tnum_is_const(reg->var_off)) {
8427 			verbose(env, "R%d is not a known constant'\n",
8428 				regno);
8429 			return -EACCES;
8430 		}
8431 		meta->mem_size = reg->var_off.value;
8432 		err = mark_chain_precision(env, regno);
8433 		if (err)
8434 			return err;
8435 		break;
8436 	case ARG_PTR_TO_CONST_STR:
8437 	{
8438 		err = check_arg_const_str(env, reg, argno_from_reg(regno));
8439 		if (err)
8440 			return err;
8441 		break;
8442 	}
8443 	case ARG_KPTR_XCHG_DEST:
8444 		err = process_kptr_func(env, regno, meta);
8445 		if (err)
8446 			return err;
8447 		break;
8448 	}
8449 
8450 	return err;
8451 }
8452 
8453 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8454 {
8455 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8456 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8457 
8458 	if (func_id != BPF_FUNC_map_update_elem &&
8459 	    func_id != BPF_FUNC_map_delete_elem)
8460 		return false;
8461 
8462 	/* It's not possible to get access to a locked struct sock in these
8463 	 * contexts, so updating is safe.
8464 	 */
8465 	switch (type) {
8466 	case BPF_PROG_TYPE_TRACING:
8467 		if (eatype == BPF_TRACE_ITER)
8468 			return true;
8469 		break;
8470 	case BPF_PROG_TYPE_SOCK_OPS:
8471 		/* map_update allowed only via dedicated helpers with event type checks */
8472 		if (func_id == BPF_FUNC_map_delete_elem)
8473 			return true;
8474 		break;
8475 	case BPF_PROG_TYPE_SOCKET_FILTER:
8476 	case BPF_PROG_TYPE_SCHED_CLS:
8477 	case BPF_PROG_TYPE_SCHED_ACT:
8478 	case BPF_PROG_TYPE_XDP:
8479 	case BPF_PROG_TYPE_SK_REUSEPORT:
8480 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8481 	case BPF_PROG_TYPE_SK_LOOKUP:
8482 		return true;
8483 	default:
8484 		break;
8485 	}
8486 
8487 	verbose(env, "cannot update sockmap in this context\n");
8488 	return false;
8489 }
8490 
8491 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8492 {
8493 	return env->prog->jit_requested &&
8494 	       bpf_jit_supports_subprog_tailcalls();
8495 }
8496 
8497 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8498 					struct bpf_map *map, int func_id)
8499 {
8500 	if (!map)
8501 		return 0;
8502 
8503 	/* We need a two way check, first is from map perspective ... */
8504 	switch (map->map_type) {
8505 	case BPF_MAP_TYPE_PROG_ARRAY:
8506 		if (func_id != BPF_FUNC_tail_call)
8507 			goto error;
8508 		break;
8509 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8510 		if (func_id != BPF_FUNC_perf_event_read &&
8511 		    func_id != BPF_FUNC_perf_event_output &&
8512 		    func_id != BPF_FUNC_skb_output &&
8513 		    func_id != BPF_FUNC_perf_event_read_value &&
8514 		    func_id != BPF_FUNC_xdp_output)
8515 			goto error;
8516 		break;
8517 	case BPF_MAP_TYPE_RINGBUF:
8518 		if (func_id != BPF_FUNC_ringbuf_output &&
8519 		    func_id != BPF_FUNC_ringbuf_reserve &&
8520 		    func_id != BPF_FUNC_ringbuf_query &&
8521 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8522 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8523 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8524 			goto error;
8525 		break;
8526 	case BPF_MAP_TYPE_USER_RINGBUF:
8527 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8528 			goto error;
8529 		break;
8530 	case BPF_MAP_TYPE_STACK_TRACE:
8531 		if (func_id != BPF_FUNC_get_stackid)
8532 			goto error;
8533 		break;
8534 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8535 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8536 		    func_id != BPF_FUNC_current_task_under_cgroup)
8537 			goto error;
8538 		break;
8539 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8540 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8541 		if (func_id != BPF_FUNC_get_local_storage)
8542 			goto error;
8543 		break;
8544 	case BPF_MAP_TYPE_DEVMAP:
8545 	case BPF_MAP_TYPE_DEVMAP_HASH:
8546 		if (func_id != BPF_FUNC_redirect_map &&
8547 		    func_id != BPF_FUNC_map_lookup_elem)
8548 			goto error;
8549 		break;
8550 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8551 	 * appear.
8552 	 */
8553 	case BPF_MAP_TYPE_CPUMAP:
8554 		if (func_id != BPF_FUNC_redirect_map)
8555 			goto error;
8556 		break;
8557 	case BPF_MAP_TYPE_XSKMAP:
8558 		if (func_id != BPF_FUNC_redirect_map &&
8559 		    func_id != BPF_FUNC_map_lookup_elem)
8560 			goto error;
8561 		break;
8562 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8563 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8564 		if (func_id != BPF_FUNC_map_lookup_elem)
8565 			goto error;
8566 		break;
8567 	case BPF_MAP_TYPE_SOCKMAP:
8568 		if (func_id != BPF_FUNC_sk_redirect_map &&
8569 		    func_id != BPF_FUNC_sock_map_update &&
8570 		    func_id != BPF_FUNC_msg_redirect_map &&
8571 		    func_id != BPF_FUNC_sk_select_reuseport &&
8572 		    func_id != BPF_FUNC_map_lookup_elem &&
8573 		    !may_update_sockmap(env, func_id))
8574 			goto error;
8575 		break;
8576 	case BPF_MAP_TYPE_SOCKHASH:
8577 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8578 		    func_id != BPF_FUNC_sock_hash_update &&
8579 		    func_id != BPF_FUNC_msg_redirect_hash &&
8580 		    func_id != BPF_FUNC_sk_select_reuseport &&
8581 		    func_id != BPF_FUNC_map_lookup_elem &&
8582 		    !may_update_sockmap(env, func_id))
8583 			goto error;
8584 		break;
8585 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8586 		if (func_id != BPF_FUNC_sk_select_reuseport)
8587 			goto error;
8588 		break;
8589 	case BPF_MAP_TYPE_QUEUE:
8590 	case BPF_MAP_TYPE_STACK:
8591 		if (func_id != BPF_FUNC_map_peek_elem &&
8592 		    func_id != BPF_FUNC_map_pop_elem &&
8593 		    func_id != BPF_FUNC_map_push_elem)
8594 			goto error;
8595 		break;
8596 	case BPF_MAP_TYPE_SK_STORAGE:
8597 		if (func_id != BPF_FUNC_sk_storage_get &&
8598 		    func_id != BPF_FUNC_sk_storage_delete &&
8599 		    func_id != BPF_FUNC_kptr_xchg)
8600 			goto error;
8601 		break;
8602 	case BPF_MAP_TYPE_INODE_STORAGE:
8603 		if (func_id != BPF_FUNC_inode_storage_get &&
8604 		    func_id != BPF_FUNC_inode_storage_delete &&
8605 		    func_id != BPF_FUNC_kptr_xchg)
8606 			goto error;
8607 		break;
8608 	case BPF_MAP_TYPE_TASK_STORAGE:
8609 		if (func_id != BPF_FUNC_task_storage_get &&
8610 		    func_id != BPF_FUNC_task_storage_delete &&
8611 		    func_id != BPF_FUNC_kptr_xchg)
8612 			goto error;
8613 		break;
8614 	case BPF_MAP_TYPE_CGRP_STORAGE:
8615 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8616 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8617 		    func_id != BPF_FUNC_kptr_xchg)
8618 			goto error;
8619 		break;
8620 	case BPF_MAP_TYPE_BLOOM_FILTER:
8621 		if (func_id != BPF_FUNC_map_peek_elem &&
8622 		    func_id != BPF_FUNC_map_push_elem)
8623 			goto error;
8624 		break;
8625 	case BPF_MAP_TYPE_INSN_ARRAY:
8626 		goto error;
8627 	default:
8628 		break;
8629 	}
8630 
8631 	/* ... and second from the function itself. */
8632 	switch (func_id) {
8633 	case BPF_FUNC_tail_call:
8634 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8635 			goto error;
8636 		if (env->subprog_cnt > 1 && !bpf_allow_tail_call_in_subprogs(env)) {
8637 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
8638 			return -EINVAL;
8639 		}
8640 		break;
8641 	case BPF_FUNC_perf_event_read:
8642 	case BPF_FUNC_perf_event_output:
8643 	case BPF_FUNC_perf_event_read_value:
8644 	case BPF_FUNC_skb_output:
8645 	case BPF_FUNC_xdp_output:
8646 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8647 			goto error;
8648 		break;
8649 	case BPF_FUNC_ringbuf_output:
8650 	case BPF_FUNC_ringbuf_reserve:
8651 	case BPF_FUNC_ringbuf_query:
8652 	case BPF_FUNC_ringbuf_reserve_dynptr:
8653 	case BPF_FUNC_ringbuf_submit_dynptr:
8654 	case BPF_FUNC_ringbuf_discard_dynptr:
8655 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8656 			goto error;
8657 		break;
8658 	case BPF_FUNC_user_ringbuf_drain:
8659 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8660 			goto error;
8661 		break;
8662 	case BPF_FUNC_get_stackid:
8663 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8664 			goto error;
8665 		break;
8666 	case BPF_FUNC_current_task_under_cgroup:
8667 	case BPF_FUNC_skb_under_cgroup:
8668 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8669 			goto error;
8670 		break;
8671 	case BPF_FUNC_redirect_map:
8672 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8673 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8674 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8675 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8676 			goto error;
8677 		break;
8678 	case BPF_FUNC_sk_redirect_map:
8679 	case BPF_FUNC_msg_redirect_map:
8680 	case BPF_FUNC_sock_map_update:
8681 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8682 			goto error;
8683 		break;
8684 	case BPF_FUNC_sk_redirect_hash:
8685 	case BPF_FUNC_msg_redirect_hash:
8686 	case BPF_FUNC_sock_hash_update:
8687 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8688 			goto error;
8689 		break;
8690 	case BPF_FUNC_get_local_storage:
8691 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8692 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8693 			goto error;
8694 		break;
8695 	case BPF_FUNC_sk_select_reuseport:
8696 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8697 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8698 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8699 			goto error;
8700 		break;
8701 	case BPF_FUNC_map_pop_elem:
8702 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8703 		    map->map_type != BPF_MAP_TYPE_STACK)
8704 			goto error;
8705 		break;
8706 	case BPF_FUNC_map_peek_elem:
8707 	case BPF_FUNC_map_push_elem:
8708 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8709 		    map->map_type != BPF_MAP_TYPE_STACK &&
8710 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8711 			goto error;
8712 		break;
8713 	case BPF_FUNC_map_lookup_percpu_elem:
8714 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8715 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8716 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8717 			goto error;
8718 		break;
8719 	case BPF_FUNC_sk_storage_get:
8720 	case BPF_FUNC_sk_storage_delete:
8721 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8722 			goto error;
8723 		break;
8724 	case BPF_FUNC_inode_storage_get:
8725 	case BPF_FUNC_inode_storage_delete:
8726 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8727 			goto error;
8728 		break;
8729 	case BPF_FUNC_task_storage_get:
8730 	case BPF_FUNC_task_storage_delete:
8731 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8732 			goto error;
8733 		break;
8734 	case BPF_FUNC_cgrp_storage_get:
8735 	case BPF_FUNC_cgrp_storage_delete:
8736 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8737 			goto error;
8738 		break;
8739 	default:
8740 		break;
8741 	}
8742 
8743 	return 0;
8744 error:
8745 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
8746 		map->map_type, func_id_name(func_id), func_id);
8747 	return -EINVAL;
8748 }
8749 
8750 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8751 {
8752 	int count = 0;
8753 
8754 	if (arg_type_is_raw_mem(fn->arg1_type))
8755 		count++;
8756 	if (arg_type_is_raw_mem(fn->arg2_type))
8757 		count++;
8758 	if (arg_type_is_raw_mem(fn->arg3_type))
8759 		count++;
8760 	if (arg_type_is_raw_mem(fn->arg4_type))
8761 		count++;
8762 	if (arg_type_is_raw_mem(fn->arg5_type))
8763 		count++;
8764 
8765 	/* We only support one arg being in raw mode at the moment,
8766 	 * which is sufficient for the helper functions we have
8767 	 * right now.
8768 	 */
8769 	return count <= 1;
8770 }
8771 
8772 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8773 {
8774 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8775 	bool has_size = fn->arg_size[arg] != 0;
8776 	bool is_next_size = false;
8777 
8778 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8779 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8780 
8781 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8782 		return is_next_size;
8783 
8784 	return has_size == is_next_size || is_next_size == is_fixed;
8785 }
8786 
8787 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8788 {
8789 	/* bpf_xxx(..., buf, len) call will access 'len'
8790 	 * bytes from memory 'buf'. Both arg types need
8791 	 * to be paired, so make sure there's no buggy
8792 	 * helper function specification.
8793 	 */
8794 	if (arg_type_is_mem_size(fn->arg1_type) ||
8795 	    check_args_pair_invalid(fn, 0) ||
8796 	    check_args_pair_invalid(fn, 1) ||
8797 	    check_args_pair_invalid(fn, 2) ||
8798 	    check_args_pair_invalid(fn, 3) ||
8799 	    check_args_pair_invalid(fn, 4))
8800 		return false;
8801 
8802 	return true;
8803 }
8804 
8805 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8806 {
8807 	int i;
8808 
8809 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8810 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8811 			return !!fn->arg_btf_id[i];
8812 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8813 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
8814 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8815 		    /* arg_btf_id and arg_size are in a union. */
8816 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8817 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8818 			return false;
8819 	}
8820 
8821 	return true;
8822 }
8823 
8824 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn)
8825 {
8826 	int i;
8827 
8828 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8829 		enum bpf_arg_type arg_type = fn->arg_type[i];
8830 
8831 		if (base_type(arg_type) != ARG_PTR_TO_MEM)
8832 			continue;
8833 		if (!(arg_type & (MEM_WRITE | MEM_RDONLY)))
8834 			return false;
8835 	}
8836 
8837 	return true;
8838 }
8839 
8840 static bool check_proto_release_reg(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta)
8841 {
8842 	int i;
8843 
8844 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8845 		enum bpf_arg_type arg_type = fn->arg_type[i];
8846 
8847 		if (arg_type_is_release(arg_type)) {
8848 			if (meta->release_regno)
8849 				return false;
8850 			meta->release_regno = i + 1;
8851 		}
8852 	}
8853 
8854 	return true;
8855 }
8856 
8857 static int check_func_proto(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta)
8858 {
8859 	return check_raw_mode_ok(fn) &&
8860 	       check_arg_pair_ok(fn) &&
8861 	       check_mem_arg_rw_flag_ok(fn) &&
8862 	       check_proto_release_reg(fn, meta) &&
8863 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
8864 }
8865 
8866 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8867  * are now invalid, so turn them into unknown SCALAR_VALUE.
8868  *
8869  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8870  * since these slices point to packet data.
8871  */
8872 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8873 {
8874 	struct bpf_func_state *state;
8875 	struct bpf_reg_state *reg;
8876 
8877 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8878 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8879 			mark_reg_invalid(env, reg);
8880 	}));
8881 }
8882 
8883 enum {
8884 	AT_PKT_END = -1,
8885 	BEYOND_PKT_END = -2,
8886 };
8887 
8888 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8889 {
8890 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8891 	struct bpf_reg_state *reg = &state->regs[regn];
8892 
8893 	if (reg->type != PTR_TO_PACKET)
8894 		/* PTR_TO_PACKET_META is not supported yet */
8895 		return;
8896 
8897 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8898 	 * How far beyond pkt_end it goes is unknown.
8899 	 * if (!range_open) it's the case of pkt >= pkt_end
8900 	 * if (range_open) it's the case of pkt > pkt_end
8901 	 * hence this pointer is at least 1 byte bigger than pkt_end
8902 	 */
8903 	if (range_open)
8904 		reg->range = BEYOND_PKT_END;
8905 	else
8906 		reg->range = AT_PKT_END;
8907 }
8908 
8909 static int release_reference_nomark(struct bpf_verifier_state *state, int id)
8910 {
8911 	int i;
8912 
8913 	for (i = 0; i < state->acquired_refs; i++) {
8914 		if (state->refs[i].type != REF_TYPE_PTR)
8915 			continue;
8916 		if (state->refs[i].id == id) {
8917 			release_reference_state(state, i);
8918 			return 0;
8919 		}
8920 	}
8921 	return -EINVAL;
8922 }
8923 
8924 static int idstack_push(struct bpf_idmap *idmap, u32 id)
8925 {
8926 	int i;
8927 
8928 	if (!id)
8929 		return 0;
8930 
8931 	for (i = 0; i < idmap->cnt; i++)
8932 		if (idmap->map[i].old == id)
8933 			return 0;
8934 
8935 	if (WARN_ON_ONCE(idmap->cnt >= BPF_ID_MAP_SIZE))
8936 		return -EFAULT;
8937 
8938 	idmap->map[idmap->cnt++].old = id;
8939 	return 0;
8940 }
8941 
8942 static int idstack_pop(struct bpf_idmap *idmap)
8943 {
8944 	if (!idmap->cnt)
8945 		return 0;
8946 
8947 	return idmap->map[--idmap->cnt].old;
8948 }
8949 
8950 /* Release id and objects derived from it iteratively in a DFS manner */
8951 static int release_reference(struct bpf_verifier_env *env, int id)
8952 {
8953 	u32 mask = (1 << STACK_SPILL) | (1 << STACK_DYNPTR);
8954 	struct bpf_verifier_state *vstate = env->cur_state;
8955 	struct bpf_idmap *idstack = &env->idmap_scratch;
8956 	struct bpf_stack_state *stack;
8957 	struct bpf_func_state *state;
8958 	struct bpf_reg_state *reg;
8959 	int i, err;
8960 
8961 	idstack->cnt = 0;
8962 	err = idstack_push(idstack, id);
8963 	if (err)
8964 		return err;
8965 
8966 	if (find_reference_state(vstate, id))
8967 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
8968 
8969 	while ((id = idstack_pop(idstack))) {
8970 		/*
8971 		 * Child references are inaccessible after parent is released,
8972 		 * any child references that exist at this point are a leak.
8973 		 */
8974 		for (i = 0; i < vstate->acquired_refs; i++) {
8975 			if (vstate->refs[i].type != REF_TYPE_PTR)
8976 				continue;
8977 			if (vstate->refs[i].parent_id != id)
8978 				continue;
8979 			verbose(env, "Leaking reference id=%d alloc_insn=%d. Release it first.\n",
8980 				vstate->refs[i].id, vstate->refs[i].insn_idx);
8981 			return -EINVAL;
8982 		}
8983 
8984 		bpf_for_each_reg_in_vstate_mask(vstate, state, reg, stack, mask, ({
8985 			if (reg->id != id && reg->parent_id != id)
8986 				continue;
8987 
8988 			/* Free objects derived from the current object */
8989 			if (reg->parent_id == id) {
8990 				err = idstack_push(idstack, reg->id);
8991 				if (err)
8992 					return err;
8993 			}
8994 
8995 			if (!stack || stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL)
8996 				mark_reg_invalid(env, reg);
8997 			else if (stack->slot_type[BPF_REG_SIZE - 1] == STACK_DYNPTR)
8998 				invalidate_dynptr(env, stack);
8999 		}));
9000 	}
9001 
9002 	return 0;
9003 }
9004 
9005 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9006 {
9007 	struct bpf_func_state *unused;
9008 	struct bpf_reg_state *reg;
9009 
9010 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9011 		if (type_is_non_owning_ref(reg->type))
9012 			mark_reg_invalid(env, reg);
9013 	}));
9014 }
9015 
9016 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env)
9017 {
9018 	struct bpf_stack_state *stack;
9019 	struct bpf_func_state *state;
9020 	struct bpf_reg_state *reg;
9021 	u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
9022 
9023 	bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, clear_mask, ({
9024 		if (reg->type & MEM_RCU) {
9025 			reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
9026 			reg->type |= PTR_UNTRUSTED;
9027 		}
9028 	}));
9029 }
9030 
9031 static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id)
9032 {
9033 	struct bpf_func_state *state;
9034 	struct bpf_reg_state *reg;
9035 	int err;
9036 
9037 	err = release_reference_nomark(env->cur_state, id);
9038 
9039 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9040 		if (reg->id != id)
9041 			continue;
9042 		if ((reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
9043 			reg->id = 0;
9044 			reg->type &= ~MEM_ALLOC;
9045 			reg->type |= MEM_RCU;
9046 		}
9047 	}));
9048 
9049 	return err;
9050 }
9051 
9052 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9053 				    struct bpf_reg_state *regs)
9054 {
9055 	int i;
9056 
9057 	/* after the call registers r0 - r5 were scratched */
9058 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9059 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
9060 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9061 	}
9062 }
9063 
9064 static void invalidate_outgoing_stack_args(const struct bpf_verifier_env *env,
9065 					   struct bpf_func_state *state)
9066 {
9067 	int i, nslots = state->out_stack_arg_cnt;
9068 
9069 	for (i = 0; i < nslots; i++)
9070 		bpf_mark_reg_not_init(env, &state->stack_arg_regs[i]);
9071 }
9072 
9073 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9074 				   struct bpf_func_state *caller,
9075 				   struct bpf_func_state *callee,
9076 				   int insn_idx);
9077 
9078 static int set_callee_state(struct bpf_verifier_env *env,
9079 			    struct bpf_func_state *caller,
9080 			    struct bpf_func_state *callee, int insn_idx);
9081 
9082 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9083 			    set_callee_state_fn set_callee_state_cb,
9084 			    struct bpf_verifier_state *state)
9085 {
9086 	struct bpf_func_state *caller, *callee;
9087 	int err;
9088 
9089 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9090 		verbose(env, "the call stack of %d frames is too deep\n",
9091 			state->curframe + 2);
9092 		return -E2BIG;
9093 	}
9094 
9095 	if (state->frame[state->curframe + 1]) {
9096 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
9097 		return -EFAULT;
9098 	}
9099 
9100 	caller = state->frame[state->curframe];
9101 	callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT);
9102 	if (!callee)
9103 		return -ENOMEM;
9104 	state->frame[state->curframe + 1] = callee;
9105 
9106 	/* callee cannot access r0, r6 - r9 for reading and has to write
9107 	 * into its own stack before reading from it.
9108 	 * callee can read/write into caller's stack
9109 	 */
9110 	init_func_state(env, callee,
9111 			/* remember the callsite, it will be used by bpf_exit */
9112 			callsite,
9113 			state->curframe + 1 /* frameno within this callchain */,
9114 			subprog /* subprog number within this prog */);
9115 	err = set_callee_state_cb(env, caller, callee, callsite);
9116 	if (err)
9117 		goto err_out;
9118 
9119 	/* only increment it after check_reg_arg() finished */
9120 	state->curframe++;
9121 
9122 	return 0;
9123 
9124 err_out:
9125 	free_func_state(callee);
9126 	state->frame[state->curframe + 1] = NULL;
9127 	return err;
9128 }
9129 
9130 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9131 				    const struct btf *btf,
9132 				    struct bpf_reg_state *regs)
9133 {
9134 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
9135 	struct bpf_func_state *caller = cur_func(env);
9136 	struct bpf_verifier_log *log = &env->log;
9137 	struct ref_obj_desc ref_obj = {};
9138 	u32 i;
9139 	int ret, err;
9140 
9141 	ret = btf_prepare_func_args(env, subprog);
9142 	if (ret) {
9143 		if (bpf_in_stack_arg_cnt(sub) > 0) {
9144 			err = check_outgoing_stack_args(env, caller, sub->arg_cnt);
9145 			if (err)
9146 				return err;
9147 		}
9148 		return ret;
9149 	}
9150 
9151 	ret = check_outgoing_stack_args(env, caller, sub->arg_cnt);
9152 	if (ret)
9153 		return ret;
9154 
9155 	/* check that BTF function arguments match actual types that the
9156 	 * verifier sees.
9157 	 */
9158 	for (i = 0; i < sub->arg_cnt; i++) {
9159 		argno_t argno = argno_from_arg(i + 1);
9160 		struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i);
9161 		struct bpf_subprog_arg_info *arg = &sub->args[i];
9162 
9163 		if (arg->arg_type == ARG_ANYTHING) {
9164 			if (reg->type != SCALAR_VALUE) {
9165 				bpf_log(log, "%s is not a scalar\n", reg_arg_name(env, argno));
9166 				return -EINVAL;
9167 			}
9168 		} else if (arg->arg_type & PTR_UNTRUSTED) {
9169 			/*
9170 			 * Anything is allowed for untrusted arguments, as these are
9171 			 * read-only and probe read instructions would protect against
9172 			 * invalid memory access.
9173 			 */
9174 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
9175 			ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_CTX);
9176 			if (ret < 0)
9177 				return ret;
9178 			/* If function expects ctx type in BTF check that caller
9179 			 * is passing PTR_TO_CTX.
9180 			 */
9181 			if (reg->type != PTR_TO_CTX) {
9182 				bpf_log(log, "%s expects pointer to ctx\n",
9183 					reg_arg_name(env, argno));
9184 				return -EINVAL;
9185 			}
9186 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9187 			ret = check_func_arg_reg_off(env, reg, argno, ARG_DONTCARE);
9188 			if (ret < 0)
9189 				return ret;
9190 			if (check_mem_reg(env, reg, argno, arg->mem_size))
9191 				return -EINVAL;
9192 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9193 				bpf_log(log, "%s is expected to be non-NULL\n",
9194 					reg_arg_name(env, argno));
9195 				return -EINVAL;
9196 			}
9197 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
9198 			/*
9199 			 * Can pass any value and the kernel won't crash, but
9200 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
9201 			 * else is a bug in the bpf program. Point it out to
9202 			 * the user at the verification time instead of
9203 			 * run-time debug nightmare.
9204 			 */
9205 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
9206 				bpf_log(log, "%s is not a pointer to arena or scalar.\n",
9207 					reg_arg_name(env, argno));
9208 				return -EINVAL;
9209 			}
9210 		} else if (arg->arg_type == ARG_PTR_TO_DYNPTR) {
9211 			ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_DYNPTR);
9212 			if (ret)
9213 				return ret;
9214 
9215 			ret = process_dynptr_func(env, reg, argno, -1, arg->arg_type, &ref_obj, NULL);
9216 			if (ret)
9217 				return ret;
9218 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
9219 			struct bpf_call_arg_meta meta;
9220 			int err;
9221 
9222 			if (bpf_register_is_null(reg) && type_may_be_null(arg->arg_type))
9223 				continue;
9224 
9225 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
9226 			err = check_reg_type(env, reg, argno, arg->arg_type, &arg->btf_id, &meta);
9227 			err = err ?: check_func_arg_reg_off(env, reg, argno, arg->arg_type);
9228 			if (err)
9229 				return err;
9230 		} else {
9231 			verifier_bug(env, "unrecognized %s type %d",
9232 				     reg_arg_name(env, argno), arg->arg_type);
9233 			return -EFAULT;
9234 		}
9235 	}
9236 
9237 	return 0;
9238 }
9239 
9240 /* Compare BTF of a function call with given bpf_reg_state.
9241  * Returns:
9242  * EFAULT - there is a verifier bug. Abort verification.
9243  * EINVAL - there is a type mismatch or BTF is not available.
9244  * 0 - BTF matches with what bpf_reg_state expects.
9245  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9246  */
9247 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9248 				  struct bpf_reg_state *regs)
9249 {
9250 	struct bpf_prog *prog = env->prog;
9251 	struct btf *btf = prog->aux->btf;
9252 	u32 btf_id;
9253 	int err;
9254 
9255 	if (!prog->aux->func_info)
9256 		return -EINVAL;
9257 
9258 	btf_id = prog->aux->func_info[subprog].type_id;
9259 	if (!btf_id)
9260 		return -EFAULT;
9261 
9262 	if (prog->aux->func_info_aux[subprog].unreliable)
9263 		return -EINVAL;
9264 
9265 	err = btf_check_func_arg_match(env, subprog, btf, regs);
9266 	/* Compiler optimizations can remove arguments from static functions
9267 	 * or mismatched type can be passed into a global function.
9268 	 * In such cases mark the function as unreliable from BTF point of view.
9269 	 */
9270 	if (err)
9271 		prog->aux->func_info_aux[subprog].unreliable = true;
9272 	return err;
9273 }
9274 
9275 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9276 			      int insn_idx, int subprog,
9277 			      set_callee_state_fn set_callee_state_cb)
9278 {
9279 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9280 	struct bpf_func_state *caller, *callee;
9281 	int err;
9282 
9283 	caller = state->frame[state->curframe];
9284 	err = btf_check_subprog_call(env, subprog, caller->regs);
9285 	if (err == -EFAULT)
9286 		return err;
9287 
9288 	/* set_callee_state is used for direct subprog calls, but we are
9289 	 * interested in validating only BPF helpers that can call subprogs as
9290 	 * callbacks
9291 	 */
9292 	env->subprog_info[subprog].is_cb = true;
9293 	if (bpf_pseudo_kfunc_call(insn) &&
9294 	    !is_callback_calling_kfunc(insn->imm)) {
9295 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
9296 			     func_id_name(insn->imm), insn->imm);
9297 		return -EFAULT;
9298 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9299 		   !is_callback_calling_function(insn->imm)) { /* helper */
9300 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
9301 			     func_id_name(insn->imm), insn->imm);
9302 		return -EFAULT;
9303 	}
9304 
9305 	if (bpf_is_async_callback_calling_insn(insn)) {
9306 		struct bpf_verifier_state *async_cb;
9307 
9308 		/* there is no real recursion here. timer and workqueue callbacks are async */
9309 		env->subprog_info[subprog].is_async_cb = true;
9310 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9311 					 insn_idx, subprog,
9312 					 is_async_cb_sleepable(env, insn));
9313 		if (IS_ERR(async_cb))
9314 			return PTR_ERR(async_cb);
9315 		callee = async_cb->frame[0];
9316 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9317 
9318 		/* Convert bpf_timer_set_callback() args into timer callback args */
9319 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9320 		if (err)
9321 			return err;
9322 
9323 		return 0;
9324 	}
9325 
9326 	/* for callback functions enqueue entry to callback and
9327 	 * proceed with next instruction within current frame.
9328 	 */
9329 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9330 	if (IS_ERR(callback_state))
9331 		return PTR_ERR(callback_state);
9332 
9333 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9334 			       callback_state);
9335 	if (err)
9336 		return err;
9337 
9338 	callback_state->callback_unroll_depth++;
9339 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9340 	caller->callback_depth = 0;
9341 	return 0;
9342 }
9343 
9344 static int process_bpf_exit_full(struct bpf_verifier_env *env,
9345 				 bool *do_print_state, bool exception_exit);
9346 
9347 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9348 			   int *insn_idx)
9349 {
9350 	struct bpf_verifier_state *state = env->cur_state;
9351 	struct bpf_subprog_info *caller_info;
9352 	u16 callee_incoming, stack_arg_cnt;
9353 	struct bpf_func_state *caller;
9354 	int err, subprog, target_insn;
9355 
9356 	target_insn = *insn_idx + insn->imm + 1;
9357 	subprog = bpf_find_subprog(env, target_insn);
9358 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
9359 			    target_insn))
9360 		return -EFAULT;
9361 
9362 	caller = state->frame[state->curframe];
9363 	err = btf_check_subprog_call(env, subprog, caller->regs);
9364 	if (err == -EFAULT)
9365 		return err;
9366 	if (bpf_subprog_is_global(env, subprog)) {
9367 		const char *sub_name = subprog_name(env, subprog);
9368 
9369 		if (env->cur_state->active_locks) {
9370 			verbose(env, "global function calls are not allowed while holding a lock,\n"
9371 				     "use static function instead\n");
9372 			return -EINVAL;
9373 		}
9374 
9375 		if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) {
9376 			verbose(env, "sleepable global function %s() called in %s\n",
9377 				sub_name, non_sleepable_context_description(env));
9378 			return -EINVAL;
9379 		}
9380 
9381 		if (err) {
9382 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9383 				subprog, sub_name);
9384 			return err;
9385 		}
9386 
9387 		if (env->log.level & BPF_LOG_LEVEL)
9388 			verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9389 				subprog, sub_name);
9390 		if (env->subprog_info[subprog].changes_pkt_data)
9391 			clear_all_pkt_pointers(env);
9392 		/* mark global subprog for verifying after main prog */
9393 		subprog_aux(env, subprog)->called = true;
9394 		clear_caller_saved_regs(env, caller->regs);
9395 		invalidate_outgoing_stack_args(env, cur_func(env));
9396 
9397 		/* All non-void global functions return a 64-bit SCALAR_VALUE. */
9398 		if (!subprog_returns_void(env, subprog)) {
9399 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
9400 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9401 		}
9402 
9403 		if (env->subprog_info[subprog].might_throw) {
9404 			struct bpf_verifier_state *branch;
9405 
9406 			branch = push_stack(env, *insn_idx + 1, *insn_idx, false);
9407 			if (IS_ERR(branch)) {
9408 				verbose(env, "failed to push state for global subprog exception path\n");
9409 				return PTR_ERR(branch);
9410 			}
9411 			return process_bpf_exit_full(env, NULL, true);
9412 		}
9413 
9414 		/* continue with next insn after call */
9415 		return 0;
9416 	}
9417 
9418 	/*
9419 	 * Track caller's total stack arg count (incoming + max outgoing).
9420 	 * This is needed so the JIT knows how much stack arg space to allocate.
9421 	 */
9422 	caller_info = &env->subprog_info[caller->subprogno];
9423 	callee_incoming = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]);
9424 	stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + callee_incoming;
9425 	if (stack_arg_cnt > caller_info->stack_arg_cnt)
9426 		caller_info->stack_arg_cnt = stack_arg_cnt;
9427 
9428 	/* for regular function entry setup new frame and continue
9429 	 * from that frame.
9430 	 */
9431 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9432 	if (err)
9433 		return err;
9434 
9435 	clear_caller_saved_regs(env, caller->regs);
9436 
9437 	/* and go analyze first insn of the callee */
9438 	*insn_idx = env->subprog_info[subprog].start - 1;
9439 
9440 	if (env->log.level & BPF_LOG_LEVEL) {
9441 		verbose(env, "caller:\n");
9442 		print_verifier_state(env, state, caller->frameno, true);
9443 		verbose(env, "callee:\n");
9444 		print_verifier_state(env, state, state->curframe, true);
9445 	}
9446 
9447 	return 0;
9448 }
9449 
9450 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9451 				   struct bpf_func_state *caller,
9452 				   struct bpf_func_state *callee)
9453 {
9454 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9455 	 *      void *callback_ctx, u64 flags);
9456 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9457 	 *      void *callback_ctx);
9458 	 */
9459 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9460 
9461 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9462 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9463 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9464 
9465 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9466 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9467 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9468 
9469 	/* pointer to stack or null */
9470 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9471 
9472 	/* unused */
9473 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9474 	return 0;
9475 }
9476 
9477 static int set_callee_state(struct bpf_verifier_env *env,
9478 			    struct bpf_func_state *caller,
9479 			    struct bpf_func_state *callee, int insn_idx)
9480 {
9481 	int i;
9482 
9483 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9484 	 * pointers, which connects us up to the liveness chain
9485 	 */
9486 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9487 		callee->regs[i] = caller->regs[i];
9488 	return 0;
9489 }
9490 
9491 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9492 				       struct bpf_func_state *caller,
9493 				       struct bpf_func_state *callee,
9494 				       int insn_idx)
9495 {
9496 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9497 	struct bpf_map *map;
9498 	int err;
9499 
9500 	/* valid map_ptr and poison value does not matter */
9501 	map = insn_aux->map_ptr_state.map_ptr;
9502 	if (!map->ops->map_set_for_each_callback_args ||
9503 	    !map->ops->map_for_each_callback) {
9504 		verbose(env, "callback function not allowed for map\n");
9505 		return -ENOTSUPP;
9506 	}
9507 
9508 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9509 	if (err)
9510 		return err;
9511 
9512 	callee->in_callback_fn = true;
9513 	callee->callback_ret_range = retval_range(0, 1);
9514 	return 0;
9515 }
9516 
9517 static int set_loop_callback_state(struct bpf_verifier_env *env,
9518 				   struct bpf_func_state *caller,
9519 				   struct bpf_func_state *callee,
9520 				   int insn_idx)
9521 {
9522 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9523 	 *	    u64 flags);
9524 	 * callback_fn(u64 index, void *callback_ctx);
9525 	 */
9526 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9527 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9528 
9529 	/* unused */
9530 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9531 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9532 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9533 
9534 	callee->in_callback_fn = true;
9535 	callee->callback_ret_range = retval_range(0, 1);
9536 	return 0;
9537 }
9538 
9539 static int set_timer_callback_state(struct bpf_verifier_env *env,
9540 				    struct bpf_func_state *caller,
9541 				    struct bpf_func_state *callee,
9542 				    int insn_idx)
9543 {
9544 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9545 
9546 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9547 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9548 	 */
9549 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9550 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9551 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9552 
9553 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9554 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9555 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9556 
9557 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9558 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9559 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9560 
9561 	/* unused */
9562 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9563 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9564 	callee->in_async_callback_fn = true;
9565 	callee->callback_ret_range = retval_range(0, 0);
9566 	return 0;
9567 }
9568 
9569 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9570 				       struct bpf_func_state *caller,
9571 				       struct bpf_func_state *callee,
9572 				       int insn_idx)
9573 {
9574 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9575 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9576 	 * (callback_fn)(struct task_struct *task,
9577 	 *               struct vm_area_struct *vma, void *callback_ctx);
9578 	 */
9579 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9580 
9581 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9582 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9583 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9584 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9585 
9586 	/* pointer to stack or null */
9587 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9588 
9589 	/* unused */
9590 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9591 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9592 	callee->in_callback_fn = true;
9593 	callee->callback_ret_range = retval_range(0, 1);
9594 	return 0;
9595 }
9596 
9597 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9598 					   struct bpf_func_state *caller,
9599 					   struct bpf_func_state *callee,
9600 					   int insn_idx)
9601 {
9602 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9603 	 *			  callback_ctx, u64 flags);
9604 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9605 	 */
9606 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9607 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9608 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9609 
9610 	/* unused */
9611 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9612 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9613 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9614 
9615 	callee->in_callback_fn = true;
9616 	callee->callback_ret_range = retval_range(0, 1);
9617 	return 0;
9618 }
9619 
9620 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9621 					 struct bpf_func_state *caller,
9622 					 struct bpf_func_state *callee,
9623 					 int insn_idx)
9624 {
9625 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9626 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9627 	 *
9628 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9629 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9630 	 * by this point, so look at 'root'
9631 	 */
9632 	struct btf_field *field;
9633 
9634 	field = reg_find_field_offset(&caller->regs[BPF_REG_1],
9635 				      caller->regs[BPF_REG_1].var_off.value,
9636 				      BPF_RB_ROOT);
9637 	if (!field || !field->graph_root.value_btf_id)
9638 		return -EFAULT;
9639 
9640 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9641 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9642 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9643 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9644 
9645 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9646 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9647 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9648 	callee->in_callback_fn = true;
9649 	callee->callback_ret_range = retval_range(0, 1);
9650 	return 0;
9651 }
9652 
9653 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
9654 						 struct bpf_func_state *caller,
9655 						 struct bpf_func_state *callee,
9656 						 int insn_idx)
9657 {
9658 	struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
9659 
9660 	/*
9661 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9662 	 */
9663 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9664 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9665 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9666 
9667 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9668 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9669 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9670 
9671 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9672 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9673 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9674 
9675 	/* unused */
9676 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9677 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9678 	callee->in_async_callback_fn = true;
9679 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
9680 	return 0;
9681 }
9682 
9683 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9684 
9685 /* Are we currently verifying the callback for a rbtree helper that must
9686  * be called with lock held? If so, no need to complain about unreleased
9687  * lock
9688  */
9689 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9690 {
9691 	struct bpf_verifier_state *state = env->cur_state;
9692 	struct bpf_insn *insn = env->prog->insnsi;
9693 	struct bpf_func_state *callee;
9694 	int kfunc_btf_id;
9695 
9696 	if (!state->curframe)
9697 		return false;
9698 
9699 	callee = state->frame[state->curframe];
9700 
9701 	if (!callee->in_callback_fn)
9702 		return false;
9703 
9704 	kfunc_btf_id = insn[callee->callsite].imm;
9705 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9706 }
9707 
9708 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
9709 {
9710 	if (range.return_32bit)
9711 		return range.minval <= reg_s32_min(reg) && reg_s32_max(reg) <= range.maxval;
9712 	else
9713 		return range.minval <= reg_smin(reg) && reg_smax(reg) <= range.maxval;
9714 }
9715 
9716 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9717 {
9718 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9719 	struct bpf_func_state *caller, *callee;
9720 	struct bpf_reg_state *r0;
9721 	bool in_callback_fn;
9722 	int err;
9723 
9724 	callee = state->frame[state->curframe];
9725 	r0 = &callee->regs[BPF_REG_0];
9726 	if (r0->type == PTR_TO_STACK) {
9727 		/* technically it's ok to return caller's stack pointer
9728 		 * (or caller's caller's pointer) back to the caller,
9729 		 * since these pointers are valid. Only current stack
9730 		 * pointer will be invalid as soon as function exits,
9731 		 * but let's be conservative
9732 		 */
9733 		verbose(env, "cannot return stack pointer to the caller\n");
9734 		return -EINVAL;
9735 	}
9736 
9737 	caller = state->frame[state->curframe - 1];
9738 	if (callee->in_callback_fn) {
9739 		if (r0->type != SCALAR_VALUE) {
9740 			verbose(env, "R0 not a scalar value\n");
9741 			return -EACCES;
9742 		}
9743 
9744 		/* we are going to rely on register's precise value */
9745 		err = mark_chain_precision(env, BPF_REG_0);
9746 		if (err)
9747 			return err;
9748 
9749 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
9750 		if (!retval_range_within(callee->callback_ret_range, r0)) {
9751 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
9752 					       "At callback return", "R0");
9753 			return -EINVAL;
9754 		}
9755 		if (!bpf_calls_callback(env, callee->callsite)) {
9756 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
9757 				     *insn_idx, callee->callsite);
9758 			return -EFAULT;
9759 		}
9760 	} else {
9761 		/* return to the caller whatever r0 had in the callee */
9762 		caller->regs[BPF_REG_0] = *r0;
9763 	}
9764 
9765 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9766 	 * there function call logic would reschedule callback visit. If iteration
9767 	 * converges is_state_visited() would prune that visit eventually.
9768 	 */
9769 	in_callback_fn = callee->in_callback_fn;
9770 	if (in_callback_fn)
9771 		*insn_idx = callee->callsite;
9772 	else
9773 		*insn_idx = callee->callsite + 1;
9774 
9775 	if (env->log.level & BPF_LOG_LEVEL) {
9776 		verbose(env, "returning from callee:\n");
9777 		print_verifier_state(env, state, callee->frameno, true);
9778 		verbose(env, "to caller at %d:\n", *insn_idx);
9779 		print_verifier_state(env, state, caller->frameno, true);
9780 	}
9781 	/* clear everything in the callee. In case of exceptional exits using
9782 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9783 	free_func_state(callee);
9784 	state->frame[state->curframe--] = NULL;
9785 	invalidate_outgoing_stack_args(env, caller);
9786 
9787 	/* for callbacks widen imprecise scalars to make programs like below verify:
9788 	 *
9789 	 *   struct ctx { int i; }
9790 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9791 	 *   ...
9792 	 *   struct ctx = { .i = 0; }
9793 	 *   bpf_loop(100, cb, &ctx, 0);
9794 	 *
9795 	 * This is similar to what is done in process_iter_next_call() for open
9796 	 * coded iterators.
9797 	 */
9798 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9799 	if (prev_st) {
9800 		err = widen_imprecise_scalars(env, prev_st, state);
9801 		if (err)
9802 			return err;
9803 	}
9804 	return 0;
9805 }
9806 
9807 static int do_refine_retval_range(struct bpf_verifier_env *env,
9808 				  struct bpf_reg_state *regs, int ret_type,
9809 				  int func_id,
9810 				  struct bpf_call_arg_meta *meta)
9811 {
9812 	struct bpf_retval_range range;
9813 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9814 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9815 
9816 	if (ret_type != RET_INTEGER)
9817 		return 0;
9818 
9819 	switch (func_id) {
9820 	case BPF_FUNC_get_stack:
9821 	case BPF_FUNC_get_task_stack:
9822 	case BPF_FUNC_probe_read_str:
9823 	case BPF_FUNC_probe_read_kernel_str:
9824 	case BPF_FUNC_probe_read_user_str:
9825 		reg_set_srange64(ret_reg, -MAX_ERRNO, meta->msize_max_value);
9826 		reg_set_srange32(ret_reg, -MAX_ERRNO, meta->msize_max_value);
9827 		reg_bounds_sync(ret_reg);
9828 		break;
9829 	case BPF_FUNC_get_smp_processor_id:
9830 		reg_set_urange64(ret_reg, 0, nr_cpu_ids - 1);
9831 		reg_set_urange32(ret_reg, 0, nr_cpu_ids - 1);
9832 		reg_bounds_sync(ret_reg);
9833 		break;
9834 	case BPF_FUNC_get_retval:
9835 		/*
9836 		 * bpf_get_retval may see arbitrary value passed by bpf_prog_run_array_cg for
9837 		 * CGROUP_GETSOCKOPT type.
9838 		 */
9839 		if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT &&
9840 		    env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT)
9841 			break;
9842 
9843 		if (prog_type == BPF_PROG_TYPE_LSM &&
9844 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9845 			if (!env->prog->aux->attach_func_proto->type)
9846 				break;
9847 			bpf_lsm_get_retval_range(env->prog, &range);
9848 		} else {
9849 			range.minval = -MAX_ERRNO;
9850 			range.maxval = 0;
9851 		}
9852 
9853 		reg_set_srange64(ret_reg, range.minval, range.maxval);
9854 		reg_set_srange32(ret_reg, range.minval, range.maxval);
9855 		reg_bounds_sync(ret_reg);
9856 		break;
9857 	}
9858 
9859 	return reg_bounds_sanity_check(env, ret_reg, "retval");
9860 }
9861 
9862 static int
9863 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9864 		int func_id, int insn_idx)
9865 {
9866 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9867 	struct bpf_map *map = meta->map.ptr;
9868 
9869 	if (func_id != BPF_FUNC_tail_call &&
9870 	    func_id != BPF_FUNC_map_lookup_elem &&
9871 	    func_id != BPF_FUNC_map_update_elem &&
9872 	    func_id != BPF_FUNC_map_delete_elem &&
9873 	    func_id != BPF_FUNC_map_push_elem &&
9874 	    func_id != BPF_FUNC_map_pop_elem &&
9875 	    func_id != BPF_FUNC_map_peek_elem &&
9876 	    func_id != BPF_FUNC_for_each_map_elem &&
9877 	    func_id != BPF_FUNC_redirect_map &&
9878 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9879 		return 0;
9880 
9881 	if (map == NULL) {
9882 		verifier_bug(env, "expected map for helper call");
9883 		return -EFAULT;
9884 	}
9885 
9886 	/* In case of read-only, some additional restrictions
9887 	 * need to be applied in order to prevent altering the
9888 	 * state of the map from program side.
9889 	 */
9890 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9891 	    (func_id == BPF_FUNC_map_delete_elem ||
9892 	     func_id == BPF_FUNC_map_update_elem ||
9893 	     func_id == BPF_FUNC_map_push_elem ||
9894 	     func_id == BPF_FUNC_map_pop_elem)) {
9895 		verbose(env, "write into map forbidden\n");
9896 		return -EACCES;
9897 	}
9898 
9899 	if (!aux->map_ptr_state.map_ptr)
9900 		bpf_map_ptr_store(aux, meta->map.ptr,
9901 				  !meta->map.ptr->bypass_spec_v1, false);
9902 	else if (aux->map_ptr_state.map_ptr != meta->map.ptr)
9903 		bpf_map_ptr_store(aux, meta->map.ptr,
9904 				  !meta->map.ptr->bypass_spec_v1, true);
9905 	return 0;
9906 }
9907 
9908 static int
9909 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9910 		int func_id, int insn_idx)
9911 {
9912 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9913 	struct bpf_reg_state *reg;
9914 	struct bpf_map *map = meta->map.ptr;
9915 	u64 val, max;
9916 	int err;
9917 
9918 	if (func_id != BPF_FUNC_tail_call)
9919 		return 0;
9920 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9921 		verbose(env, "expected prog array map for tail call");
9922 		return -EINVAL;
9923 	}
9924 
9925 	reg = reg_state(env, BPF_REG_3);
9926 	val = reg->var_off.value;
9927 	max = map->max_entries;
9928 
9929 	if (!(is_reg_const(reg, false) && val < max)) {
9930 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9931 		return 0;
9932 	}
9933 
9934 	err = mark_chain_precision(env, BPF_REG_3);
9935 	if (err)
9936 		return err;
9937 	if (bpf_map_key_unseen(aux))
9938 		bpf_map_key_store(aux, val);
9939 	else if (!bpf_map_key_poisoned(aux) &&
9940 		  bpf_map_key_immediate(aux) != val)
9941 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9942 	return 0;
9943 }
9944 
9945 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
9946 {
9947 	struct bpf_verifier_state *state = env->cur_state;
9948 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9949 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
9950 	bool refs_lingering = false;
9951 	int i;
9952 
9953 	if (!exception_exit && cur_func(env)->frameno)
9954 		return 0;
9955 
9956 	for (i = 0; i < state->acquired_refs; i++) {
9957 		if (state->refs[i].type != REF_TYPE_PTR)
9958 			continue;
9959 		/* Allow struct_ops programs to return a referenced kptr back to
9960 		 * kernel. Type checks are performed later in check_return_code.
9961 		 */
9962 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
9963 		    reg->id == state->refs[i].id)
9964 			continue;
9965 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9966 			state->refs[i].id, state->refs[i].insn_idx);
9967 		refs_lingering = true;
9968 	}
9969 	return refs_lingering ? -EINVAL : 0;
9970 }
9971 
9972 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
9973 {
9974 	int err;
9975 
9976 	if (check_lock && env->cur_state->active_locks) {
9977 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
9978 		return -EINVAL;
9979 	}
9980 
9981 	err = check_reference_leak(env, exception_exit);
9982 	if (err) {
9983 		verbose(env, "%s would lead to reference leak\n", prefix);
9984 		return err;
9985 	}
9986 
9987 	if (check_lock && env->cur_state->active_irq_id) {
9988 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
9989 		return -EINVAL;
9990 	}
9991 
9992 	if (check_lock && env->cur_state->active_rcu_locks) {
9993 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
9994 		return -EINVAL;
9995 	}
9996 
9997 	if (check_lock && env->cur_state->active_preempt_locks) {
9998 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
9999 		return -EINVAL;
10000 	}
10001 
10002 	return 0;
10003 }
10004 
10005 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10006 				   struct bpf_reg_state *regs)
10007 {
10008 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
10009 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
10010 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
10011 	struct bpf_bprintf_data data = {};
10012 	int err, fmt_map_off, num_args;
10013 	u64 fmt_addr;
10014 	char *fmt;
10015 
10016 	/* data must be an array of u64 */
10017 	if (data_len_reg->var_off.value % 8)
10018 		return -EINVAL;
10019 	num_args = data_len_reg->var_off.value / 8;
10020 
10021 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10022 	 * and map_direct_value_addr is set.
10023 	 */
10024 	fmt_map_off = fmt_reg->var_off.value;
10025 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10026 						  fmt_map_off);
10027 	if (err) {
10028 		verbose(env, "failed to retrieve map value address\n");
10029 		return -EFAULT;
10030 	}
10031 	fmt = (char *)(long)fmt_addr + fmt_map_off;
10032 
10033 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10034 	 * can focus on validating the format specifiers.
10035 	 */
10036 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10037 	if (err < 0)
10038 		verbose(env, "Invalid format string\n");
10039 
10040 	return err;
10041 }
10042 
10043 static int check_get_func_ip(struct bpf_verifier_env *env)
10044 {
10045 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10046 	int func_id = BPF_FUNC_get_func_ip;
10047 
10048 	if (type == BPF_PROG_TYPE_TRACING) {
10049 		if (!bpf_prog_has_trampoline(env->prog)) {
10050 			verbose(env, "func %s#%d supported only for fentry/fexit/fsession/fmod_ret programs\n",
10051 				func_id_name(func_id), func_id);
10052 			return -ENOTSUPP;
10053 		}
10054 		return 0;
10055 	} else if (type == BPF_PROG_TYPE_KPROBE) {
10056 		return 0;
10057 	}
10058 
10059 	verbose(env, "func %s#%d not supported for program type %d\n",
10060 		func_id_name(func_id), func_id, type);
10061 	return -ENOTSUPP;
10062 }
10063 
10064 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
10065 {
10066 	return &env->insn_aux_data[env->insn_idx];
10067 }
10068 
10069 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10070 {
10071 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_4);
10072 	bool reg_is_null = bpf_register_is_null(reg);
10073 
10074 	if (reg_is_null)
10075 		mark_chain_precision(env, BPF_REG_4);
10076 
10077 	return reg_is_null;
10078 }
10079 
10080 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10081 {
10082 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10083 
10084 	if (!state->initialized) {
10085 		state->initialized = 1;
10086 		state->fit_for_inline = loop_flag_is_zero(env);
10087 		state->callback_subprogno = subprogno;
10088 		return;
10089 	}
10090 
10091 	if (!state->fit_for_inline)
10092 		return;
10093 
10094 	state->fit_for_inline = (loop_flag_is_zero(env) &&
10095 				 state->callback_subprogno == subprogno);
10096 }
10097 
10098 /* Returns whether or not the given map can potentially elide
10099  * lookup return value nullness check. This is possible if the key
10100  * is statically known.
10101  */
10102 static bool can_elide_value_nullness(const struct bpf_map *map)
10103 {
10104 	if (map->map_flags & BPF_F_INNER_MAP)
10105 		return false;
10106 
10107 	switch (map->map_type) {
10108 	case BPF_MAP_TYPE_ARRAY:
10109 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10110 		return true;
10111 	default:
10112 		return false;
10113 	}
10114 }
10115 
10116 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id,
10117 			 const struct bpf_func_proto **ptr)
10118 {
10119 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
10120 		return -ERANGE;
10121 
10122 	if (!env->ops->get_func_proto)
10123 		return -EINVAL;
10124 
10125 	*ptr = env->ops->get_func_proto(func_id, env->prog);
10126 	return *ptr && (*ptr)->func ? 0 : -EINVAL;
10127 }
10128 
10129 /* Check if we're in a sleepable context. */
10130 static inline bool in_sleepable_context(struct bpf_verifier_env *env)
10131 {
10132 	return !env->cur_state->active_rcu_locks &&
10133 	       !env->cur_state->active_preempt_locks &&
10134 	       !env->cur_state->active_locks &&
10135 	       !env->cur_state->active_irq_id &&
10136 	       in_sleepable(env);
10137 }
10138 
10139 static const char *non_sleepable_context_description(struct bpf_verifier_env *env)
10140 {
10141 	if (env->cur_state->active_rcu_locks)
10142 		return "rcu_read_lock region";
10143 	if (env->cur_state->active_preempt_locks)
10144 		return "non-preemptible region";
10145 	if (env->cur_state->active_irq_id)
10146 		return "IRQ-disabled region";
10147 	if (env->cur_state->active_locks)
10148 		return "lock region";
10149 	return "non-sleepable prog";
10150 }
10151 
10152 static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
10153 		       bool convert_rcu, bool release_dynptr)
10154 {
10155 	int err = -EINVAL;
10156 
10157 	if (bpf_register_is_null(reg))
10158 		return 0;
10159 
10160 	if (release_dynptr)
10161 		err = unmark_stack_slots_dynptr(env, reg);
10162 	else if (convert_rcu)
10163 		err = ref_convert_alloc_rcu_protected(env, reg->id);
10164 	else if (reg_is_referenced(env, reg))
10165 		err = release_reference(env, reg->id);
10166 
10167 	return err;
10168 }
10169 
10170 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10171 			     int *insn_idx_p)
10172 {
10173 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10174 	bool returns_cpu_specific_alloc_ptr = false;
10175 	const struct bpf_func_proto *fn = NULL;
10176 	enum bpf_return_type ret_type;
10177 	enum bpf_type_flag ret_flag;
10178 	struct bpf_reg_state *regs;
10179 	struct bpf_call_arg_meta meta;
10180 	int insn_idx = *insn_idx_p;
10181 	bool changes_data;
10182 	int i, err, func_id;
10183 
10184 	/* find function prototype */
10185 	func_id = insn->imm;
10186 	err = bpf_get_helper_proto(env, insn->imm, &fn);
10187 	if (err == -ERANGE) {
10188 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
10189 		return -EINVAL;
10190 	}
10191 
10192 	if (err) {
10193 		verbose(env, "program of this type cannot use helper %s#%d\n",
10194 			func_id_name(func_id), func_id);
10195 		return err;
10196 	}
10197 
10198 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
10199 	if (!env->prog->gpl_compatible && fn->gpl_only) {
10200 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10201 		return -EINVAL;
10202 	}
10203 
10204 	if (fn->allowed && !fn->allowed(env->prog)) {
10205 		verbose(env, "helper call is not allowed in probe\n");
10206 		return -EINVAL;
10207 	}
10208 
10209 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10210 	changes_data = bpf_helper_changes_pkt_data(func_id);
10211 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10212 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
10213 		return -EFAULT;
10214 	}
10215 
10216 	memset(&meta, 0, sizeof(meta));
10217 	meta.pkt_access = fn->pkt_access;
10218 
10219 	err = check_func_proto(fn, &meta);
10220 	if (err) {
10221 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
10222 		return err;
10223 	}
10224 
10225 	if (fn->might_sleep && !in_sleepable_context(env)) {
10226 		verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id,
10227 			non_sleepable_context_description(env));
10228 		return -EINVAL;
10229 	}
10230 
10231 	/* Track non-sleepable context for helpers. */
10232 	if (!in_sleepable_context(env))
10233 		env->insn_aux_data[insn_idx].non_sleepable = true;
10234 
10235 	meta.func_id = func_id;
10236 	/* check args */
10237 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10238 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10239 		if (err)
10240 			return err;
10241 	}
10242 
10243 	err = record_func_map(env, &meta, func_id, insn_idx);
10244 	if (err)
10245 		return err;
10246 
10247 	err = record_func_key(env, &meta, func_id, insn_idx);
10248 	if (err)
10249 		return err;
10250 
10251 	regs = cur_regs(env);
10252 
10253 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10254 	 * is inferred from register state.
10255 	 */
10256 	for (i = 0; i < meta.access_size; i++) {
10257 		err = check_mem_access(env, insn_idx, regs + meta.regno, argno_from_reg(meta.regno), i, BPF_B,
10258 				       BPF_WRITE, -1, false, false);
10259 		if (err)
10260 			return err;
10261 	}
10262 
10263 	if (meta.release_regno) {
10264 		struct bpf_reg_state *reg = &regs[meta.release_regno];
10265 		bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) && in_rcu_cs(env) &&
10266 				   (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU);
10267 
10268 		err = release_reg(env, reg, convert_rcu, !!meta.dynptr.id);
10269 		if (err)
10270 			return err;
10271 	}
10272 
10273 	switch (func_id) {
10274 	case BPF_FUNC_tail_call:
10275 		err = check_resource_leak(env, false, true, "tail_call");
10276 		if (err)
10277 			return err;
10278 		break;
10279 	case BPF_FUNC_get_local_storage:
10280 		/* check that flags argument in get_local_storage(map, flags) is 0,
10281 		 * this is required because get_local_storage() can't return an error.
10282 		 */
10283 		if (!bpf_register_is_null(&regs[BPF_REG_2])) {
10284 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10285 			return -EINVAL;
10286 		}
10287 		break;
10288 	case BPF_FUNC_for_each_map_elem:
10289 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10290 					 set_map_elem_callback_state);
10291 		break;
10292 	case BPF_FUNC_timer_set_callback:
10293 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10294 					 set_timer_callback_state);
10295 		break;
10296 	case BPF_FUNC_find_vma:
10297 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10298 					 set_find_vma_callback_state);
10299 		break;
10300 	case BPF_FUNC_snprintf:
10301 		err = check_bpf_snprintf_call(env, regs);
10302 		break;
10303 	case BPF_FUNC_loop:
10304 		update_loop_inline_state(env, meta.subprogno);
10305 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10306 		 * is finished, thus mark it precise.
10307 		 */
10308 		err = mark_chain_precision(env, BPF_REG_1);
10309 		if (err)
10310 			return err;
10311 		if (cur_func(env)->callback_depth < reg_umax(&regs[BPF_REG_1])) {
10312 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10313 						 set_loop_callback_state);
10314 		} else {
10315 			cur_func(env)->callback_depth = 0;
10316 			if (env->log.level & BPF_LOG_LEVEL2)
10317 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10318 					env->cur_state->curframe);
10319 		}
10320 		break;
10321 	case BPF_FUNC_dynptr_from_mem:
10322 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10323 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10324 				reg_type_str(env, regs[BPF_REG_1].type));
10325 			return -EACCES;
10326 		}
10327 		break;
10328 	case BPF_FUNC_set_retval:
10329 	{
10330 		struct bpf_retval_range range = {
10331 			.minval = -MAX_ERRNO,
10332 			.maxval = 0,
10333 			.return_32bit = true
10334 		};
10335 		struct bpf_reg_state *r1 = &regs[BPF_REG_1];
10336 
10337 		if (r1->type != SCALAR_VALUE) {
10338 			verbose(env, "R1 is not a scalar\n");
10339 			return -EINVAL;
10340 		}
10341 
10342 		/* CGROUP_GETSOCKOPT is allowed to return arbitrary value */
10343 		if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT &&
10344 		    env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT)
10345 			break;
10346 
10347 		if (prog_type == BPF_PROG_TYPE_LSM &&
10348 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10349 			if (!env->prog->aux->attach_func_proto->type) {
10350 				/* Make sure programs that attach to void
10351 				 * hooks don't try to modify return value.
10352 				 */
10353 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10354 				return -EINVAL;
10355 			}
10356 			bpf_lsm_get_retval_range(env->prog, &range);
10357 		}
10358 
10359 		err = mark_chain_precision(env, BPF_REG_1);
10360 		if (err)
10361 			return err;
10362 
10363 		if (!retval_range_within(range, r1)) {
10364 			verbose_invalid_scalar(env, r1, range, "At bpf_set_retval", "R1");
10365 			return -EINVAL;
10366 		}
10367 
10368 		break;
10369 	}
10370 	case BPF_FUNC_dynptr_write:
10371 	{
10372 		enum bpf_dynptr_type dynptr_type = meta.dynptr.type;
10373 
10374 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10375 			return -EFAULT;
10376 
10377 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
10378 		    dynptr_type == BPF_DYNPTR_TYPE_SKB_META)
10379 			/* this will trigger clear_all_pkt_pointers(), which will
10380 			 * invalidate all dynptr slices associated with the skb
10381 			 */
10382 			changes_data = true;
10383 
10384 		break;
10385 	}
10386 	case BPF_FUNC_per_cpu_ptr:
10387 	case BPF_FUNC_this_cpu_ptr:
10388 	{
10389 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
10390 		const struct btf_type *type;
10391 
10392 		if (reg->type & MEM_RCU) {
10393 			type = btf_type_by_id(reg->btf, reg->btf_id);
10394 			if (!type || !btf_type_is_struct(type)) {
10395 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
10396 				return -EFAULT;
10397 			}
10398 			returns_cpu_specific_alloc_ptr = true;
10399 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10400 		}
10401 		break;
10402 	}
10403 	case BPF_FUNC_user_ringbuf_drain:
10404 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10405 					 set_user_ringbuf_callback_state);
10406 		break;
10407 	}
10408 
10409 	if (err)
10410 		return err;
10411 
10412 	/* reset caller saved regs */
10413 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10414 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
10415 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10416 	}
10417 	invalidate_outgoing_stack_args(env, cur_func(env));
10418 
10419 	/* helper call returns 64-bit value. */
10420 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10421 
10422 	/* update return register (already marked as written above) */
10423 	ret_type = fn->ret_type;
10424 	ret_flag = type_flag(ret_type);
10425 
10426 	switch (base_type(ret_type)) {
10427 	case RET_INTEGER:
10428 		/* sets type to SCALAR_VALUE */
10429 		mark_reg_unknown(env, regs, BPF_REG_0);
10430 		break;
10431 	case RET_VOID:
10432 		regs[BPF_REG_0].type = NOT_INIT;
10433 		break;
10434 	case RET_PTR_TO_MAP_VALUE:
10435 		/* There is no offset yet applied, variable or fixed */
10436 		mark_reg_known_zero(env, regs, BPF_REG_0);
10437 		/* remember map_ptr, so that check_map_access()
10438 		 * can check 'value_size' boundary of memory access
10439 		 * to map element returned from bpf_map_lookup_elem()
10440 		 */
10441 		if (meta.map.ptr == NULL) {
10442 			verifier_bug(env, "unexpected null map_ptr");
10443 			return -EFAULT;
10444 		}
10445 
10446 		if (func_id == BPF_FUNC_map_lookup_elem &&
10447 		    can_elide_value_nullness(meta.map.ptr) &&
10448 		    meta.const_map_key >= 0 &&
10449 		    meta.const_map_key < meta.map.ptr->max_entries)
10450 			ret_flag &= ~PTR_MAYBE_NULL;
10451 
10452 		regs[BPF_REG_0].map_ptr = meta.map.ptr;
10453 		regs[BPF_REG_0].map_uid = meta.map.uid;
10454 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10455 		if (!type_may_be_null(ret_flag) &&
10456 		    btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
10457 			regs[BPF_REG_0].id = ++env->id_gen;
10458 		}
10459 		break;
10460 	case RET_PTR_TO_SOCKET:
10461 		mark_reg_known_zero(env, regs, BPF_REG_0);
10462 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10463 		break;
10464 	case RET_PTR_TO_SOCK_COMMON:
10465 		mark_reg_known_zero(env, regs, BPF_REG_0);
10466 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10467 		break;
10468 	case RET_PTR_TO_TCP_SOCK:
10469 		mark_reg_known_zero(env, regs, BPF_REG_0);
10470 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10471 		break;
10472 	case RET_PTR_TO_MEM:
10473 		mark_reg_known_zero(env, regs, BPF_REG_0);
10474 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10475 		regs[BPF_REG_0].mem_size = meta.mem_size;
10476 		break;
10477 	case RET_PTR_TO_MEM_OR_BTF_ID:
10478 	{
10479 		const struct btf_type *t;
10480 
10481 		mark_reg_known_zero(env, regs, BPF_REG_0);
10482 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10483 		if (!btf_type_is_struct(t)) {
10484 			u32 tsize;
10485 			const struct btf_type *ret;
10486 			const char *tname;
10487 
10488 			/* resolve the type size of ksym. */
10489 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10490 			if (IS_ERR(ret)) {
10491 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10492 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10493 					tname, PTR_ERR(ret));
10494 				return -EINVAL;
10495 			}
10496 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10497 			regs[BPF_REG_0].mem_size = tsize;
10498 		} else {
10499 			if (returns_cpu_specific_alloc_ptr) {
10500 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10501 			} else {
10502 				/* MEM_RDONLY may be carried from ret_flag, but it
10503 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10504 				 * it will confuse the check of PTR_TO_BTF_ID in
10505 				 * check_mem_access().
10506 				 */
10507 				ret_flag &= ~MEM_RDONLY;
10508 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10509 			}
10510 
10511 			regs[BPF_REG_0].btf = meta.ret_btf;
10512 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10513 		}
10514 		break;
10515 	}
10516 	case RET_PTR_TO_BTF_ID:
10517 	{
10518 		struct btf *ret_btf;
10519 		int ret_btf_id;
10520 
10521 		mark_reg_known_zero(env, regs, BPF_REG_0);
10522 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10523 		if (func_id == BPF_FUNC_kptr_xchg) {
10524 			ret_btf = meta.kptr_field->kptr.btf;
10525 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10526 			if (!btf_is_kernel(ret_btf)) {
10527 				regs[BPF_REG_0].type |= MEM_ALLOC;
10528 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10529 					regs[BPF_REG_0].type |= MEM_PERCPU;
10530 			}
10531 		} else {
10532 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10533 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
10534 					     func_id_name(func_id));
10535 				return -EFAULT;
10536 			}
10537 			ret_btf = btf_vmlinux;
10538 			ret_btf_id = *fn->ret_btf_id;
10539 		}
10540 		if (ret_btf_id == 0) {
10541 			verbose(env, "invalid return type %u of func %s#%d\n",
10542 				base_type(ret_type), func_id_name(func_id),
10543 				func_id);
10544 			return -EINVAL;
10545 		}
10546 		regs[BPF_REG_0].btf = ret_btf;
10547 		regs[BPF_REG_0].btf_id = ret_btf_id;
10548 		break;
10549 	}
10550 	default:
10551 		verbose(env, "unknown return type %u of func %s#%d\n",
10552 			base_type(ret_type), func_id_name(func_id), func_id);
10553 		return -EINVAL;
10554 	}
10555 
10556 	if (type_may_be_null(regs[BPF_REG_0].type))
10557 		regs[BPF_REG_0].id = ++env->id_gen;
10558 
10559 	if (is_ptr_cast_function(func_id) &&
10560 	    find_reference_state(env->cur_state, meta.ref_obj.id)) {
10561 		struct bpf_verifier_state *branch;
10562 		struct bpf_reg_state *r0;
10563 
10564 		err = validate_ref_obj(env, &meta.ref_obj);
10565 		if (err)
10566 			return err;
10567 
10568 		/*
10569 		 * In order for a release of any of the original or cast pointers
10570 		 * to invalidate all other pointers, reuse the same reference id for
10571 		 * the cast result.
10572 		 * This reference id can't be used for nullness propagation,
10573 		 * as cast might return NULL for a non-NULL input.
10574 		 * Hence, explore the NULL case as a separate branch.
10575 		 */
10576 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
10577 		if (IS_ERR(branch))
10578 			return PTR_ERR(branch);
10579 
10580 		r0 = &branch->frame[branch->curframe]->regs[BPF_REG_0];
10581 		__mark_reg_known_zero(r0);
10582 		r0->type = SCALAR_VALUE;
10583 
10584 		regs[BPF_REG_0].type &= ~PTR_MAYBE_NULL;
10585 		regs[BPF_REG_0].id = meta.ref_obj.id;
10586 	} else if (is_acquire_function(func_id, meta.map.ptr)) {
10587 		int id = acquire_reference(env, insn_idx, 0);
10588 
10589 		if (id < 0)
10590 			return id;
10591 
10592 		regs[BPF_REG_0].id = id;
10593 	}
10594 
10595 	if (func_id == BPF_FUNC_dynptr_data)
10596 		regs[BPF_REG_0].parent_id = meta.dynptr.id;
10597 
10598 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10599 	if (err)
10600 		return err;
10601 
10602 	err = check_map_func_compatibility(env, meta.map.ptr, func_id);
10603 	if (err)
10604 		return err;
10605 
10606 	if ((func_id == BPF_FUNC_get_stack ||
10607 	     func_id == BPF_FUNC_get_task_stack) &&
10608 	    !env->prog->has_callchain_buf) {
10609 		const char *err_str;
10610 
10611 #ifdef CONFIG_PERF_EVENTS
10612 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10613 		err_str = "cannot get callchain buffer for func %s#%d\n";
10614 #else
10615 		err = -ENOTSUPP;
10616 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10617 #endif
10618 		if (err) {
10619 			verbose(env, err_str, func_id_name(func_id), func_id);
10620 			return err;
10621 		}
10622 
10623 		env->prog->has_callchain_buf = true;
10624 	}
10625 
10626 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10627 		env->prog->call_get_stack = true;
10628 
10629 	if (func_id == BPF_FUNC_get_func_ip) {
10630 		if (check_get_func_ip(env))
10631 			return -ENOTSUPP;
10632 		env->prog->call_get_func_ip = true;
10633 	}
10634 
10635 	if (func_id == BPF_FUNC_tail_call) {
10636 		if (env->cur_state->curframe) {
10637 			struct bpf_verifier_state *branch;
10638 
10639 			mark_reg_scratched(env, BPF_REG_0);
10640 			branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
10641 			if (IS_ERR(branch))
10642 				return PTR_ERR(branch);
10643 			clear_all_pkt_pointers(env);
10644 			mark_reg_unknown(env, regs, BPF_REG_0);
10645 			err = prepare_func_exit(env, &env->insn_idx);
10646 			if (err)
10647 				return err;
10648 			env->insn_idx--;
10649 		} else {
10650 			changes_data = false;
10651 		}
10652 	}
10653 
10654 	if (changes_data)
10655 		clear_all_pkt_pointers(env);
10656 	return 0;
10657 }
10658 
10659 /* mark_btf_func_reg_size() is used when the reg size is determined by
10660  * the BTF func_proto's return value size and argument.
10661  */
10662 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
10663 				     u32 regno, size_t reg_size)
10664 {
10665 	struct bpf_reg_state *reg = &regs[regno];
10666 
10667 	if (regno == BPF_REG_0) {
10668 		/* Function return value */
10669 		reg->subreg_def = reg_size == sizeof(u64) ?
10670 			DEF_NOT_SUBREG : env->insn_idx + 1;
10671 	} else if (reg_size == sizeof(u64)) {
10672 		/* Function argument */
10673 		mark_insn_zext(env, reg);
10674 	}
10675 }
10676 
10677 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10678 				   size_t reg_size)
10679 {
10680 	return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size);
10681 }
10682 
10683 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10684 {
10685 	return meta->kfunc_flags & KF_ACQUIRE;
10686 }
10687 
10688 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10689 {
10690 	return meta->kfunc_flags & KF_RELEASE;
10691 }
10692 
10693 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10694 {
10695 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10696 }
10697 
10698 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10699 {
10700 	return meta->kfunc_flags & KF_RCU;
10701 }
10702 
10703 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10704 {
10705 	return meta->kfunc_flags & KF_RCU_PROTECTED;
10706 }
10707 
10708 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10709 				  const struct btf_param *arg,
10710 				  const struct bpf_reg_state *reg)
10711 {
10712 	const struct btf_type *t;
10713 
10714 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10715 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10716 		return false;
10717 
10718 	return btf_param_match_suffix(btf, arg, "__sz");
10719 }
10720 
10721 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10722 					const struct btf_param *arg,
10723 					const struct bpf_reg_state *reg)
10724 {
10725 	const struct btf_type *t;
10726 
10727 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10728 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10729 		return false;
10730 
10731 	return btf_param_match_suffix(btf, arg, "__szk");
10732 }
10733 
10734 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10735 {
10736 	return btf_param_match_suffix(btf, arg, "__k");
10737 }
10738 
10739 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10740 {
10741 	return btf_param_match_suffix(btf, arg, "__ign");
10742 }
10743 
10744 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
10745 {
10746 	return btf_param_match_suffix(btf, arg, "__map");
10747 }
10748 
10749 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10750 {
10751 	return btf_param_match_suffix(btf, arg, "__alloc");
10752 }
10753 
10754 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10755 {
10756 	return btf_param_match_suffix(btf, arg, "__uninit");
10757 }
10758 
10759 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10760 {
10761 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
10762 }
10763 
10764 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10765 {
10766 	return btf_param_match_suffix(btf, arg, "__nullable");
10767 }
10768 
10769 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf, const struct btf_param *arg)
10770 {
10771 	return btf_param_match_suffix(btf, arg, "__nonown_allowed");
10772 }
10773 
10774 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
10775 {
10776 	return btf_param_match_suffix(btf, arg, "__str");
10777 }
10778 
10779 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
10780 {
10781 	return btf_param_match_suffix(btf, arg, "__irq_flag");
10782 }
10783 
10784 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10785 					  const struct btf_param *arg,
10786 					  const char *name)
10787 {
10788 	int len, target_len = strlen(name);
10789 	const char *param_name;
10790 
10791 	param_name = btf_name_by_offset(btf, arg->name_off);
10792 	if (str_is_empty(param_name))
10793 		return false;
10794 	len = strlen(param_name);
10795 	if (len != target_len)
10796 		return false;
10797 	if (strcmp(param_name, name))
10798 		return false;
10799 
10800 	return true;
10801 }
10802 
10803 enum {
10804 	KF_ARG_DYNPTR_ID,
10805 	KF_ARG_LIST_HEAD_ID,
10806 	KF_ARG_LIST_NODE_ID,
10807 	KF_ARG_RB_ROOT_ID,
10808 	KF_ARG_RB_NODE_ID,
10809 	KF_ARG_WORKQUEUE_ID,
10810 	KF_ARG_RES_SPIN_LOCK_ID,
10811 	KF_ARG_TASK_WORK_ID,
10812 	KF_ARG_PROG_AUX_ID,
10813 	KF_ARG_TIMER_ID
10814 };
10815 
10816 BTF_ID_LIST(kf_arg_btf_ids)
10817 BTF_ID(struct, bpf_dynptr)
10818 BTF_ID(struct, bpf_list_head)
10819 BTF_ID(struct, bpf_list_node)
10820 BTF_ID(struct, bpf_rb_root)
10821 BTF_ID(struct, bpf_rb_node)
10822 BTF_ID(struct, bpf_wq)
10823 BTF_ID(struct, bpf_res_spin_lock)
10824 BTF_ID(struct, bpf_task_work)
10825 BTF_ID(struct, bpf_prog_aux)
10826 BTF_ID(struct, bpf_timer)
10827 
10828 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10829 				    const struct btf_param *arg, int type)
10830 {
10831 	const struct btf_type *t;
10832 	u32 res_id;
10833 
10834 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10835 	if (!t)
10836 		return false;
10837 	if (!btf_type_is_ptr(t))
10838 		return false;
10839 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10840 	if (!t)
10841 		return false;
10842 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10843 }
10844 
10845 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10846 {
10847 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10848 }
10849 
10850 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10851 {
10852 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10853 }
10854 
10855 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10856 {
10857 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10858 }
10859 
10860 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10861 {
10862 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10863 }
10864 
10865 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10866 {
10867 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10868 }
10869 
10870 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg)
10871 {
10872 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID);
10873 }
10874 
10875 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
10876 {
10877 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
10878 }
10879 
10880 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
10881 {
10882 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
10883 }
10884 
10885 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
10886 {
10887 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
10888 }
10889 
10890 static bool is_rbtree_node_type(const struct btf_type *t)
10891 {
10892 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
10893 }
10894 
10895 static bool is_list_node_type(const struct btf_type *t)
10896 {
10897 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
10898 }
10899 
10900 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10901 				  const struct btf_param *arg)
10902 {
10903 	const struct btf_type *t;
10904 
10905 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10906 	if (!t)
10907 		return false;
10908 
10909 	return true;
10910 }
10911 
10912 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg)
10913 {
10914 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID);
10915 }
10916 
10917 /*
10918  * A kfunc with KF_IMPLICIT_ARGS has two prototypes in BTF:
10919  *   - the _impl prototype with full arg list (meta->func_proto)
10920  *   - the BPF API prototype w/o implicit args (func->type in BTF)
10921  * To determine whether an argument is implicit, we compare its position
10922  * against the number of arguments in the prototype w/o implicit args.
10923  */
10924 static bool is_kfunc_arg_implicit(const struct bpf_kfunc_call_arg_meta *meta, u32 arg_idx)
10925 {
10926 	const struct btf_type *func, *func_proto;
10927 	u32 argn;
10928 
10929 	if (!(meta->kfunc_flags & KF_IMPLICIT_ARGS))
10930 		return false;
10931 
10932 	func = btf_type_by_id(meta->btf, meta->func_id);
10933 	func_proto = btf_type_by_id(meta->btf, func->type);
10934 	argn = btf_type_vlen(func_proto);
10935 
10936 	return argn <= arg_idx;
10937 }
10938 
10939 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10940 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10941 					const struct btf *btf,
10942 					const struct btf_type *t, int rec)
10943 {
10944 	const struct btf_type *member_type;
10945 	const struct btf_member *member;
10946 	u32 i;
10947 
10948 	if (!btf_type_is_struct(t))
10949 		return false;
10950 
10951 	for_each_member(i, t, member) {
10952 		const struct btf_array *array;
10953 
10954 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10955 		if (btf_type_is_struct(member_type)) {
10956 			if (rec >= 3) {
10957 				verbose(env, "max struct nesting depth exceeded\n");
10958 				return false;
10959 			}
10960 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10961 				return false;
10962 			continue;
10963 		}
10964 		if (btf_type_is_array(member_type)) {
10965 			array = btf_array(member_type);
10966 			if (!array->nelems)
10967 				return false;
10968 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10969 			if (!btf_type_is_scalar(member_type))
10970 				return false;
10971 			continue;
10972 		}
10973 		if (!btf_type_is_scalar(member_type))
10974 			return false;
10975 	}
10976 	return true;
10977 }
10978 
10979 enum kfunc_ptr_arg_type {
10980 	KF_ARG_PTR_TO_CTX,
10981 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10982 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10983 	KF_ARG_PTR_TO_DYNPTR,
10984 	KF_ARG_PTR_TO_ITER,
10985 	KF_ARG_PTR_TO_LIST_HEAD,
10986 	KF_ARG_PTR_TO_LIST_NODE,
10987 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10988 	KF_ARG_PTR_TO_MEM,
10989 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10990 	KF_ARG_PTR_TO_CALLBACK,
10991 	KF_ARG_PTR_TO_RB_ROOT,
10992 	KF_ARG_PTR_TO_RB_NODE,
10993 	KF_ARG_PTR_TO_NULL,
10994 	KF_ARG_PTR_TO_CONST_STR,
10995 	KF_ARG_PTR_TO_MAP,
10996 	KF_ARG_PTR_TO_TIMER,
10997 	KF_ARG_PTR_TO_WORKQUEUE,
10998 	KF_ARG_PTR_TO_IRQ_FLAG,
10999 	KF_ARG_PTR_TO_RES_SPIN_LOCK,
11000 	KF_ARG_PTR_TO_TASK_WORK,
11001 };
11002 
11003 enum special_kfunc_type {
11004 	KF_bpf_obj_new_impl,
11005 	KF_bpf_obj_new,
11006 	KF_bpf_obj_drop_impl,
11007 	KF_bpf_obj_drop,
11008 	KF_bpf_refcount_acquire_impl,
11009 	KF_bpf_refcount_acquire,
11010 	KF_bpf_list_push_front_impl,
11011 	KF_bpf_list_push_front,
11012 	KF_bpf_list_push_back_impl,
11013 	KF_bpf_list_push_back,
11014 	KF_bpf_list_add,
11015 	KF_bpf_list_pop_front,
11016 	KF_bpf_list_pop_back,
11017 	KF_bpf_list_del,
11018 	KF_bpf_list_front,
11019 	KF_bpf_list_back,
11020 	KF_bpf_list_is_first,
11021 	KF_bpf_list_is_last,
11022 	KF_bpf_list_empty,
11023 	KF_bpf_cast_to_kern_ctx,
11024 	KF_bpf_rdonly_cast,
11025 	KF_bpf_rcu_read_lock,
11026 	KF_bpf_rcu_read_unlock,
11027 	KF_bpf_rbtree_remove,
11028 	KF_bpf_rbtree_add_impl,
11029 	KF_bpf_rbtree_add,
11030 	KF_bpf_rbtree_first,
11031 	KF_bpf_rbtree_root,
11032 	KF_bpf_rbtree_left,
11033 	KF_bpf_rbtree_right,
11034 	KF_bpf_dynptr_from_skb,
11035 	KF_bpf_dynptr_from_xdp,
11036 	KF_bpf_dynptr_from_skb_meta,
11037 	KF_bpf_xdp_pull_data,
11038 	KF_bpf_dynptr_slice,
11039 	KF_bpf_dynptr_slice_rdwr,
11040 	KF_bpf_dynptr_clone,
11041 	KF_bpf_percpu_obj_new_impl,
11042 	KF_bpf_percpu_obj_new,
11043 	KF_bpf_percpu_obj_drop_impl,
11044 	KF_bpf_percpu_obj_drop,
11045 	KF_bpf_throw,
11046 	KF_bpf_wq_set_callback,
11047 	KF_bpf_preempt_disable,
11048 	KF_bpf_preempt_enable,
11049 	KF_bpf_iter_css_task_new,
11050 	KF_bpf_session_cookie,
11051 	KF_bpf_get_kmem_cache,
11052 	KF_bpf_local_irq_save,
11053 	KF_bpf_local_irq_restore,
11054 	KF_bpf_iter_num_new,
11055 	KF_bpf_iter_num_next,
11056 	KF_bpf_iter_num_destroy,
11057 	KF_bpf_set_dentry_xattr,
11058 	KF_bpf_remove_dentry_xattr,
11059 	KF_bpf_res_spin_lock,
11060 	KF_bpf_res_spin_unlock,
11061 	KF_bpf_res_spin_lock_irqsave,
11062 	KF_bpf_res_spin_unlock_irqrestore,
11063 	KF_bpf_dynptr_from_file,
11064 	KF_bpf_dynptr_file_discard,
11065 	KF___bpf_trap,
11066 	KF_bpf_task_work_schedule_signal,
11067 	KF_bpf_task_work_schedule_resume,
11068 	KF_bpf_arena_alloc_pages,
11069 	KF_bpf_arena_free_pages,
11070 	KF_bpf_arena_reserve_pages,
11071 	KF_bpf_session_is_return,
11072 	KF_bpf_stream_vprintk,
11073 	KF_bpf_stream_print_stack,
11074 };
11075 
11076 BTF_ID_LIST(special_kfunc_list)
11077 BTF_ID(func, bpf_obj_new_impl)
11078 BTF_ID(func, bpf_obj_new)
11079 BTF_ID(func, bpf_obj_drop_impl)
11080 BTF_ID(func, bpf_obj_drop)
11081 BTF_ID(func, bpf_refcount_acquire_impl)
11082 BTF_ID(func, bpf_refcount_acquire)
11083 BTF_ID(func, bpf_list_push_front_impl)
11084 BTF_ID(func, bpf_list_push_front)
11085 BTF_ID(func, bpf_list_push_back_impl)
11086 BTF_ID(func, bpf_list_push_back)
11087 BTF_ID(func, bpf_list_add)
11088 BTF_ID(func, bpf_list_pop_front)
11089 BTF_ID(func, bpf_list_pop_back)
11090 BTF_ID(func, bpf_list_del)
11091 BTF_ID(func, bpf_list_front)
11092 BTF_ID(func, bpf_list_back)
11093 BTF_ID(func, bpf_list_is_first)
11094 BTF_ID(func, bpf_list_is_last)
11095 BTF_ID(func, bpf_list_empty)
11096 BTF_ID(func, bpf_cast_to_kern_ctx)
11097 BTF_ID(func, bpf_rdonly_cast)
11098 BTF_ID(func, bpf_rcu_read_lock)
11099 BTF_ID(func, bpf_rcu_read_unlock)
11100 BTF_ID(func, bpf_rbtree_remove)
11101 BTF_ID(func, bpf_rbtree_add_impl)
11102 BTF_ID(func, bpf_rbtree_add)
11103 BTF_ID(func, bpf_rbtree_first)
11104 BTF_ID(func, bpf_rbtree_root)
11105 BTF_ID(func, bpf_rbtree_left)
11106 BTF_ID(func, bpf_rbtree_right)
11107 #ifdef CONFIG_NET
11108 BTF_ID(func, bpf_dynptr_from_skb)
11109 BTF_ID(func, bpf_dynptr_from_xdp)
11110 BTF_ID(func, bpf_dynptr_from_skb_meta)
11111 BTF_ID(func, bpf_xdp_pull_data)
11112 #else
11113 BTF_ID_UNUSED
11114 BTF_ID_UNUSED
11115 BTF_ID_UNUSED
11116 BTF_ID_UNUSED
11117 #endif
11118 BTF_ID(func, bpf_dynptr_slice)
11119 BTF_ID(func, bpf_dynptr_slice_rdwr)
11120 BTF_ID(func, bpf_dynptr_clone)
11121 BTF_ID(func, bpf_percpu_obj_new_impl)
11122 BTF_ID(func, bpf_percpu_obj_new)
11123 BTF_ID(func, bpf_percpu_obj_drop_impl)
11124 BTF_ID(func, bpf_percpu_obj_drop)
11125 BTF_ID(func, bpf_throw)
11126 BTF_ID(func, bpf_wq_set_callback)
11127 BTF_ID(func, bpf_preempt_disable)
11128 BTF_ID(func, bpf_preempt_enable)
11129 #ifdef CONFIG_CGROUPS
11130 BTF_ID(func, bpf_iter_css_task_new)
11131 #else
11132 BTF_ID_UNUSED
11133 #endif
11134 #ifdef CONFIG_BPF_EVENTS
11135 BTF_ID(func, bpf_session_cookie)
11136 #else
11137 BTF_ID_UNUSED
11138 #endif
11139 BTF_ID(func, bpf_get_kmem_cache)
11140 BTF_ID(func, bpf_local_irq_save)
11141 BTF_ID(func, bpf_local_irq_restore)
11142 BTF_ID(func, bpf_iter_num_new)
11143 BTF_ID(func, bpf_iter_num_next)
11144 BTF_ID(func, bpf_iter_num_destroy)
11145 #ifdef CONFIG_BPF_LSM
11146 BTF_ID(func, bpf_set_dentry_xattr)
11147 BTF_ID(func, bpf_remove_dentry_xattr)
11148 #else
11149 BTF_ID_UNUSED
11150 BTF_ID_UNUSED
11151 #endif
11152 BTF_ID(func, bpf_res_spin_lock)
11153 BTF_ID(func, bpf_res_spin_unlock)
11154 BTF_ID(func, bpf_res_spin_lock_irqsave)
11155 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
11156 BTF_ID(func, bpf_dynptr_from_file)
11157 BTF_ID(func, bpf_dynptr_file_discard)
11158 BTF_ID(func, __bpf_trap)
11159 BTF_ID(func, bpf_task_work_schedule_signal)
11160 BTF_ID(func, bpf_task_work_schedule_resume)
11161 BTF_ID(func, bpf_arena_alloc_pages)
11162 BTF_ID(func, bpf_arena_free_pages)
11163 BTF_ID(func, bpf_arena_reserve_pages)
11164 #ifdef CONFIG_BPF_EVENTS
11165 BTF_ID(func, bpf_session_is_return)
11166 #else
11167 BTF_ID_UNUSED
11168 #endif
11169 BTF_ID(func, bpf_stream_vprintk)
11170 BTF_ID(func, bpf_stream_print_stack)
11171 
11172 static bool is_bpf_obj_new_kfunc(u32 func_id)
11173 {
11174 	return func_id == special_kfunc_list[KF_bpf_obj_new] ||
11175 	       func_id == special_kfunc_list[KF_bpf_obj_new_impl];
11176 }
11177 
11178 static bool is_bpf_percpu_obj_new_kfunc(u32 func_id)
11179 {
11180 	return func_id == special_kfunc_list[KF_bpf_percpu_obj_new] ||
11181 	       func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl];
11182 }
11183 
11184 static bool is_bpf_obj_drop_kfunc(u32 func_id)
11185 {
11186 	return func_id == special_kfunc_list[KF_bpf_obj_drop] ||
11187 	       func_id == special_kfunc_list[KF_bpf_obj_drop_impl];
11188 }
11189 
11190 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id)
11191 {
11192 	return func_id == special_kfunc_list[KF_bpf_percpu_obj_drop] ||
11193 	       func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl];
11194 }
11195 
11196 static bool is_bpf_refcount_acquire_kfunc(u32 func_id)
11197 {
11198 	return func_id == special_kfunc_list[KF_bpf_refcount_acquire] ||
11199 	       func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11200 }
11201 
11202 static bool is_bpf_list_push_kfunc(u32 func_id)
11203 {
11204 	return func_id == special_kfunc_list[KF_bpf_list_push_front] ||
11205 	       func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11206 	       func_id == special_kfunc_list[KF_bpf_list_push_back] ||
11207 	       func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11208 	       func_id == special_kfunc_list[KF_bpf_list_add];
11209 }
11210 
11211 static bool is_bpf_rbtree_add_kfunc(u32 func_id)
11212 {
11213 	return func_id == special_kfunc_list[KF_bpf_rbtree_add] ||
11214 	       func_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11215 }
11216 
11217 static bool is_task_work_add_kfunc(u32 func_id)
11218 {
11219 	return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] ||
11220 	       func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume];
11221 }
11222 
11223 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
11224 {
11225 	if (is_bpf_refcount_acquire_kfunc(meta->func_id) && meta->arg_owning_ref)
11226 		return false;
11227 
11228 	return meta->kfunc_flags & KF_RET_NULL;
11229 }
11230 
11231 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
11232 {
11233 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11234 }
11235 
11236 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11237 {
11238 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11239 }
11240 
11241 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
11242 {
11243 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
11244 }
11245 
11246 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
11247 {
11248 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
11249 }
11250 
11251 bool bpf_is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta)
11252 {
11253 	return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data];
11254 }
11255 
11256 static enum kfunc_ptr_arg_type
11257 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, struct bpf_func_state *caller,
11258 		       struct bpf_reg_state *regs, struct bpf_kfunc_call_arg_meta *meta,
11259 		       const struct btf_type *t, const struct btf_type *ref_t,
11260 		       const char *ref_tname, const struct btf_param *args,
11261 		       int arg, int nargs, argno_t argno, struct bpf_reg_state *reg)
11262 {
11263 	bool arg_mem_size = false;
11264 
11265 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
11266 	    meta->func_id == special_kfunc_list[KF_bpf_session_is_return] ||
11267 	    meta->func_id == special_kfunc_list[KF_bpf_session_cookie])
11268 		return KF_ARG_PTR_TO_CTX;
11269 
11270 	if (arg + 1 < nargs &&
11271 	    (is_kfunc_arg_mem_size(meta->btf, &args[arg + 1], get_func_arg_reg(caller, regs, arg + 1)) ||
11272 	     is_kfunc_arg_const_mem_size(meta->btf, &args[arg + 1], get_func_arg_reg(caller, regs, arg + 1))))
11273 		arg_mem_size = true;
11274 
11275 	/* In this function, we verify the kfunc's BTF as per the argument type,
11276 	 * leaving the rest of the verification with respect to the register
11277 	 * type to our caller. When a set of conditions hold in the BTF type of
11278 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11279 	 */
11280 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), arg))
11281 		return KF_ARG_PTR_TO_CTX;
11282 
11283 	if (is_kfunc_arg_nullable(meta->btf, &args[arg]) && bpf_register_is_null(reg) &&
11284 	    !arg_mem_size)
11285 		return KF_ARG_PTR_TO_NULL;
11286 
11287 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[arg]))
11288 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11289 
11290 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[arg]))
11291 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11292 
11293 	if (is_kfunc_arg_dynptr(meta->btf, &args[arg]))
11294 		return KF_ARG_PTR_TO_DYNPTR;
11295 
11296 	if (is_kfunc_arg_iter(meta, arg, &args[arg]))
11297 		return KF_ARG_PTR_TO_ITER;
11298 
11299 	if (is_kfunc_arg_list_head(meta->btf, &args[arg]))
11300 		return KF_ARG_PTR_TO_LIST_HEAD;
11301 
11302 	if (is_kfunc_arg_list_node(meta->btf, &args[arg]))
11303 		return KF_ARG_PTR_TO_LIST_NODE;
11304 
11305 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[arg]))
11306 		return KF_ARG_PTR_TO_RB_ROOT;
11307 
11308 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[arg]))
11309 		return KF_ARG_PTR_TO_RB_NODE;
11310 
11311 	if (is_kfunc_arg_const_str(meta->btf, &args[arg]))
11312 		return KF_ARG_PTR_TO_CONST_STR;
11313 
11314 	if (is_kfunc_arg_map(meta->btf, &args[arg]))
11315 		return KF_ARG_PTR_TO_MAP;
11316 
11317 	if (is_kfunc_arg_wq(meta->btf, &args[arg]))
11318 		return KF_ARG_PTR_TO_WORKQUEUE;
11319 
11320 	if (is_kfunc_arg_timer(meta->btf, &args[arg]))
11321 		return KF_ARG_PTR_TO_TIMER;
11322 
11323 	if (is_kfunc_arg_task_work(meta->btf, &args[arg]))
11324 		return KF_ARG_PTR_TO_TASK_WORK;
11325 
11326 	if (is_kfunc_arg_irq_flag(meta->btf, &args[arg]))
11327 		return KF_ARG_PTR_TO_IRQ_FLAG;
11328 
11329 	if (is_kfunc_arg_res_spin_lock(meta->btf, &args[arg]))
11330 		return KF_ARG_PTR_TO_RES_SPIN_LOCK;
11331 
11332 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11333 		if (!btf_type_is_struct(ref_t)) {
11334 			verbose(env, "kernel function %s %s pointer type %s %s is not supported\n",
11335 				meta->func_name, reg_arg_name(env, argno),
11336 				btf_type_str(ref_t), ref_tname);
11337 			return -EINVAL;
11338 		}
11339 		return KF_ARG_PTR_TO_BTF_ID;
11340 	}
11341 
11342 	if (is_kfunc_arg_callback(env, meta->btf, &args[arg]))
11343 		return KF_ARG_PTR_TO_CALLBACK;
11344 
11345 	/* This is the catch all argument type of register types supported by
11346 	 * check_helper_mem_access. However, we only allow when argument type is
11347 	 * pointer to scalar, or struct composed (recursively) of scalars. When
11348 	 * arg_mem_size is true, the pointer can be void *.
11349 	 */
11350 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11351 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11352 		verbose(env, "%s pointer type %s %s must point to %sscalar, or struct with scalar\n",
11353 			reg_arg_name(env, argno),
11354 			btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11355 		return -EINVAL;
11356 	}
11357 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11358 }
11359 
11360 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11361 					struct bpf_reg_state *reg,
11362 					const struct btf_type *ref_t,
11363 					const char *ref_tname, u32 ref_id,
11364 					struct bpf_kfunc_call_arg_meta *meta,
11365 					int arg, argno_t argno)
11366 {
11367 	const struct btf_type *reg_ref_t;
11368 	bool strict_type_match = false;
11369 	const struct btf *reg_btf;
11370 	const char *reg_ref_tname;
11371 	bool taking_projection;
11372 	bool struct_same;
11373 	u32 reg_ref_id;
11374 
11375 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
11376 		reg_btf = reg->btf;
11377 		reg_ref_id = reg->btf_id;
11378 	} else {
11379 		reg_btf = btf_vmlinux;
11380 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11381 	}
11382 
11383 	/* Enforce strict type matching for calls to kfuncs that are acquiring
11384 	 * or releasing a reference, or are no-cast aliases. We do _not_
11385 	 * enforce strict matching for kfuncs by default,
11386 	 * as we want to enable BPF programs to pass types that are bitwise
11387 	 * equivalent without forcing them to explicitly cast with something
11388 	 * like bpf_cast_to_kern_ctx().
11389 	 *
11390 	 * For example, say we had a type like the following:
11391 	 *
11392 	 * struct bpf_cpumask {
11393 	 *	cpumask_t cpumask;
11394 	 *	refcount_t usage;
11395 	 * };
11396 	 *
11397 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11398 	 * to a struct cpumask, so it would be safe to pass a struct
11399 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11400 	 *
11401 	 * The philosophy here is similar to how we allow scalars of different
11402 	 * types to be passed to kfuncs as long as the size is the same. The
11403 	 * only difference here is that we're simply allowing
11404 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11405 	 * resolve types.
11406 	 */
11407 	if ((is_kfunc_release(meta) && reg_is_referenced(env, reg)) ||
11408 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11409 		strict_type_match = true;
11410 
11411 	WARN_ON_ONCE(is_kfunc_release(meta) && !tnum_is_const(reg->var_off));
11412 
11413 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
11414 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11415 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->var_off.value,
11416 					   meta->btf, ref_id, strict_type_match);
11417 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
11418 	 * actually use it -- it must cast to the underlying type. So we allow
11419 	 * caller to pass in the underlying type.
11420 	 */
11421 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
11422 	if (!taking_projection && !struct_same) {
11423 		verbose(env, "kernel function %s %s expected pointer to %s %s but %s has a pointer to %s %s\n",
11424 			meta->func_name, reg_arg_name(env, argno),
11425 			btf_type_str(ref_t), ref_tname, reg_arg_name(env, argno),
11426 			btf_type_str(reg_ref_t), reg_ref_tname);
11427 		return -EINVAL;
11428 	}
11429 	return 0;
11430 }
11431 
11432 static int process_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
11433 			     struct bpf_kfunc_call_arg_meta *meta)
11434 {
11435 	int err, spi, kfunc_class = IRQ_NATIVE_KFUNC;
11436 	bool irq_save;
11437 
11438 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
11439 	    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
11440 		irq_save = true;
11441 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
11442 			kfunc_class = IRQ_LOCK_KFUNC;
11443 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
11444 		   meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
11445 		irq_save = false;
11446 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
11447 			kfunc_class = IRQ_LOCK_KFUNC;
11448 	} else {
11449 		verifier_bug(env, "unknown irq flags kfunc");
11450 		return -EFAULT;
11451 	}
11452 
11453 	if (irq_save) {
11454 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
11455 			verbose(env, "expected uninitialized irq flag as %s\n",
11456 				reg_arg_name(env, argno));
11457 			return -EINVAL;
11458 		}
11459 
11460 		err = check_mem_access(env, env->insn_idx, reg, argno, 0, BPF_DW,
11461 				       BPF_WRITE, -1, false, false);
11462 		if (err)
11463 			return err;
11464 
11465 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
11466 		if (err)
11467 			return err;
11468 	} else {
11469 		err = is_irq_flag_reg_valid_init(env, reg);
11470 		if (err) {
11471 			verbose(env, "expected an initialized irq flag as %s\n",
11472 				reg_arg_name(env, argno));
11473 			return err;
11474 		}
11475 
11476 		spi = irq_flag_get_spi(env, reg);
11477 		if (spi < 0)
11478 			return spi;
11479 
11480 		mark_stack_slots_scratched(env, spi, 1);
11481 
11482 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
11483 		if (err)
11484 			return err;
11485 	}
11486 	return 0;
11487 }
11488 
11489 
11490 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11491 {
11492 	struct btf_record *rec = reg_btf_record(reg);
11493 
11494 	if (!env->cur_state->active_locks) {
11495 		verifier_bug(env, "%s w/o active lock", __func__);
11496 		return -EFAULT;
11497 	}
11498 
11499 	if (type_flag(reg->type) & NON_OWN_REF) {
11500 		verifier_bug(env, "NON_OWN_REF already set");
11501 		return -EFAULT;
11502 	}
11503 
11504 	reg->type |= NON_OWN_REF;
11505 	if (rec->refcount_off >= 0)
11506 		reg->type |= MEM_RCU;
11507 
11508 	return 0;
11509 }
11510 
11511 static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id)
11512 {
11513 	struct bpf_func_state *unused;
11514 	struct bpf_reg_state *reg;
11515 
11516 	WARN_ON_ONCE(release_reference_nomark(env->cur_state, id));
11517 
11518 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11519 		if (reg->id == id) {
11520 			reg->id = 0;
11521 			ref_set_non_owning(env, reg);
11522 		}
11523 	}));
11524 
11525 	return;
11526 }
11527 
11528 /* Implementation details:
11529  *
11530  * Each register points to some region of memory, which we define as an
11531  * allocation. Each allocation may embed a bpf_spin_lock which protects any
11532  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11533  * allocation. The lock and the data it protects are colocated in the same
11534  * memory region.
11535  *
11536  * Hence, everytime a register holds a pointer value pointing to such
11537  * allocation, the verifier preserves a unique reg->id for it.
11538  *
11539  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11540  * bpf_spin_lock is called.
11541  *
11542  * To enable this, lock state in the verifier captures two values:
11543  *	active_lock.ptr = Register's type specific pointer
11544  *	active_lock.id  = A unique ID for each register pointer value
11545  *
11546  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11547  * supported register types.
11548  *
11549  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11550  * allocated objects is the reg->btf pointer.
11551  *
11552  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11553  * can establish the provenance of the map value statically for each distinct
11554  * lookup into such maps. They always contain a single map value hence unique
11555  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11556  *
11557  * So, in case of global variables, they use array maps with max_entries = 1,
11558  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11559  * into the same map value as max_entries is 1, as described above).
11560  *
11561  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11562  * outer map pointer (in verifier context), but each lookup into an inner map
11563  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11564  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11565  * will get different reg->id assigned to each lookup, hence different
11566  * active_lock.id.
11567  *
11568  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11569  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11570  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11571  */
11572 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11573 {
11574 	struct bpf_reference_state *s;
11575 	void *ptr;
11576 	u32 id;
11577 
11578 	switch ((int)reg->type) {
11579 	case PTR_TO_MAP_VALUE:
11580 		ptr = reg->map_ptr;
11581 		break;
11582 	case PTR_TO_BTF_ID | MEM_ALLOC:
11583 		ptr = reg->btf;
11584 		break;
11585 	default:
11586 		verifier_bug(env, "unknown reg type for lock check");
11587 		return -EFAULT;
11588 	}
11589 	id = reg->id;
11590 
11591 	if (!env->cur_state->active_locks)
11592 		return -EINVAL;
11593 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
11594 	if (!s) {
11595 		verbose(env, "held lock and object are not in the same allocation\n");
11596 		return -EINVAL;
11597 	}
11598 	return 0;
11599 }
11600 
11601 static bool is_bpf_list_api_kfunc(u32 btf_id)
11602 {
11603 	return is_bpf_list_push_kfunc(btf_id) ||
11604 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11605 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
11606 	       btf_id == special_kfunc_list[KF_bpf_list_del] ||
11607 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
11608 	       btf_id == special_kfunc_list[KF_bpf_list_back] ||
11609 	       btf_id == special_kfunc_list[KF_bpf_list_is_first] ||
11610 	       btf_id == special_kfunc_list[KF_bpf_list_is_last] ||
11611 	       btf_id == special_kfunc_list[KF_bpf_list_empty];
11612 }
11613 
11614 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11615 {
11616 	return is_bpf_rbtree_add_kfunc(btf_id) ||
11617 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11618 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
11619 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
11620 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
11621 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
11622 }
11623 
11624 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
11625 {
11626 	return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
11627 	       btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
11628 	       btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
11629 }
11630 
11631 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11632 {
11633 	return is_bpf_list_api_kfunc(btf_id) ||
11634 	       is_bpf_rbtree_api_kfunc(btf_id) ||
11635 	       is_bpf_refcount_acquire_kfunc(btf_id);
11636 }
11637 
11638 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
11639 {
11640 	return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
11641 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
11642 	       btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
11643 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
11644 }
11645 
11646 static bool is_bpf_arena_kfunc(u32 btf_id)
11647 {
11648 	return btf_id == special_kfunc_list[KF_bpf_arena_alloc_pages] ||
11649 	       btf_id == special_kfunc_list[KF_bpf_arena_free_pages] ||
11650 	       btf_id == special_kfunc_list[KF_bpf_arena_reserve_pages];
11651 }
11652 
11653 static bool is_bpf_stream_kfunc(u32 btf_id)
11654 {
11655 	return btf_id == special_kfunc_list[KF_bpf_stream_vprintk] ||
11656 	       btf_id == special_kfunc_list[KF_bpf_stream_print_stack];
11657 }
11658 
11659 static bool kfunc_spin_allowed(u32 btf_id)
11660 {
11661 	return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) ||
11662 	       is_bpf_res_spin_lock_kfunc(btf_id) || is_bpf_arena_kfunc(btf_id) ||
11663 	       is_bpf_stream_kfunc(btf_id);
11664 }
11665 
11666 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11667 {
11668 	return is_bpf_rbtree_add_kfunc(btf_id);
11669 }
11670 
11671 static bool is_async_callback_calling_kfunc(u32 btf_id)
11672 {
11673 	return is_bpf_wq_set_callback_kfunc(btf_id) ||
11674 	       is_task_work_add_kfunc(btf_id);
11675 }
11676 
11677 bool bpf_is_throw_kfunc(struct bpf_insn *insn)
11678 {
11679 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11680 	       insn->imm == special_kfunc_list[KF_bpf_throw];
11681 }
11682 
11683 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id)
11684 {
11685 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback];
11686 }
11687 
11688 static bool is_callback_calling_kfunc(u32 btf_id)
11689 {
11690 	return is_sync_callback_calling_kfunc(btf_id) ||
11691 	       is_async_callback_calling_kfunc(btf_id);
11692 }
11693 
11694 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11695 {
11696 	return is_bpf_rbtree_api_kfunc(btf_id);
11697 }
11698 
11699 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11700 					  enum btf_field_type head_field_type,
11701 					  u32 kfunc_btf_id)
11702 {
11703 	bool ret;
11704 
11705 	switch (head_field_type) {
11706 	case BPF_LIST_HEAD:
11707 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11708 		break;
11709 	case BPF_RB_ROOT:
11710 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11711 		break;
11712 	default:
11713 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11714 			btf_field_type_name(head_field_type));
11715 		return false;
11716 	}
11717 
11718 	if (!ret)
11719 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11720 			btf_field_type_name(head_field_type));
11721 	return ret;
11722 }
11723 
11724 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11725 					  enum btf_field_type node_field_type,
11726 					  u32 kfunc_btf_id)
11727 {
11728 	bool ret;
11729 
11730 	switch (node_field_type) {
11731 	case BPF_LIST_NODE:
11732 		ret = is_bpf_list_push_kfunc(kfunc_btf_id) ||
11733 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_del] ||
11734 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_first] ||
11735 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_last];
11736 		break;
11737 	case BPF_RB_NODE:
11738 		ret = (is_bpf_rbtree_add_kfunc(kfunc_btf_id) ||
11739 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11740 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
11741 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
11742 		break;
11743 	default:
11744 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11745 			btf_field_type_name(node_field_type));
11746 		return false;
11747 	}
11748 
11749 	if (!ret)
11750 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11751 			btf_field_type_name(node_field_type));
11752 	return ret;
11753 }
11754 
11755 static int
11756 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11757 				   struct bpf_reg_state *reg, argno_t argno,
11758 				   struct bpf_kfunc_call_arg_meta *meta,
11759 				   enum btf_field_type head_field_type,
11760 				   struct btf_field **head_field)
11761 {
11762 	const char *head_type_name;
11763 	struct btf_field *field;
11764 	struct btf_record *rec;
11765 	u32 head_off;
11766 
11767 	if (meta->btf != btf_vmlinux) {
11768 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
11769 		return -EFAULT;
11770 	}
11771 
11772 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11773 		return -EFAULT;
11774 
11775 	head_type_name = btf_field_type_name(head_field_type);
11776 	if (!tnum_is_const(reg->var_off)) {
11777 		verbose(env,
11778 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
11779 			reg_arg_name(env, argno), head_type_name);
11780 		return -EINVAL;
11781 	}
11782 
11783 	rec = reg_btf_record(reg);
11784 	head_off = reg->var_off.value;
11785 	field = btf_record_find(rec, head_off, head_field_type);
11786 	if (!field) {
11787 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11788 		return -EINVAL;
11789 	}
11790 
11791 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11792 	if (check_reg_allocation_locked(env, reg)) {
11793 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11794 			rec->spin_lock_off, head_type_name);
11795 		return -EINVAL;
11796 	}
11797 
11798 	if (*head_field) {
11799 		verifier_bug(env, "repeating %s arg", head_type_name);
11800 		return -EFAULT;
11801 	}
11802 	*head_field = field;
11803 	return 0;
11804 }
11805 
11806 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11807 					   struct bpf_reg_state *reg, argno_t argno,
11808 					   struct bpf_kfunc_call_arg_meta *meta)
11809 {
11810 	return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_LIST_HEAD,
11811 							  &meta->arg_list_head.field);
11812 }
11813 
11814 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11815 					     struct bpf_reg_state *reg, argno_t argno,
11816 					     struct bpf_kfunc_call_arg_meta *meta)
11817 {
11818 	return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_RB_ROOT,
11819 							  &meta->arg_rbtree_root.field);
11820 }
11821 
11822 static int
11823 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11824 				   struct bpf_reg_state *reg, argno_t argno,
11825 				   struct bpf_kfunc_call_arg_meta *meta,
11826 				   enum btf_field_type head_field_type,
11827 				   enum btf_field_type node_field_type,
11828 				   struct btf_field **node_field)
11829 {
11830 	const char *node_type_name;
11831 	const struct btf_type *et, *t;
11832 	struct btf_field *field;
11833 	u32 node_off;
11834 
11835 	if (meta->btf != btf_vmlinux) {
11836 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
11837 		return -EFAULT;
11838 	}
11839 
11840 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11841 		return -EFAULT;
11842 
11843 	node_type_name = btf_field_type_name(node_field_type);
11844 	if (!tnum_is_const(reg->var_off)) {
11845 		verbose(env,
11846 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
11847 			reg_arg_name(env, argno), node_type_name);
11848 		return -EINVAL;
11849 	}
11850 
11851 	node_off = reg->var_off.value;
11852 	field = reg_find_field_offset(reg, node_off, node_field_type);
11853 	if (!field) {
11854 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11855 		return -EINVAL;
11856 	}
11857 
11858 	field = *node_field;
11859 
11860 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11861 	t = btf_type_by_id(reg->btf, reg->btf_id);
11862 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11863 				  field->graph_root.value_btf_id, true)) {
11864 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11865 			"in struct %s, but arg is at offset=%d in struct %s\n",
11866 			btf_field_type_name(head_field_type),
11867 			btf_field_type_name(node_field_type),
11868 			field->graph_root.node_offset,
11869 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11870 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11871 		return -EINVAL;
11872 	}
11873 	meta->arg_btf = reg->btf;
11874 	meta->arg_btf_id = reg->btf_id;
11875 
11876 	if (node_off != field->graph_root.node_offset) {
11877 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11878 			node_off, btf_field_type_name(node_field_type),
11879 			field->graph_root.node_offset,
11880 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11881 		return -EINVAL;
11882 	}
11883 
11884 	return 0;
11885 }
11886 
11887 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11888 					   struct bpf_reg_state *reg, argno_t argno,
11889 					   struct bpf_kfunc_call_arg_meta *meta)
11890 {
11891 	return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta,
11892 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11893 						  &meta->arg_list_head.field);
11894 }
11895 
11896 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11897 					     struct bpf_reg_state *reg, argno_t argno,
11898 					     struct bpf_kfunc_call_arg_meta *meta)
11899 {
11900 	return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta,
11901 						  BPF_RB_ROOT, BPF_RB_NODE,
11902 						  &meta->arg_rbtree_root.field);
11903 }
11904 
11905 /*
11906  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11907  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11908  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11909  * them can only be attached to some specific hook points.
11910  */
11911 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11912 {
11913 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11914 
11915 	switch (prog_type) {
11916 	case BPF_PROG_TYPE_LSM:
11917 		return true;
11918 	case BPF_PROG_TYPE_TRACING:
11919 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11920 			return true;
11921 		fallthrough;
11922 	default:
11923 		return in_sleepable(env);
11924 	}
11925 }
11926 
11927 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11928 			    int insn_idx)
11929 {
11930 	const char *func_name = meta->func_name, *ref_tname;
11931 	struct bpf_func_state *caller = cur_func(env);
11932 	struct bpf_reg_state *regs = cur_regs(env);
11933 	const struct btf *btf = meta->btf;
11934 	const struct btf_param *args;
11935 	struct btf_record *rec;
11936 	u32 i, nargs;
11937 	int ret;
11938 
11939 	args = (const struct btf_param *)(meta->func_proto + 1);
11940 	nargs = btf_type_vlen(meta->func_proto);
11941 	if (nargs > MAX_BPF_FUNC_ARGS) {
11942 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11943 			MAX_BPF_FUNC_ARGS);
11944 		return -EINVAL;
11945 	}
11946 	if (nargs > MAX_BPF_FUNC_REG_ARGS && !bpf_jit_supports_stack_args()) {
11947 		verbose(env, "JIT does not support kfunc %s() with %d args\n",
11948 			func_name, nargs);
11949 		return -ENOTSUPP;
11950 	}
11951 
11952 	ret = check_outgoing_stack_args(env, caller, nargs);
11953 	if (ret)
11954 		return ret;
11955 
11956 	/* Check that BTF function arguments match actual types that the
11957 	 * verifier sees.
11958 	 */
11959 	for (i = 0; i < nargs; i++) {
11960 		struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i);
11961 		const struct btf_type *t, *ref_t, *resolve_ret;
11962 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11963 		argno_t argno = argno_from_arg(i + 1);
11964 		int regno = reg_from_argno(argno);
11965 		bool btf_id_fixed_off_ok = true;
11966 		u32 ref_id, type_size;
11967 		bool is_ret_buf_sz = false;
11968 		int kf_arg_type;
11969 
11970 		if (is_kfunc_arg_prog_aux(btf, &args[i])) {
11971 			/* Reject repeated use bpf_prog_aux */
11972 			if (meta->arg_prog) {
11973 				verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc");
11974 				return -EFAULT;
11975 			}
11976 			if (regno < 0) {
11977 				verbose(env, "%s prog->aux cannot be a stack argument\n",
11978 					reg_arg_name(env, argno));
11979 				return -EINVAL;
11980 			}
11981 			meta->arg_prog = true;
11982 			cur_aux(env)->arg_prog = regno;
11983 			continue;
11984 		}
11985 
11986 		if (is_kfunc_arg_ignore(btf, &args[i]) || is_kfunc_arg_implicit(meta, i))
11987 			continue;
11988 
11989 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11990 
11991 		if (btf_type_is_scalar(t)) {
11992 			if (reg->type != SCALAR_VALUE) {
11993 				verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno));
11994 				return -EINVAL;
11995 			}
11996 
11997 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11998 				if (meta->arg_constant.found) {
11999 					verifier_bug(env, "only one constant argument permitted");
12000 					return -EFAULT;
12001 				}
12002 				if (!tnum_is_const(reg->var_off)) {
12003 					verbose(env, "%s must be a known constant\n",
12004 						reg_arg_name(env, argno));
12005 					return -EINVAL;
12006 				}
12007 				if (regno >= 0)
12008 					ret = mark_chain_precision(env, regno);
12009 				else
12010 					ret = mark_stack_arg_precision(env, i);
12011 				if (ret < 0)
12012 					return ret;
12013 				meta->arg_constant.found = true;
12014 				meta->arg_constant.value = reg->var_off.value;
12015 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
12016 				meta->r0_rdonly = true;
12017 				is_ret_buf_sz = true;
12018 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
12019 				is_ret_buf_sz = true;
12020 			}
12021 
12022 			if (is_ret_buf_sz) {
12023 				if (meta->r0_size) {
12024 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
12025 					return -EINVAL;
12026 				}
12027 
12028 				if (!tnum_is_const(reg->var_off)) {
12029 					verbose(env, "%s is not a const\n",
12030 						reg_arg_name(env, argno));
12031 					return -EINVAL;
12032 				}
12033 
12034 				meta->r0_size = reg->var_off.value;
12035 				if (regno >= 0)
12036 					ret = mark_chain_precision(env, regno);
12037 				else
12038 					ret = mark_stack_arg_precision(env, i);
12039 				if (ret)
12040 					return ret;
12041 			}
12042 			continue;
12043 		}
12044 
12045 		if (!btf_type_is_ptr(t)) {
12046 			verbose(env, "Unrecognized %s type %s\n",
12047 				reg_arg_name(env, argno), btf_type_str(t));
12048 			return -EINVAL;
12049 		}
12050 
12051 		if ((bpf_register_is_null(reg) || type_may_be_null(reg->type)) &&
12052 		    !is_kfunc_arg_nullable(meta->btf, &args[i])) {
12053 			verbose(env, "Possibly NULL pointer passed to trusted %s\n",
12054 				reg_arg_name(env, argno));
12055 			return -EACCES;
12056 		}
12057 
12058 		if (regno == meta->release_regno && !is_kfunc_arg_dynptr(meta->btf, &args[i]) &&
12059 		    !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) {
12060 			verbose(env, "release kfunc %s expects referenced PTR_TO_BTF_ID passed to %s\n",
12061 				func_name, reg_arg_name(env, argno));
12062 			return -EINVAL;
12063 		}
12064 
12065 		if (reg_is_referenced(env, reg))
12066 			update_ref_obj(&meta->ref_obj, reg);
12067 
12068 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
12069 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12070 
12071 		kf_arg_type = get_kfunc_ptr_arg_type(env, caller, regs, meta, t, ref_t, ref_tname,
12072 						     args, i, nargs, argno, reg);
12073 		if (kf_arg_type < 0)
12074 			return kf_arg_type;
12075 
12076 		switch (kf_arg_type) {
12077 		case KF_ARG_PTR_TO_NULL:
12078 			continue;
12079 		case KF_ARG_PTR_TO_MAP:
12080 			if (!reg->map_ptr) {
12081 				verbose(env, "pointer in %s isn't map pointer\n",
12082 					reg_arg_name(env, argno));
12083 				return -EINVAL;
12084 			}
12085 			if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 ||
12086 					      reg->map_ptr->record->task_work_off >= 0)) {
12087 				/* Use map_uid (which is unique id of inner map) to reject:
12088 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
12089 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
12090 				 * if (inner_map1 && inner_map2) {
12091 				 *     wq = bpf_map_lookup_elem(inner_map1);
12092 				 *     if (wq)
12093 				 *         // mismatch would have been allowed
12094 				 *         bpf_wq_init(wq, inner_map2);
12095 				 * }
12096 				 *
12097 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
12098 				 */
12099 				if (meta->map.ptr != reg->map_ptr ||
12100 				    meta->map.uid != reg->map_uid) {
12101 					if (reg->map_ptr->record->task_work_off >= 0) {
12102 						verbose(env,
12103 							"bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n",
12104 							meta->map.uid, reg->map_uid);
12105 						return -EINVAL;
12106 					}
12107 					verbose(env,
12108 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
12109 						meta->map.uid, reg->map_uid);
12110 					return -EINVAL;
12111 				}
12112 			}
12113 			meta->map.ptr = reg->map_ptr;
12114 			meta->map.uid = reg->map_uid;
12115 			fallthrough;
12116 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12117 		case KF_ARG_PTR_TO_BTF_ID:
12118 			if (!is_trusted_reg(env, reg)) {
12119 				if (!is_kfunc_rcu(meta)) {
12120 					verbose(env, "%s must be referenced or trusted\n",
12121 						reg_arg_name(env, argno));
12122 					return -EINVAL;
12123 				}
12124 				if (!is_rcu_reg(reg)) {
12125 					verbose(env, "%s must be a rcu pointer\n",
12126 						reg_arg_name(env, argno));
12127 					return -EINVAL;
12128 				}
12129 			}
12130 			fallthrough;
12131 		case KF_ARG_PTR_TO_ITER:
12132 		case KF_ARG_PTR_TO_LIST_HEAD:
12133 		case KF_ARG_PTR_TO_LIST_NODE:
12134 		case KF_ARG_PTR_TO_RB_ROOT:
12135 		case KF_ARG_PTR_TO_RB_NODE:
12136 		case KF_ARG_PTR_TO_MEM:
12137 		case KF_ARG_PTR_TO_MEM_SIZE:
12138 		case KF_ARG_PTR_TO_CALLBACK:
12139 		case KF_ARG_PTR_TO_CONST_STR:
12140 		case KF_ARG_PTR_TO_WORKQUEUE:
12141 		case KF_ARG_PTR_TO_TIMER:
12142 		case KF_ARG_PTR_TO_TASK_WORK:
12143 		case KF_ARG_PTR_TO_IRQ_FLAG:
12144 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
12145 			break;
12146 		case KF_ARG_PTR_TO_DYNPTR:
12147 			arg_type = ARG_PTR_TO_DYNPTR;
12148 			break;
12149 		case KF_ARG_PTR_TO_CTX:
12150 			arg_type = ARG_PTR_TO_CTX;
12151 			break;
12152 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12153 			arg_type = ARG_PTR_TO_BTF_ID;
12154 			btf_id_fixed_off_ok = false;
12155 			break;
12156 		default:
12157 			verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type);
12158 			return -EFAULT;
12159 		}
12160 
12161 		if (regno == meta->release_regno)
12162 			arg_type |= OBJ_RELEASE;
12163 		ret = __check_func_arg_reg_off(env, reg, argno, arg_type,
12164 					       btf_id_fixed_off_ok);
12165 		if (ret < 0)
12166 			return ret;
12167 
12168 		switch (kf_arg_type) {
12169 		case KF_ARG_PTR_TO_CTX:
12170 			if (reg->type != PTR_TO_CTX) {
12171 				verbose(env, "%s expected pointer to ctx, but got %s\n",
12172 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
12173 				return -EINVAL;
12174 			}
12175 
12176 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12177 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
12178 				if (ret < 0)
12179 					return -EINVAL;
12180 				meta->ret_btf_id  = ret;
12181 			}
12182 			break;
12183 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12184 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
12185 				if (!is_bpf_obj_drop_kfunc(meta->func_id)) {
12186 					verbose(env, "%s expected for bpf_obj_drop()\n",
12187 						reg_arg_name(env, argno));
12188 					return -EINVAL;
12189 				}
12190 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
12191 				if (!is_bpf_percpu_obj_drop_kfunc(meta->func_id)) {
12192 					verbose(env, "%s expected for bpf_percpu_obj_drop()\n",
12193 						reg_arg_name(env, argno));
12194 					return -EINVAL;
12195 				}
12196 			} else {
12197 				verbose(env, "%s expected pointer to allocated object\n",
12198 					reg_arg_name(env, argno));
12199 				return -EINVAL;
12200 			}
12201 			if (!reg_is_referenced(env, reg)) {
12202 				verbose(env, "allocated object must be referenced\n");
12203 				return -EINVAL;
12204 			}
12205 			if (meta->btf == btf_vmlinux) {
12206 				meta->arg_btf = reg->btf;
12207 				meta->arg_btf_id = reg->btf_id;
12208 			}
12209 			break;
12210 		case KF_ARG_PTR_TO_DYNPTR:
12211 		{
12212 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
12213 
12214 			if (is_kfunc_arg_uninit(btf, &args[i]))
12215 				dynptr_arg_type |= MEM_UNINIT;
12216 
12217 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
12218 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
12219 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
12220 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
12221 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
12222 				dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
12223 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
12224 				dynptr_arg_type |= DYNPTR_TYPE_FILE;
12225 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) {
12226 				dynptr_arg_type |= DYNPTR_TYPE_FILE | OBJ_RELEASE;
12227 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
12228 				   (dynptr_arg_type & MEM_UNINIT)) {
12229 				enum bpf_dynptr_type parent_type = meta->dynptr.type;
12230 
12231 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
12232 					verifier_bug(env, "no dynptr type for parent of clone");
12233 					return -EFAULT;
12234 				}
12235 
12236 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
12237 			}
12238 
12239 			ret = process_dynptr_func(env, reg, argno, insn_idx, dynptr_arg_type,
12240 						  &meta->ref_obj, &meta->dynptr);
12241 			if (ret < 0)
12242 				return ret;
12243 			break;
12244 		}
12245 		case KF_ARG_PTR_TO_ITER:
12246 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
12247 				if (!check_css_task_iter_allowlist(env)) {
12248 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
12249 					return -EINVAL;
12250 				}
12251 			}
12252 			ret = process_iter_arg(env, reg, argno, insn_idx, meta);
12253 			if (ret < 0)
12254 				return ret;
12255 			break;
12256 		case KF_ARG_PTR_TO_LIST_HEAD:
12257 			if (reg->type != PTR_TO_MAP_VALUE &&
12258 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12259 				verbose(env, "%s expected pointer to map value or allocated object\n",
12260 					reg_arg_name(env, argno));
12261 				return -EINVAL;
12262 			}
12263 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) &&
12264 			    !reg_is_referenced(env, reg)) {
12265 				verbose(env, "allocated object must be referenced\n");
12266 				return -EINVAL;
12267 			}
12268 			ret = process_kf_arg_ptr_to_list_head(env, reg, argno, meta);
12269 			if (ret < 0)
12270 				return ret;
12271 			break;
12272 		case KF_ARG_PTR_TO_RB_ROOT:
12273 			if (reg->type != PTR_TO_MAP_VALUE &&
12274 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12275 				verbose(env, "%s expected pointer to map value or allocated object\n",
12276 					reg_arg_name(env, argno));
12277 				return -EINVAL;
12278 			}
12279 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) &&
12280 			    !reg_is_referenced(env, reg)) {
12281 				verbose(env, "allocated object must be referenced\n");
12282 				return -EINVAL;
12283 			}
12284 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, argno, meta);
12285 			if (ret < 0)
12286 				return ret;
12287 			break;
12288 		case KF_ARG_PTR_TO_LIST_NODE:
12289 			if (is_kfunc_arg_nonown_allowed(btf, &args[i]) &&
12290 			    type_is_non_owning_ref(reg->type) && !reg_is_referenced(env, reg)) {
12291 				/* Allow bpf_list_front/back return value for
12292 				 * __nonown_allowed list-node arguments.
12293 				 */
12294 				goto check_ok;
12295 			}
12296 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12297 				verbose(env, "%s expected pointer to allocated object\n",
12298 					reg_arg_name(env, argno));
12299 				return -EINVAL;
12300 			}
12301 			if (!reg_is_referenced(env, reg)) {
12302 				verbose(env, "allocated object must be referenced\n");
12303 				return -EINVAL;
12304 			}
12305 check_ok:
12306 			ret = process_kf_arg_ptr_to_list_node(env, reg, argno, meta);
12307 			if (ret < 0)
12308 				return ret;
12309 			break;
12310 		case KF_ARG_PTR_TO_RB_NODE:
12311 			if (is_bpf_rbtree_add_kfunc(meta->func_id)) {
12312 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12313 					verbose(env, "%s expected pointer to allocated object\n",
12314 						reg_arg_name(env, argno));
12315 					return -EINVAL;
12316 				}
12317 				if (!reg_is_referenced(env, reg)) {
12318 					verbose(env, "allocated object must be referenced\n");
12319 					return -EINVAL;
12320 				}
12321 			} else {
12322 				if (!type_is_non_owning_ref(reg->type) &&
12323 				    !reg_is_referenced(env, reg)) {
12324 					verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
12325 					return -EINVAL;
12326 				}
12327 				if (in_rbtree_lock_required_cb(env)) {
12328 					verbose(env, "%s not allowed in rbtree cb\n", func_name);
12329 					return -EINVAL;
12330 				}
12331 			}
12332 
12333 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, argno, meta);
12334 			if (ret < 0)
12335 				return ret;
12336 			break;
12337 		case KF_ARG_PTR_TO_MAP:
12338 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
12339 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
12340 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
12341 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12342 			fallthrough;
12343 		case KF_ARG_PTR_TO_BTF_ID:
12344 			/* Only base_type is checked, further checks are done here */
12345 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
12346 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
12347 			    !reg2btf_ids[base_type(reg->type)]) {
12348 				verbose(env, "%s is %s ", reg_arg_name(env, argno),
12349 					reg_type_str(env, reg->type));
12350 				verbose(env, "expected %s or socket\n",
12351 					reg_type_str(env, base_type(reg->type) |
12352 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
12353 				return -EINVAL;
12354 			}
12355 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i, argno);
12356 			if (ret < 0)
12357 				return ret;
12358 			break;
12359 		case KF_ARG_PTR_TO_MEM:
12360 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
12361 			if (IS_ERR(resolve_ret)) {
12362 				verbose(env, "%s reference type('%s %s') size cannot be determined: %ld\n",
12363 					reg_arg_name(env, argno), btf_type_str(ref_t),
12364 					ref_tname, PTR_ERR(resolve_ret));
12365 				return -EINVAL;
12366 			}
12367 			ret = check_mem_reg(env, reg, argno, type_size);
12368 			if (ret < 0)
12369 				return ret;
12370 			break;
12371 		case KF_ARG_PTR_TO_MEM_SIZE:
12372 		{
12373 			struct bpf_reg_state *buff_reg = reg;
12374 			const struct btf_param *buff_arg = &args[i];
12375 			struct bpf_reg_state *size_reg = get_func_arg_reg(caller, regs, i + 1);
12376 			const struct btf_param *size_arg = &args[i + 1];
12377 			argno_t next_argno = argno_from_arg(i + 2);
12378 
12379 			if (!bpf_register_is_null(buff_reg) || !is_kfunc_arg_nullable(meta->btf, buff_arg)) {
12380 				ret = check_kfunc_mem_size_reg(env, buff_reg, size_reg,
12381 							       argno, next_argno);
12382 				if (ret < 0) {
12383 					verbose(env, "%s and ", reg_arg_name(env, argno));
12384 					verbose(env, "%s memory, len pair leads to invalid memory access\n",
12385 						reg_arg_name(env, next_argno));
12386 					return ret;
12387 				}
12388 			}
12389 
12390 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
12391 				if (meta->arg_constant.found) {
12392 					verifier_bug(env, "only one constant argument permitted");
12393 					return -EFAULT;
12394 				}
12395 				if (!tnum_is_const(size_reg->var_off)) {
12396 					verbose(env, "%s must be a known constant\n",
12397 						reg_arg_name(env, next_argno));
12398 					return -EINVAL;
12399 				}
12400 				meta->arg_constant.found = true;
12401 				meta->arg_constant.value = size_reg->var_off.value;
12402 			}
12403 
12404 			/* Skip next '__sz' or '__szk' argument */
12405 			i++;
12406 			break;
12407 		}
12408 		case KF_ARG_PTR_TO_CALLBACK:
12409 			if (reg->type != PTR_TO_FUNC) {
12410 				verbose(env, "%s expected pointer to func\n", reg_arg_name(env, argno));
12411 				return -EINVAL;
12412 			}
12413 			meta->subprogno = reg->subprogno;
12414 			break;
12415 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12416 			if (!type_is_ptr_alloc_obj(reg->type)) {
12417 				verbose(env, "%s is neither owning or non-owning ref\n",
12418 					reg_arg_name(env, argno));
12419 				return -EINVAL;
12420 			}
12421 			if (!type_is_non_owning_ref(reg->type))
12422 				meta->arg_owning_ref = true;
12423 
12424 			rec = reg_btf_record(reg);
12425 			if (!rec) {
12426 				verifier_bug(env, "Couldn't find btf_record");
12427 				return -EFAULT;
12428 			}
12429 
12430 			if (rec->refcount_off < 0) {
12431 				verbose(env, "%s doesn't point to a type with bpf_refcount field\n",
12432 					reg_arg_name(env, argno));
12433 				return -EINVAL;
12434 			}
12435 
12436 			meta->arg_btf = reg->btf;
12437 			meta->arg_btf_id = reg->btf_id;
12438 			break;
12439 		case KF_ARG_PTR_TO_CONST_STR:
12440 			if (reg->type != PTR_TO_MAP_VALUE) {
12441 				verbose(env, "%s doesn't point to a const string\n",
12442 					reg_arg_name(env, argno));
12443 				return -EINVAL;
12444 			}
12445 			ret = check_arg_const_str(env, reg, argno);
12446 			if (ret)
12447 				return ret;
12448 			break;
12449 		case KF_ARG_PTR_TO_WORKQUEUE:
12450 			if (reg->type != PTR_TO_MAP_VALUE) {
12451 				verbose(env, "%s doesn't point to a map value\n",
12452 					reg_arg_name(env, argno));
12453 				return -EINVAL;
12454 			}
12455 			ret = check_map_field_pointer(env, reg, argno, BPF_WORKQUEUE, &meta->map);
12456 			if (ret < 0)
12457 				return ret;
12458 			break;
12459 		case KF_ARG_PTR_TO_TIMER:
12460 			if (reg->type != PTR_TO_MAP_VALUE) {
12461 				verbose(env, "%s doesn't point to a map value\n",
12462 					reg_arg_name(env, argno));
12463 				return -EINVAL;
12464 			}
12465 			ret = process_timer_kfunc(env, reg, argno, meta);
12466 			if (ret < 0)
12467 				return ret;
12468 			break;
12469 		case KF_ARG_PTR_TO_TASK_WORK:
12470 			if (reg->type != PTR_TO_MAP_VALUE) {
12471 				verbose(env, "%s doesn't point to a map value\n",
12472 					reg_arg_name(env, argno));
12473 				return -EINVAL;
12474 			}
12475 			ret = check_map_field_pointer(env, reg, argno, BPF_TASK_WORK, &meta->map);
12476 			if (ret < 0)
12477 				return ret;
12478 			break;
12479 		case KF_ARG_PTR_TO_IRQ_FLAG:
12480 			if (reg->type != PTR_TO_STACK) {
12481 				verbose(env, "%s doesn't point to an irq flag on stack\n",
12482 					reg_arg_name(env, argno));
12483 				return -EINVAL;
12484 			}
12485 			ret = process_irq_flag(env, reg, argno, meta);
12486 			if (ret < 0)
12487 				return ret;
12488 			break;
12489 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
12490 		{
12491 			int flags = PROCESS_RES_LOCK;
12492 
12493 			if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12494 				verbose(env, "%s doesn't point to map value or allocated object\n",
12495 					reg_arg_name(env, argno));
12496 				return -EINVAL;
12497 			}
12498 
12499 			if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
12500 				return -EFAULT;
12501 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
12502 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12503 				flags |= PROCESS_SPIN_LOCK;
12504 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
12505 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12506 				flags |= PROCESS_LOCK_IRQ;
12507 			ret = process_spin_lock(env, reg, argno, flags);
12508 			if (ret < 0)
12509 				return ret;
12510 			break;
12511 		}
12512 		}
12513 	}
12514 
12515 	return 0;
12516 }
12517 
12518 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env,
12519 			     s32 func_id,
12520 			     s16 offset,
12521 			     struct bpf_kfunc_call_arg_meta *meta)
12522 {
12523 	struct bpf_kfunc_meta kfunc;
12524 	int err;
12525 
12526 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
12527 	if (err)
12528 		return err;
12529 
12530 	memset(meta, 0, sizeof(*meta));
12531 	meta->btf = kfunc.btf;
12532 	meta->func_id = kfunc.id;
12533 	meta->func_proto = kfunc.proto;
12534 	meta->func_name = kfunc.name;
12535 
12536 	if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog))
12537 		return -EACCES;
12538 
12539 	meta->kfunc_flags = *kfunc.flags;
12540 
12541 	/* Only support release referenced argument passed by register */
12542 	if (is_kfunc_release(meta))
12543 		meta->release_regno = BPF_REG_1;
12544 
12545 	return 0;
12546 }
12547 
12548 /*
12549  * Determine how many bytes a helper accesses through a stack pointer at
12550  * argument position @arg (0-based, corresponding to R1-R5).
12551  *
12552  * Returns:
12553  *   > 0   known read access size in bytes
12554  *     0   doesn't read anything directly
12555  * S64_MIN unknown
12556  *   < 0   known write access of (-return) bytes
12557  */
12558 s64 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
12559 				  int arg, int insn_idx)
12560 {
12561 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
12562 	const struct bpf_func_proto *fn;
12563 	enum bpf_arg_type at;
12564 	s64 size;
12565 
12566 	if (bpf_get_helper_proto(env, insn->imm, &fn) < 0)
12567 		return S64_MIN;
12568 
12569 	at = fn->arg_type[arg];
12570 
12571 	switch (base_type(at)) {
12572 	case ARG_PTR_TO_MAP_KEY:
12573 	case ARG_PTR_TO_MAP_VALUE: {
12574 		bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY;
12575 		u64 val;
12576 		int i, map_reg;
12577 
12578 		for (i = 0; i < arg; i++) {
12579 			if (base_type(fn->arg_type[i]) == ARG_CONST_MAP_PTR)
12580 				break;
12581 		}
12582 		if (i >= arg)
12583 			goto scan_all_maps;
12584 
12585 		map_reg = BPF_REG_1 + i;
12586 
12587 		if (!(aux->const_reg_map_mask & BIT(map_reg)))
12588 			goto scan_all_maps;
12589 
12590 		i = aux->const_reg_vals[map_reg];
12591 		if (i < env->used_map_cnt) {
12592 			size = is_key ? env->used_maps[i]->key_size
12593 				      : env->used_maps[i]->value_size;
12594 			goto out;
12595 		}
12596 scan_all_maps:
12597 		/*
12598 		 * Map pointer is not known at this call site (e.g. different
12599 		 * maps on merged paths).  Conservatively return the largest
12600 		 * key_size or value_size across all maps used by the program.
12601 		 */
12602 		val = 0;
12603 		for (i = 0; i < env->used_map_cnt; i++) {
12604 			struct bpf_map *map = env->used_maps[i];
12605 			u32 sz = is_key ? map->key_size : map->value_size;
12606 
12607 			if (sz > val)
12608 				val = sz;
12609 			if (map->inner_map_meta) {
12610 				sz = is_key ? map->inner_map_meta->key_size
12611 					    : map->inner_map_meta->value_size;
12612 				if (sz > val)
12613 					val = sz;
12614 			}
12615 		}
12616 		if (!val)
12617 			return S64_MIN;
12618 		size = val;
12619 		goto out;
12620 	}
12621 	case ARG_PTR_TO_MEM:
12622 		if (at & MEM_FIXED_SIZE) {
12623 			size = fn->arg_size[arg];
12624 			goto out;
12625 		}
12626 		if (arg + 1 < ARRAY_SIZE(fn->arg_type) &&
12627 		    arg_type_is_mem_size(fn->arg_type[arg + 1])) {
12628 			int size_reg = BPF_REG_1 + arg + 1;
12629 
12630 			if (aux->const_reg_mask & BIT(size_reg)) {
12631 				size = (s64)aux->const_reg_vals[size_reg];
12632 				goto out;
12633 			}
12634 			/*
12635 			 * Size arg is const on each path but differs across merged
12636 			 * paths. MAX_BPF_STACK is a safe upper bound for reads.
12637 			 */
12638 			if (at & MEM_UNINIT)
12639 				return 0;
12640 			return MAX_BPF_STACK;
12641 		}
12642 		return S64_MIN;
12643 	case ARG_PTR_TO_DYNPTR:
12644 		size = BPF_DYNPTR_SIZE;
12645 		break;
12646 	case ARG_PTR_TO_STACK:
12647 		/*
12648 		 * Only used by bpf_calls_callback() helpers. The helper itself
12649 		 * doesn't access stack. The callback subprog does and it's
12650 		 * analyzed separately.
12651 		 */
12652 		return 0;
12653 	default:
12654 		return S64_MIN;
12655 	}
12656 out:
12657 	/*
12658 	 * MEM_UNINIT args are write-only: the helper initializes the
12659 	 * buffer without reading it.
12660 	 */
12661 	if (at & MEM_UNINIT)
12662 		return -size;
12663 	return size;
12664 }
12665 
12666 /*
12667  * Determine how many bytes a kfunc accesses through a stack pointer at
12668  * argument position @arg (0-based, corresponding to R1-R5).
12669  *
12670  * Returns:
12671  *   > 0      known read access size in bytes
12672  *     0      doesn't access memory through that argument (ex: not a pointer)
12673  *   S64_MIN  unknown
12674  *   < 0      known write access of (-return) bytes
12675  */
12676 s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
12677 				 int arg, int insn_idx)
12678 {
12679 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
12680 	struct bpf_kfunc_call_arg_meta meta;
12681 	const struct btf_param *args;
12682 	const struct btf_type *t, *ref_t;
12683 	const struct btf *btf;
12684 	u32 nargs, type_size;
12685 	s64 size;
12686 
12687 	if (bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) < 0)
12688 		return S64_MIN;
12689 
12690 	btf = meta.btf;
12691 	args = btf_params(meta.func_proto);
12692 	nargs = btf_type_vlen(meta.func_proto);
12693 	if (arg >= nargs)
12694 		return 0;
12695 
12696 	t = btf_type_skip_modifiers(btf, args[arg].type, NULL);
12697 	if (!btf_type_is_ptr(t))
12698 		return 0;
12699 
12700 	/* dynptr: fixed 16-byte on-stack representation */
12701 	if (is_kfunc_arg_dynptr(btf, &args[arg])) {
12702 		size = BPF_DYNPTR_SIZE;
12703 		goto out;
12704 	}
12705 
12706 	/* ptr + __sz/__szk pair: size is in the next register */
12707 	if (arg + 1 < nargs &&
12708 	    (btf_param_match_suffix(btf, &args[arg + 1], "__sz") ||
12709 	     btf_param_match_suffix(btf, &args[arg + 1], "__szk"))) {
12710 		int size_reg = BPF_REG_1 + arg + 1;
12711 
12712 		if (aux->const_reg_mask & BIT(size_reg)) {
12713 			size = (s64)aux->const_reg_vals[size_reg];
12714 			goto out;
12715 		}
12716 		return MAX_BPF_STACK;
12717 	}
12718 
12719 	/* fixed-size pointed-to type: resolve via BTF */
12720 	ref_t = btf_type_skip_modifiers(btf, t->type, NULL);
12721 	if (!IS_ERR(btf_resolve_size(btf, ref_t, &type_size))) {
12722 		size = type_size;
12723 		goto out;
12724 	}
12725 
12726 	return S64_MIN;
12727 out:
12728 	/* KF_ITER_NEW kfuncs initialize the iterator state at arg 0 */
12729 	if (arg == 0 && meta.kfunc_flags & KF_ITER_NEW)
12730 		return -size;
12731 	if (is_kfunc_arg_uninit(btf, &args[arg]))
12732 		return -size;
12733 	return size;
12734 }
12735 
12736 /* check special kfuncs and return:
12737  *  1  - not fall-through to 'else' branch, continue verification
12738  *  0  - fall-through to 'else' branch
12739  * < 0 - not fall-through to 'else' branch, return error
12740  */
12741 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
12742 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
12743 			       const struct btf_type *ptr_type, struct btf *desc_btf)
12744 {
12745 	const struct btf_type *ret_t;
12746 	int err = 0;
12747 
12748 	if (meta->btf != btf_vmlinux)
12749 		return 0;
12750 
12751 	if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
12752 		struct btf_struct_meta *struct_meta;
12753 		struct btf *ret_btf;
12754 		u32 ret_btf_id;
12755 
12756 		if (is_bpf_obj_new_kfunc(meta->func_id) && !bpf_global_ma_set)
12757 			return -ENOMEM;
12758 
12759 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
12760 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12761 			return -EINVAL;
12762 		}
12763 
12764 		ret_btf = env->prog->aux->btf;
12765 		ret_btf_id = meta->arg_constant.value;
12766 
12767 		/* This may be NULL due to user not supplying a BTF */
12768 		if (!ret_btf) {
12769 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12770 			return -EINVAL;
12771 		}
12772 
12773 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12774 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
12775 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12776 			return -EINVAL;
12777 		}
12778 
12779 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
12780 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12781 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12782 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12783 				return -EINVAL;
12784 			}
12785 
12786 			if (!bpf_global_percpu_ma_set) {
12787 				mutex_lock(&bpf_percpu_ma_lock);
12788 				if (!bpf_global_percpu_ma_set) {
12789 					/* Charge memory allocated with bpf_global_percpu_ma to
12790 					 * root memcg. The obj_cgroup for root memcg is NULL.
12791 					 */
12792 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12793 					if (!err)
12794 						bpf_global_percpu_ma_set = true;
12795 				}
12796 				mutex_unlock(&bpf_percpu_ma_lock);
12797 				if (err)
12798 					return err;
12799 			}
12800 
12801 			mutex_lock(&bpf_percpu_ma_lock);
12802 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12803 			mutex_unlock(&bpf_percpu_ma_lock);
12804 			if (err)
12805 				return err;
12806 		}
12807 
12808 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12809 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
12810 			if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12811 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12812 				return -EINVAL;
12813 			}
12814 
12815 			if (struct_meta) {
12816 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12817 				return -EINVAL;
12818 			}
12819 		}
12820 
12821 		mark_reg_known_zero(env, regs, BPF_REG_0);
12822 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12823 		regs[BPF_REG_0].btf = ret_btf;
12824 		regs[BPF_REG_0].btf_id = ret_btf_id;
12825 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id))
12826 			regs[BPF_REG_0].type |= MEM_PERCPU;
12827 
12828 		insn_aux->obj_new_size = ret_t->size;
12829 		insn_aux->kptr_struct_meta = struct_meta;
12830 	} else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) {
12831 		mark_reg_known_zero(env, regs, BPF_REG_0);
12832 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12833 		regs[BPF_REG_0].btf = meta->arg_btf;
12834 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
12835 
12836 		insn_aux->kptr_struct_meta =
12837 			btf_find_struct_meta(meta->arg_btf,
12838 					     meta->arg_btf_id);
12839 	} else if (is_list_node_type(ptr_type)) {
12840 		struct btf_field *field = meta->arg_list_head.field;
12841 
12842 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12843 	} else if (is_rbtree_node_type(ptr_type)) {
12844 		struct btf_field *field = meta->arg_rbtree_root.field;
12845 
12846 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12847 	} else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12848 		mark_reg_known_zero(env, regs, BPF_REG_0);
12849 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12850 		regs[BPF_REG_0].btf = desc_btf;
12851 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
12852 	} else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12853 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
12854 		if (!ret_t) {
12855 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
12856 				meta->arg_constant.value);
12857 			return -EINVAL;
12858 		} else if (btf_type_is_struct(ret_t)) {
12859 			mark_reg_known_zero(env, regs, BPF_REG_0);
12860 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12861 			regs[BPF_REG_0].btf = desc_btf;
12862 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
12863 		} else if (btf_type_is_void(ret_t)) {
12864 			mark_reg_known_zero(env, regs, BPF_REG_0);
12865 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
12866 			regs[BPF_REG_0].mem_size = 0;
12867 		} else {
12868 			verbose(env,
12869 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
12870 			return -EINVAL;
12871 		}
12872 	} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12873 		   meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12874 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->dynptr.type);
12875 
12876 		mark_reg_known_zero(env, regs, BPF_REG_0);
12877 
12878 		if (!meta->arg_constant.found) {
12879 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
12880 			return -EFAULT;
12881 		}
12882 
12883 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
12884 
12885 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12886 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12887 
12888 		if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12889 			regs[BPF_REG_0].type |= MEM_RDONLY;
12890 		} else {
12891 			/* this will set env->seen_direct_write to true */
12892 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12893 				verbose(env, "the prog does not allow writes to packet data\n");
12894 				return -EINVAL;
12895 			}
12896 		}
12897 
12898 		if (!meta->dynptr.id) {
12899 			verifier_bug(env, "no dynptr id");
12900 			return -EFAULT;
12901 		}
12902 		regs[BPF_REG_0].parent_id = meta->dynptr.id;
12903 	} else {
12904 		return 0;
12905 	}
12906 
12907 	return 1;
12908 }
12909 
12910 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12911 
12912 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12913 			    int *insn_idx_p)
12914 {
12915 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
12916 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12917 	struct bpf_reg_state *regs = cur_regs(env);
12918 	const char *func_name, *ptr_type_name;
12919 	const struct btf_type *t, *ptr_type;
12920 	struct bpf_kfunc_call_arg_meta meta;
12921 	struct bpf_insn_aux_data *insn_aux;
12922 	int err, insn_idx = *insn_idx_p;
12923 	const struct btf_param *args;
12924 	u32 i, nargs, ptr_type_id;
12925 	struct btf *desc_btf;
12926 	int id;
12927 
12928 	/* skip for now, but return error when we find this in fixup_kfunc_call */
12929 	if (!insn->imm)
12930 		return 0;
12931 
12932 	err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
12933 	if (err == -EACCES && meta.func_name)
12934 		verbose(env, "calling kernel function %s is not allowed\n", meta.func_name);
12935 	if (err)
12936 		return err;
12937 	desc_btf = meta.btf;
12938 	func_name = meta.func_name;
12939 	insn_aux = &env->insn_aux_data[insn_idx];
12940 
12941 	insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta);
12942 
12943 	if (!insn->off &&
12944 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
12945 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
12946 		struct bpf_verifier_state *branch;
12947 		struct bpf_reg_state *regs;
12948 
12949 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
12950 		if (IS_ERR(branch)) {
12951 			verbose(env, "failed to push state for failed lock acquisition\n");
12952 			return PTR_ERR(branch);
12953 		}
12954 
12955 		regs = branch->frame[branch->curframe]->regs;
12956 
12957 		/* Clear r0-r5 registers in forked state */
12958 		for (i = 0; i < CALLER_SAVED_REGS; i++)
12959 			bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
12960 
12961 		mark_reg_unknown(env, regs, BPF_REG_0);
12962 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
12963 		if (err) {
12964 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
12965 			return err;
12966 		}
12967 		__mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32));
12968 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
12969 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
12970 		return -EFAULT;
12971 	}
12972 
12973 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12974 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12975 		return -EACCES;
12976 	}
12977 
12978 	sleepable = bpf_is_kfunc_sleepable(&meta);
12979 	if (sleepable && !in_sleepable(env)) {
12980 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12981 		return -EACCES;
12982 	}
12983 
12984 	/* Track non-sleepable context for kfuncs, same as for helpers. */
12985 	if (!in_sleepable_context(env))
12986 		insn_aux->non_sleepable = true;
12987 
12988 	/* Check the arguments */
12989 	err = check_kfunc_args(env, &meta, insn_idx);
12990 	if (err < 0)
12991 		return err;
12992 
12993 	if ((is_bpf_obj_drop_kfunc(meta.func_id) ||
12994 	     is_bpf_percpu_obj_drop_kfunc(meta.func_id)) && (is_tracing_prog_type(prog_type) ||
12995 	     /* is_tracing_prog_type() for now doesn't cover non-iterator tracing progs. */
12996 	     (prog_type == BPF_PROG_TYPE_TRACING && env->prog->expected_attach_type != BPF_TRACE_ITER
12997 	      && !env->prog->sleepable))) {
12998 		struct btf_struct_meta *struct_meta;
12999 
13000 		struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
13001 		if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) {
13002 			verbose(env, "%s cannot be used in tracing programs on types with NMI unsafe fields\n",
13003 				func_name);
13004 			return -EINVAL;
13005 		}
13006 	}
13007 
13008 	if (is_bpf_rbtree_add_kfunc(meta.func_id)) {
13009 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13010 					 set_rbtree_add_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 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
13019 		meta.r0_size = sizeof(u64);
13020 		meta.r0_rdonly = false;
13021 	}
13022 
13023 	if (is_bpf_wq_set_callback_kfunc(meta.func_id)) {
13024 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13025 					 set_timer_callback_state);
13026 		if (err) {
13027 			verbose(env, "kfunc %s#%d failed callback verification\n",
13028 				func_name, meta.func_id);
13029 			return err;
13030 		}
13031 	}
13032 
13033 	if (is_task_work_add_kfunc(meta.func_id)) {
13034 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13035 					 set_task_work_schedule_callback_state);
13036 		if (err) {
13037 			verbose(env, "kfunc %s#%d failed callback verification\n",
13038 				func_name, meta.func_id);
13039 			return err;
13040 		}
13041 	}
13042 
13043 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
13044 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
13045 
13046 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
13047 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
13048 
13049 	if (rcu_lock) {
13050 		env->cur_state->active_rcu_locks++;
13051 	} else if (rcu_unlock) {
13052 		if (env->cur_state->active_rcu_locks == 0) {
13053 			verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
13054 			return -EINVAL;
13055 		}
13056 		if (--env->cur_state->active_rcu_locks == 0)
13057 			invalidate_rcu_protected_refs(env);
13058 	} else if (preempt_disable) {
13059 		env->cur_state->active_preempt_locks++;
13060 	} else if (preempt_enable) {
13061 		if (env->cur_state->active_preempt_locks == 0) {
13062 			verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
13063 			return -EINVAL;
13064 		}
13065 		env->cur_state->active_preempt_locks--;
13066 	}
13067 
13068 	if (sleepable && !in_sleepable_context(env)) {
13069 		verbose(env, "kernel func %s is sleepable within %s\n",
13070 			func_name, non_sleepable_context_description(env));
13071 		return -EACCES;
13072 	}
13073 
13074 	if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
13075 		verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
13076 		return -EACCES;
13077 	}
13078 
13079 	if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
13080 		verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
13081 		return -EACCES;
13082 	}
13083 
13084 	/* In case of release function, we get register number of refcounted
13085 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
13086 	 */
13087 	if (meta.release_regno) {
13088 		err = release_reg(env, &regs[meta.release_regno], false, !!meta.dynptr.id);
13089 		if (err)
13090 			return err;
13091 	}
13092 
13093 	if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) {
13094 		id = regs[BPF_REG_2].id;
13095 		insn_aux->insert_off = regs[BPF_REG_2].var_off.value;
13096 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
13097 		ref_convert_owning_non_owning(env, id);
13098 	}
13099 
13100 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
13101 		if (!bpf_jit_supports_exceptions()) {
13102 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
13103 				func_name, meta.func_id);
13104 			return -ENOTSUPP;
13105 		}
13106 		env->seen_exception = true;
13107 
13108 		/* In the case of the default callback, the cookie value passed
13109 		 * to bpf_throw becomes the return value of the program.
13110 		 */
13111 		if (!env->exception_callback_subprog) {
13112 			err = check_return_code(env, BPF_REG_1, "R1");
13113 			if (err < 0)
13114 				return err;
13115 		}
13116 	}
13117 
13118 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
13119 		u32 regno = caller_saved[i];
13120 
13121 		bpf_mark_reg_not_init(env, &regs[regno]);
13122 		regs[regno].subreg_def = DEF_NOT_SUBREG;
13123 	}
13124 	invalidate_outgoing_stack_args(env, cur_func(env));
13125 
13126 	/* Check return type */
13127 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
13128 
13129 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
13130 		if (meta.btf != btf_vmlinux ||
13131 		    (!is_bpf_obj_new_kfunc(meta.func_id) &&
13132 		     !is_bpf_percpu_obj_new_kfunc(meta.func_id) &&
13133 		     !is_bpf_refcount_acquire_kfunc(meta.func_id))) {
13134 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
13135 			return -EINVAL;
13136 		}
13137 	}
13138 
13139 	if (btf_type_is_scalar(t)) {
13140 		mark_reg_unknown(env, regs, BPF_REG_0);
13141 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13142 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
13143 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
13144 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
13145 	} else if (btf_type_is_ptr(t)) {
13146 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
13147 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
13148 		if (err) {
13149 			if (err < 0)
13150 				return err;
13151 		} else if (btf_type_is_void(ptr_type)) {
13152 			/* kfunc returning 'void *' is equivalent to returning scalar */
13153 			mark_reg_unknown(env, regs, BPF_REG_0);
13154 		} else if (!__btf_type_is_struct(ptr_type)) {
13155 			if (!meta.r0_size) {
13156 				__u32 sz;
13157 
13158 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
13159 					meta.r0_size = sz;
13160 					meta.r0_rdonly = true;
13161 				}
13162 			}
13163 			if (!meta.r0_size) {
13164 				ptr_type_name = btf_name_by_offset(desc_btf,
13165 								   ptr_type->name_off);
13166 				verbose(env,
13167 					"kernel function %s returns pointer type %s %s is not supported\n",
13168 					func_name,
13169 					btf_type_str(ptr_type),
13170 					ptr_type_name);
13171 				return -EINVAL;
13172 			}
13173 
13174 			mark_reg_known_zero(env, regs, BPF_REG_0);
13175 			regs[BPF_REG_0].type = PTR_TO_MEM;
13176 			regs[BPF_REG_0].mem_size = meta.r0_size;
13177 
13178 			if (meta.r0_rdonly)
13179 				regs[BPF_REG_0].type |= MEM_RDONLY;
13180 
13181 			/* Ensures we don't access the memory after a release_reference() */
13182 			if (meta.ref_obj.id) {
13183 				err = validate_ref_obj(env, &meta.ref_obj);
13184 				if (err)
13185 					return err;
13186 				regs[BPF_REG_0].parent_id = meta.ref_obj.id;
13187 			}
13188 
13189 			if (is_kfunc_rcu_protected(&meta))
13190 				regs[BPF_REG_0].type |= MEM_RCU;
13191 		} else {
13192 			enum bpf_reg_type type = PTR_TO_BTF_ID;
13193 
13194 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
13195 				type |= PTR_UNTRUSTED;
13196 			else if (is_kfunc_rcu_protected(&meta) ||
13197 				 (bpf_is_iter_next_kfunc(&meta) &&
13198 				  (get_iter_from_state(env->cur_state, &meta)
13199 					   ->type & MEM_RCU))) {
13200 				/*
13201 				 * If the iterator's constructor (the _new
13202 				 * function e.g., bpf_iter_task_new) has been
13203 				 * annotated with BPF kfunc flag
13204 				 * KF_RCU_PROTECTED and was called within a RCU
13205 				 * read-side critical section, also propagate
13206 				 * the MEM_RCU flag to the pointer returned from
13207 				 * the iterator's next function (e.g.,
13208 				 * bpf_iter_task_next).
13209 				 */
13210 				type |= MEM_RCU;
13211 			} else {
13212 				/*
13213 				 * Any PTR_TO_BTF_ID that is returned from a BPF
13214 				 * kfunc should by default be treated as
13215 				 * implicitly trusted.
13216 				 */
13217 				type |= PTR_TRUSTED;
13218 			}
13219 
13220 			mark_reg_known_zero(env, regs, BPF_REG_0);
13221 			regs[BPF_REG_0].btf = desc_btf;
13222 			regs[BPF_REG_0].type = type;
13223 			regs[BPF_REG_0].btf_id = ptr_type_id;
13224 		}
13225 
13226 		if (is_kfunc_ret_null(&meta)) {
13227 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
13228 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
13229 			regs[BPF_REG_0].id = ++env->id_gen;
13230 		}
13231 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
13232 		if (is_kfunc_acquire(&meta)) {
13233 			id = acquire_reference(env, insn_idx, 0);
13234 			if (id < 0)
13235 				return id;
13236 			regs[BPF_REG_0].id = id;
13237 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
13238 			ref_set_non_owning(env, &regs[BPF_REG_0]);
13239 		}
13240 
13241 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
13242 			regs[BPF_REG_0].id = ++env->id_gen;
13243 	} else if (btf_type_is_void(t)) {
13244 		if (meta.btf == btf_vmlinux) {
13245 			if (is_bpf_obj_drop_kfunc(meta.func_id) ||
13246 			    is_bpf_percpu_obj_drop_kfunc(meta.func_id)) {
13247 				insn_aux->kptr_struct_meta =
13248 					btf_find_struct_meta(meta.arg_btf,
13249 							     meta.arg_btf_id);
13250 			}
13251 		}
13252 	}
13253 
13254 	if (bpf_is_kfunc_pkt_changing(&meta))
13255 		clear_all_pkt_pointers(env);
13256 
13257 	nargs = btf_type_vlen(meta.func_proto);
13258 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
13259 		struct bpf_func_state *caller = cur_func(env);
13260 		struct bpf_subprog_info *caller_info = &env->subprog_info[caller->subprogno];
13261 		u16 out_stack_arg_cnt = nargs - MAX_BPF_FUNC_REG_ARGS;
13262 		u16 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + out_stack_arg_cnt;
13263 
13264 		if (stack_arg_cnt > caller_info->stack_arg_cnt)
13265 			caller_info->stack_arg_cnt = stack_arg_cnt;
13266 	}
13267 
13268 	args = (const struct btf_param *)(meta.func_proto + 1);
13269 	for (i = 0; i < min_t(int, nargs, MAX_BPF_FUNC_REG_ARGS); i++) {
13270 		u32 regno = i + 1;
13271 
13272 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
13273 		if (btf_type_is_ptr(t))
13274 			mark_btf_func_reg_size(env, regno, sizeof(void *));
13275 		else
13276 			/* scalar. ensured by check_kfunc_args() */
13277 			mark_btf_func_reg_size(env, regno, t->size);
13278 	}
13279 
13280 	if (bpf_is_iter_next_kfunc(&meta)) {
13281 		err = process_iter_next_call(env, insn_idx, &meta);
13282 		if (err)
13283 			return err;
13284 	}
13285 
13286 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie])
13287 		env->prog->call_session_cookie = true;
13288 
13289 	if (bpf_is_throw_kfunc(insn))
13290 		return process_bpf_exit_full(env, NULL, true);
13291 
13292 	return 0;
13293 }
13294 
13295 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env,
13296 					 const struct bpf_reg_state *reg,
13297 					 enum bpf_reg_type type)
13298 {
13299 	bool known = tnum_is_const(reg->var_off);
13300 	s64 val = reg->var_off.value;
13301 	s64 smin = reg_smin(reg);
13302 
13303 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
13304 		verbose(env, "math between %s pointer and %lld is not allowed\n",
13305 			reg_type_str(env, type), val);
13306 		return false;
13307 	}
13308 
13309 	if (smin == S64_MIN) {
13310 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
13311 			reg_type_str(env, type));
13312 		return false;
13313 	}
13314 
13315 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
13316 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
13317 			smin, reg_type_str(env, type));
13318 		return false;
13319 	}
13320 
13321 	return true;
13322 }
13323 
13324 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env,
13325 				      const struct bpf_reg_state *reg,
13326 				      enum bpf_reg_type type)
13327 {
13328 	bool known = tnum_is_const(reg->var_off);
13329 	s64 val = reg->var_off.value;
13330 	s64 smin = reg_smin(reg);
13331 
13332 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
13333 		verbose(env, "%s pointer offset %lld is not allowed\n",
13334 			reg_type_str(env, type), val);
13335 		return false;
13336 	}
13337 
13338 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
13339 		verbose(env, "%s pointer offset %lld is not allowed\n",
13340 			reg_type_str(env, type), smin);
13341 		return false;
13342 	}
13343 
13344 	return true;
13345 }
13346 
13347 enum {
13348 	REASON_BOUNDS	= -1,
13349 	REASON_TYPE	= -2,
13350 	REASON_PATHS	= -3,
13351 	REASON_LIMIT	= -4,
13352 	REASON_STACK	= -5,
13353 };
13354 
13355 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
13356 			      u32 *alu_limit, bool mask_to_left)
13357 {
13358 	u32 max = 0, ptr_limit = 0;
13359 
13360 	switch (ptr_reg->type) {
13361 	case PTR_TO_STACK:
13362 		/* Offset 0 is out-of-bounds, but acceptable start for the
13363 		 * left direction, see BPF_REG_FP. Also, unknown scalar
13364 		 * offset where we would need to deal with min/max bounds is
13365 		 * currently prohibited for unprivileged.
13366 		 */
13367 		max = MAX_BPF_STACK + mask_to_left;
13368 		ptr_limit = -ptr_reg->var_off.value;
13369 		break;
13370 	case PTR_TO_MAP_VALUE:
13371 		max = ptr_reg->map_ptr->value_size;
13372 		ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg);
13373 		break;
13374 	default:
13375 		return REASON_TYPE;
13376 	}
13377 
13378 	if (ptr_limit >= max)
13379 		return REASON_LIMIT;
13380 	*alu_limit = ptr_limit;
13381 	return 0;
13382 }
13383 
13384 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
13385 				    const struct bpf_insn *insn)
13386 {
13387 	return env->bypass_spec_v1 ||
13388 		BPF_SRC(insn->code) == BPF_K ||
13389 		cur_aux(env)->nospec;
13390 }
13391 
13392 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
13393 				       u32 alu_state, u32 alu_limit)
13394 {
13395 	/* If we arrived here from different branches with different
13396 	 * state or limits to sanitize, then this won't work.
13397 	 */
13398 	if (aux->alu_state &&
13399 	    (aux->alu_state != alu_state ||
13400 	     aux->alu_limit != alu_limit))
13401 		return REASON_PATHS;
13402 
13403 	/* Corresponding fixup done in do_misc_fixups(). */
13404 	aux->alu_state = alu_state;
13405 	aux->alu_limit = alu_limit;
13406 	return 0;
13407 }
13408 
13409 static int sanitize_val_alu(struct bpf_verifier_env *env,
13410 			    struct bpf_insn *insn)
13411 {
13412 	struct bpf_insn_aux_data *aux = cur_aux(env);
13413 
13414 	if (can_skip_alu_sanitation(env, insn))
13415 		return 0;
13416 
13417 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
13418 }
13419 
13420 static bool sanitize_needed(u8 opcode)
13421 {
13422 	return opcode == BPF_ADD || opcode == BPF_SUB;
13423 }
13424 
13425 struct bpf_sanitize_info {
13426 	struct bpf_insn_aux_data aux;
13427 	bool mask_to_left;
13428 };
13429 
13430 static int sanitize_speculative_path(struct bpf_verifier_env *env,
13431 				     const struct bpf_insn *insn,
13432 				     u32 next_idx, u32 curr_idx)
13433 {
13434 	struct bpf_verifier_state *branch;
13435 	struct bpf_reg_state *regs;
13436 
13437 	branch = push_stack(env, next_idx, curr_idx, true);
13438 	if (!IS_ERR(branch) && insn) {
13439 		regs = branch->frame[branch->curframe]->regs;
13440 		if (BPF_SRC(insn->code) == BPF_K) {
13441 			mark_reg_unknown(env, regs, insn->dst_reg);
13442 		} else if (BPF_SRC(insn->code) == BPF_X) {
13443 			mark_reg_unknown(env, regs, insn->dst_reg);
13444 			mark_reg_unknown(env, regs, insn->src_reg);
13445 		}
13446 	}
13447 	return PTR_ERR_OR_ZERO(branch);
13448 }
13449 
13450 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
13451 			    struct bpf_insn *insn,
13452 			    const struct bpf_reg_state *ptr_reg,
13453 			    const struct bpf_reg_state *off_reg,
13454 			    struct bpf_reg_state *dst_reg,
13455 			    struct bpf_sanitize_info *info,
13456 			    const bool commit_window)
13457 {
13458 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
13459 	struct bpf_verifier_state *vstate = env->cur_state;
13460 	bool off_is_imm = tnum_is_const(off_reg->var_off);
13461 	bool off_is_neg = reg_smin(off_reg) < 0;
13462 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
13463 	u8 opcode = BPF_OP(insn->code);
13464 	u32 alu_state, alu_limit;
13465 	struct bpf_reg_state tmp;
13466 	int err;
13467 
13468 	if (can_skip_alu_sanitation(env, insn))
13469 		return 0;
13470 
13471 	/* We already marked aux for masking from non-speculative
13472 	 * paths, thus we got here in the first place. We only care
13473 	 * to explore bad access from here.
13474 	 */
13475 	if (vstate->speculative)
13476 		goto do_sim;
13477 
13478 	if (!commit_window) {
13479 		if (!tnum_is_const(off_reg->var_off) &&
13480 		    (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0))
13481 			return REASON_BOUNDS;
13482 
13483 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
13484 				     (opcode == BPF_SUB && !off_is_neg);
13485 	}
13486 
13487 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
13488 	if (err < 0)
13489 		return err;
13490 
13491 	if (commit_window) {
13492 		/* In commit phase we narrow the masking window based on
13493 		 * the observed pointer move after the simulated operation.
13494 		 */
13495 		alu_state = info->aux.alu_state;
13496 		alu_limit = abs(info->aux.alu_limit - alu_limit);
13497 	} else {
13498 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
13499 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
13500 		alu_state |= ptr_is_dst_reg ?
13501 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
13502 
13503 		/* Limit pruning on unknown scalars to enable deep search for
13504 		 * potential masking differences from other program paths.
13505 		 */
13506 		if (!off_is_imm)
13507 			env->explore_alu_limits = true;
13508 	}
13509 
13510 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
13511 	if (err < 0)
13512 		return err;
13513 do_sim:
13514 	/* If we're in commit phase, we're done here given we already
13515 	 * pushed the truncated dst_reg into the speculative verification
13516 	 * stack.
13517 	 *
13518 	 * Also, when register is a known constant, we rewrite register-based
13519 	 * operation to immediate-based, and thus do not need masking (and as
13520 	 * a consequence, do not need to simulate the zero-truncation either).
13521 	 */
13522 	if (commit_window || off_is_imm)
13523 		return 0;
13524 
13525 	/* Simulate and find potential out-of-bounds access under
13526 	 * speculative execution from truncation as a result of
13527 	 * masking when off was not within expected range. If off
13528 	 * sits in dst, then we temporarily need to move ptr there
13529 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
13530 	 * for cases where we use K-based arithmetic in one direction
13531 	 * and truncated reg-based in the other in order to explore
13532 	 * bad access.
13533 	 */
13534 	if (!ptr_is_dst_reg) {
13535 		tmp = *dst_reg;
13536 		*dst_reg = *ptr_reg;
13537 	}
13538 	err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx);
13539 	if (err < 0)
13540 		return REASON_STACK;
13541 	if (!ptr_is_dst_reg)
13542 		*dst_reg = tmp;
13543 	return 0;
13544 }
13545 
13546 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
13547 {
13548 	struct bpf_verifier_state *vstate = env->cur_state;
13549 
13550 	/* If we simulate paths under speculation, we don't update the
13551 	 * insn as 'seen' such that when we verify unreachable paths in
13552 	 * the non-speculative domain, sanitize_dead_code() can still
13553 	 * rewrite/sanitize them.
13554 	 */
13555 	if (!vstate->speculative)
13556 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
13557 }
13558 
13559 static int sanitize_err(struct bpf_verifier_env *env,
13560 			const struct bpf_insn *insn, int reason,
13561 			const struct bpf_reg_state *off_reg,
13562 			const struct bpf_reg_state *dst_reg)
13563 {
13564 	static const char *err = "pointer arithmetic with it prohibited for !root";
13565 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
13566 	u32 dst = insn->dst_reg, src = insn->src_reg;
13567 
13568 	switch (reason) {
13569 	case REASON_BOUNDS:
13570 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
13571 			off_reg == dst_reg ? dst : src, err);
13572 		break;
13573 	case REASON_TYPE:
13574 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
13575 			off_reg == dst_reg ? src : dst, err);
13576 		break;
13577 	case REASON_PATHS:
13578 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
13579 			dst, op, err);
13580 		break;
13581 	case REASON_LIMIT:
13582 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
13583 			dst, op, err);
13584 		break;
13585 	case REASON_STACK:
13586 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
13587 			dst, err);
13588 		return -ENOMEM;
13589 	default:
13590 		verifier_bug(env, "unknown reason (%d)", reason);
13591 		break;
13592 	}
13593 
13594 	return -EACCES;
13595 }
13596 
13597 /* check that stack access falls within stack limits and that 'reg' doesn't
13598  * have a variable offset.
13599  *
13600  * Variable offset is prohibited for unprivileged mode for simplicity since it
13601  * requires corresponding support in Spectre masking for stack ALU.  See also
13602  * retrieve_ptr_limit().
13603  */
13604 static int check_stack_access_for_ptr_arithmetic(
13605 				struct bpf_verifier_env *env,
13606 				int regno,
13607 				const struct bpf_reg_state *reg,
13608 				int off)
13609 {
13610 	if (!tnum_is_const(reg->var_off)) {
13611 		char tn_buf[48];
13612 
13613 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
13614 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
13615 			regno, tn_buf, off);
13616 		return -EACCES;
13617 	}
13618 
13619 	if (off >= 0 || off < -MAX_BPF_STACK) {
13620 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
13621 			"prohibited for !root; off=%d\n", regno, off);
13622 		return -EACCES;
13623 	}
13624 
13625 	return 0;
13626 }
13627 
13628 static int sanitize_check_bounds(struct bpf_verifier_env *env,
13629 				 const struct bpf_insn *insn,
13630 				 struct bpf_reg_state *dst_reg)
13631 {
13632 	u32 dst = insn->dst_reg;
13633 
13634 	/* For unprivileged we require that resulting offset must be in bounds
13635 	 * in order to be able to sanitize access later on.
13636 	 */
13637 	if (env->bypass_spec_v1)
13638 		return 0;
13639 
13640 	switch (dst_reg->type) {
13641 	case PTR_TO_STACK:
13642 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
13643 							  dst_reg->var_off.value))
13644 			return -EACCES;
13645 		break;
13646 	case PTR_TO_MAP_VALUE:
13647 		if (check_map_access(env, dst_reg, argno_from_reg(dst), 0, 1, false, ACCESS_HELPER)) {
13648 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
13649 				"prohibited for !root\n", dst);
13650 			return -EACCES;
13651 		}
13652 		break;
13653 	default:
13654 		return -EOPNOTSUPP;
13655 	}
13656 
13657 	return 0;
13658 }
13659 
13660 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
13661  * Caller should also handle BPF_MOV case separately.
13662  * If we return -EACCES, caller may want to try again treating pointer as a
13663  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
13664  */
13665 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
13666 				   struct bpf_insn *insn,
13667 				   const struct bpf_reg_state *ptr_reg,
13668 				   const struct bpf_reg_state *off_reg)
13669 {
13670 	struct bpf_verifier_state *vstate = env->cur_state;
13671 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13672 	struct bpf_reg_state *regs = state->regs, *dst_reg;
13673 	bool known = tnum_is_const(off_reg->var_off);
13674 	s64 smin_val = reg_smin(off_reg), smax_val = reg_smax(off_reg);
13675 	u64 umin_val = reg_umin(off_reg), umax_val = reg_umax(off_reg);
13676 	struct bpf_sanitize_info info = {};
13677 	u8 opcode = BPF_OP(insn->code);
13678 	u32 dst = insn->dst_reg;
13679 	int ret, bounds_ret;
13680 
13681 	dst_reg = &regs[dst];
13682 
13683 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
13684 	    smin_val > smax_val || umin_val > umax_val) {
13685 		/* Taint dst register if offset had invalid bounds derived from
13686 		 * e.g. dead branches.
13687 		 */
13688 		__mark_reg_unknown(env, dst_reg);
13689 		return 0;
13690 	}
13691 
13692 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
13693 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
13694 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13695 			__mark_reg_unknown(env, dst_reg);
13696 			return 0;
13697 		}
13698 
13699 		verbose(env,
13700 			"R%d 32-bit pointer arithmetic prohibited\n",
13701 			dst);
13702 		return -EACCES;
13703 	}
13704 
13705 	if (ptr_reg->type & PTR_MAYBE_NULL) {
13706 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
13707 			dst, reg_type_str(env, ptr_reg->type));
13708 		return -EACCES;
13709 	}
13710 
13711 	/*
13712 	 * Accesses to untrusted PTR_TO_MEM are done through probe
13713 	 * instructions, hence no need to track offsets.
13714 	 */
13715 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
13716 		return 0;
13717 
13718 	switch (base_type(ptr_reg->type)) {
13719 	case PTR_TO_CTX:
13720 	case PTR_TO_MAP_VALUE:
13721 	case PTR_TO_MAP_KEY:
13722 	case PTR_TO_STACK:
13723 	case PTR_TO_PACKET_META:
13724 	case PTR_TO_PACKET:
13725 	case PTR_TO_TP_BUFFER:
13726 	case PTR_TO_BTF_ID:
13727 	case PTR_TO_MEM:
13728 	case PTR_TO_BUF:
13729 	case PTR_TO_FUNC:
13730 	case CONST_PTR_TO_DYNPTR:
13731 		break;
13732 	case PTR_TO_FLOW_KEYS:
13733 		if (known)
13734 			break;
13735 		fallthrough;
13736 	case CONST_PTR_TO_MAP:
13737 		/* smin_val represents the known value */
13738 		if (known && smin_val == 0 && opcode == BPF_ADD)
13739 			break;
13740 		fallthrough;
13741 	default:
13742 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
13743 			dst, reg_type_str(env, ptr_reg->type));
13744 		return -EACCES;
13745 	}
13746 
13747 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
13748 	 * The id may be overwritten later if we create a new variable offset.
13749 	 */
13750 	dst_reg->type = ptr_reg->type;
13751 	dst_reg->id = ptr_reg->id;
13752 
13753 	if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type) ||
13754 	    !check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type))
13755 		return -EINVAL;
13756 
13757 	/* pointer types do not carry 32-bit bounds at the moment. */
13758 	__mark_reg32_unbounded(dst_reg);
13759 
13760 	if (sanitize_needed(opcode)) {
13761 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
13762 				       &info, false);
13763 		if (ret < 0)
13764 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13765 	}
13766 
13767 	switch (opcode) {
13768 	case BPF_ADD:
13769 		/*
13770 		 * dst_reg gets the pointer type and since some positive
13771 		 * integer value was added to the pointer, give it a new 'id'
13772 		 * if it's a PTR_TO_PACKET.
13773 		 * this creates a new 'base' pointer, off_reg (variable) gets
13774 		 * added into the variable offset, and we copy the fixed offset
13775 		 * from ptr_reg.
13776 		 */
13777 		dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64);
13778 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
13779 		dst_reg->raw = ptr_reg->raw;
13780 		if (reg_is_pkt_pointer(ptr_reg)) {
13781 			if (!known)
13782 				dst_reg->id = ++env->id_gen;
13783 			/*
13784 			 * Clear range for unknown addends since we can't know
13785 			 * where the pkt pointer ended up. Also clear AT_PKT_END /
13786 			 * BEYOND_PKT_END from prior comparison as any pointer
13787 			 * arithmetic invalidates them.
13788 			 */
13789 			if (!known || dst_reg->range < 0)
13790 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13791 		}
13792 		break;
13793 	case BPF_SUB:
13794 		if (dst_reg == off_reg) {
13795 			/* scalar -= pointer.  Creates an unknown scalar */
13796 			verbose(env, "R%d tried to subtract pointer from scalar\n",
13797 				dst);
13798 			return -EACCES;
13799 		}
13800 		/* We don't allow subtraction from FP, because (according to
13801 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
13802 		 * be able to deal with it.
13803 		 */
13804 		if (ptr_reg->type == PTR_TO_STACK) {
13805 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
13806 				dst);
13807 			return -EACCES;
13808 		}
13809 		dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64));
13810 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13811 		dst_reg->raw = ptr_reg->raw;
13812 		if (reg_is_pkt_pointer(ptr_reg)) {
13813 			if (!known)
13814 				dst_reg->id = ++env->id_gen;
13815 			/*
13816 			 * Clear range if the subtrahend may be negative since
13817 			 * pkt pointer could move past its bounds. A positive
13818 			 * subtrahend moves it backwards keeping positive range
13819 			 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from
13820 			 * prior comparison as arithmetic invalidates them.
13821 			 */
13822 			if ((!known && smin_val < 0) || dst_reg->range < 0)
13823 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13824 		}
13825 		break;
13826 	case BPF_AND:
13827 	case BPF_OR:
13828 	case BPF_XOR:
13829 		/* bitwise ops on pointers are troublesome, prohibit. */
13830 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13831 			dst, bpf_alu_string[opcode >> 4]);
13832 		return -EACCES;
13833 	default:
13834 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
13835 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13836 			dst, bpf_alu_string[opcode >> 4]);
13837 		return -EACCES;
13838 	}
13839 
13840 	if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type))
13841 		return -EINVAL;
13842 	reg_bounds_sync(dst_reg);
13843 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
13844 	if (bounds_ret == -EACCES)
13845 		return bounds_ret;
13846 	if (sanitize_needed(opcode)) {
13847 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13848 				       &info, true);
13849 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
13850 				    && !env->cur_state->speculative
13851 				    && bounds_ret
13852 				    && !ret,
13853 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
13854 			return -EFAULT;
13855 		}
13856 		if (ret < 0)
13857 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13858 	}
13859 
13860 	return 0;
13861 }
13862 
13863 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13864 				 struct bpf_reg_state *src_reg)
13865 {
13866 	dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32);
13867 }
13868 
13869 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13870 			       struct bpf_reg_state *src_reg)
13871 {
13872 	dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64);
13873 }
13874 
13875 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13876 				 struct bpf_reg_state *src_reg)
13877 {
13878 	dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32));
13879 }
13880 
13881 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13882 			       struct bpf_reg_state *src_reg)
13883 {
13884 	dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64));
13885 }
13886 
13887 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13888 				 struct bpf_reg_state *src_reg)
13889 {
13890 	s32 smin = reg_s32_min(dst_reg);
13891 	s32 smax = reg_s32_max(dst_reg);
13892 	u32 umin = reg_u32_min(dst_reg);
13893 	u32 umax = reg_u32_max(dst_reg);
13894 	s32 tmp_prod[4];
13895 
13896 	if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) ||
13897 	    check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) {
13898 		/* Overflow possible, we know nothing */
13899 		umin = 0;
13900 		umax = U32_MAX;
13901 	}
13902 	if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) ||
13903 	    check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) ||
13904 	    check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) ||
13905 	    check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) {
13906 		/* Overflow possible, we know nothing */
13907 		smin = S32_MIN;
13908 		smax = S32_MAX;
13909 	} else {
13910 		smin = min_array(tmp_prod, 4);
13911 		smax = max_array(tmp_prod, 4);
13912 	}
13913 
13914 	dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax),
13915 					cnum32_from_srange(smin, smax));
13916 }
13917 
13918 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13919 			       struct bpf_reg_state *src_reg)
13920 {
13921 	s64 smin = reg_smin(dst_reg);
13922 	s64 smax = reg_smax(dst_reg);
13923 	u64 umin = reg_umin(dst_reg);
13924 	u64 umax = reg_umax(dst_reg);
13925 	s64 tmp_prod[4];
13926 
13927 	if (check_mul_overflow(umax, reg_umax(src_reg), &umax) ||
13928 	    check_mul_overflow(umin, reg_umin(src_reg), &umin)) {
13929 		/* Overflow possible, we know nothing */
13930 		umin = 0;
13931 		umax = U64_MAX;
13932 	}
13933 	if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) ||
13934 	    check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) ||
13935 	    check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) ||
13936 	    check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) {
13937 		/* Overflow possible, we know nothing */
13938 		smin = S64_MIN;
13939 		smax = S64_MAX;
13940 	} else {
13941 		smin = min_array(tmp_prod, 4);
13942 		smax = max_array(tmp_prod, 4);
13943 	}
13944 
13945 	dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax),
13946 					cnum64_from_srange(smin, smax));
13947 }
13948 
13949 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg,
13950 				  struct bpf_reg_state *src_reg)
13951 {
13952 	u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */
13953 
13954 	reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val,
13955 			 reg_u32_max(dst_reg) / src_val);
13956 
13957 	/* Reset other ranges/tnum to unbounded/unknown. */
13958 	reset_reg64_and_tnum(dst_reg);
13959 }
13960 
13961 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg,
13962 				struct bpf_reg_state *src_reg)
13963 {
13964 	u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */
13965 
13966 	reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val),
13967 			 div64_u64(reg_umax(dst_reg), src_val));
13968 
13969 	/* Reset other ranges/tnum to unbounded/unknown. */
13970 	reset_reg32_and_tnum(dst_reg);
13971 }
13972 
13973 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg,
13974 				  struct bpf_reg_state *src_reg)
13975 {
13976 	s32 smin = reg_s32_min(dst_reg);
13977 	s32 smax = reg_s32_max(dst_reg);
13978 	s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */
13979 	s32 res1, res2;
13980 
13981 	/* BPF div specification: S32_MIN / -1 = S32_MIN */
13982 	if (smin == S32_MIN && src_val == -1) {
13983 		/*
13984 		 * If the dividend range contains more than just S32_MIN,
13985 		 * we cannot precisely track the result, so it becomes unbounded.
13986 		 * e.g., [S32_MIN, S32_MIN+10]/(-1),
13987 		 *     = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)]
13988 		 *     = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX]
13989 		 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN.
13990 		 */
13991 		if (smax != S32_MIN) {
13992 			smin = S32_MIN;
13993 			smax = S32_MAX;
13994 		}
13995 		goto reset;
13996 	}
13997 
13998 	res1 = smin / src_val;
13999 	res2 = smax / src_val;
14000 	smin = min(res1, res2);
14001 	smax = max(res1, res2);
14002 
14003 reset:
14004 	reg_set_srange32(dst_reg, smin, smax);
14005 	/* Reset other ranges/tnum to unbounded/unknown. */
14006 	reset_reg64_and_tnum(dst_reg);
14007 }
14008 
14009 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg,
14010 				struct bpf_reg_state *src_reg)
14011 {
14012 	s64 smin = reg_smin(dst_reg);
14013 	s64 smax = reg_smax(dst_reg);
14014 	s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */
14015 	s64 res1, res2;
14016 
14017 	/* BPF div specification: S64_MIN / -1 = S64_MIN */
14018 	if (smin == S64_MIN && src_val == -1) {
14019 		/*
14020 		 * If the dividend range contains more than just S64_MIN,
14021 		 * we cannot precisely track the result, so it becomes unbounded.
14022 		 * e.g., [S64_MIN, S64_MIN+10]/(-1),
14023 		 *     = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)]
14024 		 *     = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX]
14025 		 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN.
14026 		 */
14027 		if (smax != S64_MIN) {
14028 			smin = S64_MIN;
14029 			smax = S64_MAX;
14030 		}
14031 		goto reset;
14032 	}
14033 
14034 	res1 = div64_s64(smin, src_val);
14035 	res2 = div64_s64(smax, src_val);
14036 	smin = min(res1, res2);
14037 	smax = max(res1, res2);
14038 
14039 reset:
14040 	reg_set_srange64(dst_reg, smin, smax);
14041 	/* Reset other ranges/tnum to unbounded/unknown. */
14042 	reset_reg32_and_tnum(dst_reg);
14043 }
14044 
14045 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg,
14046 				  struct bpf_reg_state *src_reg)
14047 {
14048 	u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */
14049 	u32 res_max = src_val - 1;
14050 
14051 	/*
14052 	 * If dst_umax <= res_max, the result remains unchanged.
14053 	 * e.g., [2, 5] % 10 = [2, 5].
14054 	 */
14055 	if (reg_u32_max(dst_reg) <= res_max)
14056 		return;
14057 
14058 	reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max));
14059 
14060 	/* Reset other ranges/tnum to unbounded/unknown. */
14061 	reset_reg64_and_tnum(dst_reg);
14062 }
14063 
14064 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg,
14065 				struct bpf_reg_state *src_reg)
14066 {
14067 	u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */
14068 	u64 res_max = src_val - 1;
14069 
14070 	/*
14071 	 * If dst_umax <= res_max, the result remains unchanged.
14072 	 * e.g., [2, 5] % 10 = [2, 5].
14073 	 */
14074 	if (reg_umax(dst_reg) <= res_max)
14075 		return;
14076 
14077 	reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max));
14078 
14079 	/* Reset other ranges/tnum to unbounded/unknown. */
14080 	reset_reg32_and_tnum(dst_reg);
14081 }
14082 
14083 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg,
14084 				  struct bpf_reg_state *src_reg)
14085 {
14086 	s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */
14087 
14088 	/*
14089 	 * Safe absolute value calculation:
14090 	 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648.
14091 	 * Here use unsigned integer to avoid overflow.
14092 	 */
14093 	u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val;
14094 
14095 	/*
14096 	 * Calculate the maximum possible absolute value of the result.
14097 	 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives
14098 	 * 2147483647 (S32_MAX), which fits perfectly in s32.
14099 	 */
14100 	s32 res_max_abs = src_abs - 1;
14101 
14102 	/*
14103 	 * If the dividend is already within the result range,
14104 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
14105 	 */
14106 	if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs)
14107 		return;
14108 
14109 	/* General case: result has the same sign as the dividend. */
14110 	if (reg_s32_min(dst_reg) >= 0) {
14111 		reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs));
14112 	} else if (reg_s32_max(dst_reg) <= 0) {
14113 		reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0);
14114 	} else {
14115 		reg_set_srange32(dst_reg, -res_max_abs, res_max_abs);
14116 	}
14117 
14118 	/* Reset other ranges/tnum to unbounded/unknown. */
14119 	reset_reg64_and_tnum(dst_reg);
14120 }
14121 
14122 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg,
14123 				struct bpf_reg_state *src_reg)
14124 {
14125 	s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */
14126 
14127 	/*
14128 	 * Safe absolute value calculation:
14129 	 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63.
14130 	 * Here use unsigned integer to avoid overflow.
14131 	 */
14132 	u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val;
14133 
14134 	/*
14135 	 * Calculate the maximum possible absolute value of the result.
14136 	 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives
14137 	 * 2^63 - 1 (S64_MAX), which fits perfectly in s64.
14138 	 */
14139 	s64 res_max_abs = src_abs - 1;
14140 
14141 	/*
14142 	 * If the dividend is already within the result range,
14143 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
14144 	 */
14145 	if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs)
14146 		return;
14147 
14148 	/* General case: result has the same sign as the dividend. */
14149 	if (reg_smin(dst_reg) >= 0) {
14150 		reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs));
14151 	} else if (reg_smax(dst_reg) <= 0) {
14152 		reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0);
14153 	} else {
14154 		reg_set_srange64(dst_reg, -res_max_abs, res_max_abs);
14155 	}
14156 
14157 	/* Reset other ranges/tnum to unbounded/unknown. */
14158 	reset_reg32_and_tnum(dst_reg);
14159 }
14160 
14161 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
14162 				 struct bpf_reg_state *src_reg)
14163 {
14164 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14165 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14166 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14167 	u32 umax_val = reg_u32_max(src_reg);
14168 
14169 	if (src_known && dst_known) {
14170 		__mark_reg32_known(dst_reg, var32_off.value);
14171 		return;
14172 	}
14173 
14174 	/* We get our minimum from the var_off, since that's inherently
14175 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14176 	 */
14177 	reg_set_urange32(dst_reg,
14178 			 var32_off.value,
14179 			 min(reg_u32_max(dst_reg), umax_val));
14180 }
14181 
14182 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
14183 			       struct bpf_reg_state *src_reg)
14184 {
14185 	bool src_known = tnum_is_const(src_reg->var_off);
14186 	bool dst_known = tnum_is_const(dst_reg->var_off);
14187 	u64 umax_val = reg_umax(src_reg);
14188 
14189 	if (src_known && dst_known) {
14190 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14191 		return;
14192 	}
14193 
14194 	/* We get our minimum from the var_off, since that's inherently
14195 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14196 	 */
14197 	reg_set_urange64(dst_reg,
14198 			 dst_reg->var_off.value,
14199 			 min(reg_umax(dst_reg), umax_val));
14200 
14201 	/* We may learn something more from the var_off */
14202 	__update_reg_bounds(dst_reg);
14203 }
14204 
14205 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
14206 				struct bpf_reg_state *src_reg)
14207 {
14208 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14209 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14210 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14211 	u32 umin_val = reg_u32_min(src_reg);
14212 
14213 	if (src_known && dst_known) {
14214 		__mark_reg32_known(dst_reg, var32_off.value);
14215 		return;
14216 	}
14217 
14218 	/* We get our maximum from the var_off, and our minimum is the
14219 	 * maximum of the operands' minima
14220 	 */
14221 	reg_set_urange32(dst_reg,
14222 			 max(reg_u32_min(dst_reg), umin_val),
14223 			 var32_off.value | var32_off.mask);
14224 }
14225 
14226 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
14227 			      struct bpf_reg_state *src_reg)
14228 {
14229 	bool src_known = tnum_is_const(src_reg->var_off);
14230 	bool dst_known = tnum_is_const(dst_reg->var_off);
14231 	u64 umin_val = reg_umin(src_reg);
14232 
14233 	if (src_known && dst_known) {
14234 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14235 		return;
14236 	}
14237 
14238 	/* We get our maximum from the var_off, and our minimum is the
14239 	 * maximum of the operands' minima
14240 	 */
14241 	reg_set_urange64(dst_reg,
14242 			 max(reg_umin(dst_reg), umin_val),
14243 			 dst_reg->var_off.value | dst_reg->var_off.mask);
14244 
14245 	/* We may learn something more from the var_off */
14246 	__update_reg_bounds(dst_reg);
14247 }
14248 
14249 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
14250 				 struct bpf_reg_state *src_reg)
14251 {
14252 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14253 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14254 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14255 
14256 	if (src_known && dst_known) {
14257 		__mark_reg32_known(dst_reg, var32_off.value);
14258 		return;
14259 	}
14260 
14261 	/* We get both minimum and maximum from the var32_off. */
14262 	reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask);
14263 }
14264 
14265 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
14266 			       struct bpf_reg_state *src_reg)
14267 {
14268 	bool src_known = tnum_is_const(src_reg->var_off);
14269 	bool dst_known = tnum_is_const(dst_reg->var_off);
14270 
14271 	if (src_known && dst_known) {
14272 		/* dst_reg->var_off.value has been updated earlier */
14273 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14274 		return;
14275 	}
14276 
14277 	/* We get both minimum and maximum from the var_off. */
14278 	reg_set_urange64(dst_reg,
14279 			 dst_reg->var_off.value,
14280 			 dst_reg->var_off.value | dst_reg->var_off.mask);
14281 }
14282 
14283 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
14284 				   u64 umin_val, u64 umax_val)
14285 {
14286 	/* If we might shift our top bit out, then we know nothing */
14287 	if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val))
14288 		reg_set_urange32(dst_reg, 0, U32_MAX);
14289 	else
14290 		/* We lose all sign bit information (except what we can pick
14291 		 * up from var_off)
14292 		 */
14293 		reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val,
14294 				 reg_u32_max(dst_reg) << umax_val);
14295 }
14296 
14297 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
14298 				 struct bpf_reg_state *src_reg)
14299 {
14300 	u32 umax_val = reg_u32_max(src_reg);
14301 	u32 umin_val = reg_u32_min(src_reg);
14302 	/* u32 alu operation will zext upper bits */
14303 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
14304 
14305 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
14306 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
14307 	/* Not required but being careful mark reg64 bounds as unknown so
14308 	 * that we are forced to pick them up from tnum and zext later and
14309 	 * if some path skips this step we are still safe.
14310 	 */
14311 	__mark_reg64_unbounded(dst_reg);
14312 	__update_reg32_bounds(dst_reg);
14313 }
14314 
14315 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
14316 				   u64 umin_val, u64 umax_val)
14317 {
14318 	struct cnum64 u, s;
14319 
14320 	/* Special case <<32 because it is a common compiler pattern to sign
14321 	 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct
14322 	 * because s32 bounds don't flip sign when shifting to the left by
14323 	 * 32bits.
14324 	 */
14325 	if (umin_val == 32 && umax_val == 32)
14326 		s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32,
14327 				       (s64)reg_s32_max(dst_reg) << 32);
14328 	else
14329 		s = CNUM64_UNBOUNDED;
14330 
14331 	/* If we might shift our top bit out, then we know nothing */
14332 	if (reg_umax(dst_reg) > 1ULL << (63 - umax_val))
14333 		u = CNUM64_UNBOUNDED;
14334 	else
14335 		u = cnum64_from_urange(reg_umin(dst_reg) << umin_val,
14336 				       reg_umax(dst_reg) << umax_val);
14337 
14338 	dst_reg->r64 = cnum64_intersect(u, s);
14339 }
14340 
14341 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
14342 			       struct bpf_reg_state *src_reg)
14343 {
14344 	u64 umax_val = reg_umax(src_reg);
14345 	u64 umin_val = reg_umin(src_reg);
14346 
14347 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
14348 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
14349 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
14350 
14351 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
14352 	/* We may learn something more from the var_off */
14353 	__update_reg_bounds(dst_reg);
14354 }
14355 
14356 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
14357 				 struct bpf_reg_state *src_reg)
14358 {
14359 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
14360 	u32 umax_val = reg_u32_max(src_reg);
14361 	u32 umin_val = reg_u32_min(src_reg);
14362 
14363 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
14364 	 * be negative, then either:
14365 	 * 1) src_reg might be zero, so the sign bit of the result is
14366 	 *    unknown, so we lose our signed bounds
14367 	 * 2) it's known negative, thus the unsigned bounds capture the
14368 	 *    signed bounds
14369 	 * 3) the signed bounds cross zero, so they tell us nothing
14370 	 *    about the result
14371 	 * If the value in dst_reg is known nonnegative, then again the
14372 	 * unsigned bounds capture the signed bounds.
14373 	 * Thus, in all cases it suffices to blow away our signed bounds
14374 	 * and rely on inferring new ones from the unsigned bounds and
14375 	 * var_off of the result.
14376 	 */
14377 
14378 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
14379 	reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val,
14380 			 reg_u32_max(dst_reg) >> umin_val);
14381 
14382 	__mark_reg64_unbounded(dst_reg);
14383 	__update_reg32_bounds(dst_reg);
14384 }
14385 
14386 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
14387 			       struct bpf_reg_state *src_reg)
14388 {
14389 	u64 umax_val = reg_umax(src_reg);
14390 	u64 umin_val = reg_umin(src_reg);
14391 
14392 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
14393 	 * be negative, then either:
14394 	 * 1) src_reg might be zero, so the sign bit of the result is
14395 	 *    unknown, so we lose our signed bounds
14396 	 * 2) it's known negative, thus the unsigned bounds capture the
14397 	 *    signed bounds
14398 	 * 3) the signed bounds cross zero, so they tell us nothing
14399 	 *    about the result
14400 	 * If the value in dst_reg is known nonnegative, then again the
14401 	 * unsigned bounds capture the signed bounds.
14402 	 * Thus, in all cases it suffices to blow away our signed bounds
14403 	 * and rely on inferring new ones from the unsigned bounds and
14404 	 * var_off of the result.
14405 	 */
14406 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
14407 	reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val,
14408 			 reg_umax(dst_reg) >> umin_val);
14409 
14410 	/* Its not easy to operate on alu32 bounds here because it depends
14411 	 * on bits being shifted in. Take easy way out and mark unbounded
14412 	 * so we can recalculate later from tnum.
14413 	 */
14414 	__mark_reg32_unbounded(dst_reg);
14415 	__update_reg_bounds(dst_reg);
14416 }
14417 
14418 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
14419 				  struct bpf_reg_state *src_reg)
14420 {
14421 	u64 umin_val = reg_u32_min(src_reg);
14422 
14423 	/* Upon reaching here, src_known is true and
14424 	 * umax_val is equal to umin_val.
14425 	 * Blow away the dst_reg umin_value/umax_value and rely on
14426 	 * dst_reg var_off to refine the result.
14427 	 */
14428 	reg_set_srange32(dst_reg,
14429 			 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val),
14430 			 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val));
14431 
14432 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
14433 
14434 	__mark_reg64_unbounded(dst_reg);
14435 	__update_reg32_bounds(dst_reg);
14436 }
14437 
14438 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
14439 				struct bpf_reg_state *src_reg)
14440 {
14441 	u64 umin_val = reg_umin(src_reg);
14442 
14443 	/* Upon reaching here, src_known is true and umax_val is equal
14444 	 * to umin_val.
14445 	 */
14446 	reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val,
14447 			 reg_smax(dst_reg) >> umin_val);
14448 
14449 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
14450 
14451 	/* Its not easy to operate on alu32 bounds here because it depends
14452 	 * on bits being shifted in from upper 32-bits. Take easy way out
14453 	 * and mark unbounded so we can recalculate later from tnum.
14454 	 */
14455 	__mark_reg32_unbounded(dst_reg);
14456 	__update_reg_bounds(dst_reg);
14457 }
14458 
14459 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn)
14460 {
14461 	/*
14462 	 * Byte swap operation - update var_off using tnum_bswap.
14463 	 * Three cases:
14464 	 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE)
14465 	 *    unconditional swap
14466 	 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE)
14467 	 *    swap on big-endian, truncation or no-op on little-endian
14468 	 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE)
14469 	 *    swap on little-endian, truncation or no-op on big-endian
14470 	 */
14471 
14472 	bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64;
14473 	bool to_le = BPF_SRC(insn->code) == BPF_TO_LE;
14474 	bool is_big_endian;
14475 #ifdef CONFIG_CPU_BIG_ENDIAN
14476 	is_big_endian = true;
14477 #else
14478 	is_big_endian = false;
14479 #endif
14480 	/* Apply bswap if alu64 or switch between big-endian and little-endian machines */
14481 	bool need_bswap = alu64 || (to_le == is_big_endian);
14482 
14483 	/*
14484 	 * If the register is mutated, manually reset its scalar ID to break
14485 	 * any existing ties and avoid incorrect bounds propagation.
14486 	 */
14487 	if (need_bswap || insn->imm == 16 || insn->imm == 32)
14488 		clear_scalar_id(dst_reg);
14489 
14490 	if (need_bswap) {
14491 		if (insn->imm == 16)
14492 			dst_reg->var_off = tnum_bswap16(dst_reg->var_off);
14493 		else if (insn->imm == 32)
14494 			dst_reg->var_off = tnum_bswap32(dst_reg->var_off);
14495 		else if (insn->imm == 64)
14496 			dst_reg->var_off = tnum_bswap64(dst_reg->var_off);
14497 		/*
14498 		 * Byteswap scrambles the range, so we must reset bounds.
14499 		 * Bounds will be re-derived from the new tnum later.
14500 		 */
14501 		__mark_reg_unbounded(dst_reg);
14502 	}
14503 	/* For bswap16/32, truncate dst register to match the swapped size */
14504 	if (insn->imm == 16 || insn->imm == 32)
14505 		coerce_reg_to_size(dst_reg, insn->imm / 8);
14506 }
14507 
14508 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
14509 					     const struct bpf_reg_state *src_reg)
14510 {
14511 	bool src_is_const = false;
14512 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
14513 
14514 	if (insn_bitness == 32) {
14515 		if (tnum_subreg_is_const(src_reg->var_off)
14516 		    && reg_s32_min(src_reg) == reg_s32_max(src_reg)
14517 		    && reg_u32_min(src_reg) == reg_u32_max(src_reg))
14518 			src_is_const = true;
14519 	} else {
14520 		if (tnum_is_const(src_reg->var_off)
14521 		    && reg_smin(src_reg) == reg_smax(src_reg)
14522 		    && reg_umin(src_reg) == reg_umax(src_reg))
14523 			src_is_const = true;
14524 	}
14525 
14526 	switch (BPF_OP(insn->code)) {
14527 	case BPF_ADD:
14528 	case BPF_SUB:
14529 	case BPF_NEG:
14530 	case BPF_AND:
14531 	case BPF_XOR:
14532 	case BPF_OR:
14533 	case BPF_MUL:
14534 	case BPF_END:
14535 		return true;
14536 
14537 	/*
14538 	 * Division and modulo operators range is only safe to compute when the
14539 	 * divisor is a constant.
14540 	 */
14541 	case BPF_DIV:
14542 	case BPF_MOD:
14543 		return src_is_const;
14544 
14545 	/* Shift operators range is only computable if shift dimension operand
14546 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
14547 	 * includes shifts by a negative number.
14548 	 */
14549 	case BPF_LSH:
14550 	case BPF_RSH:
14551 	case BPF_ARSH:
14552 		return (src_is_const && reg_umax(src_reg) < insn_bitness);
14553 	default:
14554 		return false;
14555 	}
14556 }
14557 
14558 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn,
14559 			      struct bpf_reg_state *dst_reg)
14560 {
14561 	struct bpf_verifier_state *branch;
14562 	struct bpf_reg_state *regs;
14563 	bool alu32;
14564 
14565 	if (reg_smin(dst_reg) == -1 && reg_smax(dst_reg) == 0)
14566 		alu32 = false;
14567 	else if (reg_s32_min(dst_reg) == -1 && reg_s32_max(dst_reg) == 0)
14568 		alu32 = true;
14569 	else
14570 		return 0;
14571 
14572 	branch = push_stack(env, env->insn_idx, env->insn_idx, false);
14573 	if (IS_ERR(branch))
14574 		return PTR_ERR(branch);
14575 
14576 	regs = branch->frame[branch->curframe]->regs;
14577 	if (alu32) {
14578 		__mark_reg32_known(&regs[insn->dst_reg], 0);
14579 		__mark_reg32_known(dst_reg, -1ull);
14580 	} else {
14581 		__mark_reg_known(&regs[insn->dst_reg], 0);
14582 		__mark_reg_known(dst_reg, -1ull);
14583 	}
14584 	return 0;
14585 }
14586 
14587 /* WARNING: This function does calculations on 64-bit values, but the actual
14588  * execution may occur on 32-bit values. Therefore, things like bitshifts
14589  * need extra checks in the 32-bit case.
14590  */
14591 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
14592 				      struct bpf_insn *insn,
14593 				      struct bpf_reg_state *dst_reg,
14594 				      struct bpf_reg_state src_reg)
14595 {
14596 	u8 opcode = BPF_OP(insn->code);
14597 	s16 off = insn->off;
14598 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
14599 	int ret;
14600 
14601 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
14602 		__mark_reg_unknown(env, dst_reg);
14603 		return 0;
14604 	}
14605 
14606 	if (sanitize_needed(opcode)) {
14607 		ret = sanitize_val_alu(env, insn);
14608 		if (ret < 0)
14609 			return sanitize_err(env, insn, ret, NULL, NULL);
14610 	}
14611 
14612 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
14613 	 * There are two classes of instructions: The first class we track both
14614 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
14615 	 * greatest amount of precision when alu operations are mixed with jmp32
14616 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
14617 	 * and BPF_OR. This is possible because these ops have fairly easy to
14618 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
14619 	 * See alu32 verifier tests for examples. The second class of
14620 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
14621 	 * with regards to tracking sign/unsigned bounds because the bits may
14622 	 * cross subreg boundaries in the alu64 case. When this happens we mark
14623 	 * the reg unbounded in the subreg bound space and use the resulting
14624 	 * tnum to calculate an approximation of the sign/unsigned bounds.
14625 	 */
14626 	switch (opcode) {
14627 	case BPF_ADD:
14628 		scalar32_min_max_add(dst_reg, &src_reg);
14629 		scalar_min_max_add(dst_reg, &src_reg);
14630 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
14631 		break;
14632 	case BPF_SUB:
14633 		scalar32_min_max_sub(dst_reg, &src_reg);
14634 		scalar_min_max_sub(dst_reg, &src_reg);
14635 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
14636 		break;
14637 	case BPF_NEG:
14638 		env->fake_reg[0] = *dst_reg;
14639 		__mark_reg_known(dst_reg, 0);
14640 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
14641 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
14642 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
14643 		break;
14644 	case BPF_MUL:
14645 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
14646 		scalar32_min_max_mul(dst_reg, &src_reg);
14647 		scalar_min_max_mul(dst_reg, &src_reg);
14648 		break;
14649 	case BPF_DIV:
14650 		/* BPF div specification: x / 0 = 0 */
14651 		if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) {
14652 			___mark_reg_known(dst_reg, 0);
14653 			break;
14654 		}
14655 		if (alu32)
14656 			if (off == 1)
14657 				scalar32_min_max_sdiv(dst_reg, &src_reg);
14658 			else
14659 				scalar32_min_max_udiv(dst_reg, &src_reg);
14660 		else
14661 			if (off == 1)
14662 				scalar_min_max_sdiv(dst_reg, &src_reg);
14663 			else
14664 				scalar_min_max_udiv(dst_reg, &src_reg);
14665 		break;
14666 	case BPF_MOD:
14667 		/* BPF mod specification: x % 0 = x */
14668 		if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0))
14669 			break;
14670 		if (alu32)
14671 			if (off == 1)
14672 				scalar32_min_max_smod(dst_reg, &src_reg);
14673 			else
14674 				scalar32_min_max_umod(dst_reg, &src_reg);
14675 		else
14676 			if (off == 1)
14677 				scalar_min_max_smod(dst_reg, &src_reg);
14678 			else
14679 				scalar_min_max_umod(dst_reg, &src_reg);
14680 		break;
14681 	case BPF_AND:
14682 		if (tnum_is_const(src_reg.var_off)) {
14683 			ret = maybe_fork_scalars(env, insn, dst_reg);
14684 			if (ret)
14685 				return ret;
14686 		}
14687 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
14688 		scalar32_min_max_and(dst_reg, &src_reg);
14689 		scalar_min_max_and(dst_reg, &src_reg);
14690 		break;
14691 	case BPF_OR:
14692 		if (tnum_is_const(src_reg.var_off)) {
14693 			ret = maybe_fork_scalars(env, insn, dst_reg);
14694 			if (ret)
14695 				return ret;
14696 		}
14697 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
14698 		scalar32_min_max_or(dst_reg, &src_reg);
14699 		scalar_min_max_or(dst_reg, &src_reg);
14700 		break;
14701 	case BPF_XOR:
14702 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
14703 		scalar32_min_max_xor(dst_reg, &src_reg);
14704 		scalar_min_max_xor(dst_reg, &src_reg);
14705 		break;
14706 	case BPF_LSH:
14707 		if (alu32)
14708 			scalar32_min_max_lsh(dst_reg, &src_reg);
14709 		else
14710 			scalar_min_max_lsh(dst_reg, &src_reg);
14711 		break;
14712 	case BPF_RSH:
14713 		if (alu32)
14714 			scalar32_min_max_rsh(dst_reg, &src_reg);
14715 		else
14716 			scalar_min_max_rsh(dst_reg, &src_reg);
14717 		break;
14718 	case BPF_ARSH:
14719 		if (alu32)
14720 			scalar32_min_max_arsh(dst_reg, &src_reg);
14721 		else
14722 			scalar_min_max_arsh(dst_reg, &src_reg);
14723 		break;
14724 	case BPF_END:
14725 		scalar_byte_swap(dst_reg, insn);
14726 		break;
14727 	default:
14728 		break;
14729 	}
14730 
14731 	/*
14732 	 * ALU32 ops are zero extended into 64bit register.
14733 	 *
14734 	 * BPF_END is already handled inside the helper (truncation),
14735 	 * so skip zext here to avoid unexpected zero extension.
14736 	 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40
14737 	 * This is a 64bit byte swap operation with alu32==true,
14738 	 * but we should not zero extend the result.
14739 	 */
14740 	if (alu32 && opcode != BPF_END)
14741 		zext_32_to_64(dst_reg);
14742 	reg_bounds_sync(dst_reg);
14743 	return 0;
14744 }
14745 
14746 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
14747  * and var_off.
14748  */
14749 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
14750 				   struct bpf_insn *insn)
14751 {
14752 	struct bpf_verifier_state *vstate = env->cur_state;
14753 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14754 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
14755 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
14756 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
14757 	u8 opcode = BPF_OP(insn->code);
14758 	int err;
14759 
14760 	dst_reg = &regs[insn->dst_reg];
14761 	if (BPF_SRC(insn->code) == BPF_X)
14762 		src_reg = &regs[insn->src_reg];
14763 	else
14764 		src_reg = NULL;
14765 
14766 	/* Case where at least one operand is an arena. */
14767 	if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) {
14768 		struct bpf_insn_aux_data *aux = cur_aux(env);
14769 
14770 		if (dst_reg->type != PTR_TO_ARENA)
14771 			*dst_reg = *src_reg;
14772 
14773 		dst_reg->subreg_def = env->insn_idx + 1;
14774 
14775 		if (BPF_CLASS(insn->code) == BPF_ALU64)
14776 			/*
14777 			 * 32-bit operations zero upper bits automatically.
14778 			 * 64-bit operations need to be converted to 32.
14779 			 */
14780 			aux->needs_zext = true;
14781 
14782 		/* Any arithmetic operations are allowed on arena pointers */
14783 		return 0;
14784 	}
14785 
14786 	if (dst_reg->type != SCALAR_VALUE)
14787 		ptr_reg = dst_reg;
14788 
14789 	if (BPF_SRC(insn->code) == BPF_X) {
14790 		if (src_reg->type != SCALAR_VALUE) {
14791 			if (dst_reg->type != SCALAR_VALUE) {
14792 				/* Combining two pointers by any ALU op yields
14793 				 * an arbitrary scalar. Disallow all math except
14794 				 * pointer subtraction
14795 				 */
14796 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14797 					mark_reg_unknown(env, regs, insn->dst_reg);
14798 					return 0;
14799 				}
14800 				verbose(env, "R%d pointer %s pointer prohibited\n",
14801 					insn->dst_reg,
14802 					bpf_alu_string[opcode >> 4]);
14803 				return -EACCES;
14804 			} else {
14805 				/* scalar += pointer
14806 				 * This is legal, but we have to reverse our
14807 				 * src/dest handling in computing the range
14808 				 */
14809 				err = mark_chain_precision(env, insn->dst_reg);
14810 				if (err)
14811 					return err;
14812 				return adjust_ptr_min_max_vals(env, insn,
14813 							       src_reg, dst_reg);
14814 			}
14815 		} else if (ptr_reg) {
14816 			/* pointer += scalar */
14817 			err = mark_chain_precision(env, insn->src_reg);
14818 			if (err)
14819 				return err;
14820 			return adjust_ptr_min_max_vals(env, insn,
14821 						       dst_reg, src_reg);
14822 		} else if (dst_reg->precise) {
14823 			/* if dst_reg is precise, src_reg should be precise as well */
14824 			err = mark_chain_precision(env, insn->src_reg);
14825 			if (err)
14826 				return err;
14827 		}
14828 	} else {
14829 		/* Pretend the src is a reg with a known value, since we only
14830 		 * need to be able to read from this state.
14831 		 */
14832 		off_reg.type = SCALAR_VALUE;
14833 		__mark_reg_known(&off_reg, insn->imm);
14834 		src_reg = &off_reg;
14835 		if (ptr_reg) /* pointer += K */
14836 			return adjust_ptr_min_max_vals(env, insn,
14837 						       ptr_reg, src_reg);
14838 	}
14839 
14840 	/* Got here implies adding two SCALAR_VALUEs */
14841 	if (WARN_ON_ONCE(ptr_reg)) {
14842 		print_verifier_state(env, vstate, vstate->curframe, true);
14843 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
14844 		return -EFAULT;
14845 	}
14846 	if (WARN_ON(!src_reg)) {
14847 		print_verifier_state(env, vstate, vstate->curframe, true);
14848 		verbose(env, "verifier internal error: no src_reg\n");
14849 		return -EFAULT;
14850 	}
14851 	/*
14852 	 * For alu32 linked register tracking, we need to check dst_reg's
14853 	 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(),
14854 	 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX.
14855 	 */
14856 	u64 dst_umax = reg_umax(dst_reg);
14857 
14858 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
14859 	if (err)
14860 		return err;
14861 	/*
14862 	 * Compilers can generate the code
14863 	 * r1 = r2
14864 	 * r1 += 0x1
14865 	 * if r2 < 1000 goto ...
14866 	 * use r1 in memory access
14867 	 * So remember constant delta between r2 and r1 and update r1 after
14868 	 * 'if' condition.
14869 	 */
14870 	if (env->bpf_capable &&
14871 	    (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) &&
14872 	    dst_reg->id && is_reg_const(src_reg, alu32) &&
14873 	    !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) {
14874 		u64 val = reg_const_value(src_reg, alu32);
14875 		s32 off;
14876 
14877 		if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX))
14878 			goto clear_id;
14879 
14880 		if (alu32 && (dst_umax > U32_MAX))
14881 			goto clear_id;
14882 
14883 		off = (s32)val;
14884 
14885 		if (BPF_OP(insn->code) == BPF_SUB) {
14886 			/* Negating S32_MIN would overflow */
14887 			if (off == S32_MIN)
14888 				goto clear_id;
14889 			off = -off;
14890 		}
14891 
14892 		if (dst_reg->id & BPF_ADD_CONST) {
14893 			/*
14894 			 * If the register already went through rX += val
14895 			 * we cannot accumulate another val into rx->off.
14896 			 */
14897 clear_id:
14898 			clear_scalar_id(dst_reg);
14899 		} else {
14900 			if (alu32)
14901 				dst_reg->id |= BPF_ADD_CONST32;
14902 			else
14903 				dst_reg->id |= BPF_ADD_CONST64;
14904 			dst_reg->delta = off;
14905 		}
14906 	} else {
14907 		/*
14908 		 * Make sure ID is cleared otherwise dst_reg min/max could be
14909 		 * incorrectly propagated into other registers by sync_linked_regs()
14910 		 */
14911 		clear_scalar_id(dst_reg);
14912 	}
14913 	return 0;
14914 }
14915 
14916 /* check validity of 32-bit and 64-bit arithmetic operations */
14917 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
14918 {
14919 	struct bpf_reg_state *regs = cur_regs(env);
14920 	u8 opcode = BPF_OP(insn->code);
14921 	int err;
14922 
14923 	if (opcode == BPF_END || opcode == BPF_NEG) {
14924 		/* check src operand */
14925 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14926 		if (err)
14927 			return err;
14928 
14929 		if (is_pointer_value(env, insn->dst_reg)) {
14930 			verbose(env, "R%d pointer arithmetic prohibited\n",
14931 				insn->dst_reg);
14932 			return -EACCES;
14933 		}
14934 
14935 		/* check dest operand */
14936 		if (regs[insn->dst_reg].type == SCALAR_VALUE) {
14937 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14938 			err = err ?: adjust_scalar_min_max_vals(env, insn,
14939 							 &regs[insn->dst_reg],
14940 							 regs[insn->dst_reg]);
14941 		} else {
14942 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
14943 		}
14944 		if (err)
14945 			return err;
14946 
14947 	} else if (opcode == BPF_MOV) {
14948 
14949 		if (BPF_SRC(insn->code) == BPF_X) {
14950 			if (insn->off == BPF_ADDR_SPACE_CAST) {
14951 				if (!env->prog->aux->arena) {
14952 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
14953 					return -EINVAL;
14954 				}
14955 			}
14956 
14957 			/* check src operand */
14958 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14959 			if (err)
14960 				return err;
14961 		}
14962 
14963 		/* check dest operand, mark as required later */
14964 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14965 		if (err)
14966 			return err;
14967 
14968 		if (BPF_SRC(insn->code) == BPF_X) {
14969 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
14970 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
14971 
14972 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14973 				if (insn->imm) {
14974 					/* off == BPF_ADDR_SPACE_CAST */
14975 					mark_reg_unknown(env, regs, insn->dst_reg);
14976 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
14977 						dst_reg->type = PTR_TO_ARENA;
14978 						/* PTR_TO_ARENA is 32-bit */
14979 						dst_reg->subreg_def = env->insn_idx + 1;
14980 					}
14981 				} else if (insn->off == 0) {
14982 					/* case: R1 = R2
14983 					 * copy register state to dest reg
14984 					 */
14985 					assign_scalar_id_before_mov(env, src_reg);
14986 					*dst_reg = *src_reg;
14987 					dst_reg->subreg_def = DEF_NOT_SUBREG;
14988 				} else {
14989 					/* case: R1 = (s8, s16 s32)R2 */
14990 					if (is_pointer_value(env, insn->src_reg)) {
14991 						verbose(env,
14992 							"R%d sign-extension part of pointer\n",
14993 							insn->src_reg);
14994 						return -EACCES;
14995 					} else if (src_reg->type == SCALAR_VALUE) {
14996 						bool no_sext;
14997 
14998 						no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
14999 						if (no_sext)
15000 							assign_scalar_id_before_mov(env, src_reg);
15001 						*dst_reg = *src_reg;
15002 						if (!no_sext)
15003 							clear_scalar_id(dst_reg);
15004 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
15005 						dst_reg->subreg_def = DEF_NOT_SUBREG;
15006 					} else {
15007 						mark_reg_unknown(env, regs, insn->dst_reg);
15008 					}
15009 				}
15010 			} else {
15011 				/* R1 = (u32) R2 */
15012 				if (is_pointer_value(env, insn->src_reg)) {
15013 					verbose(env,
15014 						"R%d partial copy of pointer\n",
15015 						insn->src_reg);
15016 					return -EACCES;
15017 				} else if (src_reg->type == SCALAR_VALUE) {
15018 					if (insn->off == 0) {
15019 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
15020 
15021 						if (is_src_reg_u32)
15022 							assign_scalar_id_before_mov(env, src_reg);
15023 						*dst_reg = *src_reg;
15024 						/* Make sure ID is cleared if src_reg is not in u32
15025 						 * range otherwise dst_reg min/max could be incorrectly
15026 						 * propagated into src_reg by sync_linked_regs()
15027 						 */
15028 						if (!is_src_reg_u32)
15029 							clear_scalar_id(dst_reg);
15030 						dst_reg->subreg_def = env->insn_idx + 1;
15031 					} else {
15032 						/* case: W1 = (s8, s16)W2 */
15033 						bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
15034 
15035 						if (no_sext)
15036 							assign_scalar_id_before_mov(env, src_reg);
15037 						*dst_reg = *src_reg;
15038 						if (!no_sext)
15039 							clear_scalar_id(dst_reg);
15040 						dst_reg->subreg_def = env->insn_idx + 1;
15041 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
15042 					}
15043 				} else {
15044 					mark_reg_unknown(env, regs,
15045 							 insn->dst_reg);
15046 				}
15047 				zext_32_to_64(dst_reg);
15048 				reg_bounds_sync(dst_reg);
15049 			}
15050 		} else {
15051 			/* case: R = imm
15052 			 * remember the value we stored into this reg
15053 			 */
15054 			/* clear any state __mark_reg_known doesn't set */
15055 			mark_reg_unknown(env, regs, insn->dst_reg);
15056 			regs[insn->dst_reg].type = SCALAR_VALUE;
15057 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15058 				__mark_reg_known(regs + insn->dst_reg,
15059 						 insn->imm);
15060 			} else {
15061 				__mark_reg_known(regs + insn->dst_reg,
15062 						 (u32)insn->imm);
15063 			}
15064 		}
15065 
15066 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
15067 
15068 		if (BPF_SRC(insn->code) == BPF_X) {
15069 			/* check src1 operand */
15070 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15071 			if (err)
15072 				return err;
15073 		}
15074 
15075 		/* check src2 operand */
15076 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15077 		if (err)
15078 			return err;
15079 
15080 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
15081 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
15082 			verbose(env, "div by zero\n");
15083 			return -EINVAL;
15084 		}
15085 
15086 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
15087 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
15088 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
15089 
15090 			if (insn->imm < 0 || insn->imm >= size) {
15091 				verbose(env, "invalid shift %d\n", insn->imm);
15092 				return -EINVAL;
15093 			}
15094 		}
15095 
15096 		/* check dest operand */
15097 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15098 		err = err ?: adjust_reg_min_max_vals(env, insn);
15099 		if (err)
15100 			return err;
15101 	}
15102 
15103 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
15104 }
15105 
15106 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
15107 				   struct bpf_reg_state *dst_reg,
15108 				   enum bpf_reg_type type,
15109 				   bool range_right_open)
15110 {
15111 	struct bpf_func_state *state;
15112 	struct bpf_reg_state *reg;
15113 	int new_range;
15114 
15115 	if (reg_umax(dst_reg) == 0 && range_right_open)
15116 		/* This doesn't give us any range */
15117 		return;
15118 
15119 	if (reg_umax(dst_reg) > MAX_PACKET_OFF)
15120 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
15121 		 * than pkt_end, but that's because it's also less than pkt.
15122 		 */
15123 		return;
15124 
15125 	new_range = reg_umax(dst_reg);
15126 	if (range_right_open)
15127 		new_range++;
15128 
15129 	/* Examples for register markings:
15130 	 *
15131 	 * pkt_data in dst register:
15132 	 *
15133 	 *   r2 = r3;
15134 	 *   r2 += 8;
15135 	 *   if (r2 > pkt_end) goto <handle exception>
15136 	 *   <access okay>
15137 	 *
15138 	 *   r2 = r3;
15139 	 *   r2 += 8;
15140 	 *   if (r2 < pkt_end) goto <access okay>
15141 	 *   <handle exception>
15142 	 *
15143 	 *   Where:
15144 	 *     r2 == dst_reg, pkt_end == src_reg
15145 	 *     r2=pkt(id=n,off=8,r=0)
15146 	 *     r3=pkt(id=n,off=0,r=0)
15147 	 *
15148 	 * pkt_data in src register:
15149 	 *
15150 	 *   r2 = r3;
15151 	 *   r2 += 8;
15152 	 *   if (pkt_end >= r2) goto <access okay>
15153 	 *   <handle exception>
15154 	 *
15155 	 *   r2 = r3;
15156 	 *   r2 += 8;
15157 	 *   if (pkt_end <= r2) goto <handle exception>
15158 	 *   <access okay>
15159 	 *
15160 	 *   Where:
15161 	 *     pkt_end == dst_reg, r2 == src_reg
15162 	 *     r2=pkt(id=n,off=8,r=0)
15163 	 *     r3=pkt(id=n,off=0,r=0)
15164 	 *
15165 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
15166 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
15167 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
15168 	 * the check.
15169 	 */
15170 
15171 	/* If our ids match, then we must have the same max_value.  And we
15172 	 * don't care about the other reg's fixed offset, since if it's too big
15173 	 * the range won't allow anything.
15174 	 * reg_umax(dst_reg) is known < MAX_PACKET_OFF, therefore it fits in a u16.
15175 	 */
15176 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15177 		if (reg->type == type && reg->id == dst_reg->id)
15178 			/* keep the maximum range already checked */
15179 			reg->range = max(reg->range, new_range);
15180 	}));
15181 }
15182 
15183 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15184 				u8 opcode, bool is_jmp32);
15185 static u8 rev_opcode(u8 opcode);
15186 
15187 /*
15188  * Learn more information about live branches by simulating refinement on both branches.
15189  * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means
15190  * that branch is dead.
15191  */
15192 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32)
15193 {
15194 	/* Fallthrough (FALSE) branch */
15195 	regs_refine_cond_op(&env->false_reg1, &env->false_reg2, rev_opcode(opcode), is_jmp32);
15196 	reg_bounds_sync(&env->false_reg1);
15197 	reg_bounds_sync(&env->false_reg2);
15198 	/*
15199 	 * If there is a range bounds violation in *any* of the abstract values in either
15200 	 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only
15201 	 * TRUE branch will be taken.
15202 	 */
15203 	if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2))
15204 		return 1;
15205 
15206 	/* Jump (TRUE) branch */
15207 	regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32);
15208 	reg_bounds_sync(&env->true_reg1);
15209 	reg_bounds_sync(&env->true_reg2);
15210 	/*
15211 	 * If there is a range bounds violation in *any* of the abstract values in either
15212 	 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead.
15213 	 * Only FALSE branch will be taken.
15214 	 */
15215 	if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2))
15216 		return 0;
15217 
15218 	/* Both branches are possible, we can't determine which one will be taken. */
15219 	return -1;
15220 }
15221 
15222 /*
15223  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
15224  */
15225 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1,
15226 				  struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32)
15227 {
15228 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
15229 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
15230 	u64 umin1 = is_jmp32 ? (u64)reg_u32_min(reg1) : reg_umin(reg1);
15231 	u64 umax1 = is_jmp32 ? (u64)reg_u32_max(reg1) : reg_umax(reg1);
15232 	s64 smin1 = is_jmp32 ? (s64)reg_s32_min(reg1) : reg_smin(reg1);
15233 	s64 smax1 = is_jmp32 ? (s64)reg_s32_max(reg1) : reg_smax(reg1);
15234 	u64 umin2 = is_jmp32 ? (u64)reg_u32_min(reg2) : reg_umin(reg2);
15235 	u64 umax2 = is_jmp32 ? (u64)reg_u32_max(reg2) : reg_umax(reg2);
15236 	s64 smin2 = is_jmp32 ? (s64)reg_s32_min(reg2) : reg_smin(reg2);
15237 	s64 smax2 = is_jmp32 ? (s64)reg_s32_max(reg2) : reg_smax(reg2);
15238 
15239 	if (reg1 == reg2) {
15240 		switch (opcode) {
15241 		case BPF_JGE:
15242 		case BPF_JLE:
15243 		case BPF_JSGE:
15244 		case BPF_JSLE:
15245 		case BPF_JEQ:
15246 			return 1;
15247 		case BPF_JGT:
15248 		case BPF_JLT:
15249 		case BPF_JSGT:
15250 		case BPF_JSLT:
15251 		case BPF_JNE:
15252 			return 0;
15253 		case BPF_JSET:
15254 			if (tnum_is_const(t1))
15255 				return t1.value != 0;
15256 			else
15257 				return (smin1 <= 0 && smax1 >= 0) ? -1 : 1;
15258 		default:
15259 			return -1;
15260 		}
15261 	}
15262 
15263 	switch (opcode) {
15264 	case BPF_JEQ:
15265 		/* constants, umin/umax and smin/smax checks would be
15266 		 * redundant in this case because they all should match
15267 		 */
15268 		if (tnum_is_const(t1) && tnum_is_const(t2))
15269 			return t1.value == t2.value;
15270 		if (!tnum_overlap(t1, t2))
15271 			return 0;
15272 		/* non-overlapping ranges */
15273 		if (umin1 > umax2 || umax1 < umin2)
15274 			return 0;
15275 		if (smin1 > smax2 || smax1 < smin2)
15276 			return 0;
15277 		if (!is_jmp32) {
15278 			/* if 64-bit ranges are inconclusive, see if we can
15279 			 * utilize 32-bit subrange knowledge to eliminate
15280 			 * branches that can't be taken a priori
15281 			 */
15282 			if (reg_u32_min(reg1) > reg_u32_max(reg2) ||
15283 			    reg_u32_max(reg1) < reg_u32_min(reg2))
15284 				return 0;
15285 			if (reg_s32_min(reg1) > reg_s32_max(reg2) ||
15286 			    reg_s32_max(reg1) < reg_s32_min(reg2))
15287 				return 0;
15288 		}
15289 		break;
15290 	case BPF_JNE:
15291 		/* constants, umin/umax and smin/smax checks would be
15292 		 * redundant in this case because they all should match
15293 		 */
15294 		if (tnum_is_const(t1) && tnum_is_const(t2))
15295 			return t1.value != t2.value;
15296 		if (!tnum_overlap(t1, t2))
15297 			return 1;
15298 		/* non-overlapping ranges */
15299 		if (umin1 > umax2 || umax1 < umin2)
15300 			return 1;
15301 		if (smin1 > smax2 || smax1 < smin2)
15302 			return 1;
15303 		if (!is_jmp32) {
15304 			/* if 64-bit ranges are inconclusive, see if we can
15305 			 * utilize 32-bit subrange knowledge to eliminate
15306 			 * branches that can't be taken a priori
15307 			 */
15308 			if (reg_u32_min(reg1) > reg_u32_max(reg2) ||
15309 			    reg_u32_max(reg1) < reg_u32_min(reg2))
15310 				return 1;
15311 			if (reg_s32_min(reg1) > reg_s32_max(reg2) ||
15312 			    reg_s32_max(reg1) < reg_s32_min(reg2))
15313 				return 1;
15314 		}
15315 		break;
15316 	case BPF_JSET:
15317 		if (!is_reg_const(reg2, is_jmp32)) {
15318 			swap(reg1, reg2);
15319 			swap(t1, t2);
15320 		}
15321 		if (!is_reg_const(reg2, is_jmp32))
15322 			return -1;
15323 		if ((~t1.mask & t1.value) & t2.value)
15324 			return 1;
15325 		if (!((t1.mask | t1.value) & t2.value))
15326 			return 0;
15327 		break;
15328 	case BPF_JGT:
15329 		if (umin1 > umax2)
15330 			return 1;
15331 		else if (umax1 <= umin2)
15332 			return 0;
15333 		break;
15334 	case BPF_JSGT:
15335 		if (smin1 > smax2)
15336 			return 1;
15337 		else if (smax1 <= smin2)
15338 			return 0;
15339 		break;
15340 	case BPF_JLT:
15341 		if (umax1 < umin2)
15342 			return 1;
15343 		else if (umin1 >= umax2)
15344 			return 0;
15345 		break;
15346 	case BPF_JSLT:
15347 		if (smax1 < smin2)
15348 			return 1;
15349 		else if (smin1 >= smax2)
15350 			return 0;
15351 		break;
15352 	case BPF_JGE:
15353 		if (umin1 >= umax2)
15354 			return 1;
15355 		else if (umax1 < umin2)
15356 			return 0;
15357 		break;
15358 	case BPF_JSGE:
15359 		if (smin1 >= smax2)
15360 			return 1;
15361 		else if (smax1 < smin2)
15362 			return 0;
15363 		break;
15364 	case BPF_JLE:
15365 		if (umax1 <= umin2)
15366 			return 1;
15367 		else if (umin1 > umax2)
15368 			return 0;
15369 		break;
15370 	case BPF_JSLE:
15371 		if (smax1 <= smin2)
15372 			return 1;
15373 		else if (smin1 > smax2)
15374 			return 0;
15375 		break;
15376 	}
15377 
15378 	return simulate_both_branches_taken(env, opcode, is_jmp32);
15379 }
15380 
15381 static int flip_opcode(u32 opcode)
15382 {
15383 	/* How can we transform "a <op> b" into "b <op> a"? */
15384 	static const u8 opcode_flip[16] = {
15385 		/* these stay the same */
15386 		[BPF_JEQ  >> 4] = BPF_JEQ,
15387 		[BPF_JNE  >> 4] = BPF_JNE,
15388 		[BPF_JSET >> 4] = BPF_JSET,
15389 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
15390 		[BPF_JGE  >> 4] = BPF_JLE,
15391 		[BPF_JGT  >> 4] = BPF_JLT,
15392 		[BPF_JLE  >> 4] = BPF_JGE,
15393 		[BPF_JLT  >> 4] = BPF_JGT,
15394 		[BPF_JSGE >> 4] = BPF_JSLE,
15395 		[BPF_JSGT >> 4] = BPF_JSLT,
15396 		[BPF_JSLE >> 4] = BPF_JSGE,
15397 		[BPF_JSLT >> 4] = BPF_JSGT
15398 	};
15399 	return opcode_flip[opcode >> 4];
15400 }
15401 
15402 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
15403 				   struct bpf_reg_state *src_reg,
15404 				   u8 opcode)
15405 {
15406 	struct bpf_reg_state *pkt;
15407 
15408 	if (src_reg->type == PTR_TO_PACKET_END) {
15409 		pkt = dst_reg;
15410 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
15411 		pkt = src_reg;
15412 		opcode = flip_opcode(opcode);
15413 	} else {
15414 		return -1;
15415 	}
15416 
15417 	if (pkt->range >= 0)
15418 		return -1;
15419 
15420 	switch (opcode) {
15421 	case BPF_JLE:
15422 		/* pkt <= pkt_end */
15423 		fallthrough;
15424 	case BPF_JGT:
15425 		/* pkt > pkt_end */
15426 		if (pkt->range == BEYOND_PKT_END)
15427 			/* pkt has at last one extra byte beyond pkt_end */
15428 			return opcode == BPF_JGT;
15429 		break;
15430 	case BPF_JLT:
15431 		/* pkt < pkt_end */
15432 		fallthrough;
15433 	case BPF_JGE:
15434 		/* pkt >= pkt_end */
15435 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
15436 			return opcode == BPF_JGE;
15437 		break;
15438 	}
15439 	return -1;
15440 }
15441 
15442 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
15443  * and return:
15444  *  1 - branch will be taken and "goto target" will be executed
15445  *  0 - branch will not be taken and fall-through to next insn
15446  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
15447  *      range [0,10]
15448  */
15449 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1,
15450 			   struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32)
15451 {
15452 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
15453 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
15454 
15455 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
15456 		u64 val;
15457 
15458 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
15459 		if (!is_reg_const(reg2, is_jmp32)) {
15460 			opcode = flip_opcode(opcode);
15461 			swap(reg1, reg2);
15462 		}
15463 		/* and ensure that reg2 is a constant */
15464 		if (!is_reg_const(reg2, is_jmp32))
15465 			return -1;
15466 
15467 		if (!reg_not_null(env, reg1))
15468 			return -1;
15469 
15470 		/* If pointer is valid tests against zero will fail so we can
15471 		 * use this to direct branch taken.
15472 		 */
15473 		val = reg_const_value(reg2, is_jmp32);
15474 		if (val != 0)
15475 			return -1;
15476 
15477 		switch (opcode) {
15478 		case BPF_JEQ:
15479 			return 0;
15480 		case BPF_JNE:
15481 			return 1;
15482 		default:
15483 			return -1;
15484 		}
15485 	}
15486 
15487 	/* now deal with two scalars, but not necessarily constants */
15488 	return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32);
15489 }
15490 
15491 /* Opcode that corresponds to a *false* branch condition.
15492  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
15493  */
15494 static u8 rev_opcode(u8 opcode)
15495 {
15496 	switch (opcode) {
15497 	case BPF_JEQ:		return BPF_JNE;
15498 	case BPF_JNE:		return BPF_JEQ;
15499 	/* JSET doesn't have it's reverse opcode in BPF, so add
15500 	 * BPF_X flag to denote the reverse of that operation
15501 	 */
15502 	case BPF_JSET:		return BPF_JSET | BPF_X;
15503 	case BPF_JSET | BPF_X:	return BPF_JSET;
15504 	case BPF_JGE:		return BPF_JLT;
15505 	case BPF_JGT:		return BPF_JLE;
15506 	case BPF_JLE:		return BPF_JGT;
15507 	case BPF_JLT:		return BPF_JGE;
15508 	case BPF_JSGE:		return BPF_JSLT;
15509 	case BPF_JSGT:		return BPF_JSLE;
15510 	case BPF_JSLE:		return BPF_JSGT;
15511 	case BPF_JSLT:		return BPF_JSGE;
15512 	default:		return 0;
15513 	}
15514 }
15515 
15516 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
15517 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15518 				u8 opcode, bool is_jmp32)
15519 {
15520 	struct tnum t;
15521 	u64 val;
15522 
15523 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
15524 	switch (opcode) {
15525 	case BPF_JGE:
15526 	case BPF_JGT:
15527 	case BPF_JSGE:
15528 	case BPF_JSGT:
15529 		opcode = flip_opcode(opcode);
15530 		swap(reg1, reg2);
15531 		break;
15532 	default:
15533 		break;
15534 	}
15535 
15536 	switch (opcode) {
15537 	case BPF_JEQ:
15538 		if (is_jmp32) {
15539 			reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32);
15540 			reg2->r32 = reg1->r32;
15541 
15542 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
15543 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15544 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
15545 		} else {
15546 			reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64);
15547 			reg2->r64 = reg1->r64;
15548 
15549 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
15550 			reg2->var_off = reg1->var_off;
15551 		}
15552 		break;
15553 	case BPF_JNE:
15554 		if (!is_reg_const(reg2, is_jmp32))
15555 			swap(reg1, reg2);
15556 		if (!is_reg_const(reg2, is_jmp32))
15557 			break;
15558 
15559 		/* try to recompute the bound of reg1 if reg2 is a const and
15560 		 * is exactly the edge of reg1.
15561 		 */
15562 		val = reg_const_value(reg2, is_jmp32);
15563 		if (is_jmp32) {
15564 			/* Complement of the range [val, val] as cnum32. */
15565 			cnum32_intersect_with(&reg1->r32, (struct cnum32){ val + 1, U32_MAX - 1 });
15566 		} else {
15567 			/* Complement of the range [val, val] as cnum64. */
15568 			cnum64_intersect_with(&reg1->r64, (struct cnum64){ val + 1, U64_MAX - 1 });
15569 		}
15570 		break;
15571 	case BPF_JSET:
15572 		if (!is_reg_const(reg2, is_jmp32))
15573 			swap(reg1, reg2);
15574 		if (!is_reg_const(reg2, is_jmp32))
15575 			break;
15576 		val = reg_const_value(reg2, is_jmp32);
15577 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
15578 		 * requires single bit to learn something useful. E.g., if we
15579 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
15580 		 * are actually set? We can learn something definite only if
15581 		 * it's a single-bit value to begin with.
15582 		 *
15583 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
15584 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
15585 		 * bit 1 is set, which we can readily use in adjustments.
15586 		 */
15587 		if (!is_power_of_2(val))
15588 			break;
15589 		if (is_jmp32) {
15590 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
15591 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15592 		} else {
15593 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
15594 		}
15595 		break;
15596 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
15597 		if (!is_reg_const(reg2, is_jmp32))
15598 			swap(reg1, reg2);
15599 		if (!is_reg_const(reg2, is_jmp32))
15600 			break;
15601 		val = reg_const_value(reg2, is_jmp32);
15602 		/* Forget the ranges before narrowing tnums, to avoid invariant
15603 		 * violations if we're on a dead branch.
15604 		 */
15605 		__mark_reg_unbounded(reg1);
15606 		if (is_jmp32) {
15607 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
15608 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15609 		} else {
15610 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
15611 		}
15612 		break;
15613 	case BPF_JLE:
15614 		if (is_jmp32) {
15615 			cnum32_intersect_with_urange(&reg1->r32, 0, reg_u32_max(reg2));
15616 			cnum32_intersect_with_urange(&reg2->r32, reg_u32_min(reg1), U32_MAX);
15617 		} else {
15618 			cnum64_intersect_with_urange(&reg1->r64, 0, reg_umax(reg2));
15619 			cnum64_intersect_with_urange(&reg2->r64, reg_umin(reg1), U64_MAX);
15620 		}
15621 		break;
15622 	case BPF_JLT:
15623 		if (is_jmp32) {
15624 			cnum32_intersect_with_urange(&reg1->r32, 0, reg_u32_max(reg2) - 1);
15625 			cnum32_intersect_with_urange(&reg2->r32, reg_u32_min(reg1) + 1, U32_MAX);
15626 		} else {
15627 			cnum64_intersect_with_urange(&reg1->r64, 0, reg_umax(reg2) - 1);
15628 			cnum64_intersect_with_urange(&reg2->r64, reg_umin(reg1) + 1, U64_MAX);
15629 		}
15630 		break;
15631 	case BPF_JSLE:
15632 		if (is_jmp32) {
15633 			cnum32_intersect_with_srange(&reg1->r32, S32_MIN, reg_s32_max(reg2));
15634 			cnum32_intersect_with_srange(&reg2->r32, reg_s32_min(reg1), S32_MAX);
15635 		} else {
15636 			cnum64_intersect_with_srange(&reg1->r64, S64_MIN, reg_smax(reg2));
15637 			cnum64_intersect_with_srange(&reg2->r64, reg_smin(reg1), S64_MAX);
15638 		}
15639 		break;
15640 	case BPF_JSLT:
15641 		if (is_jmp32) {
15642 			cnum32_intersect_with_srange(&reg1->r32, S32_MIN, reg_s32_max(reg2) - 1);
15643 			cnum32_intersect_with_srange(&reg2->r32, reg_s32_min(reg1) + 1, S32_MAX);
15644 		} else {
15645 			cnum64_intersect_with_srange(&reg1->r64, S64_MIN, reg_smax(reg2) - 1);
15646 			cnum64_intersect_with_srange(&reg2->r64, reg_smin(reg1) + 1, S64_MAX);
15647 		}
15648 		break;
15649 	default:
15650 		return;
15651 	}
15652 }
15653 
15654 /* Check for invariant violations on the registers for both branches of a condition */
15655 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env)
15656 {
15657 	int err;
15658 
15659 	err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1");
15660 	err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2");
15661 	err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1");
15662 	err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2");
15663 	return err;
15664 }
15665 
15666 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
15667 				 struct bpf_reg_state *reg, u32 id,
15668 				 bool is_null)
15669 {
15670 	if (type_may_be_null(reg->type) && reg->id == id &&
15671 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
15672 		/* Old offset should have been known-zero, because we don't
15673 		 * allow pointer arithmetic on pointers that might be NULL.
15674 		 * If we see this happening, don't convert the register.
15675 		 *
15676 		 * But in some cases, some helpers that return local kptrs
15677 		 * advance offset for the returned pointer. In those cases,
15678 		 * it is fine to expect to see reg->var_off.
15679 		 */
15680 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
15681 		    WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0)))
15682 			return;
15683 		if (is_null) {
15684 			/* We don't need id from this point
15685 			 * onwards anymore, thus we should better reset it,
15686 			 * so that state pruning has chances to take effect.
15687 			 */
15688 			__mark_reg_known_zero(reg);
15689 			reg->type = SCALAR_VALUE;
15690 
15691 			return;
15692 		}
15693 
15694 		mark_ptr_not_null_reg(reg);
15695 
15696 		/*
15697 		 * reg->id is preserved for object relationship tracking
15698 		 * and spin_lock lock state tracking
15699 		 */
15700 	}
15701 }
15702 
15703 /* The logic is similar to find_good_pkt_pointers(), both could eventually
15704  * be folded together at some point.
15705  */
15706 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
15707 				  bool is_null)
15708 {
15709 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15710 	struct bpf_reg_state *regs = state->regs, *reg;
15711 	u32 id = regs[regno].id;
15712 
15713 	if (is_null && find_reference_state(vstate, id))
15714 		/* regs[regno] is in the " == NULL" branch.
15715 		 * No one could have freed the reference state before
15716 		 * doing the NULL check.
15717 		 */
15718 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
15719 
15720 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15721 		mark_ptr_or_null_reg(state, reg, id, is_null);
15722 	}));
15723 }
15724 
15725 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
15726 				   struct bpf_reg_state *dst_reg,
15727 				   struct bpf_reg_state *src_reg,
15728 				   struct bpf_verifier_state *this_branch,
15729 				   struct bpf_verifier_state *other_branch)
15730 {
15731 	if (BPF_SRC(insn->code) != BPF_X)
15732 		return false;
15733 
15734 	/* Pointers are always 64-bit. */
15735 	if (BPF_CLASS(insn->code) == BPF_JMP32)
15736 		return false;
15737 
15738 	switch (BPF_OP(insn->code)) {
15739 	case BPF_JGT:
15740 		if ((dst_reg->type == PTR_TO_PACKET &&
15741 		     src_reg->type == PTR_TO_PACKET_END) ||
15742 		    (dst_reg->type == PTR_TO_PACKET_META &&
15743 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15744 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
15745 			find_good_pkt_pointers(this_branch, dst_reg,
15746 					       dst_reg->type, false);
15747 			mark_pkt_end(other_branch, insn->dst_reg, true);
15748 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15749 			    src_reg->type == PTR_TO_PACKET) ||
15750 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15751 			    src_reg->type == PTR_TO_PACKET_META)) {
15752 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
15753 			find_good_pkt_pointers(other_branch, src_reg,
15754 					       src_reg->type, true);
15755 			mark_pkt_end(this_branch, insn->src_reg, false);
15756 		} else {
15757 			return false;
15758 		}
15759 		break;
15760 	case BPF_JLT:
15761 		if ((dst_reg->type == PTR_TO_PACKET &&
15762 		     src_reg->type == PTR_TO_PACKET_END) ||
15763 		    (dst_reg->type == PTR_TO_PACKET_META &&
15764 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15765 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
15766 			find_good_pkt_pointers(other_branch, dst_reg,
15767 					       dst_reg->type, true);
15768 			mark_pkt_end(this_branch, insn->dst_reg, false);
15769 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15770 			    src_reg->type == PTR_TO_PACKET) ||
15771 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15772 			    src_reg->type == PTR_TO_PACKET_META)) {
15773 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
15774 			find_good_pkt_pointers(this_branch, src_reg,
15775 					       src_reg->type, false);
15776 			mark_pkt_end(other_branch, insn->src_reg, true);
15777 		} else {
15778 			return false;
15779 		}
15780 		break;
15781 	case BPF_JGE:
15782 		if ((dst_reg->type == PTR_TO_PACKET &&
15783 		     src_reg->type == PTR_TO_PACKET_END) ||
15784 		    (dst_reg->type == PTR_TO_PACKET_META &&
15785 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15786 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
15787 			find_good_pkt_pointers(this_branch, dst_reg,
15788 					       dst_reg->type, true);
15789 			mark_pkt_end(other_branch, insn->dst_reg, false);
15790 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15791 			    src_reg->type == PTR_TO_PACKET) ||
15792 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15793 			    src_reg->type == PTR_TO_PACKET_META)) {
15794 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
15795 			find_good_pkt_pointers(other_branch, src_reg,
15796 					       src_reg->type, false);
15797 			mark_pkt_end(this_branch, insn->src_reg, true);
15798 		} else {
15799 			return false;
15800 		}
15801 		break;
15802 	case BPF_JLE:
15803 		if ((dst_reg->type == PTR_TO_PACKET &&
15804 		     src_reg->type == PTR_TO_PACKET_END) ||
15805 		    (dst_reg->type == PTR_TO_PACKET_META &&
15806 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15807 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
15808 			find_good_pkt_pointers(other_branch, dst_reg,
15809 					       dst_reg->type, false);
15810 			mark_pkt_end(this_branch, insn->dst_reg, true);
15811 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15812 			    src_reg->type == PTR_TO_PACKET) ||
15813 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15814 			    src_reg->type == PTR_TO_PACKET_META)) {
15815 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
15816 			find_good_pkt_pointers(this_branch, src_reg,
15817 					       src_reg->type, true);
15818 			mark_pkt_end(other_branch, insn->src_reg, false);
15819 		} else {
15820 			return false;
15821 		}
15822 		break;
15823 	default:
15824 		return false;
15825 	}
15826 
15827 	return true;
15828 }
15829 
15830 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
15831 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
15832 {
15833 	struct linked_reg *e;
15834 
15835 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
15836 		return;
15837 
15838 	e = linked_regs_push(reg_set);
15839 	if (e) {
15840 		e->frameno = frameno;
15841 		e->is_reg = is_reg;
15842 		e->regno = spi_or_reg;
15843 	} else {
15844 		clear_scalar_id(reg);
15845 	}
15846 }
15847 
15848 /* For all R being scalar registers or spilled scalar registers
15849  * in verifier state, save R in linked_regs if R->id == id.
15850  * If there are too many Rs sharing same id, reset id for leftover Rs.
15851  */
15852 static void collect_linked_regs(struct bpf_verifier_env *env,
15853 				struct bpf_verifier_state *vstate,
15854 				u32 id,
15855 				struct linked_regs *linked_regs)
15856 {
15857 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
15858 	struct bpf_func_state *func;
15859 	struct bpf_reg_state *reg;
15860 	u16 live_regs;
15861 	int i, j;
15862 
15863 	id = id & ~BPF_ADD_CONST;
15864 	for (i = vstate->curframe; i >= 0; i--) {
15865 		live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before;
15866 		func = vstate->frame[i];
15867 		for (j = 0; j < BPF_REG_FP; j++) {
15868 			if (!(live_regs & BIT(j)))
15869 				continue;
15870 			reg = &func->regs[j];
15871 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
15872 		}
15873 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
15874 			if (!bpf_is_spilled_reg(&func->stack[j]))
15875 				continue;
15876 			reg = &func->stack[j].spilled_ptr;
15877 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
15878 		}
15879 	}
15880 }
15881 
15882 /* For all R in linked_regs, copy known_reg range into R
15883  * if R->id == known_reg->id.
15884  */
15885 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,
15886 			     struct bpf_reg_state *known_reg, struct linked_regs *linked_regs)
15887 {
15888 	struct bpf_reg_state fake_reg;
15889 	struct bpf_reg_state *reg;
15890 	struct linked_reg *e;
15891 	int i;
15892 
15893 	for (i = 0; i < linked_regs->cnt; ++i) {
15894 		e = &linked_regs->entries[i];
15895 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
15896 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
15897 		if (reg->type != SCALAR_VALUE || reg == known_reg)
15898 			continue;
15899 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
15900 			continue;
15901 		/*
15902 		 * Skip mixed 32/64-bit links: the delta relationship doesn't
15903 		 * hold across different ALU widths.
15904 		 */
15905 		if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST)
15906 			continue;
15907 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
15908 		    reg->delta == known_reg->delta) {
15909 			s32 saved_subreg_def = reg->subreg_def;
15910 
15911 			*reg = *known_reg;
15912 			reg->subreg_def = saved_subreg_def;
15913 		} else {
15914 			s32 saved_subreg_def = reg->subreg_def;
15915 			s32 saved_off = reg->delta;
15916 			u32 saved_id = reg->id;
15917 
15918 			fake_reg.type = SCALAR_VALUE;
15919 			__mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta);
15920 
15921 			/* reg = known_reg; reg += delta */
15922 			*reg = *known_reg;
15923 			/*
15924 			 * Must preserve off, id and subreg_def flag,
15925 			 * otherwise another sync_linked_regs() will be incorrect.
15926 			 */
15927 			reg->delta = saved_off;
15928 			reg->id = saved_id;
15929 			reg->subreg_def = saved_subreg_def;
15930 
15931 			scalar32_min_max_add(reg, &fake_reg);
15932 			scalar_min_max_add(reg, &fake_reg);
15933 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
15934 			if ((reg->id | known_reg->id) & BPF_ADD_CONST32)
15935 				zext_32_to_64(reg);
15936 			reg_bounds_sync(reg);
15937 		}
15938 		if (e->is_reg)
15939 			mark_reg_scratched(env, e->regno);
15940 		else
15941 			mark_stack_slot_scratched(env, e->spi);
15942 	}
15943 }
15944 
15945 static int check_cond_jmp_op(struct bpf_verifier_env *env,
15946 			     struct bpf_insn *insn, int *insn_idx)
15947 {
15948 	struct bpf_verifier_state *this_branch = env->cur_state;
15949 	struct bpf_verifier_state *other_branch;
15950 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
15951 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
15952 	struct bpf_reg_state *eq_branch_regs;
15953 	struct linked_regs linked_regs = {};
15954 	u8 opcode = BPF_OP(insn->code);
15955 	int insn_flags = 0;
15956 	bool is_jmp32;
15957 	int pred = -1;
15958 	int err;
15959 
15960 	/* Only conditional jumps are expected to reach here. */
15961 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
15962 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
15963 		return -EINVAL;
15964 	}
15965 
15966 	if (opcode == BPF_JCOND) {
15967 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
15968 		int idx = *insn_idx;
15969 
15970 		prev_st = find_prev_entry(env, cur_st->parent, idx);
15971 
15972 		/* branch out 'fallthrough' insn as a new state to explore */
15973 		queued_st = push_stack(env, idx + 1, idx, false);
15974 		if (IS_ERR(queued_st))
15975 			return PTR_ERR(queued_st);
15976 
15977 		queued_st->may_goto_depth++;
15978 		if (prev_st)
15979 			widen_imprecise_scalars(env, prev_st, queued_st);
15980 		*insn_idx += insn->off;
15981 		return 0;
15982 	}
15983 
15984 	/* check src2 operand */
15985 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15986 	if (err)
15987 		return err;
15988 
15989 	dst_reg = &regs[insn->dst_reg];
15990 	if (BPF_SRC(insn->code) == BPF_X) {
15991 		/* check src1 operand */
15992 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15993 		if (err)
15994 			return err;
15995 
15996 		src_reg = &regs[insn->src_reg];
15997 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
15998 		    is_pointer_value(env, insn->src_reg)) {
15999 			verbose(env, "R%d pointer comparison prohibited\n",
16000 				insn->src_reg);
16001 			return -EACCES;
16002 		}
16003 
16004 		if (src_reg->type == PTR_TO_STACK)
16005 			insn_flags |= INSN_F_SRC_REG_STACK;
16006 		if (dst_reg->type == PTR_TO_STACK)
16007 			insn_flags |= INSN_F_DST_REG_STACK;
16008 	} else {
16009 		src_reg = &env->fake_reg[0];
16010 		memset(src_reg, 0, sizeof(*src_reg));
16011 		src_reg->type = SCALAR_VALUE;
16012 		__mark_reg_known(src_reg, insn->imm);
16013 
16014 		if (dst_reg->type == PTR_TO_STACK)
16015 			insn_flags |= INSN_F_DST_REG_STACK;
16016 	}
16017 
16018 	if (insn_flags) {
16019 		err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, 0);
16020 		if (err)
16021 			return err;
16022 	}
16023 
16024 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
16025 	env->false_reg1 = *dst_reg;
16026 	env->false_reg2 = *src_reg;
16027 	env->true_reg1 = *dst_reg;
16028 	env->true_reg2 = *src_reg;
16029 	pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32);
16030 	if (pred >= 0) {
16031 		/* If we get here with a dst_reg pointer type it is because
16032 		 * above is_branch_taken() special cased the 0 comparison.
16033 		 */
16034 		if (!__is_pointer_value(false, dst_reg))
16035 			err = mark_chain_precision(env, insn->dst_reg);
16036 		if (BPF_SRC(insn->code) == BPF_X && !err &&
16037 		    !__is_pointer_value(false, src_reg))
16038 			err = mark_chain_precision(env, insn->src_reg);
16039 		if (err)
16040 			return err;
16041 	}
16042 
16043 	if (pred == 1) {
16044 		/* Only follow the goto, ignore fall-through. If needed, push
16045 		 * the fall-through branch for simulation under speculative
16046 		 * execution.
16047 		 */
16048 		if (!env->bypass_spec_v1) {
16049 			err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx);
16050 			if (err < 0)
16051 				return err;
16052 		}
16053 		if (env->log.level & BPF_LOG_LEVEL)
16054 			print_insn_state(env, this_branch, this_branch->curframe);
16055 		*insn_idx += insn->off;
16056 		return 0;
16057 	} else if (pred == 0) {
16058 		/* Only follow the fall-through branch, since that's where the
16059 		 * program will go. If needed, push the goto branch for
16060 		 * simulation under speculative execution.
16061 		 */
16062 		if (!env->bypass_spec_v1) {
16063 			err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1,
16064 							*insn_idx);
16065 			if (err < 0)
16066 				return err;
16067 		}
16068 		if (env->log.level & BPF_LOG_LEVEL)
16069 			print_insn_state(env, this_branch, this_branch->curframe);
16070 		return 0;
16071 	}
16072 
16073 	/* Push scalar registers sharing same ID to jump history,
16074 	 * do this before creating 'other_branch', so that both
16075 	 * 'this_branch' and 'other_branch' share this history
16076 	 * if parent state is created.
16077 	 */
16078 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
16079 		collect_linked_regs(env, this_branch, src_reg->id, &linked_regs);
16080 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
16081 		collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs);
16082 	if (linked_regs.cnt > 1) {
16083 		err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, linked_regs_pack(&linked_regs));
16084 		if (err)
16085 			return err;
16086 	}
16087 
16088 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
16089 	if (IS_ERR(other_branch))
16090 		return PTR_ERR(other_branch);
16091 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
16092 
16093 	err = regs_bounds_sanity_check_branches(env);
16094 	if (err)
16095 		return err;
16096 
16097 	*dst_reg = env->false_reg1;
16098 	*src_reg = env->false_reg2;
16099 	other_branch_regs[insn->dst_reg] = env->true_reg1;
16100 	if (BPF_SRC(insn->code) == BPF_X)
16101 		other_branch_regs[insn->src_reg] = env->true_reg2;
16102 
16103 	if (BPF_SRC(insn->code) == BPF_X &&
16104 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
16105 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
16106 		sync_linked_regs(env, this_branch, src_reg, &linked_regs);
16107 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg],
16108 				 &linked_regs);
16109 	}
16110 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
16111 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
16112 		sync_linked_regs(env, this_branch, dst_reg, &linked_regs);
16113 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg],
16114 				 &linked_regs);
16115 	}
16116 
16117 	/* if one pointer register is compared to another pointer
16118 	 * register check if PTR_MAYBE_NULL could be lifted.
16119 	 * E.g. register A - maybe null
16120 	 *      register B - not null
16121 	 * for JNE A, B, ... - A is not null in the false branch;
16122 	 * for JEQ A, B, ... - A is not null in the true branch.
16123 	 *
16124 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
16125 	 * not need to be null checked by the BPF program, i.e.,
16126 	 * could be null even without PTR_MAYBE_NULL marking, so
16127 	 * only propagate nullness when neither reg is that type.
16128 	 */
16129 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
16130 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
16131 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
16132 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
16133 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
16134 		eq_branch_regs = NULL;
16135 		switch (opcode) {
16136 		case BPF_JEQ:
16137 			eq_branch_regs = other_branch_regs;
16138 			break;
16139 		case BPF_JNE:
16140 			eq_branch_regs = regs;
16141 			break;
16142 		default:
16143 			/* do nothing */
16144 			break;
16145 		}
16146 		if (eq_branch_regs) {
16147 			if (type_may_be_null(src_reg->type))
16148 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
16149 			else
16150 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
16151 		}
16152 	}
16153 
16154 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
16155 	 * Also does the same detection for a register whose the value is
16156 	 * known to be 0.
16157 	 * NOTE: these optimizations below are related with pointer comparison
16158 	 *       which will never be JMP32.
16159 	 */
16160 	if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
16161 	    type_may_be_null(dst_reg->type) &&
16162 	    ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) ||
16163 	     (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) {
16164 		/* Mark all identical registers in each branch as either
16165 		 * safe or unknown depending R == 0 or R != 0 conditional.
16166 		 */
16167 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
16168 				      opcode == BPF_JNE);
16169 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
16170 				      opcode == BPF_JEQ);
16171 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
16172 					   this_branch, other_branch) &&
16173 		   is_pointer_value(env, insn->dst_reg)) {
16174 		verbose(env, "R%d pointer comparison prohibited\n",
16175 			insn->dst_reg);
16176 		return -EACCES;
16177 	}
16178 	if (env->log.level & BPF_LOG_LEVEL)
16179 		print_insn_state(env, this_branch, this_branch->curframe);
16180 	return 0;
16181 }
16182 
16183 /* verify BPF_LD_IMM64 instruction */
16184 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
16185 {
16186 	struct bpf_insn_aux_data *aux = cur_aux(env);
16187 	struct bpf_reg_state *regs = cur_regs(env);
16188 	struct bpf_reg_state *dst_reg;
16189 	struct bpf_map *map;
16190 	int err;
16191 
16192 	if (BPF_SIZE(insn->code) != BPF_DW) {
16193 		verbose(env, "invalid BPF_LD_IMM insn\n");
16194 		return -EINVAL;
16195 	}
16196 
16197 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
16198 	if (err)
16199 		return err;
16200 
16201 	dst_reg = &regs[insn->dst_reg];
16202 	if (insn->src_reg == 0) {
16203 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
16204 
16205 		dst_reg->type = SCALAR_VALUE;
16206 		__mark_reg_known(&regs[insn->dst_reg], imm);
16207 		return 0;
16208 	}
16209 
16210 	/* All special src_reg cases are listed below. From this point onwards
16211 	 * we either succeed and assign a corresponding dst_reg->type after
16212 	 * zeroing the offset, or fail and reject the program.
16213 	 */
16214 	mark_reg_known_zero(env, regs, insn->dst_reg);
16215 
16216 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
16217 		dst_reg->type = aux->btf_var.reg_type;
16218 		switch (base_type(dst_reg->type)) {
16219 		case PTR_TO_MEM:
16220 			dst_reg->mem_size = aux->btf_var.mem_size;
16221 			break;
16222 		case PTR_TO_BTF_ID:
16223 			dst_reg->btf = aux->btf_var.btf;
16224 			dst_reg->btf_id = aux->btf_var.btf_id;
16225 			break;
16226 		default:
16227 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
16228 			return -EFAULT;
16229 		}
16230 		return 0;
16231 	}
16232 
16233 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
16234 		struct bpf_prog_aux *aux = env->prog->aux;
16235 		u32 subprogno = bpf_find_subprog(env,
16236 						 env->insn_idx + insn->imm + 1);
16237 
16238 		if (!aux->func_info) {
16239 			verbose(env, "missing btf func_info\n");
16240 			return -EINVAL;
16241 		}
16242 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
16243 			verbose(env, "callback function not static\n");
16244 			return -EINVAL;
16245 		}
16246 
16247 		dst_reg->type = PTR_TO_FUNC;
16248 		dst_reg->subprogno = subprogno;
16249 		return 0;
16250 	}
16251 
16252 	map = env->used_maps[aux->map_index];
16253 
16254 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
16255 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
16256 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
16257 			__mark_reg_unknown(env, dst_reg);
16258 			dst_reg->map_ptr = map;
16259 			return 0;
16260 		}
16261 		__mark_reg_known(dst_reg, aux->map_off);
16262 		dst_reg->type = PTR_TO_MAP_VALUE;
16263 		dst_reg->map_ptr = map;
16264 		WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY &&
16265 			     map->max_entries != 1);
16266 		/* We want reg->id to be same (0) as map_value is not distinct */
16267 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
16268 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
16269 		dst_reg->type = CONST_PTR_TO_MAP;
16270 		dst_reg->map_ptr = map;
16271 	} else {
16272 		verifier_bug(env, "unexpected src reg value for ldimm64");
16273 		return -EFAULT;
16274 	}
16275 
16276 	return 0;
16277 }
16278 
16279 static bool may_access_skb(enum bpf_prog_type type)
16280 {
16281 	switch (type) {
16282 	case BPF_PROG_TYPE_SOCKET_FILTER:
16283 	case BPF_PROG_TYPE_SCHED_CLS:
16284 	case BPF_PROG_TYPE_SCHED_ACT:
16285 		return true;
16286 	default:
16287 		return false;
16288 	}
16289 }
16290 
16291 /* verify safety of LD_ABS|LD_IND instructions:
16292  * - they can only appear in the programs where ctx == skb
16293  * - since they are wrappers of function calls, they scratch R1-R5 registers,
16294  *   preserve R6-R9, and store return value into R0
16295  *
16296  * Implicit input:
16297  *   ctx == skb == R6 == CTX
16298  *
16299  * Explicit input:
16300  *   SRC == any register
16301  *   IMM == 32-bit immediate
16302  *
16303  * Output:
16304  *   R0 - 8/16/32-bit skb data converted to cpu endianness
16305  */
16306 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
16307 {
16308 	struct bpf_reg_state *regs = cur_regs(env);
16309 	static const int ctx_reg = BPF_REG_6;
16310 	u8 mode = BPF_MODE(insn->code);
16311 	int i, err;
16312 
16313 	if (!may_access_skb(resolve_prog_type(env->prog))) {
16314 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
16315 		return -EINVAL;
16316 	}
16317 
16318 	if (!env->ops->gen_ld_abs) {
16319 		verifier_bug(env, "gen_ld_abs is null");
16320 		return -EFAULT;
16321 	}
16322 
16323 	/* check whether implicit source operand (register R6) is readable */
16324 	err = check_reg_arg(env, ctx_reg, SRC_OP);
16325 	if (err)
16326 		return err;
16327 
16328 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
16329 	 * gen_ld_abs() may terminate the program at runtime, leading to
16330 	 * reference leak.
16331 	 */
16332 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
16333 	if (err)
16334 		return err;
16335 
16336 	if (regs[ctx_reg].type != PTR_TO_CTX) {
16337 		verbose(env,
16338 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
16339 		return -EINVAL;
16340 	}
16341 
16342 	if (mode == BPF_IND) {
16343 		/* check explicit source operand */
16344 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16345 		if (err)
16346 			return err;
16347 	}
16348 
16349 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
16350 	if (err < 0)
16351 		return err;
16352 
16353 	/* reset caller saved regs to unreadable */
16354 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
16355 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
16356 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
16357 	}
16358 
16359 	/* mark destination R0 register as readable, since it contains
16360 	 * the value fetched from the packet.
16361 	 * Already marked as written above.
16362 	 */
16363 	mark_reg_unknown(env, regs, BPF_REG_0);
16364 	/* ld_abs load up to 32-bit skb data. */
16365 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
16366 	/*
16367 	 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0
16368 	 * which must be explored by the verifier when in a subprog.
16369 	 */
16370 	if (env->cur_state->curframe) {
16371 		struct bpf_verifier_state *branch;
16372 
16373 		mark_reg_scratched(env, BPF_REG_0);
16374 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
16375 		if (IS_ERR(branch))
16376 			return PTR_ERR(branch);
16377 		mark_reg_known_zero(env, regs, BPF_REG_0);
16378 		err = prepare_func_exit(env, &env->insn_idx);
16379 		if (err)
16380 			return err;
16381 		env->insn_idx--;
16382 	}
16383 	return 0;
16384 }
16385 
16386 
16387 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range)
16388 {
16389 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
16390 
16391 	/* Default return value range. */
16392 	*range = retval_range(0, 1);
16393 
16394 	switch (prog_type) {
16395 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
16396 		switch (env->prog->expected_attach_type) {
16397 		case BPF_CGROUP_UDP4_RECVMSG:
16398 		case BPF_CGROUP_UDP6_RECVMSG:
16399 		case BPF_CGROUP_UNIX_RECVMSG:
16400 		case BPF_CGROUP_INET4_GETPEERNAME:
16401 		case BPF_CGROUP_INET6_GETPEERNAME:
16402 		case BPF_CGROUP_UNIX_GETPEERNAME:
16403 		case BPF_CGROUP_INET4_GETSOCKNAME:
16404 		case BPF_CGROUP_INET6_GETSOCKNAME:
16405 		case BPF_CGROUP_UNIX_GETSOCKNAME:
16406 			*range = retval_range(1, 1);
16407 			break;
16408 		case BPF_CGROUP_INET4_BIND:
16409 		case BPF_CGROUP_INET6_BIND:
16410 			*range = retval_range(0, 3);
16411 			break;
16412 		default:
16413 			break;
16414 		}
16415 		break;
16416 	case BPF_PROG_TYPE_CGROUP_SKB:
16417 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)
16418 			*range = retval_range(0, 3);
16419 		break;
16420 	case BPF_PROG_TYPE_CGROUP_SOCK:
16421 	case BPF_PROG_TYPE_SOCK_OPS:
16422 	case BPF_PROG_TYPE_CGROUP_DEVICE:
16423 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
16424 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
16425 		break;
16426 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
16427 		if (!env->prog->aux->attach_btf_id)
16428 			return false;
16429 		*range = retval_range(0, 0);
16430 		break;
16431 	case BPF_PROG_TYPE_TRACING:
16432 		switch (env->prog->expected_attach_type) {
16433 		case BPF_TRACE_FENTRY:
16434 		case BPF_TRACE_FEXIT:
16435 		case BPF_TRACE_FSESSION:
16436 		case BPF_TRACE_FENTRY_MULTI:
16437 		case BPF_TRACE_FEXIT_MULTI:
16438 		case BPF_TRACE_FSESSION_MULTI:
16439 			*range = retval_range(0, 0);
16440 			break;
16441 		case BPF_TRACE_RAW_TP:
16442 		case BPF_MODIFY_RETURN:
16443 			return false;
16444 		case BPF_TRACE_ITER:
16445 		default:
16446 			break;
16447 		}
16448 		break;
16449 	case BPF_PROG_TYPE_KPROBE:
16450 		switch (env->prog->expected_attach_type) {
16451 		case BPF_TRACE_KPROBE_SESSION:
16452 		case BPF_TRACE_UPROBE_SESSION:
16453 			break;
16454 		default:
16455 			return false;
16456 		}
16457 		break;
16458 	case BPF_PROG_TYPE_SK_LOOKUP:
16459 		*range = retval_range(SK_DROP, SK_PASS);
16460 		break;
16461 
16462 	case BPF_PROG_TYPE_LSM:
16463 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
16464 			/* no range found, any return value is allowed */
16465 			if (!get_func_retval_range(env->prog, range))
16466 				return false;
16467 			/* no restricted range, any return value is allowed */
16468 			if (range->minval == S32_MIN && range->maxval == S32_MAX)
16469 				return false;
16470 			range->return_32bit = true;
16471 		} else if (!env->prog->aux->attach_func_proto->type) {
16472 			/* Make sure programs that attach to void
16473 			 * hooks don't try to modify return value.
16474 			 */
16475 			*range = retval_range(1, 1);
16476 		}
16477 		break;
16478 
16479 	case BPF_PROG_TYPE_NETFILTER:
16480 		*range = retval_range(NF_DROP, NF_ACCEPT);
16481 		break;
16482 	case BPF_PROG_TYPE_STRUCT_OPS:
16483 		*range = retval_range(0, 0);
16484 		break;
16485 	case BPF_PROG_TYPE_EXT:
16486 		/* freplace program can return anything as its return value
16487 		 * depends on the to-be-replaced kernel func or bpf program.
16488 		 */
16489 	default:
16490 		return false;
16491 	}
16492 
16493 	/* Continue calculating. */
16494 
16495 	return true;
16496 }
16497 
16498 static bool program_returns_void(struct bpf_verifier_env *env)
16499 {
16500 	const struct bpf_prog *prog = env->prog;
16501 	enum bpf_prog_type prog_type = prog->type;
16502 
16503 	switch (prog_type) {
16504 	case BPF_PROG_TYPE_LSM:
16505 		/* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */
16506 		if (prog->expected_attach_type != BPF_LSM_CGROUP &&
16507 		    !prog->aux->attach_func_proto->type)
16508 			return true;
16509 		break;
16510 	case BPF_PROG_TYPE_STRUCT_OPS:
16511 		if (!prog->aux->attach_func_proto->type)
16512 			return true;
16513 		break;
16514 	case BPF_PROG_TYPE_EXT:
16515 		/*
16516 		 * If the actual program is an extension, let it
16517 		 * return void - attaching will succeed only if the
16518 		 * program being replaced also returns void, and since
16519 		 * it has passed verification its actual type doesn't matter.
16520 		 */
16521 		if (subprog_returns_void(env, 0))
16522 			return true;
16523 		break;
16524 	default:
16525 		break;
16526 	}
16527 	return false;
16528 }
16529 
16530 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
16531 {
16532 	const char *exit_ctx = "At program exit";
16533 	struct tnum enforce_attach_type_range = tnum_unknown;
16534 	const struct bpf_prog *prog = env->prog;
16535 	struct bpf_reg_state *reg = reg_state(env, regno);
16536 	struct bpf_retval_range range = retval_range(0, 1);
16537 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
16538 	struct bpf_func_state *frame = env->cur_state->frame[0];
16539 	const struct btf_type *reg_type, *ret_type = NULL;
16540 	int err;
16541 
16542 	/* LSM and struct_ops func-ptr's return type could be "void" */
16543 	if (!frame->in_async_callback_fn && program_returns_void(env))
16544 		return 0;
16545 
16546 	if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) {
16547 		/* Allow a struct_ops program to return a referenced kptr if it
16548 		 * matches the operator's return type and is in its unmodified
16549 		 * form. A scalar zero (i.e., a null pointer) is also allowed.
16550 		 */
16551 		reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
16552 		ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
16553 						prog->aux->attach_func_proto->type,
16554 						NULL);
16555 		if (ret_type && ret_type == reg_type && reg_is_referenced(env, reg))
16556 			return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false);
16557 	}
16558 
16559 	/* eBPF calling convention is such that R0 is used
16560 	 * to return the value from eBPF program.
16561 	 * Make sure that it's readable at this time
16562 	 * of bpf_exit, which means that program wrote
16563 	 * something into it earlier
16564 	 */
16565 	err = check_reg_arg(env, regno, SRC_OP);
16566 	if (err)
16567 		return err;
16568 
16569 	if (is_pointer_value(env, regno)) {
16570 		verbose(env, "R%d leaks addr as return value\n", regno);
16571 		return -EACCES;
16572 	}
16573 
16574 	if (frame->in_async_callback_fn) {
16575 		exit_ctx = "At async callback return";
16576 		range = frame->callback_ret_range;
16577 		goto enforce_retval;
16578 	}
16579 
16580 	if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type)
16581 		return 0;
16582 
16583 	if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS))
16584 		enforce_attach_type_range = tnum_range(2, 3);
16585 
16586 	if (!return_retval_range(env, &range))
16587 		return 0;
16588 
16589 enforce_retval:
16590 	if (reg->type != SCALAR_VALUE) {
16591 		verbose(env, "%s the register R%d is not a known value (%s)\n",
16592 			exit_ctx, regno, reg_type_str(env, reg->type));
16593 		return -EINVAL;
16594 	}
16595 
16596 	err = mark_chain_precision(env, regno);
16597 	if (err)
16598 		return err;
16599 
16600 	if (!retval_range_within(range, reg)) {
16601 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
16602 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
16603 		    prog_type == BPF_PROG_TYPE_LSM &&
16604 		    !prog->aux->attach_func_proto->type)
16605 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
16606 		return -EINVAL;
16607 	}
16608 
16609 	if (!tnum_is_unknown(enforce_attach_type_range) &&
16610 	    tnum_in(enforce_attach_type_range, reg->var_off))
16611 		env->prog->enforce_expected_attach_type = 1;
16612 	return 0;
16613 }
16614 
16615 static int check_global_subprog_return_code(struct bpf_verifier_env *env)
16616 {
16617 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
16618 	struct bpf_func_state *cur_frame = cur_func(env);
16619 	int err;
16620 
16621 	if (subprog_returns_void(env, cur_frame->subprogno))
16622 		return 0;
16623 
16624 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
16625 	if (err)
16626 		return err;
16627 
16628 	/* Pointers to arena are safe to pass between subprograms. */
16629 	if (is_arena_reg(env, BPF_REG_0))
16630 		return 0;
16631 
16632 	if (is_pointer_value(env, BPF_REG_0)) {
16633 		verbose(env, "R%d leaks addr as return value\n", BPF_REG_0);
16634 		return -EACCES;
16635 	}
16636 
16637 	if (reg->type != SCALAR_VALUE) {
16638 		verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
16639 			reg_type_str(env, reg->type));
16640 		return -EINVAL;
16641 	}
16642 
16643 	return 0;
16644 }
16645 
16646 /* Bitmask with 1s for all caller saved registers */
16647 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
16648 
16649 /* True if do_misc_fixups() replaces calls to helper number 'imm',
16650  * replacement patch is presumed to follow bpf_fastcall contract
16651  * (see mark_fastcall_pattern_for_call() below).
16652  */
16653 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
16654 {
16655 	switch (imm) {
16656 #ifdef CONFIG_X86_64
16657 	case BPF_FUNC_get_smp_processor_id:
16658 #ifdef CONFIG_SMP
16659 	case BPF_FUNC_get_current_task_btf:
16660 	case BPF_FUNC_get_current_task:
16661 #endif
16662 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
16663 #endif
16664 	default:
16665 		return false;
16666 	}
16667 }
16668 
16669 /* If @call is a kfunc or helper call, fills @cs and returns true,
16670  * otherwise returns false.
16671  */
16672 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
16673 			  struct bpf_call_summary *cs)
16674 {
16675 	struct bpf_kfunc_call_arg_meta meta;
16676 	const struct bpf_func_proto *fn;
16677 	int i;
16678 
16679 	if (bpf_helper_call(call)) {
16680 
16681 		if (bpf_get_helper_proto(env, call->imm, &fn) < 0)
16682 			/* error would be reported later */
16683 			return false;
16684 		cs->fastcall = fn->allow_fastcall &&
16685 			       (bpf_verifier_inlines_helper_call(env, call->imm) ||
16686 				bpf_jit_inlines_helper_call(call->imm));
16687 		cs->is_void = fn->ret_type == RET_VOID;
16688 		cs->num_params = 0;
16689 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
16690 			if (fn->arg_type[i] == ARG_DONTCARE)
16691 				break;
16692 			cs->num_params++;
16693 		}
16694 		return true;
16695 	}
16696 
16697 	if (bpf_pseudo_kfunc_call(call)) {
16698 		int err;
16699 
16700 		err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta);
16701 		if (err < 0)
16702 			/* error would be reported later */
16703 			return false;
16704 		cs->num_params = btf_type_vlen(meta.func_proto);
16705 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
16706 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
16707 		return true;
16708 	}
16709 
16710 	return false;
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 	u32 clobbered_regs_mask;
16794 	struct bpf_call_summary cs;
16795 	u32 expected_regs_mask;
16796 	s16 off;
16797 	int i;
16798 
16799 	if (!bpf_get_call_summary(env, call, &cs))
16800 		return;
16801 
16802 	/* A bitmask specifying which caller saved registers are clobbered
16803 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
16804 	 * bpf_fastcall contract:
16805 	 * - includes R0 if function is non-void;
16806 	 * - includes R1-R5 if corresponding parameter has is described
16807 	 *   in the function prototype.
16808 	 */
16809 	clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
16810 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
16811 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
16812 
16813 	/* match pairs of form:
16814 	 *
16815 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
16816 	 * ...
16817 	 * call %[to_be_inlined]
16818 	 * ...
16819 	 * rX = *(u64 *)(r10 - Y)
16820 	 */
16821 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
16822 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
16823 			break;
16824 		stx = &insns[insn_idx - i];
16825 		ldx = &insns[insn_idx + i];
16826 		/* must be a stack spill/fill pair */
16827 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
16828 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
16829 		    stx->dst_reg != BPF_REG_10 ||
16830 		    ldx->src_reg != BPF_REG_10)
16831 			break;
16832 		/* must be a spill/fill for the same reg */
16833 		if (stx->src_reg != ldx->dst_reg)
16834 			break;
16835 		/* must be one of the previously unseen registers */
16836 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
16837 			break;
16838 		/* must be a spill/fill for the same expected offset,
16839 		 * no need to check offset alignment, BPF_DW stack access
16840 		 * is always 8-byte aligned.
16841 		 */
16842 		if (stx->off != off || ldx->off != off)
16843 			break;
16844 		expected_regs_mask &= ~BIT(stx->src_reg);
16845 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
16846 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
16847 	}
16848 	if (i == 1)
16849 		return;
16850 
16851 	/* Conditionally set 'fastcall_spills_num' to allow forward
16852 	 * compatibility when more helper functions are marked as
16853 	 * bpf_fastcall at compile time than current kernel supports, e.g:
16854 	 *
16855 	 *   1: *(u64 *)(r10 - 8) = r1
16856 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
16857 	 *   3: r1 = *(u64 *)(r10 - 8)
16858 	 *   4: *(u64 *)(r10 - 8) = r1
16859 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
16860 	 *   6: r1 = *(u64 *)(r10 - 8)
16861 	 *
16862 	 * There is no need to block bpf_fastcall rewrite for such program.
16863 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
16864 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
16865 	 * does not remove spill/fill pair {4,6}.
16866 	 */
16867 	if (cs.fastcall)
16868 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
16869 	else
16870 		subprog->keep_fastcall_stack = 1;
16871 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
16872 }
16873 
16874 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
16875 {
16876 	struct bpf_subprog_info *subprog = env->subprog_info;
16877 	struct bpf_insn *insn;
16878 	s16 lowest_off;
16879 	int s, i;
16880 
16881 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
16882 		/* find lowest stack spill offset used in this subprog */
16883 		lowest_off = 0;
16884 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
16885 			insn = env->prog->insnsi + i;
16886 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
16887 			    insn->dst_reg != BPF_REG_10)
16888 				continue;
16889 			lowest_off = min(lowest_off, insn->off);
16890 		}
16891 		/* use this offset to find fastcall patterns */
16892 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
16893 			insn = env->prog->insnsi + i;
16894 			if (insn->code != (BPF_JMP | BPF_CALL))
16895 				continue;
16896 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
16897 		}
16898 	}
16899 	return 0;
16900 }
16901 
16902 static void adjust_btf_func(struct bpf_verifier_env *env)
16903 {
16904 	struct bpf_prog_aux *aux = env->prog->aux;
16905 	int i;
16906 
16907 	if (!aux->func_info)
16908 		return;
16909 
16910 	/* func_info is not available for hidden subprogs */
16911 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
16912 		aux->func_info[i].insn_off = env->subprog_info[i].start;
16913 }
16914 
16915 /* Find id in idset and increment its count, or add new entry */
16916 static void idset_cnt_inc(struct bpf_idset *idset, u32 id)
16917 {
16918 	u32 i;
16919 
16920 	for (i = 0; i < idset->num_ids; i++) {
16921 		if (idset->entries[i].id == id) {
16922 			idset->entries[i].cnt++;
16923 			return;
16924 		}
16925 	}
16926 	/* New id */
16927 	if (idset->num_ids < BPF_ID_MAP_SIZE) {
16928 		idset->entries[idset->num_ids].id = id;
16929 		idset->entries[idset->num_ids].cnt = 1;
16930 		idset->num_ids++;
16931 	}
16932 }
16933 
16934 /* Find id in idset and return its count, or 0 if not found */
16935 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id)
16936 {
16937 	u32 i;
16938 
16939 	for (i = 0; i < idset->num_ids; i++) {
16940 		if (idset->entries[i].id == id)
16941 			return idset->entries[i].cnt;
16942 	}
16943 	return 0;
16944 }
16945 
16946 /*
16947  * Clear singular scalar ids in a state.
16948  * A register with a non-zero id is called singular if no other register shares
16949  * the same base id. Such registers can be treated as independent (id=0).
16950  */
16951 void bpf_clear_singular_ids(struct bpf_verifier_env *env,
16952 			    struct bpf_verifier_state *st)
16953 {
16954 	struct bpf_idset *idset = &env->idset_scratch;
16955 	struct bpf_func_state *func;
16956 	struct bpf_reg_state *reg;
16957 
16958 	idset->num_ids = 0;
16959 
16960 	bpf_for_each_reg_in_vstate(st, func, reg, ({
16961 		if (reg->type != SCALAR_VALUE)
16962 			continue;
16963 		if (!reg->id)
16964 			continue;
16965 		idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST);
16966 	}));
16967 
16968 	bpf_for_each_reg_in_vstate(st, func, reg, ({
16969 		if (reg->type != SCALAR_VALUE)
16970 			continue;
16971 		if (!reg->id)
16972 			continue;
16973 		if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1)
16974 			clear_scalar_id(reg);
16975 	}));
16976 }
16977 
16978 /* Return true if it's OK to have the same insn return a different type. */
16979 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16980 {
16981 	switch (base_type(type)) {
16982 	case PTR_TO_CTX:
16983 	case PTR_TO_SOCKET:
16984 	case PTR_TO_SOCK_COMMON:
16985 	case PTR_TO_TCP_SOCK:
16986 	case PTR_TO_XDP_SOCK:
16987 	case PTR_TO_BTF_ID:
16988 	case PTR_TO_ARENA:
16989 		return false;
16990 	default:
16991 		return true;
16992 	}
16993 }
16994 
16995 /* If an instruction was previously used with particular pointer types, then we
16996  * need to be careful to avoid cases such as the below, where it may be ok
16997  * for one branch accessing the pointer, but not ok for the other branch:
16998  *
16999  * R1 = sock_ptr
17000  * goto X;
17001  * ...
17002  * R1 = some_other_valid_ptr;
17003  * goto X;
17004  * ...
17005  * R2 = *(u32 *)(R1 + 0);
17006  */
17007 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17008 {
17009 	return src != prev && (!reg_type_mismatch_ok(src) ||
17010 			       !reg_type_mismatch_ok(prev));
17011 }
17012 
17013 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
17014 {
17015 	switch (base_type(type)) {
17016 	case PTR_TO_MEM:
17017 	case PTR_TO_BTF_ID:
17018 		return true;
17019 	default:
17020 		return false;
17021 	}
17022 }
17023 
17024 static bool is_ptr_to_mem(enum bpf_reg_type type)
17025 {
17026 	return base_type(type) == PTR_TO_MEM;
17027 }
17028 
17029 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17030 			     bool allow_trust_mismatch)
17031 {
17032 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17033 	enum bpf_reg_type merged_type;
17034 
17035 	if (*prev_type == NOT_INIT) {
17036 		/* Saw a valid insn
17037 		 * dst_reg = *(u32 *)(src_reg + off)
17038 		 * save type to validate intersecting paths
17039 		 */
17040 		*prev_type = type;
17041 	} else if (reg_type_mismatch(type, *prev_type)) {
17042 		/* Abuser program is trying to use the same insn
17043 		 * dst_reg = *(u32*) (src_reg + off)
17044 		 * with different pointer types:
17045 		 * src_reg == ctx in one branch and
17046 		 * src_reg == stack|map in some other branch.
17047 		 * Reject it.
17048 		 */
17049 		if (allow_trust_mismatch &&
17050 		    is_ptr_to_mem_or_btf_id(type) &&
17051 		    is_ptr_to_mem_or_btf_id(*prev_type)) {
17052 			/*
17053 			 * Have to support a use case when one path through
17054 			 * the program yields TRUSTED pointer while another
17055 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17056 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17057 			 * Same behavior of MEM_RDONLY flag.
17058 			 */
17059 			if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type))
17060 				merged_type = PTR_TO_MEM;
17061 			else
17062 				merged_type = PTR_TO_BTF_ID;
17063 			if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED))
17064 				merged_type |= PTR_UNTRUSTED;
17065 			if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY))
17066 				merged_type |= MEM_RDONLY;
17067 			*prev_type = merged_type;
17068 		} else {
17069 			verbose(env, "same insn cannot be used with different pointers\n");
17070 			return -EINVAL;
17071 		}
17072 	}
17073 
17074 	return 0;
17075 }
17076 
17077 enum {
17078 	PROCESS_BPF_EXIT = 1,
17079 	INSN_IDX_UPDATED = 2,
17080 };
17081 
17082 static int process_bpf_exit_full(struct bpf_verifier_env *env,
17083 				 bool *do_print_state,
17084 				 bool exception_exit)
17085 {
17086 	struct bpf_func_state *cur_frame = cur_func(env);
17087 
17088 	/* We must do check_reference_leak here before
17089 	 * prepare_func_exit to handle the case when
17090 	 * state->curframe > 0, it may be a callback function,
17091 	 * for which reference_state must match caller reference
17092 	 * state when it exits.
17093 	 */
17094 	int err = check_resource_leak(env, exception_exit,
17095 				      exception_exit || !env->cur_state->curframe,
17096 				      exception_exit ? "bpf_throw" :
17097 				      "BPF_EXIT instruction in main prog");
17098 	if (err)
17099 		return err;
17100 
17101 	/* The side effect of the prepare_func_exit which is
17102 	 * being skipped is that it frees bpf_func_state.
17103 	 * Typically, process_bpf_exit will only be hit with
17104 	 * outermost exit. copy_verifier_state in pop_stack will
17105 	 * handle freeing of any extra bpf_func_state left over
17106 	 * from not processing all nested function exits. We
17107 	 * also skip return code checks as they are not needed
17108 	 * for exceptional exits.
17109 	 */
17110 	if (exception_exit)
17111 		return PROCESS_BPF_EXIT;
17112 
17113 	if (env->cur_state->curframe) {
17114 		/* exit from nested function */
17115 		err = prepare_func_exit(env, &env->insn_idx);
17116 		if (err)
17117 			return err;
17118 		*do_print_state = true;
17119 		return INSN_IDX_UPDATED;
17120 	}
17121 
17122 	/*
17123 	 * Return from a regular global subprogram differs from return
17124 	 * from the main program or async/exception callback.
17125 	 * Main program exit implies return code restrictions
17126 	 * that depend on program type.
17127 	 * Exit from exception callback is equivalent to main program exit.
17128 	 * Exit from async callback implies return code restrictions
17129 	 * that depend on async scheduling mechanism.
17130 	 */
17131 	if (cur_frame->subprogno &&
17132 	    !cur_frame->in_async_callback_fn &&
17133 	    !cur_frame->in_exception_callback_fn)
17134 		err = check_global_subprog_return_code(env);
17135 	else
17136 		err = check_return_code(env, BPF_REG_0, "R0");
17137 	if (err)
17138 		return err;
17139 	return PROCESS_BPF_EXIT;
17140 }
17141 
17142 static int indirect_jump_min_max_index(struct bpf_verifier_env *env,
17143 				       int regno,
17144 				       struct bpf_map *map,
17145 				       u32 *pmin_index, u32 *pmax_index)
17146 {
17147 	struct bpf_reg_state *reg = reg_state(env, regno);
17148 	u64 min_index = reg_umin(reg);
17149 	u64 max_index = reg_umax(reg);
17150 	const u32 size = 8;
17151 
17152 	if (min_index > (u64) U32_MAX * size) {
17153 		verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg_umin(reg));
17154 		return -ERANGE;
17155 	}
17156 	if (max_index > (u64) U32_MAX * size) {
17157 		verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg_umax(reg));
17158 		return -ERANGE;
17159 	}
17160 
17161 	min_index /= size;
17162 	max_index /= size;
17163 
17164 	if (max_index >= map->max_entries) {
17165 		verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n",
17166 			     regno, min_index, max_index, map->max_entries);
17167 		return -EINVAL;
17168 	}
17169 
17170 	*pmin_index = min_index;
17171 	*pmax_index = max_index;
17172 	return 0;
17173 }
17174 
17175 /* gotox *dst_reg */
17176 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
17177 {
17178 	struct bpf_verifier_state *other_branch;
17179 	struct bpf_reg_state *dst_reg;
17180 	struct bpf_map *map;
17181 	u32 min_index, max_index;
17182 	int err = 0;
17183 	int n;
17184 	int i;
17185 
17186 	dst_reg = reg_state(env, insn->dst_reg);
17187 	if (dst_reg->type != PTR_TO_INSN) {
17188 		verbose(env, "R%d has type %s, expected PTR_TO_INSN\n",
17189 			     insn->dst_reg, reg_type_str(env, dst_reg->type));
17190 		return -EINVAL;
17191 	}
17192 
17193 	map = dst_reg->map_ptr;
17194 	if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg))
17195 		return -EFAULT;
17196 
17197 	if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env,
17198 			    "R%d has incorrect map type %d", insn->dst_reg, map->map_type))
17199 		return -EFAULT;
17200 
17201 	err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
17202 	if (err)
17203 		return err;
17204 
17205 	/* Ensure that the buffer is large enough */
17206 	if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) {
17207 		env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf,
17208 						        max_index - min_index + 1);
17209 		if (!env->gotox_tmp_buf)
17210 			return -ENOMEM;
17211 	}
17212 
17213 	n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items);
17214 	if (n < 0)
17215 		return n;
17216 	if (n == 0) {
17217 		verbose(env, "register R%d doesn't point to any offset in map id=%d\n",
17218 			     insn->dst_reg, map->id);
17219 		return -EINVAL;
17220 	}
17221 
17222 	for (i = 0; i < n - 1; i++) {
17223 		mark_indirect_target(env, env->gotox_tmp_buf->items[i]);
17224 		other_branch = push_stack(env, env->gotox_tmp_buf->items[i],
17225 					  env->insn_idx, env->cur_state->speculative);
17226 		if (IS_ERR(other_branch))
17227 			return PTR_ERR(other_branch);
17228 	}
17229 	env->insn_idx = env->gotox_tmp_buf->items[n-1];
17230 	mark_indirect_target(env, env->insn_idx);
17231 	return INSN_IDX_UPDATED;
17232 }
17233 
17234 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
17235 {
17236 	int err;
17237 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
17238 	u8 class = BPF_CLASS(insn->code);
17239 
17240 	switch (class) {
17241 	case BPF_ALU:
17242 	case BPF_ALU64:
17243 		return check_alu_op(env, insn);
17244 
17245 	case BPF_LDX:
17246 		return check_load_mem(env, insn, false,
17247 				      BPF_MODE(insn->code) == BPF_MEMSX,
17248 				      true, "ldx");
17249 
17250 	case BPF_STX:
17251 		if (BPF_MODE(insn->code) == BPF_ATOMIC)
17252 			return check_atomic(env, insn);
17253 		return check_store_reg(env, insn, false);
17254 
17255 	case BPF_ST: {
17256 		/* Handle stack arg write (store immediate) */
17257 		if (is_stack_arg_st(insn)) {
17258 			struct bpf_verifier_state *vstate = env->cur_state;
17259 			struct bpf_func_state *state = vstate->frame[vstate->curframe];
17260 
17261 			return check_stack_arg_write(env, state, insn->off, NULL);
17262 		}
17263 
17264 		enum bpf_reg_type dst_reg_type;
17265 
17266 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17267 		if (err)
17268 			return err;
17269 
17270 		dst_reg_type = cur_regs(env)[insn->dst_reg].type;
17271 
17272 		err = check_mem_access(env, env->insn_idx, cur_regs(env) + insn->dst_reg, argno_from_reg(insn->dst_reg),
17273 				       insn->off, BPF_SIZE(insn->code),
17274 				       BPF_WRITE, -1, false, false);
17275 		if (err)
17276 			return err;
17277 
17278 		return save_aux_ptr_type(env, dst_reg_type, false);
17279 	}
17280 	case BPF_JMP:
17281 	case BPF_JMP32: {
17282 		u8 opcode = BPF_OP(insn->code);
17283 
17284 		env->jmps_processed++;
17285 		if (opcode == BPF_CALL) {
17286 			if (env->cur_state->active_locks) {
17287 				if ((insn->src_reg == BPF_REG_0 &&
17288 				     insn->imm != BPF_FUNC_spin_unlock &&
17289 				     insn->imm != BPF_FUNC_kptr_xchg) ||
17290 				    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17291 				     (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
17292 					verbose(env,
17293 						"function calls are not allowed while holding a lock\n");
17294 					return -EINVAL;
17295 				}
17296 			}
17297 			mark_reg_scratched(env, BPF_REG_0);
17298 			if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno]))
17299 				cur_func(env)->no_stack_arg_load = true;
17300 			if (insn->src_reg == BPF_PSEUDO_CALL)
17301 				return check_func_call(env, insn, &env->insn_idx);
17302 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17303 				return check_kfunc_call(env, insn, &env->insn_idx);
17304 			return check_helper_call(env, insn, &env->insn_idx);
17305 		} else if (opcode == BPF_JA) {
17306 			if (BPF_SRC(insn->code) == BPF_X)
17307 				return check_indirect_jump(env, insn);
17308 
17309 			if (class == BPF_JMP)
17310 				env->insn_idx += insn->off + 1;
17311 			else
17312 				env->insn_idx += insn->imm + 1;
17313 			return INSN_IDX_UPDATED;
17314 		} else if (opcode == BPF_EXIT) {
17315 			return process_bpf_exit_full(env, do_print_state, false);
17316 		}
17317 		return check_cond_jmp_op(env, insn, &env->insn_idx);
17318 	}
17319 	case BPF_LD: {
17320 		u8 mode = BPF_MODE(insn->code);
17321 
17322 		if (mode == BPF_ABS || mode == BPF_IND)
17323 			return check_ld_abs(env, insn);
17324 
17325 		if (mode == BPF_IMM) {
17326 			err = check_ld_imm(env, insn);
17327 			if (err)
17328 				return err;
17329 
17330 			env->insn_idx++;
17331 			sanitize_mark_insn_seen(env);
17332 		}
17333 		return 0;
17334 	}
17335 	}
17336 	/* all class values are handled above. silence compiler warning */
17337 	return -EFAULT;
17338 }
17339 
17340 static int do_check(struct bpf_verifier_env *env)
17341 {
17342 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17343 	struct bpf_verifier_state *state = env->cur_state;
17344 	struct bpf_insn *insns = env->prog->insnsi;
17345 	int insn_cnt = env->prog->len;
17346 	bool do_print_state = false;
17347 	int prev_insn_idx = -1;
17348 
17349 	for (;;) {
17350 		struct bpf_insn *insn;
17351 		struct bpf_insn_aux_data *insn_aux;
17352 		int err;
17353 
17354 		/* reset current history entry on each new instruction */
17355 		env->cur_hist_ent = NULL;
17356 
17357 		env->prev_insn_idx = prev_insn_idx;
17358 		if (env->insn_idx >= insn_cnt) {
17359 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17360 				env->insn_idx, insn_cnt);
17361 			return -EFAULT;
17362 		}
17363 
17364 		insn = &insns[env->insn_idx];
17365 		insn_aux = &env->insn_aux_data[env->insn_idx];
17366 
17367 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17368 			verbose(env,
17369 				"BPF program is too large. Processed %d insn\n",
17370 				env->insn_processed);
17371 			return -E2BIG;
17372 		}
17373 
17374 		state->last_insn_idx = env->prev_insn_idx;
17375 		state->insn_idx = env->insn_idx;
17376 
17377 		if (bpf_is_prune_point(env, env->insn_idx)) {
17378 			err = bpf_is_state_visited(env, env->insn_idx);
17379 			if (err < 0)
17380 				return err;
17381 			if (err == 1) {
17382 				/* found equivalent state, can prune the search */
17383 				if (env->log.level & BPF_LOG_LEVEL) {
17384 					if (do_print_state)
17385 						verbose(env, "\nfrom %d to %d%s: safe\n",
17386 							env->prev_insn_idx, env->insn_idx,
17387 							env->cur_state->speculative ?
17388 							" (speculative execution)" : "");
17389 					else
17390 						verbose(env, "%d: safe\n", env->insn_idx);
17391 				}
17392 				goto process_bpf_exit;
17393 			}
17394 		}
17395 
17396 		if (bpf_is_jmp_point(env, env->insn_idx)) {
17397 			err = bpf_push_jmp_history(env, state, 0, 0, 0, 0);
17398 			if (err)
17399 				return err;
17400 		}
17401 
17402 		if (signal_pending(current))
17403 			return -EAGAIN;
17404 
17405 		if (need_resched())
17406 			cond_resched();
17407 
17408 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17409 			verbose(env, "\nfrom %d to %d%s:",
17410 				env->prev_insn_idx, env->insn_idx,
17411 				env->cur_state->speculative ?
17412 				" (speculative execution)" : "");
17413 			print_verifier_state(env, state, state->curframe, true);
17414 			do_print_state = false;
17415 		}
17416 
17417 		if (env->log.level & BPF_LOG_LEVEL) {
17418 			if (verifier_state_scratched(env))
17419 				print_insn_state(env, state, state->curframe);
17420 
17421 			verbose_linfo(env, env->insn_idx, "; ");
17422 			env->prev_log_pos = env->log.end_pos;
17423 			verbose(env, "%d: ", env->insn_idx);
17424 			bpf_verbose_insn(env, insn);
17425 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17426 			env->prev_log_pos = env->log.end_pos;
17427 		}
17428 
17429 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17430 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17431 							   env->prev_insn_idx);
17432 			if (err)
17433 				return err;
17434 		}
17435 
17436 		sanitize_mark_insn_seen(env);
17437 		prev_insn_idx = env->insn_idx;
17438 
17439 		/* Sanity check: precomputed constants must match verifier state */
17440 		if (!state->speculative && insn_aux->const_reg_mask) {
17441 			struct bpf_reg_state *regs = cur_regs(env);
17442 			u16 mask = insn_aux->const_reg_mask;
17443 
17444 			for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) {
17445 				u32 cval = insn_aux->const_reg_vals[r];
17446 
17447 				if (!(mask & BIT(r)))
17448 					continue;
17449 				if (regs[r].type != SCALAR_VALUE)
17450 					continue;
17451 				if (!tnum_is_const(regs[r].var_off))
17452 					continue;
17453 				if (verifier_bug_if((u32)regs[r].var_off.value != cval,
17454 						    env, "const R%d: %u != %llu",
17455 						    r, cval, regs[r].var_off.value))
17456 					return -EFAULT;
17457 			}
17458 		}
17459 
17460 		/* Reduce verification complexity by stopping speculative path
17461 		 * verification when a nospec is encountered.
17462 		 */
17463 		if (state->speculative && insn_aux->nospec)
17464 			goto process_bpf_exit;
17465 
17466 		err = do_check_insn(env, &do_print_state);
17467 		if (error_recoverable_with_nospec(err) && state->speculative) {
17468 			/* Prevent this speculative path from ever reaching the
17469 			 * insn that would have been unsafe to execute.
17470 			 */
17471 			insn_aux->nospec = true;
17472 			/* If it was an ADD/SUB insn, potentially remove any
17473 			 * markings for alu sanitization.
17474 			 */
17475 			insn_aux->alu_state = 0;
17476 			goto process_bpf_exit;
17477 		} else if (err < 0) {
17478 			return err;
17479 		} else if (err == PROCESS_BPF_EXIT) {
17480 			goto process_bpf_exit;
17481 		} else if (err == INSN_IDX_UPDATED) {
17482 		} else if (err == 0) {
17483 			env->insn_idx++;
17484 		}
17485 
17486 		if (state->speculative && insn_aux->nospec_result) {
17487 			/* If we are on a path that performed a jump-op, this
17488 			 * may skip a nospec patched-in after the jump. This can
17489 			 * currently never happen because nospec_result is only
17490 			 * used for the write-ops
17491 			 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper
17492 			 * calls. These must never skip the following insn
17493 			 * (i.e., bpf_insn_successors()'s opcode_info.can_jump
17494 			 * is false). Still, add a warning to document this in
17495 			 * case nospec_result is used elsewhere in the future.
17496 			 *
17497 			 * All non-branch instructions have a single
17498 			 * fall-through edge. For these, nospec_result should
17499 			 * already work.
17500 			 */
17501 			if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP ||
17502 					     BPF_CLASS(insn->code) == BPF_JMP32) &&
17503 					    BPF_OP(insn->code) != BPF_CALL, env,
17504 					    "speculation barrier after jump instruction may not have the desired effect"))
17505 				return -EFAULT;
17506 process_bpf_exit:
17507 			mark_verifier_state_scratched(env);
17508 			err = bpf_update_branch_counts(env, env->cur_state);
17509 			if (err)
17510 				return err;
17511 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
17512 					pop_log);
17513 			if (err < 0) {
17514 				if (err != -ENOENT)
17515 					return err;
17516 				break;
17517 			} else {
17518 				do_print_state = true;
17519 				continue;
17520 			}
17521 		}
17522 	}
17523 
17524 	return 0;
17525 }
17526 
17527 static int find_btf_percpu_datasec(struct btf *btf)
17528 {
17529 	const struct btf_type *t;
17530 	const char *tname;
17531 	int i, n;
17532 
17533 	/*
17534 	 * Both vmlinux and module each have their own ".data..percpu"
17535 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17536 	 * types to look at only module's own BTF types.
17537 	 */
17538 	n = btf_nr_types(btf);
17539 	for (i = btf_named_start_id(btf, true); i < n; i++) {
17540 		t = btf_type_by_id(btf, i);
17541 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17542 			continue;
17543 
17544 		tname = btf_name_by_offset(btf, t->name_off);
17545 		if (!strcmp(tname, ".data..percpu"))
17546 			return i;
17547 	}
17548 
17549 	return -ENOENT;
17550 }
17551 
17552 /*
17553  * Add btf to the env->used_btfs array. If needed, refcount the
17554  * corresponding kernel module. To simplify caller's logic
17555  * in case of error or if btf was added before the function
17556  * decreases the btf refcount.
17557  */
17558 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
17559 {
17560 	struct btf_mod_pair *btf_mod;
17561 	int ret = 0;
17562 	int i;
17563 
17564 	/* check whether we recorded this BTF (and maybe module) already */
17565 	for (i = 0; i < env->used_btf_cnt; i++)
17566 		if (env->used_btfs[i].btf == btf)
17567 			goto ret_put;
17568 
17569 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17570 		verbose(env, "The total number of btfs per program has reached the limit of %u\n",
17571 			MAX_USED_BTFS);
17572 		ret = -E2BIG;
17573 		goto ret_put;
17574 	}
17575 
17576 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17577 	btf_mod->btf = btf;
17578 	btf_mod->module = NULL;
17579 
17580 	/* if we reference variables from kernel module, bump its refcount */
17581 	if (btf_is_module(btf)) {
17582 		btf_mod->module = btf_try_get_module(btf);
17583 		if (!btf_mod->module) {
17584 			ret = -ENXIO;
17585 			goto ret_put;
17586 		}
17587 	}
17588 
17589 	env->used_btf_cnt++;
17590 	return 0;
17591 
17592 ret_put:
17593 	/* Either error or this BTF was already added */
17594 	btf_put(btf);
17595 	return ret;
17596 }
17597 
17598 /* replace pseudo btf_id with kernel symbol address */
17599 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
17600 				 struct bpf_insn *insn,
17601 				 struct bpf_insn_aux_data *aux,
17602 				 struct btf *btf)
17603 {
17604 	const struct btf_var_secinfo *vsi;
17605 	const struct btf_type *datasec;
17606 	const struct btf_type *t;
17607 	const char *sym_name;
17608 	bool percpu = false;
17609 	u32 type, id = insn->imm;
17610 	s32 datasec_id;
17611 	u64 addr;
17612 	int i;
17613 
17614 	t = btf_type_by_id(btf, id);
17615 	if (!t) {
17616 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17617 		return -ENOENT;
17618 	}
17619 
17620 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17621 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17622 		return -EINVAL;
17623 	}
17624 
17625 	sym_name = btf_name_by_offset(btf, t->name_off);
17626 	addr = kallsyms_lookup_name(sym_name);
17627 	if (!addr) {
17628 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17629 			sym_name);
17630 		return -ENOENT;
17631 	}
17632 	insn[0].imm = (u32)addr;
17633 	insn[1].imm = addr >> 32;
17634 
17635 	if (btf_type_is_func(t)) {
17636 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17637 		aux->btf_var.mem_size = 0;
17638 		return 0;
17639 	}
17640 
17641 	datasec_id = find_btf_percpu_datasec(btf);
17642 	if (datasec_id > 0) {
17643 		datasec = btf_type_by_id(btf, datasec_id);
17644 		for_each_vsi(i, datasec, vsi) {
17645 			if (vsi->type == id) {
17646 				percpu = true;
17647 				break;
17648 			}
17649 		}
17650 	}
17651 
17652 	type = t->type;
17653 	t = btf_type_skip_modifiers(btf, type, NULL);
17654 	if (percpu) {
17655 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17656 		aux->btf_var.btf = btf;
17657 		aux->btf_var.btf_id = type;
17658 	} else if (!btf_type_is_struct(t)) {
17659 		const struct btf_type *ret;
17660 		const char *tname;
17661 		u32 tsize;
17662 
17663 		/* resolve the type size of ksym. */
17664 		ret = btf_resolve_size(btf, t, &tsize);
17665 		if (IS_ERR(ret)) {
17666 			tname = btf_name_by_offset(btf, t->name_off);
17667 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17668 				tname, PTR_ERR(ret));
17669 			return -EINVAL;
17670 		}
17671 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17672 		aux->btf_var.mem_size = tsize;
17673 	} else {
17674 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17675 		aux->btf_var.btf = btf;
17676 		aux->btf_var.btf_id = type;
17677 	}
17678 
17679 	return 0;
17680 }
17681 
17682 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17683 			       struct bpf_insn *insn,
17684 			       struct bpf_insn_aux_data *aux)
17685 {
17686 	struct btf *btf;
17687 	int btf_fd;
17688 	int err;
17689 
17690 	btf_fd = insn[1].imm;
17691 	if (btf_fd) {
17692 		btf = btf_get_by_fd(btf_fd);
17693 		if (IS_ERR(btf)) {
17694 			verbose(env, "invalid module BTF object FD specified.\n");
17695 			return -EINVAL;
17696 		}
17697 	} else {
17698 		if (!btf_vmlinux) {
17699 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17700 			return -EINVAL;
17701 		}
17702 		btf_get(btf_vmlinux);
17703 		btf = btf_vmlinux;
17704 	}
17705 
17706 	err = __check_pseudo_btf_id(env, insn, aux, btf);
17707 	if (err) {
17708 		btf_put(btf);
17709 		return err;
17710 	}
17711 
17712 	return __add_used_btf(env, btf);
17713 }
17714 
17715 static bool is_tracing_prog_type(enum bpf_prog_type type)
17716 {
17717 	switch (type) {
17718 	case BPF_PROG_TYPE_KPROBE:
17719 	case BPF_PROG_TYPE_TRACEPOINT:
17720 	case BPF_PROG_TYPE_PERF_EVENT:
17721 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17722 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17723 		return true;
17724 	default:
17725 		return false;
17726 	}
17727 }
17728 
17729 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17730 {
17731 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17732 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17733 }
17734 
17735 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17736 					struct bpf_map *map,
17737 					struct bpf_prog *prog)
17738 
17739 {
17740 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17741 
17742 	if (map->excl_prog_sha &&
17743 	    memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) {
17744 		verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
17745 		return -EACCES;
17746 	}
17747 
17748 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17749 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17750 		if (is_tracing_prog_type(prog_type)) {
17751 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17752 			return -EINVAL;
17753 		}
17754 	}
17755 
17756 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
17757 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17758 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17759 			return -EINVAL;
17760 		}
17761 
17762 		if (is_tracing_prog_type(prog_type)) {
17763 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17764 			return -EINVAL;
17765 		}
17766 	}
17767 
17768 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17769 	    !bpf_offload_prog_map_match(prog, map)) {
17770 		verbose(env, "offload device mismatch between prog and map\n");
17771 		return -EINVAL;
17772 	}
17773 
17774 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17775 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17776 		return -EINVAL;
17777 	}
17778 
17779 	if (prog->sleepable)
17780 		switch (map->map_type) {
17781 		case BPF_MAP_TYPE_HASH:
17782 		case BPF_MAP_TYPE_RHASH:
17783 		case BPF_MAP_TYPE_LRU_HASH:
17784 		case BPF_MAP_TYPE_ARRAY:
17785 		case BPF_MAP_TYPE_PERCPU_HASH:
17786 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17787 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17788 		case BPF_MAP_TYPE_LPM_TRIE:
17789 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17790 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17791 		case BPF_MAP_TYPE_RINGBUF:
17792 		case BPF_MAP_TYPE_USER_RINGBUF:
17793 		case BPF_MAP_TYPE_INODE_STORAGE:
17794 		case BPF_MAP_TYPE_SK_STORAGE:
17795 		case BPF_MAP_TYPE_TASK_STORAGE:
17796 		case BPF_MAP_TYPE_CGRP_STORAGE:
17797 		case BPF_MAP_TYPE_QUEUE:
17798 		case BPF_MAP_TYPE_STACK:
17799 		case BPF_MAP_TYPE_ARENA:
17800 		case BPF_MAP_TYPE_INSN_ARRAY:
17801 		case BPF_MAP_TYPE_PROG_ARRAY:
17802 			break;
17803 		default:
17804 			verbose(env,
17805 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17806 			return -EINVAL;
17807 		}
17808 
17809 	if (bpf_map_is_cgroup_storage(map) &&
17810 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17811 		verbose(env, "only one cgroup storage of each type is allowed\n");
17812 		return -EBUSY;
17813 	}
17814 
17815 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
17816 		if (env->prog->aux->arena) {
17817 			verbose(env, "Only one arena per program\n");
17818 			return -EBUSY;
17819 		}
17820 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
17821 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
17822 			return -EPERM;
17823 		}
17824 		if (!env->prog->jit_requested) {
17825 			verbose(env, "JIT is required to use arena\n");
17826 			return -EOPNOTSUPP;
17827 		}
17828 		if (!bpf_jit_supports_arena()) {
17829 			verbose(env, "JIT doesn't support arena\n");
17830 			return -EOPNOTSUPP;
17831 		}
17832 		env->prog->aux->arena = (void *)map;
17833 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
17834 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
17835 			return -EINVAL;
17836 		}
17837 	}
17838 
17839 	return 0;
17840 }
17841 
17842 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
17843 {
17844 	int i, err;
17845 
17846 	/* check whether we recorded this map already */
17847 	for (i = 0; i < env->used_map_cnt; i++)
17848 		if (env->used_maps[i] == map)
17849 			return i;
17850 
17851 	if (env->used_map_cnt >= MAX_USED_MAPS) {
17852 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
17853 			MAX_USED_MAPS);
17854 		return -E2BIG;
17855 	}
17856 
17857 	err = check_map_prog_compatibility(env, map, env->prog);
17858 	if (err)
17859 		return err;
17860 
17861 	if (env->prog->sleepable)
17862 		atomic64_inc(&map->sleepable_refcnt);
17863 
17864 	/* hold the map. If the program is rejected by verifier,
17865 	 * the map will be released by release_maps() or it
17866 	 * will be used by the valid program until it's unloaded
17867 	 * and all maps are released in bpf_free_used_maps()
17868 	 */
17869 	bpf_map_inc(map);
17870 
17871 	env->used_maps[env->used_map_cnt++] = map;
17872 
17873 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
17874 		err = bpf_insn_array_init(map, env->prog);
17875 		if (err) {
17876 			verbose(env, "Failed to properly initialize insn array\n");
17877 			return err;
17878 		}
17879 		env->insn_array_maps[env->insn_array_map_cnt++] = map;
17880 	}
17881 
17882 	return env->used_map_cnt - 1;
17883 }
17884 
17885 /* Add map behind fd to used maps list, if it's not already there, and return
17886  * its index.
17887  * Returns <0 on error, or >= 0 index, on success.
17888  */
17889 static int add_used_map(struct bpf_verifier_env *env, int fd)
17890 {
17891 	struct bpf_map *map;
17892 	CLASS(fd, f)(fd);
17893 
17894 	map = __bpf_map_get(f);
17895 	if (IS_ERR(map)) {
17896 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
17897 		return PTR_ERR(map);
17898 	}
17899 
17900 	return __add_used_map(env, map);
17901 }
17902 
17903 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
17904 {
17905 	u8 class = BPF_CLASS(insn->code);
17906 	u8 opcode = BPF_OP(insn->code);
17907 
17908 	switch (opcode) {
17909 	case BPF_NEG:
17910 		if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 ||
17911 		    insn->off != 0 || insn->imm != 0) {
17912 			verbose(env, "BPF_NEG uses reserved fields\n");
17913 			return -EINVAL;
17914 		}
17915 		return 0;
17916 	case BPF_END:
17917 		if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
17918 		    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
17919 		    (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) {
17920 			verbose(env, "BPF_END uses reserved fields\n");
17921 			return -EINVAL;
17922 		}
17923 		return 0;
17924 	case BPF_MOV:
17925 		if (BPF_SRC(insn->code) == BPF_X) {
17926 			if (class == BPF_ALU) {
17927 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
17928 				    insn->imm) {
17929 					verbose(env, "BPF_MOV uses reserved fields\n");
17930 					return -EINVAL;
17931 				}
17932 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
17933 				if (insn->imm != 1 && insn->imm != 1u << 16) {
17934 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
17935 					return -EINVAL;
17936 				}
17937 			} else if ((insn->off != 0 && insn->off != 8 &&
17938 				    insn->off != 16 && insn->off != 32) || insn->imm) {
17939 				verbose(env, "BPF_MOV uses reserved fields\n");
17940 				return -EINVAL;
17941 			}
17942 		} else if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
17943 			verbose(env, "BPF_MOV uses reserved fields\n");
17944 			return -EINVAL;
17945 		}
17946 		return 0;
17947 	case BPF_ADD:
17948 	case BPF_SUB:
17949 	case BPF_AND:
17950 	case BPF_OR:
17951 	case BPF_XOR:
17952 	case BPF_LSH:
17953 	case BPF_RSH:
17954 	case BPF_ARSH:
17955 	case BPF_MUL:
17956 	case BPF_DIV:
17957 	case BPF_MOD:
17958 		if (BPF_SRC(insn->code) == BPF_X) {
17959 			if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
17960 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
17961 				verbose(env, "BPF_ALU uses reserved fields\n");
17962 				return -EINVAL;
17963 			}
17964 		} else if (insn->src_reg != BPF_REG_0 ||
17965 			   (insn->off != 0 && insn->off != 1) ||
17966 			   (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
17967 			verbose(env, "BPF_ALU uses reserved fields\n");
17968 			return -EINVAL;
17969 		}
17970 		return 0;
17971 	default:
17972 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17973 		return -EINVAL;
17974 	}
17975 }
17976 
17977 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
17978 {
17979 	u8 class = BPF_CLASS(insn->code);
17980 	u8 opcode = BPF_OP(insn->code);
17981 
17982 	switch (opcode) {
17983 	case BPF_CALL:
17984 		if (BPF_SRC(insn->code) != BPF_K ||
17985 		    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) ||
17986 		    (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL &&
17987 		     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17988 		    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
17989 			verbose(env, "BPF_CALL uses reserved fields\n");
17990 			return -EINVAL;
17991 		}
17992 		return 0;
17993 	case BPF_JA:
17994 		if (BPF_SRC(insn->code) == BPF_X) {
17995 			if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) {
17996 				verbose(env, "BPF_JA|BPF_X uses reserved fields\n");
17997 				return -EINVAL;
17998 			}
17999 		} else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 ||
18000 			   (class == BPF_JMP && insn->imm != 0) ||
18001 			   (class == BPF_JMP32 && insn->off != 0)) {
18002 			verbose(env, "BPF_JA uses reserved fields\n");
18003 			return -EINVAL;
18004 		}
18005 		return 0;
18006 	case BPF_EXIT:
18007 		if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 ||
18008 		    insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 ||
18009 		    class == BPF_JMP32) {
18010 			verbose(env, "BPF_EXIT uses reserved fields\n");
18011 			return -EINVAL;
18012 		}
18013 		return 0;
18014 	case BPF_JCOND:
18015 		if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg != BPF_MAY_GOTO ||
18016 		    insn->dst_reg || insn->imm) {
18017 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
18018 			return -EINVAL;
18019 		}
18020 		return 0;
18021 	default:
18022 		if (BPF_SRC(insn->code) == BPF_X) {
18023 			if (insn->imm != 0) {
18024 				verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
18025 				return -EINVAL;
18026 			}
18027 		} else if (insn->src_reg != BPF_REG_0) {
18028 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
18029 			return -EINVAL;
18030 		}
18031 		return 0;
18032 	}
18033 }
18034 
18035 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
18036 {
18037 	switch (BPF_CLASS(insn->code)) {
18038 	case BPF_ALU:
18039 	case BPF_ALU64:
18040 		return check_alu_fields(env, insn);
18041 	case BPF_LDX:
18042 		if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
18043 		    insn->imm != 0) {
18044 			verbose(env, "BPF_LDX uses reserved fields\n");
18045 			return -EINVAL;
18046 		}
18047 		return 0;
18048 	case BPF_STX:
18049 		if (BPF_MODE(insn->code) == BPF_ATOMIC)
18050 			return 0;
18051 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
18052 			verbose(env, "BPF_STX uses reserved fields\n");
18053 			return -EINVAL;
18054 		}
18055 		return 0;
18056 	case BPF_ST:
18057 		if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) {
18058 			verbose(env, "BPF_ST uses reserved fields\n");
18059 			return -EINVAL;
18060 		}
18061 		return 0;
18062 	case BPF_JMP:
18063 	case BPF_JMP32:
18064 		return check_jmp_fields(env, insn);
18065 	case BPF_LD: {
18066 		u8 mode = BPF_MODE(insn->code);
18067 
18068 		if (mode == BPF_ABS || mode == BPF_IND) {
18069 			if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
18070 			    BPF_SIZE(insn->code) == BPF_DW ||
18071 			    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
18072 				verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
18073 				return -EINVAL;
18074 			}
18075 		} else if (mode != BPF_IMM) {
18076 			verbose(env, "invalid BPF_LD mode\n");
18077 			return -EINVAL;
18078 		}
18079 		return 0;
18080 	}
18081 	default:
18082 		verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code));
18083 		return -EINVAL;
18084 	}
18085 }
18086 
18087 /*
18088  * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions:
18089  *
18090  * 1. if it accesses map FD, replace it with actual map pointer.
18091  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
18092  *
18093  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
18094  */
18095 static int check_and_resolve_insns(struct bpf_verifier_env *env)
18096 {
18097 	struct bpf_insn *insn = env->prog->insnsi;
18098 	int insn_cnt = env->prog->len;
18099 	int i, err;
18100 
18101 	err = bpf_prog_calc_tag(env->prog);
18102 	if (err)
18103 		return err;
18104 
18105 	for (i = 0; i < insn_cnt; i++, insn++) {
18106 		if (insn->dst_reg >= MAX_BPF_REG &&
18107 		    !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) {
18108 			verbose(env, "R%d is invalid\n", insn->dst_reg);
18109 			return -EINVAL;
18110 		}
18111 		if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) {
18112 			verbose(env, "R%d is invalid\n", insn->src_reg);
18113 			return -EINVAL;
18114 		}
18115 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
18116 			struct bpf_insn_aux_data *aux;
18117 			struct bpf_map *map;
18118 			int map_idx;
18119 			u64 addr;
18120 			u32 fd;
18121 
18122 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
18123 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
18124 			    insn[1].off != 0) {
18125 				verbose(env, "invalid bpf_ld_imm64 insn\n");
18126 				return -EINVAL;
18127 			}
18128 
18129 			if (insn[0].off != 0) {
18130 				verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
18131 				return -EINVAL;
18132 			}
18133 
18134 			if (insn[0].src_reg == 0)
18135 				/* valid generic load 64-bit imm */
18136 				goto next_insn;
18137 
18138 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
18139 				aux = &env->insn_aux_data[i];
18140 				err = check_pseudo_btf_id(env, insn, aux);
18141 				if (err)
18142 					return err;
18143 				goto next_insn;
18144 			}
18145 
18146 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
18147 				aux = &env->insn_aux_data[i];
18148 				aux->ptr_type = PTR_TO_FUNC;
18149 				goto next_insn;
18150 			}
18151 
18152 			/* In final convert_pseudo_ld_imm64() step, this is
18153 			 * converted into regular 64-bit imm load insn.
18154 			 */
18155 			switch (insn[0].src_reg) {
18156 			case BPF_PSEUDO_MAP_VALUE:
18157 			case BPF_PSEUDO_MAP_IDX_VALUE:
18158 				break;
18159 			case BPF_PSEUDO_MAP_FD:
18160 			case BPF_PSEUDO_MAP_IDX:
18161 				if (insn[1].imm == 0)
18162 					break;
18163 				fallthrough;
18164 			default:
18165 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
18166 				return -EINVAL;
18167 			}
18168 
18169 			switch (insn[0].src_reg) {
18170 			case BPF_PSEUDO_MAP_IDX_VALUE:
18171 			case BPF_PSEUDO_MAP_IDX:
18172 				if (bpfptr_is_null(env->fd_array)) {
18173 					verbose(env, "fd_idx without fd_array is invalid\n");
18174 					return -EPROTO;
18175 				}
18176 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
18177 							    insn[0].imm * sizeof(fd),
18178 							    sizeof(fd)))
18179 					return -EFAULT;
18180 				break;
18181 			default:
18182 				fd = insn[0].imm;
18183 				break;
18184 			}
18185 
18186 			map_idx = add_used_map(env, fd);
18187 			if (map_idx < 0)
18188 				return map_idx;
18189 			map = env->used_maps[map_idx];
18190 
18191 			aux = &env->insn_aux_data[i];
18192 			aux->map_index = map_idx;
18193 
18194 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18195 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
18196 				addr = (unsigned long)map;
18197 			} else {
18198 				u32 off = insn[1].imm;
18199 
18200 				if (!map->ops->map_direct_value_addr) {
18201 					verbose(env, "no direct value access support for this map type\n");
18202 					return -EINVAL;
18203 				}
18204 
18205 				err = map->ops->map_direct_value_addr(map, &addr, off);
18206 				if (err) {
18207 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18208 						map->value_size, off);
18209 					return err;
18210 				}
18211 
18212 				aux->map_off = off;
18213 				addr += off;
18214 			}
18215 
18216 			insn[0].imm = (u32)addr;
18217 			insn[1].imm = addr >> 32;
18218 
18219 next_insn:
18220 			insn++;
18221 			i++;
18222 			continue;
18223 		}
18224 
18225 		/* Basic sanity check before we invest more work here. */
18226 		if (!bpf_opcode_in_insntable(insn->code)) {
18227 			verbose(env, "unknown opcode %02x\n", insn->code);
18228 			return -EINVAL;
18229 		}
18230 
18231 		err = check_insn_fields(env, insn);
18232 		if (err)
18233 			return err;
18234 	}
18235 
18236 	/* now all pseudo BPF_LD_IMM64 instructions load valid
18237 	 * 'struct bpf_map *' into a register instead of user map_fd.
18238 	 * These pointers will be used later by verifier to validate map access.
18239 	 */
18240 	return 0;
18241 }
18242 
18243 /* drop refcnt of maps used by the rejected program */
18244 static void release_maps(struct bpf_verifier_env *env)
18245 {
18246 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
18247 			     env->used_map_cnt);
18248 }
18249 
18250 /* drop refcnt of maps used by the rejected program */
18251 static void release_btfs(struct bpf_verifier_env *env)
18252 {
18253 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
18254 }
18255 
18256 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18257 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18258 {
18259 	struct bpf_insn *insn = env->prog->insnsi;
18260 	int insn_cnt = env->prog->len;
18261 	int i;
18262 
18263 	for (i = 0; i < insn_cnt; i++, insn++) {
18264 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18265 			continue;
18266 		if (insn->src_reg == BPF_PSEUDO_FUNC)
18267 			continue;
18268 		insn->src_reg = 0;
18269 	}
18270 }
18271 
18272 static void release_insn_arrays(struct bpf_verifier_env *env)
18273 {
18274 	int i;
18275 
18276 	for (i = 0; i < env->insn_array_map_cnt; i++)
18277 		bpf_insn_array_release(env->insn_array_maps[i]);
18278 }
18279 
18280 
18281 
18282 /* The verifier does more data flow analysis than llvm and will not
18283  * explore branches that are dead at run time. Malicious programs can
18284  * have dead code too. Therefore replace all dead at-run-time code
18285  * with 'ja -1'.
18286  *
18287  * Just nops are not optimal, e.g. if they would sit at the end of the
18288  * program and through another bug we would manage to jump there, then
18289  * we'd execute beyond program memory otherwise. Returning exception
18290  * code also wouldn't work since we can have subprogs where the dead
18291  * code could be located.
18292  */
18293 static void sanitize_dead_code(struct bpf_verifier_env *env)
18294 {
18295 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18296 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18297 	struct bpf_insn *insn = env->prog->insnsi;
18298 	const int insn_cnt = env->prog->len;
18299 	int i;
18300 
18301 	for (i = 0; i < insn_cnt; i++) {
18302 		if (aux_data[i].seen)
18303 			continue;
18304 		memcpy(insn + i, &trap, sizeof(trap));
18305 		aux_data[i].zext_dst = false;
18306 	}
18307 }
18308 
18309 
18310 
18311 static void free_states(struct bpf_verifier_env *env)
18312 {
18313 	struct bpf_verifier_state_list *sl;
18314 	struct list_head *head, *pos, *tmp;
18315 	struct bpf_scc_info *info;
18316 	int i, j;
18317 
18318 	bpf_free_verifier_state(env->cur_state, true);
18319 	env->cur_state = NULL;
18320 	while (!pop_stack(env, NULL, NULL, false));
18321 
18322 	list_for_each_safe(pos, tmp, &env->free_list) {
18323 		sl = container_of(pos, struct bpf_verifier_state_list, node);
18324 		bpf_free_verifier_state(&sl->state, false);
18325 		kfree(sl);
18326 	}
18327 	INIT_LIST_HEAD(&env->free_list);
18328 
18329 	for (i = 0; i < env->scc_cnt; ++i) {
18330 		info = env->scc_info[i];
18331 		if (!info)
18332 			continue;
18333 		for (j = 0; j < info->num_visits; j++)
18334 			bpf_free_backedges(&info->visits[j]);
18335 		kvfree(info);
18336 		env->scc_info[i] = NULL;
18337 	}
18338 
18339 	if (!env->explored_states)
18340 		return;
18341 
18342 	for (i = 0; i < state_htab_size(env); i++) {
18343 		head = &env->explored_states[i];
18344 
18345 		list_for_each_safe(pos, tmp, head) {
18346 			sl = container_of(pos, struct bpf_verifier_state_list, node);
18347 			bpf_free_verifier_state(&sl->state, false);
18348 			kfree(sl);
18349 		}
18350 		INIT_LIST_HEAD(&env->explored_states[i]);
18351 	}
18352 }
18353 
18354 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18355 {
18356 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18357 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
18358 	struct bpf_prog_aux *aux = env->prog->aux;
18359 	struct bpf_verifier_state *state;
18360 	struct bpf_reg_state *regs;
18361 	int ret, i;
18362 
18363 	env->prev_linfo = NULL;
18364 	env->pass_cnt++;
18365 
18366 	state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT);
18367 	if (!state)
18368 		return -ENOMEM;
18369 	state->curframe = 0;
18370 	state->speculative = false;
18371 	state->branches = 1;
18372 	state->in_sleepable = env->prog->sleepable;
18373 	state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT);
18374 	if (!state->frame[0]) {
18375 		kfree(state);
18376 		return -ENOMEM;
18377 	}
18378 	env->cur_state = state;
18379 	init_func_state(env, state->frame[0],
18380 			BPF_MAIN_FUNC /* callsite */,
18381 			0 /* frameno */,
18382 			subprog);
18383 	state->first_insn_idx = env->subprog_info[subprog].start;
18384 	state->last_insn_idx = -1;
18385 
18386 	regs = state->frame[state->curframe]->regs;
18387 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
18388 		const char *sub_name = subprog_name(env, subprog);
18389 		struct bpf_subprog_arg_info *arg;
18390 		struct bpf_reg_state *reg;
18391 
18392 		if (env->log.level & BPF_LOG_LEVEL)
18393 			verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
18394 		ret = btf_prepare_func_args(env, subprog);
18395 		if (ret)
18396 			goto out;
18397 
18398 		if (subprog_is_exc_cb(env, subprog)) {
18399 			state->frame[0]->in_exception_callback_fn = true;
18400 
18401 			/*
18402 			 * Global functions are scalar or void, make sure
18403 			 * we return a scalar.
18404 			 */
18405 			if (subprog_returns_void(env, subprog)) {
18406 				verbose(env, "exception cb cannot return void\n");
18407 				ret = -EINVAL;
18408 				goto out;
18409 			}
18410 
18411 			/* Also ensure the callback only has a single scalar argument. */
18412 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
18413 				verbose(env, "exception cb only supports single integer argument\n");
18414 				ret = -EINVAL;
18415 				goto out;
18416 			}
18417 		}
18418 		for (i = BPF_REG_1; i <= min_t(u32, sub->arg_cnt, MAX_BPF_FUNC_REG_ARGS); i++) {
18419 			arg = &sub->args[i - BPF_REG_1];
18420 			reg = &regs[i];
18421 
18422 			if (arg->arg_type == ARG_PTR_TO_CTX) {
18423 				reg->type = PTR_TO_CTX;
18424 				mark_reg_known_zero(env, regs, i);
18425 			} else if (arg->arg_type == ARG_ANYTHING) {
18426 				reg->type = SCALAR_VALUE;
18427 				mark_reg_unknown(env, regs, i);
18428 			} else if (arg->arg_type == ARG_PTR_TO_DYNPTR) {
18429 				/* assume unspecial LOCAL dynptr type */
18430 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen, 0);
18431 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
18432 				reg->type = PTR_TO_MEM;
18433 				reg->type |= arg->arg_type &
18434 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
18435 				mark_reg_known_zero(env, regs, i);
18436 				reg->mem_size = arg->mem_size;
18437 				if (arg->arg_type & PTR_MAYBE_NULL)
18438 					reg->id = ++env->id_gen;
18439 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
18440 				reg->type = PTR_TO_BTF_ID;
18441 				if (arg->arg_type & PTR_MAYBE_NULL)
18442 					reg->type |= PTR_MAYBE_NULL;
18443 				if (arg->arg_type & PTR_UNTRUSTED)
18444 					reg->type |= PTR_UNTRUSTED;
18445 				if (arg->arg_type & PTR_TRUSTED)
18446 					reg->type |= PTR_TRUSTED;
18447 				mark_reg_known_zero(env, regs, i);
18448 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
18449 				reg->btf_id = arg->btf_id;
18450 				reg->id = ++env->id_gen;
18451 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
18452 				/* caller can pass either PTR_TO_ARENA or SCALAR */
18453 				mark_reg_unknown(env, regs, i);
18454 			} else {
18455 				verifier_bug(env, "unhandled arg#%d type %d",
18456 					     i - BPF_REG_1 + 1, arg->arg_type);
18457 				ret = -EFAULT;
18458 				goto out;
18459 			}
18460 		}
18461 		if (env->prog->type == BPF_PROG_TYPE_EXT && sub->arg_cnt > MAX_BPF_FUNC_REG_ARGS) {
18462 			verbose(env, "freplace programs with >%d args not supported yet\n",
18463 				MAX_BPF_FUNC_REG_ARGS);
18464 			ret = -EINVAL;
18465 			goto out;
18466 		}
18467 	} else {
18468 		/* if main BPF program has associated BTF info, validate that
18469 		 * it's matching expected signature, and otherwise mark BTF
18470 		 * info for main program as unreliable
18471 		 */
18472 		if (env->prog->aux->func_info_aux) {
18473 			ret = btf_prepare_func_args(env, 0);
18474 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) {
18475 				env->prog->aux->func_info_aux[0].unreliable = true;
18476 				sub->arg_cnt = 1;
18477 				sub->stack_arg_cnt = 0;
18478 			}
18479 		}
18480 
18481 		/* 1st arg to a function */
18482 		regs[BPF_REG_1].type = PTR_TO_CTX;
18483 		mark_reg_known_zero(env, regs, BPF_REG_1);
18484 	}
18485 
18486 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
18487 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
18488 		for (i = 0; i < aux->ctx_arg_info_size; i++) {
18489 			ret = aux->ctx_arg_info[i].refcounted ? acquire_reference(env, 0, 0) : 0;
18490 			if (ret < 0)
18491 				goto out;
18492 
18493 			aux->ctx_arg_info[i].ref_id = ret;
18494 		}
18495 	}
18496 
18497 	ret = do_check(env);
18498 out:
18499 	if (!ret && pop_log)
18500 		bpf_vlog_reset(&env->log, 0);
18501 	free_states(env);
18502 	return ret;
18503 }
18504 
18505 /* Lazily verify all global functions based on their BTF, if they are called
18506  * from main BPF program or any of subprograms transitively.
18507  * BPF global subprogs called from dead code are not validated.
18508  * All callable global functions must pass verification.
18509  * Otherwise the whole program is rejected.
18510  * Consider:
18511  * int bar(int);
18512  * int foo(int f)
18513  * {
18514  *    return bar(f);
18515  * }
18516  * int bar(int b)
18517  * {
18518  *    ...
18519  * }
18520  * foo() will be verified first for R1=any_scalar_value. During verification it
18521  * will be assumed that bar() already verified successfully and call to bar()
18522  * from foo() will be checked for type match only. Later bar() will be verified
18523  * independently to check that it's safe for R1=any_scalar_value.
18524  */
18525 static int do_check_subprogs(struct bpf_verifier_env *env)
18526 {
18527 	struct bpf_prog_aux *aux = env->prog->aux;
18528 	struct bpf_func_info_aux *sub_aux;
18529 	int i, ret, new_cnt;
18530 	u32 insn_processed;
18531 
18532 	if (!aux->func_info)
18533 		return 0;
18534 
18535 	/* exception callback is presumed to be always called */
18536 	if (env->exception_callback_subprog)
18537 		subprog_aux(env, env->exception_callback_subprog)->called = true;
18538 
18539 again:
18540 	new_cnt = 0;
18541 	for (i = 1; i < env->subprog_cnt; i++) {
18542 		if (!bpf_subprog_is_global(env, i))
18543 			continue;
18544 
18545 		insn_processed = env->insn_processed;
18546 
18547 		sub_aux = subprog_aux(env, i);
18548 		if (!sub_aux->called || sub_aux->verified)
18549 			continue;
18550 
18551 		env->insn_idx = env->subprog_info[i].start;
18552 		WARN_ON_ONCE(env->insn_idx == 0);
18553 		ret = do_check_common(env, i);
18554 		env->subprog_info[i].insn_processed = env->insn_processed - insn_processed;
18555 		if (ret) {
18556 			return ret;
18557 		} else if (env->log.level & BPF_LOG_LEVEL) {
18558 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
18559 				i, subprog_name(env, i));
18560 		}
18561 
18562 		/* We verified new global subprog, it might have called some
18563 		 * more global subprogs that we haven't verified yet, so we
18564 		 * need to do another pass over subprogs to verify those.
18565 		 */
18566 		sub_aux->verified = true;
18567 		new_cnt++;
18568 	}
18569 
18570 	/* We can't loop forever as we verify at least one global subprog on
18571 	 * each pass.
18572 	 */
18573 	if (new_cnt)
18574 		goto again;
18575 
18576 	return 0;
18577 }
18578 
18579 static int do_check_main(struct bpf_verifier_env *env)
18580 {
18581 	u32 insn_processed = env->insn_processed;
18582 	int ret;
18583 
18584 	env->insn_idx = 0;
18585 	ret = do_check_common(env, 0);
18586 	env->subprog_info[0].insn_processed = env->insn_processed - insn_processed;
18587 	if (!ret)
18588 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18589 	return ret;
18590 }
18591 
18592 
18593 static void print_verification_stats(struct bpf_verifier_env *env)
18594 {
18595 	/* Skip over hidden subprogs which are not verified. */
18596 	int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
18597 
18598 	if (env->log.level & BPF_LOG_STATS) {
18599 		verbose(env, "verification time %lld usec\n",
18600 			div_u64(env->verification_time, 1000));
18601 		verbose(env, "stack depth %d", env->subprog_info[0].stack_depth);
18602 		for (i = 1; i < subprog_cnt; i++)
18603 			verbose(env, "+%d", env->subprog_info[i].stack_depth);
18604 		verbose(env, " max %d\n", env->max_stack_depth);
18605 		verbose(env, "insns processed %d", env->subprog_info[0].insn_processed);
18606 		for (i = 1; i < subprog_cnt; i++)
18607 			if (bpf_subprog_is_global(env, i))
18608 				verbose(env, "+%d", env->subprog_info[i].insn_processed);
18609 		verbose(env, "\n");
18610 	}
18611 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18612 		"total_states %d peak_states %d mark_read %d\n",
18613 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18614 		env->max_states_per_insn, env->total_states,
18615 		env->peak_states, env->longest_mark_read_walk);
18616 }
18617 
18618 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
18619 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
18620 {
18621 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
18622 	prog->aux->ctx_arg_info_size = cnt;
18623 
18624 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
18625 }
18626 
18627 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18628 {
18629 	const struct btf_type *t, *func_proto;
18630 	const struct bpf_struct_ops_desc *st_ops_desc;
18631 	const struct bpf_struct_ops *st_ops;
18632 	const struct btf_member *member;
18633 	struct bpf_prog *prog = env->prog;
18634 	bool has_refcounted_arg = false;
18635 	u32 btf_id, member_idx, member_off;
18636 	struct btf *btf;
18637 	const char *mname;
18638 	int i, err;
18639 
18640 	if (!prog->gpl_compatible) {
18641 		verbose(env, "struct ops programs must have a GPL compatible license\n");
18642 		return -EINVAL;
18643 	}
18644 
18645 	if (!prog->aux->attach_btf_id)
18646 		return -ENOTSUPP;
18647 
18648 	btf = prog->aux->attach_btf;
18649 	if (btf_is_module(btf)) {
18650 		/* Make sure st_ops is valid through the lifetime of env */
18651 		env->attach_btf_mod = btf_try_get_module(btf);
18652 		if (!env->attach_btf_mod) {
18653 			verbose(env, "struct_ops module %s is not found\n",
18654 				btf_get_name(btf));
18655 			return -ENOTSUPP;
18656 		}
18657 	}
18658 
18659 	btf_id = prog->aux->attach_btf_id;
18660 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
18661 	if (!st_ops_desc) {
18662 		verbose(env, "attach_btf_id %u is not a supported struct\n",
18663 			btf_id);
18664 		return -ENOTSUPP;
18665 	}
18666 	st_ops = st_ops_desc->st_ops;
18667 
18668 	t = st_ops_desc->type;
18669 	member_idx = prog->expected_attach_type;
18670 	if (member_idx >= btf_type_vlen(t)) {
18671 		verbose(env, "attach to invalid member idx %u of struct %s\n",
18672 			member_idx, st_ops->name);
18673 		return -EINVAL;
18674 	}
18675 
18676 	member = &btf_type_member(t)[member_idx];
18677 	mname = btf_name_by_offset(btf, member->name_off);
18678 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
18679 					       NULL);
18680 	if (!func_proto) {
18681 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18682 			mname, member_idx, st_ops->name);
18683 		return -EINVAL;
18684 	}
18685 
18686 	member_off = __btf_member_bit_offset(t, member) / 8;
18687 	err = bpf_struct_ops_supported(st_ops, member_off);
18688 	if (err) {
18689 		verbose(env, "attach to unsupported member %s of struct %s\n",
18690 			mname, st_ops->name);
18691 		return err;
18692 	}
18693 
18694 	if (st_ops->check_member) {
18695 		err = st_ops->check_member(t, member, prog);
18696 
18697 		if (err) {
18698 			verbose(env, "attach to unsupported member %s of struct %s\n",
18699 				mname, st_ops->name);
18700 			return err;
18701 		}
18702 	}
18703 
18704 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
18705 		verbose(env, "Private stack not supported by jit\n");
18706 		return -EACCES;
18707 	}
18708 
18709 	for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) {
18710 		if (st_ops_desc->arg_info[member_idx].info[i].refcounted) {
18711 			has_refcounted_arg = true;
18712 			break;
18713 		}
18714 	}
18715 
18716 	/* Tail call is not allowed for programs with refcounted arguments since we
18717 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
18718 	 */
18719 	for (i = 0; i < env->subprog_cnt; i++) {
18720 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
18721 			verbose(env, "program with __ref argument cannot tail call\n");
18722 			return -EINVAL;
18723 		}
18724 	}
18725 
18726 	prog->aux->st_ops = st_ops;
18727 	prog->aux->attach_st_ops_member_off = member_off;
18728 
18729 	prog->aux->attach_func_proto = func_proto;
18730 	prog->aux->attach_func_name = mname;
18731 	env->ops = st_ops->verifier_ops;
18732 
18733 	return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info,
18734 					  st_ops_desc->arg_info[member_idx].cnt);
18735 }
18736 #define SECURITY_PREFIX "security_"
18737 
18738 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
18739 
18740 /* list of non-sleepable functions that are otherwise on
18741  * ALLOW_ERROR_INJECTION list
18742  */
18743 BTF_SET_START(btf_non_sleepable_error_inject)
18744 /* Three functions below can be called from sleepable and non-sleepable context.
18745  * Assume non-sleepable from bpf safety point of view.
18746  */
18747 BTF_ID(func, __filemap_add_folio)
18748 #ifdef CONFIG_FAIL_PAGE_ALLOC
18749 BTF_ID(func, should_fail_alloc_page)
18750 #endif
18751 #ifdef CONFIG_FAILSLAB
18752 BTF_ID(func, should_failslab)
18753 #endif
18754 BTF_SET_END(btf_non_sleepable_error_inject)
18755 
18756 static int check_non_sleepable_error_inject(u32 btf_id)
18757 {
18758 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
18759 }
18760 
18761 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name)
18762 {
18763 	/* fentry/fexit/fmod_ret progs can be sleepable if they are
18764 	 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
18765 	 */
18766 	if (!check_non_sleepable_error_inject(btf_id) &&
18767 	    within_error_injection_list(addr))
18768 		return 0;
18769 
18770 	return -EINVAL;
18771 }
18772 
18773 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18774 {
18775 	if (within_error_injection_list(addr) ||
18776 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18777 		return 0;
18778 
18779 	return -EINVAL;
18780 }
18781 
18782 #else
18783 
18784 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code
18785  * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name()
18786  * but that just compares two concrete function names.
18787  */
18788 static bool has_arch_syscall_prefix(const char *func_name)
18789 {
18790 #if defined(__x86_64__)
18791 	return !strncmp(func_name, "__x64_", 6);
18792 #elif defined(__i386__)
18793 	return !strncmp(func_name, "__ia32_", 7);
18794 #elif defined(__s390x__)
18795 	return !strncmp(func_name, "__s390x_", 8);
18796 #elif defined(__aarch64__)
18797 	return !strncmp(func_name, "__arm64_", 8);
18798 #elif defined(__riscv)
18799 	return !strncmp(func_name, "__riscv_", 8);
18800 #elif defined(__powerpc__) || defined(__powerpc64__)
18801 	return !strncmp(func_name, "sys_", 4);
18802 #elif defined(__loongarch__)
18803 	return !strncmp(func_name, "sys_", 4);
18804 #else
18805 	return false;
18806 #endif
18807 }
18808 
18809 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */
18810 
18811 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name)
18812 {
18813 	if (has_arch_syscall_prefix(func_name))
18814 		return 0;
18815 
18816 	return -EINVAL;
18817 }
18818 
18819 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18820 {
18821 	if (has_arch_syscall_prefix(func_name) ||
18822 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18823 		return 0;
18824 
18825 	return -EINVAL;
18826 }
18827 
18828 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */
18829 
18830 static bool is_tracing_multi_id(const struct bpf_prog *prog, u32 btf_id)
18831 {
18832 	return is_tracing_multi(prog->expected_attach_type) && bpf_multi_func_btf_id[0] == btf_id;
18833 }
18834 
18835 static int btf_id_allow_sleepable(u32 btf_id, unsigned long addr, const struct bpf_prog *prog,
18836 				  const struct btf *btf)
18837 {
18838 	const struct btf_type *t;
18839 	const char *tname;
18840 
18841 	switch (prog->type) {
18842 	case BPF_PROG_TYPE_TRACING:
18843 		t = btf_type_by_id(btf, btf_id);
18844 		if (!t)
18845 			return -EINVAL;
18846 		tname = btf_name_by_offset(btf, t->name_off);
18847 		if (!tname)
18848 			return -EINVAL;
18849 
18850 		/*
18851 		 * *.multi sleepable programs will pass initial sleepable check,
18852 		 * the actual attached btf ids are checked later during the link
18853 		 * attachment.
18854 		 */
18855 		if (is_tracing_multi_id(prog, btf_id))
18856 			return 0;
18857 		if (!check_attach_sleepable(btf_id, addr, tname))
18858 			return 0;
18859 		/*
18860 		 * fentry/fexit/fmod_ret progs can also be sleepable if they are
18861 		 * in the fmodret id set with the KF_SLEEPABLE flag.
18862 		 */
18863 		else {
18864 			u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, prog);
18865 
18866 			if (flags && (*flags & KF_SLEEPABLE))
18867 				return 0;
18868 		}
18869 		break;
18870 	case BPF_PROG_TYPE_LSM:
18871 		/*
18872 		 * LSM progs check that they are attached to bpf_lsm_*() funcs.
18873 		 * Only some of them are sleepable.
18874 		 */
18875 		if (bpf_lsm_is_sleepable_hook(btf_id))
18876 			return 0;
18877 		break;
18878 	default:
18879 		break;
18880 	}
18881 	return -EINVAL;
18882 }
18883 
18884 /*
18885  * Resolve the prototype describing a trace target's real ABI. A
18886  * KF_IMPLICIT_ARGS kfunc has its injected args stripped from the public
18887  * prototype, so use the _impl prototype; other targets use their own.
18888  */
18889 static const struct btf_type *
18890 btf_attach_func_proto(struct bpf_verifier_log *log, struct btf *btf, u32 func_id)
18891 {
18892 	const struct btf_type *func;
18893 	struct module *mod = NULL;
18894 	const char *name;
18895 	int implicit;
18896 
18897 	func = btf_type_by_id(btf, func_id);
18898 	if (!func || !btf_type_is_func(func))
18899 		return NULL;
18900 	name = btf_name_by_offset(btf, func->name_off);
18901 
18902 	/*
18903 	 * btf_kfunc_check_flag() reads kfunc_set_tab, which for a module is
18904 	 * stable only once it is live; hold a module ref across the read to
18905 	 * exclude a concurrent module load.
18906 	 */
18907 	if (btf_is_module(btf)) {
18908 		mod = btf_try_get_module(btf);
18909 		if (!mod)
18910 			return NULL;
18911 	}
18912 	implicit = btf_kfunc_check_flag(btf, func_id, KF_IMPLICIT_ARGS);
18913 	module_put(mod);
18914 
18915 	if (implicit == -EINVAL) {
18916 		bpf_log(log, "kfunc %s has inconsistent KF_IMPLICIT_ARGS\n", name);
18917 		return NULL;
18918 	}
18919 	if (implicit > 0)
18920 		return find_kfunc_impl_proto(log, btf, name);
18921 
18922 	return btf_type_by_id(btf, func->type);
18923 }
18924 
18925 int bpf_check_attach_target(struct bpf_verifier_log *log,
18926 			    const struct bpf_prog *prog,
18927 			    const struct bpf_prog *tgt_prog,
18928 			    u32 btf_id,
18929 			    struct bpf_attach_target_info *tgt_info)
18930 {
18931 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
18932 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
18933 	char trace_symbol[KSYM_SYMBOL_LEN];
18934 	const char prefix[] = "btf_trace_";
18935 	struct bpf_raw_event_map *btp;
18936 	int ret = 0, subprog = -1, i;
18937 	const struct btf_type *t;
18938 	bool conservative = true;
18939 	const char *tname, *fname;
18940 	struct btf *btf;
18941 	long addr = 0;
18942 	struct module *mod = NULL;
18943 
18944 	if (!btf_id) {
18945 		bpf_log(log, "Tracing programs must provide btf_id\n");
18946 		return -EINVAL;
18947 	}
18948 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
18949 	if (!btf) {
18950 		bpf_log(log,
18951 			"Tracing program can only be attached to another program annotated with BTF\n");
18952 		return -EINVAL;
18953 	}
18954 	t = btf_type_by_id(btf, btf_id);
18955 	if (!t) {
18956 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
18957 		return -EINVAL;
18958 	}
18959 	tname = btf_name_by_offset(btf, t->name_off);
18960 	if (!tname) {
18961 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
18962 		return -EINVAL;
18963 	}
18964 	if (tgt_prog) {
18965 		struct bpf_prog_aux *aux = tgt_prog->aux;
18966 		bool tgt_changes_pkt_data;
18967 		bool tgt_might_sleep;
18968 
18969 		if (bpf_prog_is_dev_bound(prog->aux) &&
18970 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
18971 			bpf_log(log, "Target program bound device mismatch");
18972 			return -EINVAL;
18973 		}
18974 
18975 		for (i = 0; i < aux->func_info_cnt; i++)
18976 			if (aux->func_info[i].type_id == btf_id) {
18977 				subprog = i;
18978 				break;
18979 			}
18980 		if (subprog == -1) {
18981 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
18982 			return -EINVAL;
18983 		}
18984 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
18985 			bpf_log(log,
18986 				"%s programs cannot attach to exception callback\n",
18987 				prog_extension ? "Extension" : "Tracing");
18988 			return -EINVAL;
18989 		}
18990 		conservative = aux->func_info_aux[subprog].unreliable;
18991 		if (prog_extension) {
18992 			if (conservative) {
18993 				bpf_log(log,
18994 					"Cannot replace static functions\n");
18995 				return -EINVAL;
18996 			}
18997 			if (!prog->jit_requested) {
18998 				bpf_log(log,
18999 					"Extension programs should be JITed\n");
19000 				return -EINVAL;
19001 			}
19002 			tgt_changes_pkt_data = aux->func
19003 					       ? aux->func[subprog]->aux->changes_pkt_data
19004 					       : aux->changes_pkt_data;
19005 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
19006 				bpf_log(log,
19007 					"Extension program changes packet data, while original does not\n");
19008 				return -EINVAL;
19009 			}
19010 
19011 			tgt_might_sleep = aux->func
19012 					  ? aux->func[subprog]->aux->might_sleep
19013 					  : aux->might_sleep;
19014 			if (prog->aux->might_sleep && !tgt_might_sleep) {
19015 				bpf_log(log,
19016 					"Extension program may sleep, while original does not\n");
19017 				return -EINVAL;
19018 			}
19019 		}
19020 		if (!tgt_prog->jited) {
19021 			bpf_log(log, "Can attach to only JITed progs\n");
19022 			return -EINVAL;
19023 		}
19024 		if (prog_tracing) {
19025 			if (aux->attach_tracing_prog) {
19026 				/*
19027 				 * Target program is an fentry/fexit which is already attached
19028 				 * to another tracing program. More levels of nesting
19029 				 * attachment are not allowed.
19030 				 */
19031 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
19032 				return -EINVAL;
19033 			}
19034 		} else if (tgt_prog->type == prog->type) {
19035 			/*
19036 			 * To avoid potential call chain cycles, prevent attaching of a
19037 			 * program extension to another extension. It's ok to attach
19038 			 * fentry/fexit to extension program.
19039 			 */
19040 			bpf_log(log, "Cannot recursively attach\n");
19041 			return -EINVAL;
19042 		}
19043 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19044 		    prog_extension &&
19045 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19046 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT ||
19047 		     tgt_prog->expected_attach_type == BPF_TRACE_FENTRY_MULTI ||
19048 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI ||
19049 		     tgt_prog->expected_attach_type == BPF_TRACE_FSESSION ||
19050 		     tgt_prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
19051 			/* Program extensions can extend all program types
19052 			 * except fentry/fexit. The reason is the following.
19053 			 * The fentry/fexit programs are used for performance
19054 			 * analysis, stats and can be attached to any program
19055 			 * type. When extension program is replacing XDP function
19056 			 * it is necessary to allow performance analysis of all
19057 			 * functions. Both original XDP program and its program
19058 			 * extension. Hence attaching fentry/fexit to
19059 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
19060 			 * fentry/fexit was allowed it would be possible to create
19061 			 * long call chain fentry->extension->fentry->extension
19062 			 * beyond reasonable stack size. Hence extending fentry
19063 			 * is not allowed.
19064 			 */
19065 			bpf_log(log, "Cannot extend fentry/fexit/fsession\n");
19066 			return -EINVAL;
19067 		}
19068 	} else {
19069 		if (prog_extension) {
19070 			bpf_log(log, "Cannot replace kernel functions\n");
19071 			return -EINVAL;
19072 		}
19073 	}
19074 
19075 	switch (prog->expected_attach_type) {
19076 	case BPF_TRACE_RAW_TP:
19077 		if (tgt_prog) {
19078 			bpf_log(log,
19079 				"Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n");
19080 			return -EINVAL;
19081 		}
19082 		if (!btf_type_is_typedef(t)) {
19083 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19084 				btf_id);
19085 			return -EINVAL;
19086 		}
19087 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19088 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19089 				btf_id, tname);
19090 			return -EINVAL;
19091 		}
19092 		tname += sizeof(prefix) - 1;
19093 
19094 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
19095 		 * names. Thus using bpf_raw_event_map to get argument names.
19096 		 */
19097 		btp = bpf_get_raw_tracepoint(tname);
19098 		if (!btp)
19099 			return -EINVAL;
19100 		if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) {
19101 			bpf_log(log, "Sleepable program cannot attach to non-faultable tracepoint %s\n",
19102 				tname);
19103 			bpf_put_raw_tracepoint(btp);
19104 			return -EINVAL;
19105 		}
19106 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
19107 					trace_symbol);
19108 		bpf_put_raw_tracepoint(btp);
19109 
19110 		if (fname)
19111 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
19112 
19113 		if (!fname || ret < 0) {
19114 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
19115 				prefix, tname);
19116 			t = btf_type_by_id(btf, t->type);
19117 			if (!btf_type_is_ptr(t))
19118 				/* should never happen in valid vmlinux build */
19119 				return -EINVAL;
19120 		} else {
19121 			t = btf_type_by_id(btf, ret);
19122 			if (!btf_type_is_func(t))
19123 				/* should never happen in valid vmlinux build */
19124 				return -EINVAL;
19125 		}
19126 
19127 		t = btf_type_by_id(btf, t->type);
19128 		if (!btf_type_is_func_proto(t))
19129 			/* should never happen in valid vmlinux build */
19130 			return -EINVAL;
19131 
19132 		break;
19133 	case BPF_TRACE_ITER:
19134 		if (!btf_type_is_func(t)) {
19135 			bpf_log(log, "attach_btf_id %u is not a function\n",
19136 				btf_id);
19137 			return -EINVAL;
19138 		}
19139 		t = btf_type_by_id(btf, t->type);
19140 		if (!btf_type_is_func_proto(t))
19141 			return -EINVAL;
19142 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19143 		if (ret)
19144 			return ret;
19145 		break;
19146 	default:
19147 		if (!prog_extension)
19148 			return -EINVAL;
19149 		fallthrough;
19150 	case BPF_MODIFY_RETURN:
19151 	case BPF_LSM_MAC:
19152 	case BPF_LSM_CGROUP:
19153 	case BPF_TRACE_FENTRY:
19154 	case BPF_TRACE_FEXIT:
19155 	case BPF_TRACE_FSESSION:
19156 	case BPF_TRACE_FSESSION_MULTI:
19157 	case BPF_TRACE_FENTRY_MULTI:
19158 	case BPF_TRACE_FEXIT_MULTI:
19159 		if ((prog->expected_attach_type == BPF_TRACE_FSESSION ||
19160 		    prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) &&
19161 		    !bpf_jit_supports_fsession()) {
19162 			bpf_log(log, "JIT does not support fsession\n");
19163 			return -EOPNOTSUPP;
19164 		}
19165 		if (!btf_type_is_func(t)) {
19166 			bpf_log(log, "attach_btf_id %u is not a function\n",
19167 				btf_id);
19168 			return -EINVAL;
19169 		}
19170 		if (prog_extension &&
19171 		    btf_check_type_match(log, prog, btf, t))
19172 			return -EINVAL;
19173 		t = btf_attach_func_proto(log, btf, btf_id);
19174 		if (!t || !btf_type_is_func_proto(t))
19175 			return -EINVAL;
19176 
19177 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19178 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19179 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19180 			return -EINVAL;
19181 
19182 		if (tgt_prog && conservative)
19183 			t = NULL;
19184 
19185 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19186 		if (ret < 0)
19187 			return ret;
19188 
19189 		/*
19190 		 * *.multi programs don't need an address during program
19191 		 * verification, we just take the module ref if needed.
19192 		 */
19193 		if (is_tracing_multi_id(prog, btf_id)) {
19194 			if (btf_is_module(btf)) {
19195 				mod = btf_try_get_module(btf);
19196 				if (!mod)
19197 					return -ENOENT;
19198 			}
19199 			addr = 0;
19200 		} else if (tgt_prog) {
19201 			if (subprog == 0)
19202 				addr = (long) tgt_prog->bpf_func;
19203 			else
19204 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19205 		} else {
19206 			if (btf_is_module(btf)) {
19207 				mod = btf_try_get_module(btf);
19208 				if (mod)
19209 					addr = find_kallsyms_symbol_value(mod, tname);
19210 				else
19211 					addr = 0;
19212 			} else {
19213 				addr = kallsyms_lookup_name(tname);
19214 			}
19215 			if (!addr) {
19216 				module_put(mod);
19217 				bpf_log(log,
19218 					"The address of function %s cannot be found\n",
19219 					tname);
19220 				return -ENOENT;
19221 			}
19222 		}
19223 
19224 		if (prog->sleepable) {
19225 			ret = btf_id_allow_sleepable(btf_id, addr, prog, btf);
19226 			if (ret) {
19227 				module_put(mod);
19228 				bpf_log(log, "%s is not sleepable\n", tname);
19229 				return ret;
19230 			}
19231 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19232 			if (tgt_prog) {
19233 				module_put(mod);
19234 				bpf_log(log, "can't modify return codes of BPF programs\n");
19235 				return -EINVAL;
19236 			}
19237 			ret = -EINVAL;
19238 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19239 			    !check_attach_modify_return(addr, tname))
19240 				ret = 0;
19241 			if (ret) {
19242 				module_put(mod);
19243 				bpf_log(log, "%s() is not modifiable\n", tname);
19244 				return ret;
19245 			}
19246 		}
19247 
19248 		break;
19249 	}
19250 	tgt_info->tgt_addr = addr;
19251 	tgt_info->tgt_name = tname;
19252 	tgt_info->tgt_type = t;
19253 	tgt_info->tgt_mod = mod;
19254 	return 0;
19255 }
19256 
19257 BTF_SET_START(btf_id_deny)
19258 BTF_ID_UNUSED
19259 #ifdef CONFIG_SMP
19260 BTF_ID(func, ___migrate_enable)
19261 BTF_ID(func, migrate_disable)
19262 BTF_ID(func, migrate_enable)
19263 #endif
19264 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19265 BTF_ID(func, rcu_read_unlock_strict)
19266 #endif
19267 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19268 BTF_ID(func, preempt_count_add)
19269 BTF_ID(func, preempt_count_sub)
19270 #endif
19271 #ifdef CONFIG_PREEMPT_RCU
19272 BTF_ID(func, __rcu_read_lock)
19273 BTF_ID(func, __rcu_read_unlock)
19274 #endif
19275 BTF_SET_END(btf_id_deny)
19276 
19277 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
19278  * Currently, we must manually list all __noreturn functions here. Once a more
19279  * robust solution is implemented, this workaround can be removed.
19280  */
19281 BTF_SET_START(noreturn_deny)
19282 #ifdef CONFIG_IA32_EMULATION
19283 BTF_ID(func, __ia32_sys_exit)
19284 BTF_ID(func, __ia32_sys_exit_group)
19285 #endif
19286 #ifdef CONFIG_KUNIT
19287 BTF_ID(func, __kunit_abort)
19288 BTF_ID(func, kunit_try_catch_throw)
19289 #endif
19290 #ifdef CONFIG_MODULES
19291 BTF_ID(func, __module_put_and_kthread_exit)
19292 #endif
19293 #ifdef CONFIG_X86_64
19294 BTF_ID(func, __x64_sys_exit)
19295 BTF_ID(func, __x64_sys_exit_group)
19296 #endif
19297 BTF_ID(func, do_exit)
19298 BTF_ID(func, do_group_exit)
19299 BTF_ID(func, kthread_complete_and_exit)
19300 BTF_ID(func, make_task_dead)
19301 BTF_SET_END(noreturn_deny)
19302 
19303 static bool can_be_sleepable(struct bpf_prog *prog)
19304 {
19305 	if (prog->type == BPF_PROG_TYPE_TRACING) {
19306 		switch (prog->expected_attach_type) {
19307 		case BPF_TRACE_FENTRY:
19308 		case BPF_TRACE_FEXIT:
19309 		case BPF_MODIFY_RETURN:
19310 		case BPF_TRACE_ITER:
19311 		case BPF_TRACE_FSESSION:
19312 		case BPF_TRACE_RAW_TP:
19313 		case BPF_TRACE_FENTRY_MULTI:
19314 		case BPF_TRACE_FEXIT_MULTI:
19315 		case BPF_TRACE_FSESSION_MULTI:
19316 			return true;
19317 		default:
19318 			return false;
19319 		}
19320 	}
19321 	if (prog->type == BPF_PROG_TYPE_LSM)
19322 		return prog->expected_attach_type != BPF_LSM_CGROUP;
19323 
19324 	return prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19325 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
19326 	       prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT ||
19327 	       prog->type == BPF_PROG_TYPE_TRACEPOINT;
19328 }
19329 
19330 static int check_attach_btf_id(struct bpf_verifier_env *env)
19331 {
19332 	struct bpf_prog *prog = env->prog;
19333 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19334 	struct bpf_attach_target_info tgt_info = {};
19335 	u32 btf_id = prog->aux->attach_btf_id;
19336 	struct bpf_trampoline *tr;
19337 	int ret;
19338 	u64 key;
19339 
19340 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19341 		if (prog->sleepable)
19342 			/* attach_btf_id checked to be zero already */
19343 			return 0;
19344 		verbose(env, "Syscall programs can only be sleepable\n");
19345 		return -EINVAL;
19346 	}
19347 
19348 	if (prog->sleepable && !can_be_sleepable(prog)) {
19349 		verbose(env, "Program of this type cannot be sleepable\n");
19350 		return -EINVAL;
19351 	}
19352 
19353 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19354 		return check_struct_ops_btf_id(env);
19355 
19356 	if (prog->type != BPF_PROG_TYPE_TRACING &&
19357 	    prog->type != BPF_PROG_TYPE_LSM &&
19358 	    prog->type != BPF_PROG_TYPE_EXT)
19359 		return 0;
19360 
19361 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19362 	if (ret)
19363 		return ret;
19364 
19365 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19366 		/* to make freplace equivalent to their targets, they need to
19367 		 * inherit env->ops and expected_attach_type for the rest of the
19368 		 * verification
19369 		 */
19370 		env->ops = bpf_verifier_ops[tgt_prog->type];
19371 		prog->expected_attach_type = tgt_prog->expected_attach_type;
19372 	}
19373 
19374 	/* store info about the attachment target that will be used later */
19375 	prog->aux->attach_func_proto = tgt_info.tgt_type;
19376 	prog->aux->attach_func_name = tgt_info.tgt_name;
19377 	prog->aux->mod = tgt_info.tgt_mod;
19378 
19379 	if (tgt_prog) {
19380 		prog->aux->saved_dst_prog_type = tgt_prog->type;
19381 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19382 	}
19383 
19384 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19385 		prog->aux->attach_btf_trace = true;
19386 		return 0;
19387 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19388 		return bpf_iter_prog_supported(prog);
19389 	}
19390 
19391 	if (prog->type == BPF_PROG_TYPE_LSM) {
19392 		ret = bpf_lsm_verify_prog(&env->log, prog);
19393 		if (ret < 0)
19394 			return ret;
19395 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
19396 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
19397 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
19398 			tgt_info.tgt_name);
19399 		return -EINVAL;
19400 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
19401 		   prog->expected_attach_type == BPF_TRACE_FSESSION ||
19402 		   prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI ||
19403 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
19404 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
19405 		verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n",
19406 			tgt_info.tgt_name);
19407 		return -EINVAL;
19408 	}
19409 
19410 	/*
19411 	 * We don't get trampoline for tracing_multi programs at this point,
19412 	 * it's done when tracing_multi link is created.
19413 	 */
19414 	if (prog->type == BPF_PROG_TYPE_TRACING &&
19415 	    is_tracing_multi(prog->expected_attach_type))
19416 		return 0;
19417 
19418 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19419 	tr = bpf_trampoline_get(key, &tgt_info);
19420 	if (!tr)
19421 		return -ENOMEM;
19422 
19423 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
19424 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
19425 
19426 	prog->aux->dst_trampoline = tr;
19427 	return 0;
19428 }
19429 
19430 int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id,
19431 				  struct bpf_attach_target_info *tgt_info)
19432 {
19433 	const struct btf_type *t;
19434 	unsigned long addr;
19435 	const char *tname;
19436 	int err;
19437 
19438 	if (!btf_id || !btf)
19439 		return -EINVAL;
19440 
19441 	/* Check noreturn attachment. */
19442 	if ((prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI ||
19443 	     prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) &&
19444 	     btf_id_set_contains(&noreturn_deny, btf_id))
19445 		return -EINVAL;
19446 	/* Check denied attachment. */
19447 	if (btf_id_set_contains(&btf_id_deny, btf_id))
19448 		return -EINVAL;
19449 
19450 	/* Check and get function target data. */
19451 	t = btf_type_by_id(btf, btf_id);
19452 	if (!t)
19453 		return -EINVAL;
19454 	tname = btf_name_by_offset(btf, t->name_off);
19455 	if (!tname)
19456 		return -EINVAL;
19457 	t = btf_attach_func_proto(NULL, btf, btf_id);
19458 	if (!t || !btf_type_is_func_proto(t))
19459 		return -EINVAL;
19460 	err = btf_distill_func_proto(NULL, btf, t, tname, &tgt_info->fmodel);
19461 	if (err < 0)
19462 		return err;
19463 	if (btf_is_module(btf)) {
19464 		/* The bpf program already holds reference to module. */
19465 		if (WARN_ON_ONCE(!prog->aux->mod))
19466 			return -EINVAL;
19467 		addr = find_kallsyms_symbol_value(prog->aux->mod, tname);
19468 	} else {
19469 		addr = kallsyms_lookup_name(tname);
19470 	}
19471 	if (!addr || !ftrace_location(addr))
19472 		return -ENOENT;
19473 
19474 	/* Check sleepable program attachment. */
19475 	if (prog->sleepable) {
19476 		err = btf_id_allow_sleepable(btf_id, addr, prog, btf);
19477 		if (err)
19478 			return err;
19479 	}
19480 	tgt_info->tgt_addr = addr;
19481 	return 0;
19482 }
19483 
19484 struct btf *bpf_get_btf_vmlinux(void)
19485 {
19486 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19487 		mutex_lock(&bpf_verifier_lock);
19488 		if (!btf_vmlinux)
19489 			btf_vmlinux = btf_parse_vmlinux();
19490 		mutex_unlock(&bpf_verifier_lock);
19491 	}
19492 	return btf_vmlinux;
19493 }
19494 
19495 /*
19496  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
19497  * this case expect that every file descriptor in the array is either a map or
19498  * a BTF. Everything else is considered to be trash.
19499  */
19500 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
19501 {
19502 	struct bpf_map *map;
19503 	struct btf *btf;
19504 	CLASS(fd, f)(fd);
19505 	int err;
19506 
19507 	map = __bpf_map_get(f);
19508 	if (!IS_ERR(map)) {
19509 		err = __add_used_map(env, map);
19510 		if (err < 0)
19511 			return err;
19512 		return 0;
19513 	}
19514 
19515 	btf = __btf_get_by_fd(f);
19516 	if (!IS_ERR(btf)) {
19517 		btf_get(btf);
19518 		return __add_used_btf(env, btf);
19519 	}
19520 
19521 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
19522 	return PTR_ERR(map);
19523 }
19524 
19525 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
19526 {
19527 	size_t size = sizeof(int);
19528 	int ret;
19529 	int fd;
19530 	u32 i;
19531 
19532 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19533 
19534 	/*
19535 	 * The only difference between old (no fd_array_cnt is given) and new
19536 	 * APIs is that in the latter case the fd_array is expected to be
19537 	 * continuous and is scanned for map fds right away
19538 	 */
19539 	if (!attr->fd_array_cnt)
19540 		return 0;
19541 
19542 	/* Check for integer overflow */
19543 	if (attr->fd_array_cnt >= (U32_MAX / size)) {
19544 		verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
19545 		return -EINVAL;
19546 	}
19547 
19548 	for (i = 0; i < attr->fd_array_cnt; i++) {
19549 		if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
19550 			return -EFAULT;
19551 
19552 		ret = add_fd_from_fd_array(env, fd);
19553 		if (ret)
19554 			return ret;
19555 	}
19556 
19557 	return 0;
19558 }
19559 
19560 /* replace a generic kfunc with a specialized version if necessary */
19561 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)
19562 {
19563 	struct bpf_prog *prog = env->prog;
19564 	bool seen_direct_write;
19565 	void *xdp_kfunc;
19566 	bool is_rdonly;
19567 	u32 func_id = desc->func_id;
19568 	u16 offset = desc->offset;
19569 	unsigned long addr = desc->addr;
19570 
19571 	if (offset) /* return if module BTF is used */
19572 		return 0;
19573 
19574 	if (bpf_dev_bound_kfunc_id(func_id)) {
19575 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19576 		if (xdp_kfunc)
19577 			addr = (unsigned long)xdp_kfunc;
19578 		/* fallback to default kfunc when not supported by netdev */
19579 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19580 		seen_direct_write = env->seen_direct_write;
19581 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19582 
19583 		if (is_rdonly)
19584 			addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19585 
19586 		/* restore env->seen_direct_write to its original value, since
19587 		 * may_access_direct_pkt_data mutates it
19588 		 */
19589 		env->seen_direct_write = seen_direct_write;
19590 	} else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {
19591 		if (bpf_lsm_has_d_inode_locked(prog))
19592 			addr = (unsigned long)bpf_set_dentry_xattr_locked;
19593 	} else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
19594 		if (bpf_lsm_has_d_inode_locked(prog))
19595 			addr = (unsigned long)bpf_remove_dentry_xattr_locked;
19596 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
19597 		if (!env->insn_aux_data[insn_idx].non_sleepable)
19598 			addr = (unsigned long)bpf_dynptr_from_file_sleepable;
19599 	} else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) {
19600 		if (env->insn_aux_data[insn_idx].non_sleepable)
19601 			addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable;
19602 	} else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) {
19603 		if (env->insn_aux_data[insn_idx].non_sleepable)
19604 			addr = (unsigned long)bpf_arena_free_pages_non_sleepable;
19605 	}
19606 	desc->addr = addr;
19607 	return 0;
19608 }
19609 
19610 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19611 					    u16 struct_meta_reg,
19612 					    u16 node_offset_reg,
19613 					    struct bpf_insn *insn,
19614 					    struct bpf_insn *insn_buf,
19615 					    int *cnt)
19616 {
19617 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19618 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19619 
19620 	insn_buf[0] = addr[0];
19621 	insn_buf[1] = addr[1];
19622 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19623 	insn_buf[3] = *insn;
19624 	*cnt = 4;
19625 }
19626 
19627 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19628 		     struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19629 {
19630 	struct bpf_kfunc_desc *desc;
19631 	int err;
19632 
19633 	if (!insn->imm) {
19634 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19635 		return -EINVAL;
19636 	}
19637 
19638 	*cnt = 0;
19639 
19640 	/* insn->imm has the btf func_id. Replace it with an offset relative to
19641 	 * __bpf_call_base, unless the JIT needs to call functions that are
19642 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19643 	 */
19644 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19645 	if (!desc) {
19646 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
19647 			     insn->imm);
19648 		return -EFAULT;
19649 	}
19650 
19651 	err = specialize_kfunc(env, desc, insn_idx);
19652 	if (err)
19653 		return err;
19654 
19655 	if (!bpf_jit_supports_far_kfunc_call())
19656 		insn->imm = BPF_CALL_IMM(desc->addr);
19657 
19658 	if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) {
19659 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19660 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19661 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19662 
19663 		if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) {
19664 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
19665 				     insn_idx);
19666 			return -EFAULT;
19667 		}
19668 
19669 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19670 		insn_buf[1] = addr[0];
19671 		insn_buf[2] = addr[1];
19672 		insn_buf[3] = *insn;
19673 		*cnt = 4;
19674 	} else if (is_bpf_obj_drop_kfunc(desc->func_id) ||
19675 		   is_bpf_percpu_obj_drop_kfunc(desc->func_id) ||
19676 		   is_bpf_refcount_acquire_kfunc(desc->func_id)) {
19677 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19678 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19679 
19680 		if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) {
19681 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
19682 				     insn_idx);
19683 			return -EFAULT;
19684 		}
19685 
19686 		if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) {
19687 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
19688 				     insn_idx);
19689 			return -EFAULT;
19690 		}
19691 
19692 		insn_buf[0] = addr[0];
19693 		insn_buf[1] = addr[1];
19694 		insn_buf[2] = *insn;
19695 		*cnt = 3;
19696 	} else if (is_bpf_list_push_kfunc(desc->func_id) ||
19697 		   is_bpf_rbtree_add_kfunc(desc->func_id)) {
19698 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19699 		int struct_meta_reg = BPF_REG_3;
19700 		int node_offset_reg = BPF_REG_4;
19701 
19702 		/* list_add/rbtree_add have an extra arg (prev/less),
19703 		 * so args-to-fixup are in diff regs.
19704 		 */
19705 		if (desc->func_id == special_kfunc_list[KF_bpf_list_add] ||
19706 		    is_bpf_rbtree_add_kfunc(desc->func_id)) {
19707 			struct_meta_reg = BPF_REG_4;
19708 			node_offset_reg = BPF_REG_5;
19709 		}
19710 
19711 		if (!kptr_struct_meta) {
19712 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
19713 				     insn_idx);
19714 			return -EFAULT;
19715 		}
19716 
19717 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19718 						node_offset_reg, insn, insn_buf, cnt);
19719 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19720 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19721 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19722 		*cnt = 1;
19723 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] &&
19724 		   (env->prog->expected_attach_type == BPF_TRACE_FSESSION ||
19725 		    env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
19726 
19727 		/*
19728 		 * inline the bpf_session_is_return() for fsession:
19729 		 *   bool bpf_session_is_return(void *ctx)
19730 		 *   {
19731 		 *       return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1;
19732 		 *   }
19733 		 */
19734 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19735 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT);
19736 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1);
19737 		*cnt = 3;
19738 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] &&
19739 		   (env->prog->expected_attach_type == BPF_TRACE_FSESSION ||
19740 		    env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
19741 		/*
19742 		 * inline bpf_session_cookie() for fsession:
19743 		 *   __u64 *bpf_session_cookie(void *ctx)
19744 		 *   {
19745 		 *       u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF;
19746 		 *       return &((u64 *)ctx)[-off];
19747 		 *   }
19748 		 */
19749 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19750 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT);
19751 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
19752 		insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19753 		insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1);
19754 		insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0);
19755 		*cnt = 6;
19756 	}
19757 
19758 	if (env->insn_aux_data[insn_idx].arg_prog) {
19759 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
19760 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
19761 		int idx = *cnt;
19762 
19763 		insn_buf[idx++] = ld_addrs[0];
19764 		insn_buf[idx++] = ld_addrs[1];
19765 		insn_buf[idx++] = *insn;
19766 		*cnt = idx;
19767 	}
19768 	return 0;
19769 }
19770 
19771 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
19772 	      struct bpf_log_attr *attr_log)
19773 {
19774 	u64 start_time = ktime_get_ns();
19775 	struct bpf_verifier_env *env;
19776 	int i, len, ret = -EINVAL, err;
19777 	bool is_priv;
19778 
19779 	BTF_TYPE_EMIT(enum bpf_features);
19780 
19781 	/* no program is valid */
19782 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19783 		return -EINVAL;
19784 
19785 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
19786 	 * allocate/free it every time bpf_check() is called
19787 	 */
19788 	env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT);
19789 	if (!env)
19790 		return -ENOMEM;
19791 
19792 	env->bt.env = env;
19793 
19794 	len = (*prog)->len;
19795 	env->insn_aux_data =
19796 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19797 	ret = -ENOMEM;
19798 	if (!env->insn_aux_data)
19799 		goto err_free_env;
19800 	for (i = 0; i < len; i++)
19801 		env->insn_aux_data[i].orig_idx = i;
19802 	env->succ = bpf_iarray_realloc(NULL, 2);
19803 	if (!env->succ)
19804 		goto err_free_env;
19805 	env->prog = *prog;
19806 	env->ops = bpf_verifier_ops[env->prog->type];
19807 
19808 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
19809 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
19810 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
19811 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
19812 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
19813 
19814 	bpf_get_btf_vmlinux();
19815 
19816 	/* grab the mutex to protect few globals used by verifier */
19817 	if (!is_priv)
19818 		mutex_lock(&bpf_verifier_lock);
19819 
19820 	/* user could have requested verbose verifier output
19821 	 * and supplied buffer to store the verification trace
19822 	 */
19823 	ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size);
19824 	if (ret)
19825 		goto err_unlock;
19826 
19827 	ret = process_fd_array(env, attr, uattr);
19828 	if (ret)
19829 		goto skip_full_check;
19830 
19831 	mark_verifier_state_clean(env);
19832 
19833 	if (IS_ERR(btf_vmlinux)) {
19834 		/* Either gcc or pahole or kernel are broken. */
19835 		verbose(env, "in-kernel BTF is malformed\n");
19836 		ret = PTR_ERR(btf_vmlinux);
19837 		goto skip_full_check;
19838 	}
19839 
19840 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19841 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19842 		env->strict_alignment = true;
19843 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19844 		env->strict_alignment = false;
19845 
19846 	if (is_priv)
19847 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19848 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
19849 
19850 	env->explored_states = kvzalloc_objs(struct list_head,
19851 					     state_htab_size(env),
19852 					     GFP_KERNEL_ACCOUNT);
19853 	ret = -ENOMEM;
19854 	if (!env->explored_states)
19855 		goto skip_full_check;
19856 
19857 	for (i = 0; i < state_htab_size(env); i++)
19858 		INIT_LIST_HEAD(&env->explored_states[i]);
19859 	INIT_LIST_HEAD(&env->free_list);
19860 
19861 	ret = bpf_check_btf_info_early(env, attr, uattr);
19862 	if (ret < 0)
19863 		goto skip_full_check;
19864 
19865 	ret = add_subprog_and_kfunc(env);
19866 	if (ret < 0)
19867 		goto skip_full_check;
19868 
19869 	ret = check_subprogs(env);
19870 	if (ret < 0)
19871 		goto skip_full_check;
19872 
19873 	ret = bpf_check_btf_info(env, attr, uattr);
19874 	if (ret < 0)
19875 		goto skip_full_check;
19876 
19877 	ret = check_and_resolve_insns(env);
19878 	if (ret < 0)
19879 		goto skip_full_check;
19880 
19881 	if (bpf_prog_is_offloaded(env->prog->aux)) {
19882 		ret = bpf_prog_offload_verifier_prep(env->prog);
19883 		if (ret)
19884 			goto skip_full_check;
19885 	}
19886 
19887 	ret = bpf_check_cfg(env);
19888 	if (ret < 0)
19889 		goto skip_full_check;
19890 
19891 	ret = bpf_compute_postorder(env);
19892 	if (ret < 0)
19893 		goto skip_full_check;
19894 
19895 	ret = bpf_stack_liveness_init(env);
19896 	if (ret)
19897 		goto skip_full_check;
19898 
19899 	ret = check_attach_btf_id(env);
19900 	if (ret)
19901 		goto skip_full_check;
19902 
19903 	ret = bpf_compute_const_regs(env);
19904 	if (ret < 0)
19905 		goto skip_full_check;
19906 
19907 	ret = bpf_prune_dead_branches(env);
19908 	if (ret < 0)
19909 		goto skip_full_check;
19910 
19911 	ret = sort_subprogs_topo(env);
19912 	if (ret < 0)
19913 		goto skip_full_check;
19914 
19915 	ret = bpf_compute_scc(env);
19916 	if (ret < 0)
19917 		goto skip_full_check;
19918 
19919 	ret = bpf_compute_live_registers(env);
19920 	if (ret < 0)
19921 		goto skip_full_check;
19922 
19923 	ret = mark_fastcall_patterns(env);
19924 	if (ret < 0)
19925 		goto skip_full_check;
19926 
19927 	ret = do_check_main(env);
19928 	ret = ret ?: do_check_subprogs(env);
19929 
19930 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19931 		ret = bpf_prog_offload_finalize(env);
19932 
19933 skip_full_check:
19934 	kvfree(env->explored_states);
19935 
19936 	/* might decrease stack depth, keep it before passes that
19937 	 * allocate additional slots.
19938 	 */
19939 	if (ret == 0)
19940 		ret = bpf_remove_fastcall_spills_fills(env);
19941 
19942 	if (ret == 0)
19943 		ret = check_max_stack_depth(env);
19944 
19945 	/* instruction rewrites happen after this point */
19946 	if (ret == 0)
19947 		ret = bpf_optimize_bpf_loop(env);
19948 
19949 	if (is_priv) {
19950 		if (ret == 0)
19951 			bpf_opt_hard_wire_dead_code_branches(env);
19952 		if (ret == 0)
19953 			ret = bpf_opt_remove_dead_code(env);
19954 		if (ret == 0)
19955 			ret = bpf_opt_remove_nops(env);
19956 	} else {
19957 		if (ret == 0)
19958 			sanitize_dead_code(env);
19959 	}
19960 
19961 	if (ret == 0)
19962 		/* program is valid, convert *(u32*)(ctx + off) accesses */
19963 		ret = bpf_convert_ctx_accesses(env);
19964 
19965 	if (ret == 0)
19966 		ret = bpf_do_misc_fixups(env);
19967 
19968 	/* do 32-bit optimization after insn patching has done so those patched
19969 	 * insns could be handled correctly.
19970 	 */
19971 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19972 		ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr);
19973 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19974 								     : false;
19975 	}
19976 
19977 	if (ret == 0)
19978 		ret = bpf_fixup_call_args(env);
19979 
19980 	env->verification_time = ktime_get_ns() - start_time;
19981 	print_verification_stats(env);
19982 	env->prog->aux->verified_insns = env->insn_processed;
19983 
19984 	/* preserve original error even if log finalization is successful */
19985 	err = bpf_log_attr_finalize(attr_log, &env->log);
19986 	if (err)
19987 		ret = err;
19988 
19989 	if (ret)
19990 		goto err_release_maps;
19991 
19992 	if (env->used_map_cnt) {
19993 		/* if program passed verifier, update used_maps in bpf_prog_info */
19994 		env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0],
19995 							 env->used_map_cnt,
19996 							 GFP_KERNEL_ACCOUNT);
19997 
19998 		if (!env->prog->aux->used_maps) {
19999 			ret = -ENOMEM;
20000 			goto err_release_maps;
20001 		}
20002 
20003 		memcpy(env->prog->aux->used_maps, env->used_maps,
20004 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20005 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20006 	}
20007 	if (env->used_btf_cnt) {
20008 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20009 		env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0],
20010 							 env->used_btf_cnt,
20011 							 GFP_KERNEL_ACCOUNT);
20012 		if (!env->prog->aux->used_btfs) {
20013 			ret = -ENOMEM;
20014 			goto err_release_maps;
20015 		}
20016 
20017 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20018 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20019 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20020 	}
20021 	if (env->used_map_cnt || env->used_btf_cnt) {
20022 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20023 		 * bpf_ld_imm64 instructions
20024 		 */
20025 		convert_pseudo_ld_imm64(env);
20026 	}
20027 
20028 	adjust_btf_func(env);
20029 
20030 	/* extension progs temporarily inherit the attach_type of their targets
20031 	   for verification purposes, so set it back to zero before returning
20032 	 */
20033 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20034 		env->prog->expected_attach_type = 0;
20035 
20036 	env->prog = __bpf_prog_select_runtime(env, env->prog, &ret);
20037 
20038 err_release_maps:
20039 	if (ret)
20040 		release_insn_arrays(env);
20041 	if (!env->prog->aux->used_maps)
20042 		/* if we didn't copy map pointers into bpf_prog_info, release
20043 		 * them now. Otherwise free_used_maps() will release them.
20044 		 */
20045 		release_maps(env);
20046 	if (!env->prog->aux->used_btfs)
20047 		release_btfs(env);
20048 
20049 	*prog = env->prog;
20050 
20051 	module_put(env->attach_btf_mod);
20052 err_unlock:
20053 	if (!is_priv)
20054 		mutex_unlock(&bpf_verifier_lock);
20055 	bpf_clear_insn_aux_data(env, 0, env->prog->len);
20056 err_free_env:
20057 	bpf_stack_liveness_free(env);
20058 	kvfree(env->cfg.insn_postorder);
20059 	kvfree(env->scc_info);
20060 	kvfree(env->succ);
20061 	kvfree(env->gotox_tmp_buf);
20062 	vfree(env->insn_aux_data);
20063 	kvfree(env);
20064 	return ret;
20065 }
20066